lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | b42fb93409f76d69172b57ad309d4c56bcd5483a | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | ///////////////////////////////////////////////////////////////////////////////
//FILE: TileCreatorDlg.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//AUTHOR: Nico Stuurman, [email protected], January 10, 2008
//COPYRIGHT: University of California, San Francisco, 2008
//LICENSE: This file is distributed under the BSD license.
//License text is included with the source distribution.
//This file 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.
//IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.StrVector;
import org.micromanager.navigation.MultiStagePosition;
import org.micromanager.navigation.StagePosition;
import org.micromanager.utils.MMDialog;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ReportingUtils;
public class TileCreatorDlg extends MMDialog {
private static final long serialVersionUID = 1L;
private CMMCore core_;
private MultiStagePosition[] endPosition_;
private boolean[] endPositionSet_;
private PositionListDlg positionListDlg_;
private JTextField overlapField_;
private JComboBox overlapUnitsCombo_;
private enum OverlapUnitEnum {UM, PX, PERCENT};
private OverlapUnitEnum overlapUnit_ = OverlapUnitEnum.UM;
private JTextField pixelSizeField_;
private final JLabel labelLeft_ = new JLabel();
private final JLabel labelTop_ = new JLabel();
private final JLabel labelRight_ = new JLabel();
private final JLabel labelBottom_ = new JLabel();
private int prefix_ = 0;
private static final DecimalFormat FMT_POS = new DecimalFormat("000");
/**
* Create the dialog
*/
public TileCreatorDlg(CMMCore core, MMOptions opts, PositionListDlg positionListDlg) {
super();
setResizable(false);
setName("tileDialog");
getContentPane().setLayout(null);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
savePosition();
}
});
core_ = core;
positionListDlg_ = positionListDlg;
endPosition_ = new MultiStagePosition[4];
endPositionSet_ = new boolean[4];
setTitle("Tile Creator");
setBounds(300, 300, 344, 280);
Preferences root = Preferences.userNodeForPackage(this.getClass());
setPrefsNode(root.node(root.absolutePath() + "/TileCreatorDlg"));
Rectangle r = getBounds();
//loadPosition(r.x, r.y, r.width, r.height);
loadPosition(r.x, r.y);
final JButton goToLeftButton = new JButton();
goToLeftButton.setFont(new Font("", Font.PLAIN, 10));
goToLeftButton.setText("Go To");
goToLeftButton.setBounds(20, 89, 93, 23);
getContentPane().add(goToLeftButton);
goToLeftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[3])
goToPosition(endPosition_[3]);
}
});
labelLeft_.setFont(new Font("", Font.PLAIN, 8));
labelLeft_.setHorizontalAlignment(JLabel.CENTER);
labelLeft_.setText("");
labelLeft_.setBounds(0, 112, 130, 14);
getContentPane().add(labelLeft_);
final JButton setLeftButton = new JButton();
setLeftButton.setBounds(20, 66, 93, 23);
setLeftButton.setFont(new Font("", Font.PLAIN, 10));
setLeftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(3);
labelLeft_.setText(thisPosition());
}
});
setLeftButton.setText("Set");
getContentPane().add(setLeftButton);
labelTop_.setFont(new Font("", Font.PLAIN, 8));
labelTop_.setHorizontalAlignment(JLabel.CENTER);
labelTop_.setText("");
labelTop_.setBounds(115, 51, 130, 14);
getContentPane().add(labelTop_);
final JButton goToTopButton = new JButton();
goToTopButton.setFont(new Font("", Font.PLAIN, 10));
goToTopButton.setText("Go To");
goToTopButton.setBounds(133, 28, 93, 23);
getContentPane().add(goToTopButton);
goToTopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[0])
goToPosition(endPosition_[0]);
}
});
final JButton setTopButton = new JButton();
setTopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(0);
labelTop_.setText(thisPosition());
}
});
setTopButton.setBounds(133, 5, 93, 23);
setTopButton.setFont(new Font("", Font.PLAIN, 10));
setTopButton.setText("Set");
getContentPane().add(setTopButton);
labelRight_.setFont(new Font("", Font.PLAIN, 8));
labelRight_.setHorizontalAlignment(JLabel.CENTER);
labelRight_.setText("");
labelRight_.setBounds(214, 112, 130, 14);
getContentPane().add(labelRight_);
final JButton setRightButton = new JButton();
setRightButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(1);
labelRight_.setText(thisPosition());
}
});
setRightButton.setBounds(234, 66, 93, 23);
setRightButton.setFont(new Font("", Font.PLAIN, 10));
setRightButton.setText("Set");
getContentPane().add(setRightButton);
labelBottom_.setFont(new Font("", Font.PLAIN, 8));
labelBottom_.setHorizontalAlignment(JLabel.CENTER);
labelBottom_.setText("");
labelBottom_.setBounds(115, 172, 130, 14);
getContentPane().add(labelBottom_);
final JButton setBottomButton = new JButton();
setBottomButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(2);
labelBottom_.setText(thisPosition());
}
});
setBottomButton.setFont(new Font("", Font.PLAIN, 10));
setBottomButton.setText("Set");
setBottomButton.setBounds(133, 126, 93, 23);
getContentPane().add(setBottomButton);
final JButton goToRightButton = new JButton();
goToRightButton.setFont(new Font("", Font.PLAIN, 10));
goToRightButton.setText("Go To");
goToRightButton.setBounds(234, 89, 93, 23);
getContentPane().add(goToRightButton);
goToRightButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[1])
goToPosition(endPosition_[1]);
}
});
final JButton goToBottomButton = new JButton();
goToBottomButton.setFont(new Font("", Font.PLAIN, 10));
goToBottomButton.setText("Go To");
goToBottomButton.setBounds(133, 149, 93, 23);
getContentPane().add(goToBottomButton);
goToBottomButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[2])
goToPosition(endPosition_[2]);
}
});
final JLabel overlapLabel = new JLabel();
overlapLabel.setFont(new Font("", Font.PLAIN, 10));
overlapLabel.setText("Overlap");
overlapLabel.setBounds(20, 189, 80, 14);
getContentPane().add(overlapLabel);
overlapField_ = new JTextField();
overlapField_.setBounds(70, 186, 50, 20);
overlapField_.setFont(new Font("", Font.PLAIN, 10));
overlapField_.setText("0");
getContentPane().add(overlapField_);
String[] unitStrings = { "um", "px", "%" };
overlapUnitsCombo_ = new JComboBox(unitStrings);
overlapUnitsCombo_.setSelectedIndex(0);
overlapUnitsCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JComboBox cb = (JComboBox)arg0.getSource();
overlapUnit_ = OverlapUnitEnum.values()[cb.getSelectedIndex()];
}
});
overlapUnitsCombo_.setBounds(125, 186, 80, 20);
getContentPane().add(overlapUnitsCombo_);
final JLabel pixelSizeLabel = new JLabel();
pixelSizeLabel.setFont(new Font("", Font.PLAIN, 10));
pixelSizeLabel.setText("Pixel Size [um]");
pixelSizeLabel.setBounds(205, 189, 80, 14);
getContentPane().add(pixelSizeLabel);
pixelSizeField_ = new JTextField();
pixelSizeField_.setFont(new Font("", Font.PLAIN, 10));
pixelSizeField_.setBounds(280, 186, 50, 20);
pixelSizeField_.setText(NumberUtils.doubleToDisplayString(core_.getPixelSizeUm()));
getContentPane().add(pixelSizeField_);
final JButton okButton = new JButton();
okButton.setFont(new Font("", Font.PLAIN, 10));
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
savePosition();
addToPositionList();
}
});
okButton.setBounds(20, 216, 93, 23);
getContentPane().add(okButton);
final JButton cancelButton = new JButton();
cancelButton.setBounds(133, 216, 93, 23);
cancelButton.setFont(new Font("", Font.PLAIN, 10));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
savePosition();
dispose();
}
});
cancelButton.setText("Cancel");
getContentPane().add(cancelButton);
final JButton resetButton = new JButton();
resetButton.setBounds(234, 216, 93, 23);
resetButton.setFont(new Font("", Font.PLAIN, 10));
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
reset();
}
});
resetButton.setText("Reset");
getContentPane().add(resetButton);
}
/**
* Store current xyPosition.
*/
private void markPosition(int location) {
MultiStagePosition msp = new MultiStagePosition();
msp.setDefaultXYStage(core_.getXYStageDevice());
msp.setDefaultZStage(core_.getFocusDevice());
// read 1-axis stages
try {
StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice);
for (int i=0; i<stages.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages.get(i);
sp.numAxes = 1;
sp.x = core_.getPosition(stages.get(i));
msp.add(sp);
}
// read 2-axis stages
StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice);
for (int i=0; i<stages2D.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages2D.get(i);
sp.numAxes = 2;
sp.x = core_.getXPosition(stages2D.get(i));
sp.y = core_.getYPosition(stages2D.get(i));
msp.add(sp);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
endPosition_[location] = msp;
endPositionSet_[location] = true;
}
/**
* Update display of the current xy position.
*/
private String thisPosition() {
StringBuffer sb = new StringBuffer();
// read 1-axis stages
try {
StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice);
for (int i=0; i<stages.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages.get(i);
sp.numAxes = 1;
sp.x = core_.getPosition(stages.get(i));
sb.append(sp.getVerbose() + "\n");
}
// read 2-axis stages
StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice);
for (int i=0; i<stages2D.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages2D.get(i);
sp.numAxes = 2;
sp.x = core_.getXPosition(stages2D.get(i));
sp.y = core_.getYPosition(stages2D.get(i));
sb.append(sp.getVerbose() + "\n");
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return sb.toString();
}
/*
* Create the tile list based on user input, pixelsize, and imagesize
*/
private void addToPositionList() {
// check if we are calibrated, TODO: allow input of image size
double pixSizeUm = 0.0;
try {
pixSizeUm = NumberUtils.displayStringToDouble(pixelSizeField_.getText());
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (pixSizeUm <= 0.0) {
JOptionPane.showMessageDialog(this, "Pixel Size should be a value > 0 (usually 0.1 -1 um). It should be experimentally determined. ");
return;
}
double overlap = 0.0;
try {
overlap = NumberUtils.displayStringToDouble(overlapField_.getText());
} catch (Exception e) {
//handleError(e.getMessage());
}
boolean correction, transposeXY, mirrorX, mirrorY;
String camera = core_.getCameraDevice();
if (camera == null) {
JOptionPane.showMessageDialog(null, "This function does not work without a camera");
return;
}
try{
String tmp = core_.getProperty(camera, "TransposeCorrection");
if (tmp.equals("0"))
correction = false;
else
correction = true;
tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_MirrorX());
if (tmp.equals("0"))
mirrorX = false;
else
mirrorX = true;
tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_MirrorY());
if (tmp.equals("0"))
mirrorY = false;
else
mirrorY = true;
tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_SwapXY());
if (tmp.equals("0"))
transposeXY = false;
else
transposeXY = true;
} catch(Exception exc) {
ReportingUtils.showError(exc);
return;
}
double overlapUmX;
double overlapUmY;
if(overlapUnit_ == OverlapUnitEnum.UM)
overlapUmX = overlapUmY = overlap;
else if(overlapUnit_ == OverlapUnitEnum.PERCENT) {
overlapUmX = pixSizeUm * (overlap / 100) * core_.getImageWidth();
overlapUmY = pixSizeUm * (overlap / 100) * core_.getImageHeight();
} else { // overlapUnit_ == OverlapUnit.PX
overlapUmX = overlap * pixSizeUm;
overlapUmY = overlap * pixSizeUm;
}
// if camera does not correct image orientation, we'll correct for it here:
boolean swapXY = (!correction && transposeXY);
double tileSizeXUm = swapXY ?
pixSizeUm * core_.getImageHeight() - overlapUmY :
pixSizeUm * core_.getImageWidth() - overlapUmX;
double tileSizeYUm = swapXY ?
pixSizeUm * core_.getImageWidth() - overlapUmX :
pixSizeUm * core_.getImageHeight() - overlapUmY;
double imageSizeXUm = swapXY ? pixSizeUm * core_.getImageHeight() :
pixSizeUm * core_.getImageWidth();
double imageSizeYUm = swapXY ? pixSizeUm * core_.getImageWidth() :
pixSizeUm * core_.getImageHeight();
overlapUmX = swapXY ? overlapUmY : overlapUmX;
overlapUmY = swapXY ? overlapUmX : overlapUmY;
// Make sure at least two corners were set
int nrSet = 0;
for (int i=0; i<4; i++) {
if (endPositionSet_[i])
nrSet++;
}
if (nrSet < 2) {
JOptionPane.showMessageDialog(this, "At least two corners should be set");
return;
}
// Calculate a bounding rectangle around the defaultXYStage positions
// TODO: develop method to deal with multiple axis
double minX = Double.POSITIVE_INFINITY;
double minY = Double.POSITIVE_INFINITY;
double maxX = Double.NEGATIVE_INFINITY;
double maxY = Double.NEGATIVE_INFINITY;
double meanZ = 0.0;
StagePosition sp = new StagePosition();
for (int i=0; i<4; i++) {
if (endPositionSet_[i]) {
sp = endPosition_[i].get(endPosition_[i].getDefaultXYStage());
if (sp.x < minX)
minX = sp.x;
if (sp.x > maxX)
maxX = sp.x;
if (sp.y < minY)
minY = sp.y;
if (sp.y > maxY)
maxY = sp.y;
sp = endPosition_[i].get(endPosition_[i].getDefaultZStage());
meanZ += sp.x;
}
}
meanZ = meanZ/nrSet;
// if there are at least three set points, use them to define a
// focus plane: a, b, c such that z = f(x, y) = a*x + b*y + c.
double zPlaneA = 0.0, zPlaneB = 0.0, zPlaneC = 0.0;
boolean hasZPlane = false;
if (nrSet >= 3)
{
hasZPlane = true;
double x1 = 0.0, y1 = 0.0, z1 = 0.0;
double x2 = 0.0, y2 = 0.0, z2 = 0.0;
double x3 = 0.0, y3 = 0.0, z3 = 0.0;
boolean sp1Set = false;
boolean sp2Set = false;
boolean sp3Set = false;
// if there are four points set, we should either (a) choose the
// three that are least co-linear, or (b) use a linear regression to
// fit a focus plane that minimizes the errors at the four selected
// positions. this code does neither - it just uses the first three
// positions it finds.
for (int i=0; i<4; i++) {
if (endPositionSet_[i] && !sp1Set) {
x1 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x;
y1 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y;
z1 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x;
sp1Set = true;
} else if (endPositionSet_[i] && !sp2Set) {
x2 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x;
y2 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y;
z2 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x;
sp2Set = true;
} else if (endPositionSet_[i] && !sp3Set) {
x3 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x;
y3 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y;
z3 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x;
sp3Set = true;
}
}
// define vectors 1-->2, 1-->3
double x12 = x2 - x1;
double y12 = y2 - y1;
double z12 = z2 - z1;
double x13 = x3 - x1;
double y13 = y3 - y1;
double z13 = z3 - z1;
// first, make sure the points aren't co-linear: the angle between
// vectors 1-->2 and 1-->3 must be "sufficiently" large
double dot_prod = x12 * x13 + y12 * y13 + z12 * z13;
double magnitude12 = x12 * x12 + y12 * y12 + z12 * z12;
magnitude12 = Math.sqrt(magnitude12);
double magnitude13 = x13 * x13 + y13 * y13 + z13 * z13;
magnitude13 = Math.sqrt(magnitude13);
double cosTheta = dot_prod / (magnitude12 * magnitude13);
double theta = Math.acos(cosTheta); // in RADIANS
// "sufficiently" large here is 0.5 radians, or about 30 degrees
if(theta < 0.5
|| theta > (2 * Math.PI - 0.5)
|| (theta > (Math.PI - 0.5) && theta < (Math.PI + 0.5)))
hasZPlane = false;
// intermediates: ax + by + cz + d = 0
double a = y12 * z13 - y13 * z12;
double b = z12 * x13 - z13 * x12;
double c = x12 * y13 - x13 * y12;
double d = -1 * (a * x1 + b * y1 + c * z1);
// shuffle to z = f(x, y) = zPlaneA * x + zPlaneB * y + zPlaneC
zPlaneA = a / (-1 * c);
zPlaneB = b / (-1 * c);
zPlaneC = d / (-1 * c);
}
// make sure the user wants to continue if they've asked for Z positions
// but haven't defined enough (non-colinear!) points for a Z plane
if(positionListDlg_.useDrive(core_.getFocusDevice()) && !hasZPlane)
{
int choice = JOptionPane.showConfirmDialog(this,
"You are creating a position list that includes\n" +
"a Z (focus) position, but the grid locations\n" +
"you've chosen are co-linear! If you continue,\n" +
"the focus for the new positions will be\n" +
"the average focus for the grid locations you set.\n\n" +
"If you want to calculate the focus for the new\n" +
"positions, you must select at least three grid corners\n" +
"that aren't co-linear!\n\nContinue?",
"Continue with co-linear focus?",
JOptionPane.YES_NO_OPTION);
if(choice == JOptionPane.NO_OPTION || choice == JOptionPane.CLOSED_OPTION)
return;
}
// bounding box size
double boundingUmX = maxX - minX + imageSizeXUm;
double boundingUmY = maxY - minY + imageSizeYUm;
// calculate number of images in X and Y
int nrImagesX = (int) Math.ceil((boundingUmX - overlapUmX) / tileSizeXUm);
int nrImagesY = (int) Math.ceil((boundingUmY - overlapUmY) / tileSizeYUm);
double totalSizeXUm = nrImagesX * tileSizeXUm + overlapUmX;
double totalSizeYUm = nrImagesY * tileSizeYUm + overlapUmY;
double offsetXUm = (totalSizeXUm - boundingUmX) / 2;
double offsetYUm = (totalSizeYUm - boundingUmY) / 2;
// Increment prefix for these positions
prefix_ += 1;
// todo handle mirrorX mirrorY
for (int y=0; y< nrImagesY; y++) {
for (int x=0; x<nrImagesX; x++) {
// on even rows go left to right, on odd rows right to left
int tmpX = x;
if ( (y & 1) == 1)
tmpX = nrImagesX - x - 1;
MultiStagePosition msp = new MultiStagePosition();
// Add XY position
msp.setDefaultXYStage(core_.getXYStageDevice());
msp.setDefaultZStage(core_.getFocusDevice());
StagePosition spXY = new StagePosition();
spXY.stageName = core_.getXYStageDevice();
spXY.numAxes = 2;
spXY.x = minX - offsetXUm + (tmpX * tileSizeXUm);
spXY.y = minY - offsetYUm + (y * tileSizeYUm);
msp.add(spXY);
// Add Z position
StagePosition spZ = new StagePosition();
spZ.stageName = core_.getFocusDevice();
spZ.numAxes = 1;
if(hasZPlane) {
double z = zPlaneA * spXY.x + zPlaneB * spXY.y + zPlaneC;
spZ.x = z;
} else
spZ.x = meanZ;
if (positionListDlg_.useDrive(spZ.stageName))
msp.add(spZ);
// Add 'metadata'
msp.setGridCoordinates(y, tmpX);
if(overlapUnit_ == OverlapUnitEnum.UM || overlapUnit_ == OverlapUnitEnum.PX)
{
msp.setProperty("OverlapUm", NumberUtils.doubleToCoreString(overlapUmX));
int overlapPix = (int) Math.floor(overlapUmX/pixSizeUm);
msp.setProperty("OverlapPixels", NumberUtils.intToCoreString(overlapPix));
} else { // overlapUnit_ == OverlapUnit.PERCENT
// overlapUmX != overlapUmY; store both
msp.setProperty("OverlapUmX", NumberUtils.doubleToCoreString(overlapUmX));
msp.setProperty("OverlapUmY", NumberUtils.doubleToCoreString(overlapUmY));
int overlapPixX = (int) Math.floor(overlapUmX/pixSizeUm);
int overlapPixY = (int) Math.floor(overlapUmY/pixSizeUm);
msp.setProperty("OverlapPixelsX", NumberUtils.intToCoreString(overlapPixX));
msp.setProperty("OverlapPixelsY", NumberUtils.intToCoreString(overlapPixX));
}
// Add to position list
positionListDlg_.addPosition(msp, generatePosLabel(prefix_ + "-Pos", tmpX, y));
}
}
dispose();
}
/*
* Delete all positions from the dialog and update labels. Re-read pixel calibration - when available - from the core
*/
private void reset() {
for (int i=0; i<4; i++)
endPositionSet_[i] = false;
labelTop_.setText("");
labelRight_.setText("");
labelBottom_.setText("");
labelLeft_.setText("");
double pxsz = core_.getPixelSizeUm();
pixelSizeField_.setText(NumberUtils.doubleToDisplayString(pxsz));
}
/*
* Move stage to position
*/
private void goToPosition(MultiStagePosition position) {
try {
MultiStagePosition.goToPosition(position, core_);
} catch (Exception e) {
ReportingUtils.logError(e);
}
}
private void handleError(String txt) {
JOptionPane.showMessageDialog(this, txt);
}
public static String generatePosLabel(String prefix, int x, int y) {
String name = prefix + "_" + FMT_POS.format(x) + "_" + FMT_POS.format(y);
return name;
}
}
| mmstudio/src/org/micromanager/TileCreatorDlg.java | ///////////////////////////////////////////////////////////////////////////////
//FILE: TileCreatorDlg.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//AUTHOR: Nico Stuurman, [email protected], January 10, 2008
//COPYRIGHT: University of California, San Francisco, 2008
//LICENSE: This file is distributed under the BSD license.
//License text is included with the source distribution.
//This file 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.
//IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.StrVector;
import org.micromanager.navigation.MultiStagePosition;
import org.micromanager.navigation.StagePosition;
import org.micromanager.utils.MMDialog;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ReportingUtils;
public class TileCreatorDlg extends MMDialog {
private static final long serialVersionUID = 1L;
private CMMCore core_;
private MultiStagePosition[] endPosition_;
private boolean[] endPositionSet_;
private PositionListDlg positionListDlg_;
private JTextField overlapField_;
private JComboBox overlapUnitsCombo_;
private enum OverlapUnitEnum {UM, PX, PERCENT};
private OverlapUnitEnum overlapUnit_ = OverlapUnitEnum.UM;
private JTextField pixelSizeField_;
private final JLabel labelLeft_ = new JLabel();
private final JLabel labelTop_ = new JLabel();
private final JLabel labelRight_ = new JLabel();
private final JLabel labelBottom_ = new JLabel();
private int prefix_ = 0;
private static final DecimalFormat FMT_POS = new DecimalFormat("000");
/**
* Create the dialog
*/
public TileCreatorDlg(CMMCore core, MMOptions opts, PositionListDlg positionListDlg) {
super();
setResizable(false);
setName("tileDialog");
getContentPane().setLayout(null);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
savePosition();
}
});
core_ = core;
positionListDlg_ = positionListDlg;
endPosition_ = new MultiStagePosition[4];
endPositionSet_ = new boolean[4];
setTitle("Tile Creator");
setBounds(300, 300, 344, 280);
Preferences root = Preferences.userNodeForPackage(this.getClass());
setPrefsNode(root.node(root.absolutePath() + "/TileCreatorDlg"));
Rectangle r = getBounds();
//loadPosition(r.x, r.y, r.width, r.height);
loadPosition(r.x, r.y);
final JButton goToLeftButton = new JButton();
goToLeftButton.setFont(new Font("", Font.PLAIN, 10));
goToLeftButton.setText("Go To");
goToLeftButton.setBounds(20, 89, 93, 23);
getContentPane().add(goToLeftButton);
goToLeftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[3])
goToPosition(endPosition_[3]);
}
});
labelLeft_.setFont(new Font("", Font.PLAIN, 8));
labelLeft_.setHorizontalAlignment(JLabel.CENTER);
labelLeft_.setText("");
labelLeft_.setBounds(0, 112, 130, 14);
getContentPane().add(labelLeft_);
final JButton setLeftButton = new JButton();
setLeftButton.setBounds(20, 66, 93, 23);
setLeftButton.setFont(new Font("", Font.PLAIN, 10));
setLeftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(3);
labelLeft_.setText(thisPosition());
}
});
setLeftButton.setText("Set");
getContentPane().add(setLeftButton);
labelTop_.setFont(new Font("", Font.PLAIN, 8));
labelTop_.setHorizontalAlignment(JLabel.CENTER);
labelTop_.setText("");
labelTop_.setBounds(115, 51, 130, 14);
getContentPane().add(labelTop_);
final JButton goToTopButton = new JButton();
goToTopButton.setFont(new Font("", Font.PLAIN, 10));
goToTopButton.setText("Go To");
goToTopButton.setBounds(133, 28, 93, 23);
getContentPane().add(goToTopButton);
goToTopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[0])
goToPosition(endPosition_[0]);
}
});
final JButton setTopButton = new JButton();
setTopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(0);
labelTop_.setText(thisPosition());
}
});
setTopButton.setBounds(133, 5, 93, 23);
setTopButton.setFont(new Font("", Font.PLAIN, 10));
setTopButton.setText("Set");
getContentPane().add(setTopButton);
labelRight_.setFont(new Font("", Font.PLAIN, 8));
labelRight_.setHorizontalAlignment(JLabel.CENTER);
labelRight_.setText("");
labelRight_.setBounds(214, 112, 130, 14);
getContentPane().add(labelRight_);
final JButton setRightButton = new JButton();
setRightButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(1);
labelRight_.setText(thisPosition());
}
});
setRightButton.setBounds(234, 66, 93, 23);
setRightButton.setFont(new Font("", Font.PLAIN, 10));
setRightButton.setText("Set");
getContentPane().add(setRightButton);
labelBottom_.setFont(new Font("", Font.PLAIN, 8));
labelBottom_.setHorizontalAlignment(JLabel.CENTER);
labelBottom_.setText("");
labelBottom_.setBounds(115, 172, 130, 14);
getContentPane().add(labelBottom_);
final JButton setBottomButton = new JButton();
setBottomButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
markPosition(2);
labelBottom_.setText(thisPosition());
}
});
setBottomButton.setFont(new Font("", Font.PLAIN, 10));
setBottomButton.setText("Set");
setBottomButton.setBounds(133, 126, 93, 23);
getContentPane().add(setBottomButton);
final JButton goToRightButton = new JButton();
goToRightButton.setFont(new Font("", Font.PLAIN, 10));
goToRightButton.setText("Go To");
goToRightButton.setBounds(234, 89, 93, 23);
getContentPane().add(goToRightButton);
goToRightButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[1])
goToPosition(endPosition_[1]);
}
});
final JButton goToBottomButton = new JButton();
goToBottomButton.setFont(new Font("", Font.PLAIN, 10));
goToBottomButton.setText("Go To");
goToBottomButton.setBounds(133, 149, 93, 23);
getContentPane().add(goToBottomButton);
goToBottomButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (endPositionSet_[2])
goToPosition(endPosition_[2]);
}
});
final JLabel overlapLabel = new JLabel();
overlapLabel.setFont(new Font("", Font.PLAIN, 10));
overlapLabel.setText("Overlap");
overlapLabel.setBounds(20, 189, 80, 14);
getContentPane().add(overlapLabel);
overlapField_ = new JTextField();
overlapField_.setBounds(70, 186, 50, 20);
overlapField_.setFont(new Font("", Font.PLAIN, 10));
overlapField_.setText("0");
getContentPane().add(overlapField_);
String[] unitStrings = { "um", "px", "%" };
overlapUnitsCombo_ = new JComboBox(unitStrings);
overlapUnitsCombo_.setSelectedIndex(0);
overlapUnitsCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JComboBox cb = (JComboBox)arg0.getSource();
overlapUnit_ = OverlapUnitEnum.values()[cb.getSelectedIndex()];
}
});
overlapUnitsCombo_.setBounds(125, 186, 80, 20);
getContentPane().add(overlapUnitsCombo_);
final JLabel pixelSizeLabel = new JLabel();
pixelSizeLabel.setFont(new Font("", Font.PLAIN, 10));
pixelSizeLabel.setText("Pixel Size [um]");
pixelSizeLabel.setBounds(205, 189, 80, 14);
getContentPane().add(pixelSizeLabel);
pixelSizeField_ = new JTextField();
pixelSizeField_.setFont(new Font("", Font.PLAIN, 10));
pixelSizeField_.setBounds(280, 186, 50, 20);
pixelSizeField_.setText(NumberUtils.doubleToDisplayString(core_.getPixelSizeUm()));
getContentPane().add(pixelSizeField_);
final JButton okButton = new JButton();
okButton.setFont(new Font("", Font.PLAIN, 10));
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
savePosition();
addToPositionList();
}
});
okButton.setBounds(20, 216, 93, 23);
getContentPane().add(okButton);
final JButton cancelButton = new JButton();
cancelButton.setBounds(133, 216, 93, 23);
cancelButton.setFont(new Font("", Font.PLAIN, 10));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
savePosition();
dispose();
}
});
cancelButton.setText("Cancel");
getContentPane().add(cancelButton);
final JButton resetButton = new JButton();
resetButton.setBounds(234, 216, 93, 23);
resetButton.setFont(new Font("", Font.PLAIN, 10));
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
reset();
}
});
resetButton.setText("Reset");
getContentPane().add(resetButton);
}
/**
* Store current xyPosition.
*/
private void markPosition(int location) {
MultiStagePosition msp = new MultiStagePosition();
msp.setDefaultXYStage(core_.getXYStageDevice());
msp.setDefaultZStage(core_.getFocusDevice());
// read 1-axis stages
try {
StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice);
for (int i=0; i<stages.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages.get(i);
sp.numAxes = 1;
sp.x = core_.getPosition(stages.get(i));
msp.add(sp);
}
// read 2-axis stages
StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice);
for (int i=0; i<stages2D.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages2D.get(i);
sp.numAxes = 2;
sp.x = core_.getXPosition(stages2D.get(i));
sp.y = core_.getYPosition(stages2D.get(i));
msp.add(sp);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
endPosition_[location] = msp;
endPositionSet_[location] = true;
}
/**
* Update display of the current xy position.
*/
private String thisPosition() {
StringBuffer sb = new StringBuffer();
// read 1-axis stages
try {
StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice);
for (int i=0; i<stages.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages.get(i);
sp.numAxes = 1;
sp.x = core_.getPosition(stages.get(i));
sb.append(sp.getVerbose() + "\n");
}
// read 2-axis stages
StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice);
for (int i=0; i<stages2D.size(); i++) {
StagePosition sp = new StagePosition();
sp.stageName = stages2D.get(i);
sp.numAxes = 2;
sp.x = core_.getXPosition(stages2D.get(i));
sp.y = core_.getYPosition(stages2D.get(i));
sb.append(sp.getVerbose() + "\n");
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return sb.toString();
}
/*
* Create the tile list based on user input, pixelsize, and imagesize
*/
private void addToPositionList() {
// check if we are calibrated, TODO: allow input of image size
double pixSizeUm = 0.0;
try {
pixSizeUm = NumberUtils.displayStringToDouble(pixelSizeField_.getText());
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (pixSizeUm <= 0.0) {
JOptionPane.showMessageDialog(this, "Pixel Size should be a value > 0 (usually 0.1 -1 um). It should be experimentally determined. ");
return;
}
double overlap = 0.0;
try {
overlap = NumberUtils.displayStringToDouble(overlapField_.getText());
} catch (Exception e) {
//handleError(e.getMessage());
}
boolean correction, transposeXY, mirrorX, mirrorY;
String camera = core_.getCameraDevice();
if (camera == null) {
JOptionPane.showMessageDialog(null, "This function does not work without a camera");
return;
}
try{
String tmp = core_.getProperty(camera, "TransposeCorrection");
if (tmp.equals("0"))
correction = false;
else
correction = true;
tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_MirrorX());
if (tmp.equals("0"))
mirrorX = false;
else
mirrorX = true;
tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_MirrorY());
if (tmp.equals("0"))
mirrorY = false;
else
mirrorY = true;
tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_SwapXY());
if (tmp.equals("0"))
transposeXY = false;
else
transposeXY = true;
} catch(Exception exc) {
ReportingUtils.showError(exc);
return;
}
double overlapUmX;
double overlapUmY;
if(overlapUnit_ == OverlapUnitEnum.UM)
overlapUmX = overlapUmY = overlap;
else if(overlapUnit_ == OverlapUnitEnum.PERCENT) {
overlapUmX = pixSizeUm * (overlap / 100) * core_.getImageWidth();
overlapUmY = pixSizeUm * (overlap / 100) * core_.getImageHeight();
} else { // overlapUnit_ == OverlapUnit.PX
overlapUmX = overlap * pixSizeUm;
overlapUmY = overlap * pixSizeUm;
}
double tmpXUm = pixSizeUm * core_.getImageWidth() - overlapUmX;
double tmpYUm = pixSizeUm * core_.getImageHeight() - overlapUmY;
double tileSizeXUm = tmpXUm;
double tileSizeYUm = tmpYUm ;
// if camera does not correct image orientation, we'll correct for it here:
if (!correction) {
// Order: swapxy, then mirror axis
if (transposeXY) {tileSizeXUm = tmpYUm; tileSizeYUm = tmpXUm;}
}
// Make sure at least two corners were set
int nrSet = 0;
for (int i=0; i<4; i++) {
if (endPositionSet_[i])
nrSet++;
}
if (nrSet < 2) {
JOptionPane.showMessageDialog(this, "At least two corners should be set");
return;
}
// Calculate a bounding rectangle around the defaultXYStage positions
// TODO: develop method to deal with multiple axis
double minX = 0.0, minY = 0.0, maxX = 0.0, maxY = 0.0, meanZ = 0.0;
boolean firstSet = false;
StagePosition sp = new StagePosition();
for (int i=0; i<4; i++) {
if (endPositionSet_[i]) {
if (!firstSet) {
sp = endPosition_[i].get(endPosition_[i].getDefaultXYStage());
minX = maxX = sp.x;
minY = maxY = sp.y;
sp = endPosition_[i].get(endPosition_[i].getDefaultZStage());
meanZ = sp.x;
firstSet = true;
} else {
sp = endPosition_[i].get(endPosition_[i].getDefaultXYStage());
if (sp.x < minX)
minX = sp.x;
if (sp.x > maxX)
maxX = sp.x;
if (sp.y < minY)
minY = sp.y;
if (sp.y > maxY)
maxY = sp.y;
sp = endPosition_[i].get(endPosition_[i].getDefaultZStage());
meanZ += sp.x;
}
}
}
meanZ = meanZ/nrSet;
// if there are at least three set points, use them to define a
// focus plane: a, b, c such that z = f(x, y) = a*x + b*y + c.
double zPlaneA = 0.0, zPlaneB = 0.0, zPlaneC = 0.0;
boolean hasZPlane = false;
if (nrSet >= 3)
{
hasZPlane = true;
double x1 = 0.0, y1 = 0.0, z1 = 0.0;
double x2 = 0.0, y2 = 0.0, z2 = 0.0;
double x3 = 0.0, y3 = 0.0, z3 = 0.0;
boolean sp1Set = false;
boolean sp2Set = false;
boolean sp3Set = false;
// if there are four points set, we should either (a) choose the
// three that are least co-linear, or (b) use a linear regression to
// fit a focus plane that minimizes the errors at the four selected
// positions. this code does neither - it just uses the first three
// positions it finds.
for (int i=0; i<4; i++) {
if (endPositionSet_[i] && !sp1Set) {
x1 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x;
y1 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y;
z1 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x;
sp1Set = true;
} else if (endPositionSet_[i] && !sp2Set) {
x2 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x;
y2 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y;
z2 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x;
sp2Set = true;
} else if (endPositionSet_[i] && !sp3Set) {
x3 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x;
y3 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y;
z3 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x;
sp3Set = true;
}
}
// define vectors 1-->2, 1-->3
double x12 = x2 - x1;
double y12 = y2 - y1;
double z12 = z2 - z1;
double x13 = x3 - x1;
double y13 = y3 - y1;
double z13 = z3 - z1;
// first, make sure the points aren't co-linear: the angle between
// vectors 1-->2 and 1-->3 must be "sufficiently" large
double dot_prod = x12 * x13 + y12 * y13 + z12 * z13;
double magnitude12 = x12 * x12 + y12 * y12 + z12 * z12;
magnitude12 = Math.sqrt(magnitude12);
double magnitude13 = x13 * x13 + y13 * y13 + z13 * z13;
magnitude13 = Math.sqrt(magnitude13);
double cosTheta = dot_prod / (magnitude12 * magnitude13);
double theta = Math.acos(cosTheta); // in RADIANS
// "sufficiently" large here is 0.5 radians, or about 30 degrees
if(theta < 0.5
|| theta > (2 * Math.PI - 0.5)
|| (theta > (Math.PI - 0.5) && theta < (Math.PI + 0.5)))
hasZPlane = false;
// intermediates: ax + by + cz + d = 0
double a = y12 * z13 - y13 * z12;
double b = z12 * x13 - z13 * x12;
double c = x12 * y13 - x13 * y12;
double d = -1 * (a * x1 + b * y1 + c * z1);
// shuffle to z = f(x, y) = zPlaneA * x + zPlaneB * y + zPlaneC
zPlaneA = a / (-1 * c);
zPlaneB = b / (-1 * c);
zPlaneC = d / (-1 * c);
}
// make sure the user wants to continue if they've asked for Z positions
// but haven't defined enough (non-colinear!) points for a Z plane
if(positionListDlg_.useDrive(core_.getFocusDevice()) && !hasZPlane)
{
int choice = JOptionPane.showConfirmDialog(this,
"You are creating a position list that includes\n" +
"a Z (focus) position, but the grid locations\n" +
"you've chosen are co-linear! If you continue,\n" +
"the focus for the new positions will be\n" +
"the average focus for the grid locations you set.\n\n" +
"If you want to calculate the focus for the new\n" +
"positions, you must select at least three grid corners\n" +
"that aren't co-linear!\n\nContinue?",
"Continue with co-linear focus?",
JOptionPane.YES_NO_OPTION);
if(choice == JOptionPane.NO_OPTION || choice == JOptionPane.CLOSED_OPTION)
return;
}
// calculate number of images in X and Y
int nrImagesX = (int) Math.floor ( (maxX - minX) / tileSizeXUm ) + 2;
int nrImagesY = (int) Math.floor ( (maxY - minY) / tileSizeYUm ) + 2;
// Increment prefix for these positions
prefix_ += 1;
// todo handle mirrorX mirrorY
for (int y=0; y< nrImagesY; y++) {
for (int x=0; x<nrImagesX; x++) {
// on even rows go left to right, on odd rows right to left
int tmpX = x;
if ( (y & 1) == 1)
tmpX = nrImagesX - x - 1;
MultiStagePosition msp = new MultiStagePosition();
// Add XY position
msp.setDefaultXYStage(core_.getXYStageDevice());
msp.setDefaultZStage(core_.getFocusDevice());
StagePosition spXY = new StagePosition();
spXY.stageName = core_.getXYStageDevice();
spXY.numAxes = 2;
spXY.x = minX + (tmpX * tileSizeXUm);
spXY.y = minY + (y * tileSizeYUm);
msp.add(spXY);
// Add Z position
StagePosition spZ = new StagePosition();
spZ.stageName = core_.getFocusDevice();
spZ.numAxes = 1;
if(hasZPlane) {
double z = zPlaneA * spXY.x + zPlaneB * spXY.y + zPlaneC;
spZ.x = z;
} else
spZ.x = meanZ;
if (positionListDlg_.useDrive(spZ.stageName))
msp.add(spZ);
// Add 'metadata'
msp.setGridCoordinates(y, tmpX);
if(overlapUnit_ == OverlapUnitEnum.UM || overlapUnit_ == OverlapUnitEnum.PX)
{
msp.setProperty("OverlapUm", NumberUtils.doubleToCoreString(overlapUmX));
int overlapPix = (int) Math.floor(overlapUmX/pixSizeUm);
msp.setProperty("OverlapPixels", NumberUtils.intToCoreString(overlapPix));
} else { // overlapUnit_ == OverlapUnit.PERCENT
// overlapUmX != overlapUmY; store both
msp.setProperty("OverlapUmX", NumberUtils.doubleToCoreString(overlapUmX));
msp.setProperty("OverlapUmY", NumberUtils.doubleToCoreString(overlapUmY));
int overlapPixX = (int) Math.floor(overlapUmX/pixSizeUm);
int overlapPixY = (int) Math.floor(overlapUmY/pixSizeUm);
msp.setProperty("OverlapPixelsX", NumberUtils.intToCoreString(overlapPixX));
msp.setProperty("OverlapPixelsY", NumberUtils.intToCoreString(overlapPixX));
}
// Add to position list
positionListDlg_.addPosition(msp, generatePosLabel(prefix_ + "-Pos", tmpX, y));
}
}
dispose();
}
/*
* Delete all positions from the dialog and update labels. Re-read pixel calibration - when available - from the core
*/
private void reset() {
for (int i=0; i<4; i++)
endPositionSet_[i] = false;
labelTop_.setText("");
labelRight_.setText("");
labelBottom_.setText("");
labelLeft_.setText("");
double pxsz = core_.getPixelSizeUm();
pixelSizeField_.setText(NumberUtils.doubleToDisplayString(pxsz));
}
/*
* Move stage to position
*/
private void goToPosition(MultiStagePosition position) {
try {
MultiStagePosition.goToPosition(position, core_);
} catch (Exception e) {
ReportingUtils.logError(e);
}
}
private void handleError(String txt) {
JOptionPane.showMessageDialog(this, txt);
}
public static String generatePosLabel(String prefix, int x, int y) {
String name = prefix + "_" + FMT_POS.format(x) + "_" + FMT_POS.format(y);
return name;
}
}
| Patch 01_tile_centered_grid from Brian Teague
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@11085 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| mmstudio/src/org/micromanager/TileCreatorDlg.java | Patch 01_tile_centered_grid from Brian Teague |
|
Java | mit | c79c8157d6d434c96a20c9627c88d37af550ec54 | 0 | enthusiast94/kafka-visualizer,enthusiast94/kafka-visualizer,enthusiast94/kafka-visualizer | kafkavisualizer/kafka-visualizer-rest/src/main/java/com/enthusiast94/kafkavisualizer/domain/zookeeper/ZookeeperNode.java | package com.enthusiast94.kafkavisualizer.domain.zookeeper;
public class ZookeeperNode {
public String hostname;
public int port;
}
| Deleted redundant domain file.
| kafkavisualizer/kafka-visualizer-rest/src/main/java/com/enthusiast94/kafkavisualizer/domain/zookeeper/ZookeeperNode.java | Deleted redundant domain file. |
||
Java | epl-1.0 | 2bc967d30d5657b80c292126785c499dee1b04e8 | 0 | parzonka/prm4j | /*
* Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
* 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:
* Mateusz Parzonka - initial API and implementation
*/
package prm4j.indexing;
import prm4j.api.BaseEvent;
import prm4j.api.Event;
import prm4j.api.MatchHandler;
/**
* A base monitor holding a {@link BaseMonitorState} which is updated when processing {@link BaseEvent}s.
*/
public class StatefulMonitor extends BaseMonitor {
protected BaseMonitorState state;
public StatefulMonitor(BaseMonitorState state) {
this.state = state;
}
@Override
public boolean processEvent(Event event) {
if (state == null) {
terminate();
return false;
}
final BaseEvent baseEvent = event.getEvaluatedBaseEvent(this);
if (baseEvent == null) {
return true;
}
state = state.getSuccessor(baseEvent);
if (state == null) {
terminate();
return false;
}
MatchHandler matchHandler = state.getMatchHandler();
if (matchHandler != null) {
matchHandler.handleAndCountMatch(getBindings(), event.getAuxiliaryData());
// when a state is a accepting state, it is still possible we will reach another accepting state (or loop on
// an accepting state), so we don't return false here
if (state.isFinal()) {
terminate();
return false;
}
}
return true;
}
@Override
public BaseMonitor copy() {
return new StatefulMonitor(state);
}
/**
* {@inheritDoc}
* <p>
* The {@link StatefulMonitor} checks for two conditions and return <code>true</code> if one of the following is
* reached:
* <ol>
* <li>The monitor is not terminated.</li>
* <li>Its state is no final state (a state where only dead states may be reached).</li>
* <li>A subset of its bindings is alive that is necessary to reach an accepting state.</li>
* </ol>
*/
@Override
public boolean isAcceptingStateReachable() {
return !isTerminated() && state != null && !state.isFinal() && getMetaNode().isAcceptingStateReachable(state, getLowLevelBindings());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((state == null) ? 0 : state.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StatefulMonitor other = (StatefulMonitor) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
return true;
}
} | src/main/java/prm4j/indexing/StatefulMonitor.java | /*
* Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
* 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:
* Mateusz Parzonka - initial API and implementation
*/
package prm4j.indexing;
import prm4j.api.BaseEvent;
import prm4j.api.Event;
import prm4j.api.MatchHandler;
/**
* A base monitor holding a {@link BaseMonitorState} which is updated when processing {@link BaseEvent}s.
*/
public class StatefulMonitor extends BaseMonitor {
protected BaseMonitorState state;
public StatefulMonitor(BaseMonitorState state) {
this.state = state;
}
@Override
public boolean processEvent(Event event) {
if (state == null) {
terminate();
return false;
}
final BaseEvent baseEvent = event.getEvaluatedBaseEvent(this);
if (baseEvent == null) {
return true;
}
state = state.getSuccessor(baseEvent);
if (state == null) {
terminate();
return false;
}
MatchHandler matchHandler = state.getMatchHandler();
if (matchHandler != null) {
matchHandler.handleMatch(getBindings(), event.getAuxiliaryData());
// when a state is a accepting state, it is still possible we will reach another accepting state (or loop on
// an accepting state), so we don't return false here
if (state.isFinal()) {
terminate();
return false;
}
}
return true;
}
@Override
public BaseMonitor copy() {
return new StatefulMonitor(state);
}
/**
* {@inheritDoc}
* <p>
* The {@link StatefulMonitor} checks for two conditions and return <code>true</code> if one of the following is
* reached:
* <ol>
* <li>The monitor is not terminated.</li>
* <li>Its state is no final state (a state where only dead states may be reached).</li>
* <li>A subset of its bindings is alive that is necessary to reach an accepting state.</li>
* </ol>
*/
@Override
public boolean isAcceptingStateReachable() {
return !isTerminated() && state != null && !state.isFinal() && getMetaNode().isAcceptingStateReachable(state, getLowLevelBindings());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((state == null) ? 0 : state.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StatefulMonitor other = (StatefulMonitor) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
return true;
}
} | Fix StatefulMonitor 'handleAndCountMatch'
| src/main/java/prm4j/indexing/StatefulMonitor.java | Fix StatefulMonitor 'handleAndCountMatch' |
|
Java | mpl-2.0 | 31fdb4b9d6cfe73826bb622ffd47f0bc6bbec3b4 | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*************************************************************************
*
* $RCSfile: AccessBridge.java,v $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package org.openoffice.accessibility;
import com.sun.star.awt.XTopWindow;
import com.sun.star.awt.XTopWindowListener;
import com.sun.star.awt.XWindow;
import com.sun.star.lang.XInitialization;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.registry.*;
import com.sun.star.uno.*;
import com.sun.star.comp.loader.FactoryHelper;
import org.openoffice.accessibility.internal.*;
import org.openoffice.java.accessibility.*;
import com.sun.star.accessibility.XAccessible;
import drafts.com.sun.star.accessibility.bridge.XAccessibleTopWindowMap;
import com.sun.star.awt.XExtendedToolkit;
import javax.accessibility.Accessible;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class AccessBridge {
//
static public class _AccessBridge implements XAccessibleTopWindowMap, XInitialization {
static final String _serviceName = "com.sun.star.accessibility.AccessBridge";
XMultiServiceFactory serviceManager;
java.util.Hashtable frameMap;
public _AccessBridge(XMultiServiceFactory xMultiServiceFactory) {
serviceManager = xMultiServiceFactory;
frameMap = new java.util.Hashtable();
}
/*
* XInitialization
*/
public void initialize(java.lang.Object[] arguments) {
try {
// Currently there is no way to determine if key event forwarding is needed or not,
// so we have to do it always ..
XExtendedToolkit unoToolkit = (XExtendedToolkit)
AnyConverter.toObject(new Type(XExtendedToolkit.class), arguments[0]);
if(unoToolkit != null) {
unoToolkit.addKeyHandler(new KeyHandler());
} else if( Build.DEBUG) {
System.err.println("argument 0 is not of type XExtendedToolkit.");
}
} catch(com.sun.star.lang.IllegalArgumentException e) {
// FIXME: output
}
}
/*
* XAccessibleNativeFrameMap
*/
public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){
try {
// The office sometimes registers frames more than once, so check here if already done
Integer handle = new Integer(AnyConverter.toInt(any));
if (! frameMap.containsKey(handle)) {
if( Build.DEBUG ) {
System.out.println("register native frame: " + handle);
}
java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible);
if (w != null) {
frameMap.put(handle, w);
}
}
} catch (com.sun.star.lang.IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
} catch (java.lang.Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}
}
public void revokeAccessibleNativeFrame(Object any) {
try {
Integer handle = new Integer(AnyConverter.toInt(any));
// Remember the accessible object associated to this frame
java.awt.Window w = (java.awt.Window) frameMap.remove(handle);
if (w != null) {
if (Build.DEBUG) {
System.out.println("revoke native frame: " + handle);
}
w.dispose();
}
} catch (com.sun.star.lang.IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
}
}
}
static public class _WinAccessBridge extends _AccessBridge {
Method registerVirtualFrame;
Method revokeVirtualFrame;
public _WinAccessBridge(XMultiServiceFactory xMultiServiceFactory) {
super(xMultiServiceFactory);
// java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
// tk.addAWTEventListener(new WindowsAccessBridgeAdapter(), java.awt.AWTEvent.WINDOW_EVENT_MASK);
// On Windows all native frames must be registered to the access bridge. Therefor
// the bridge exports two methods that we try to find here.
try {
Class bridge = Class.forName("com.sun.java.accessibility.AccessBridge");
Class[] parameterTypes = { javax.accessibility.Accessible.class, Integer.class };
if(bridge != null) {
registerVirtualFrame = bridge.getMethod("registerVirtualFrame", parameterTypes);
revokeVirtualFrame = bridge.getMethod("revokeVirtualFrame", parameterTypes);
}
}
catch(NoSuchMethodException e) {
System.err.println("ERROR: incompatible AccessBridge found: " + e.getMessage());
// Forward this exception to UNO to indicate that the service will not work correctly.
throw new com.sun.star.uno.RuntimeException("incompatible AccessBridge class: " + e.getMessage());
}
catch(java.lang.SecurityException e) {
System.err.println("ERROR: no access to AccessBridge: " + e.getMessage());
// Forward this exception to UNO to indicate that the service will not work correctly.
throw new com.sun.star.uno.RuntimeException("Security exception caught: " + e.getMessage());
}
catch(ClassNotFoundException e) {
// Forward this exception to UNO to indicate that the service will not work correctly.
throw new com.sun.star.uno.RuntimeException("ClassNotFound exception caught: " + e.getMessage());
}
}
// Registers the native frame at the Windows access bridge
protected void registerAccessibleNativeFrameImpl(Integer handle, Accessible a) {
// register this frame to the access bridge
Object[] args = { a, handle };
try {
registerVirtualFrame.invoke(null, args);
}
catch(IllegalAccessException e) {
System.err.println("IllegalAccessException caught: " + e.getMessage());
}
catch(IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
}
catch(InvocationTargetException e) {
System.err.println("InvokationTargetException caught: " + e.getMessage());
}
}
// Revokes the native frame from the Windows access bridge
protected void revokeAccessibleNativeFrameImpl(Integer handle, Accessible a) {
Object[] args = { a, handle };
try {
revokeVirtualFrame.invoke(null, args);
}
catch(IllegalAccessException e) {
System.err.println("IllegalAccessException caught: " + e.getMessage());
}
catch(IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
}
catch(InvocationTargetException e) {
System.err.println("InvokationTargetException caught: " + e.getMessage());
}
}
/*
* XAccessibleNativeFrameMap
*/
public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){
try {
// The office sometimes registers frames more than once, so check here if already done
Integer handle = new Integer(AnyConverter.toInt(any));
if (! frameMap.containsKey(handle)) {
java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible);
if (Build.DEBUG) {
System.out.println("register native frame: " + handle);
}
if (w != null) {
// Add the window proxy object to the frame list
frameMap.put(handle, w);
// Also register the frame with the access bridge object
registerAccessibleNativeFrameImpl(handle,w);
}
}
}
catch(com.sun.star.lang.IllegalArgumentException exception) {
System.err.println("IllegalArgumentException caught: " + exception.getMessage());
}
}
public void revokeAccessibleNativeFrame(Object any) {
try {
Integer handle = new Integer(AnyConverter.toInt(any));
// Remember the accessible object associated to this frame
java.awt.Window w = (java.awt.Window) frameMap.remove(handle);
if (w != null) {
// Revoke the frame with the access bridge object
revokeAccessibleNativeFrameImpl(handle, w);
if (Build.DEBUG) {
System.out.println("revoke native frame: " + handle);
}
// It seems that we have to do this synchronously, because otherwise on exit
// the main thread of the office terminates before AWT has shut down and the
// process will hang ..
w.dispose();
/*
class DisposeAction implements Runnable {
java.awt.Window window;
DisposeAction(java.awt.Window w) {
window = w;
}
public void run() {
window.dispose();
}
}
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().invokeLater(new DisposeAction(w));
*/
}
}
catch(com.sun.star.lang.IllegalArgumentException exception) {
System.err.println("IllegalArgumentException caught: " + exception.getMessage());
}
}
}
public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey) {
XSingleServiceFactory xSingleServiceFactory = null;
if (implName.equals(AccessBridge.class.getName()) ) {
// Initialize toolkit to register at Java <-> Windows access bridge
java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
Class serviceClass;
String os = (String) System.getProperty("os.name");
if(os.startsWith("Windows")) {
serviceClass = _WinAccessBridge.class;
} else {
serviceClass = _AccessBridge.class;
}
xSingleServiceFactory = FactoryHelper.getServiceFactory(
serviceClass,
_AccessBridge._serviceName,
multiFactory,
regKey
);
}
return xSingleServiceFactory;
}
public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) {
return FactoryHelper.writeRegistryServiceInfo(AccessBridge.class.getName(), _AccessBridge._serviceName, regKey);
}
}
| accessibility/bridge/org/openoffice/accessibility/AccessBridge.java | /*************************************************************************
*
* $RCSfile: AccessBridge.java,v $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package org.openoffice.accessibility;
import com.sun.star.awt.XTopWindow;
import com.sun.star.awt.XTopWindowListener;
import com.sun.star.awt.XWindow;
import com.sun.star.lang.XInitialization;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.registry.*;
import com.sun.star.uno.*;
import com.sun.star.comp.loader.FactoryHelper;
import org.openoffice.accessibility.internal.*;
import org.openoffice.java.accessibility.*;
import com.sun.star.accessibility.XAccessible;
import drafts.com.sun.star.accessibility.bridge.XAccessibleTopWindowMap;
import com.sun.star.awt.XExtendedToolkit;
import javax.accessibility.Accessible;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class AccessBridge {
//
static public class _AccessBridge implements XAccessibleTopWindowMap, XInitialization {
static final String _serviceName = "com.sun.star.accessibilityAccessBridge";
XMultiServiceFactory serviceManager;
java.util.Hashtable frameMap;
public _AccessBridge(XMultiServiceFactory xMultiServiceFactory) {
serviceManager = xMultiServiceFactory;
frameMap = new java.util.Hashtable();
}
/*
* XInitialization
*/
public void initialize(java.lang.Object[] arguments) {
try {
// Currently there is no way to determine if key event forwarding is needed or not,
// so we have to do it always ..
XExtendedToolkit unoToolkit = (XExtendedToolkit)
AnyConverter.toObject(new Type(XExtendedToolkit.class), arguments[0]);
if(unoToolkit != null) {
unoToolkit.addKeyHandler(new KeyHandler());
} else if( Build.DEBUG) {
System.err.println("argument 0 is not of type XExtendedToolkit.");
}
} catch(com.sun.star.lang.IllegalArgumentException e) {
// FIXME: output
}
}
/*
* XAccessibleNativeFrameMap
*/
public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){
try {
// The office sometimes registers frames more than once, so check here if already done
Integer handle = new Integer(AnyConverter.toInt(any));
if (! frameMap.containsKey(handle)) {
if( Build.DEBUG ) {
System.out.println("register native frame: " + handle);
}
java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible);
if (w != null) {
frameMap.put(handle, w);
}
}
} catch (com.sun.star.lang.IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
} catch (java.lang.Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}
}
public void revokeAccessibleNativeFrame(Object any) {
try {
Integer handle = new Integer(AnyConverter.toInt(any));
// Remember the accessible object associated to this frame
java.awt.Window w = (java.awt.Window) frameMap.remove(handle);
if (w != null) {
if (Build.DEBUG) {
System.out.println("revoke native frame: " + handle);
}
w.dispose();
}
} catch (com.sun.star.lang.IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
}
}
}
static public class _WinAccessBridge extends _AccessBridge {
Method registerVirtualFrame;
Method revokeVirtualFrame;
public _WinAccessBridge(XMultiServiceFactory xMultiServiceFactory) {
super(xMultiServiceFactory);
// java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
// tk.addAWTEventListener(new WindowsAccessBridgeAdapter(), java.awt.AWTEvent.WINDOW_EVENT_MASK);
// On Windows all native frames must be registered to the access bridge. Therefor
// the bridge exports two methods that we try to find here.
try {
Class bridge = Class.forName("com.sun.java.accessibility.AccessBridge");
Class[] parameterTypes = { javax.accessibility.Accessible.class, Integer.class };
if(bridge != null) {
registerVirtualFrame = bridge.getMethod("registerVirtualFrame", parameterTypes);
revokeVirtualFrame = bridge.getMethod("revokeVirtualFrame", parameterTypes);
}
}
catch(NoSuchMethodException e) {
System.err.println("ERROR: incompatible AccessBridge found: " + e.getMessage());
// Forward this exception to UNO to indicate that the service will not work correctly.
throw new com.sun.star.uno.RuntimeException("incompatible AccessBridge class: " + e.getMessage());
}
catch(java.lang.SecurityException e) {
System.err.println("ERROR: no access to AccessBridge: " + e.getMessage());
// Forward this exception to UNO to indicate that the service will not work correctly.
throw new com.sun.star.uno.RuntimeException("Security exception caught: " + e.getMessage());
}
catch(ClassNotFoundException e) {
// Forward this exception to UNO to indicate that the service will not work correctly.
throw new com.sun.star.uno.RuntimeException("ClassNotFound exception caught: " + e.getMessage());
}
}
// Registers the native frame at the Windows access bridge
protected void registerAccessibleNativeFrameImpl(Integer handle, Accessible a) {
// register this frame to the access bridge
Object[] args = { a, handle };
try {
registerVirtualFrame.invoke(null, args);
}
catch(IllegalAccessException e) {
System.err.println("IllegalAccessException caught: " + e.getMessage());
}
catch(IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
}
catch(InvocationTargetException e) {
System.err.println("InvokationTargetException caught: " + e.getMessage());
}
}
// Revokes the native frame from the Windows access bridge
protected void revokeAccessibleNativeFrameImpl(Integer handle, Accessible a) {
Object[] args = { a, handle };
try {
revokeVirtualFrame.invoke(null, args);
}
catch(IllegalAccessException e) {
System.err.println("IllegalAccessException caught: " + e.getMessage());
}
catch(IllegalArgumentException e) {
System.err.println("IllegalArgumentException caught: " + e.getMessage());
}
catch(InvocationTargetException e) {
System.err.println("InvokationTargetException caught: " + e.getMessage());
}
}
/*
* XAccessibleNativeFrameMap
*/
public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){
try {
// The office sometimes registers frames more than once, so check here if already done
Integer handle = new Integer(AnyConverter.toInt(any));
if (! frameMap.containsKey(handle)) {
java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible);
if (Build.DEBUG) {
System.out.println("register native frame: " + handle);
}
if (w != null) {
// Add the window proxy object to the frame list
frameMap.put(handle, w);
// Also register the frame with the access bridge object
registerAccessibleNativeFrameImpl(handle,w);
}
}
}
catch(com.sun.star.lang.IllegalArgumentException exception) {
System.err.println("IllegalArgumentException caught: " + exception.getMessage());
}
}
public void revokeAccessibleNativeFrame(Object any) {
try {
Integer handle = new Integer(AnyConverter.toInt(any));
// Remember the accessible object associated to this frame
java.awt.Window w = (java.awt.Window) frameMap.remove(handle);
if (w != null) {
// Revoke the frame with the access bridge object
revokeAccessibleNativeFrameImpl(handle, w);
if (Build.DEBUG) {
System.out.println("revoke native frame: " + handle);
}
// It seems that we have to do this synchronously, because otherwise on exit
// the main thread of the office terminates before AWT has shut down and the
// process will hang ..
w.dispose();
/*
class DisposeAction implements Runnable {
java.awt.Window window;
DisposeAction(java.awt.Window w) {
window = w;
}
public void run() {
window.dispose();
}
}
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().invokeLater(new DisposeAction(w));
*/
}
}
catch(com.sun.star.lang.IllegalArgumentException exception) {
System.err.println("IllegalArgumentException caught: " + exception.getMessage());
}
}
}
public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey) {
XSingleServiceFactory xSingleServiceFactory = null;
if (implName.equals(AccessBridge.class.getName()) ) {
// Initialize toolkit to register at Java <-> Windows access bridge
java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
Class serviceClass;
String os = (String) System.getProperty("os.name");
if(os.startsWith("Windows")) {
serviceClass = _WinAccessBridge.class;
} else {
serviceClass = _AccessBridge.class;
}
xSingleServiceFactory = FactoryHelper.getServiceFactory(
serviceClass,
_AccessBridge._serviceName,
multiFactory,
regKey
);
}
return xSingleServiceFactory;
}
public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) {
return FactoryHelper.writeRegistryServiceInfo(AccessBridge.class.getName(), _AccessBridge._serviceName, regKey);
}
}
| INTEGRATION: CWS beta2regression02 (1.14.2); FILE MERGED
2003/04/29 16:08:34 obr 1.14.2.1: #109204# transisiont from drafts to stable
| accessibility/bridge/org/openoffice/accessibility/AccessBridge.java | INTEGRATION: CWS beta2regression02 (1.14.2); FILE MERGED 2003/04/29 16:08:34 obr 1.14.2.1: #109204# transisiont from drafts to stable |
|
Java | agpl-3.0 | 6a8c32c8aff45c6198c6b8910ed765b8d57360dd | 0 | devent/sscontrol,devent/sscontrol | /*
* Copyright 2012 Erwin Müller <[email protected]>
*
* This file is part of sscontrol-hostname.
*
* sscontrol-hostname is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* sscontrol-hostname 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 Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with sscontrol-hostname. If not, see <http://www.gnu.org/licenses/>.
*/
package com.anrisoftware.sscontrol.hostname.service;
import static com.anrisoftware.sscontrol.hostname.service.HostnameFactory.NAME;
import groovy.lang.GroovyObjectSupport;
import groovy.lang.Script;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.anrisoftware.resources.templates.api.TemplatesFactory;
import com.anrisoftware.sscontrol.core.api.ProfileService;
import com.anrisoftware.sscontrol.core.api.Service;
import com.anrisoftware.sscontrol.core.api.ServiceException;
import com.anrisoftware.sscontrol.workers.command.script.ScriptCommandWorkerFactory;
import com.anrisoftware.sscontrol.workers.text.tokentemplate.TokensTemplateWorkerFactory;
import com.google.inject.Provider;
class HostnameServiceImpl extends GroovyObjectSupport implements Service {
/**
* @version 0.1
*/
private static final long serialVersionUID = 8026832603525631371L;
private final HostnameServiceImplLogger log;
private final Map<String, Provider<Script>> scripts;
private ProfileService profile;
private String hostname;
private final TemplatesFactory templatesFactory;
@Inject
private TokensTemplateWorkerFactory tokensTemplateWorkerFactory;
@Inject
private ScriptCommandWorkerFactory scriptCommandWorkerFactory;
@Inject
HostnameServiceImpl(HostnameServiceImplLogger logger,
Map<String, Provider<Script>> scripts, TemplatesFactory templates,
@Named("hostname-service-properties") Properties properties) {
this.log = logger;
this.scripts = scripts;
this.templatesFactory = templates;
}
/**
* Entry point for the DNS service script.
*
* @return this {@link Service}.
*/
public Service hostname(Object closure) {
return this;
}
/**
* Sets the host name.
*
* @param name
* the host name.
*/
public void set_hostname(String name) {
log.checkHostname(this, name);
hostname = name;
log.hostnameSet(this, name);
}
/**
* Returns the host name.
*
* @return the host name.
*/
public String getHostname() {
return hostname;
}
/**
* Returns the hostname service name.
*/
@Override
public String getName() {
return NAME;
}
/**
* Sets the profile for the DNS service.
*
* @param newProfile
* the {@link ProfileService}.
*/
public void setProfile(ProfileService newProfile) {
profile = newProfile;
log.profileSet(this, newProfile);
}
/**
* Returns the profile for the DNS service.
*
* @return the {@link ProfileService}.
*/
public ProfileService getProfile() {
return profile;
}
@Override
public Service call() throws ServiceException {
String name = profile.getProfileName();
Script script = scripts.get(name).get();
Map<Class<?>, Object> workers = getWorkers();
script.setProperty("workers", workers);
script.setProperty("templatesFactory", templatesFactory);
script.setProperty("system", profile.getEntry("system"));
script.setProperty("profile", profile.getEntry(NAME));
script.setProperty("service", this);
script.setProperty("name", name);
script.run();
return this;
}
private Map<Class<?>, Object> getWorkers() {
Map<Class<?>, Object> workers = new HashMap<Class<?>, Object>();
workers.put(TokensTemplateWorkerFactory.class,
tokensTemplateWorkerFactory);
workers.put(ScriptCommandWorkerFactory.class,
scriptCommandWorkerFactory);
return workers;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("profile", profile.getProfileName())
.append("hostname", hostname).toString();
}
}
| sscontrol-hostname/src/main/java/com/anrisoftware/sscontrol/hostname/service/HostnameServiceImpl.java | /*
* Copyright 2012 Erwin Müller <[email protected]>
*
* This file is part of sscontrol-hostname.
*
* sscontrol-hostname is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* sscontrol-hostname 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 Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with sscontrol-hostname. If not, see <http://www.gnu.org/licenses/>.
*/
package com.anrisoftware.sscontrol.hostname.service;
import static com.anrisoftware.sscontrol.hostname.service.HostnameFactory.NAME;
import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;
import groovy.lang.Script;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.anrisoftware.resources.templates.api.TemplatesFactory;
import com.anrisoftware.sscontrol.core.api.ProfileService;
import com.anrisoftware.sscontrol.core.api.Service;
import com.anrisoftware.sscontrol.core.api.ServiceException;
import com.anrisoftware.sscontrol.workers.command.script.ScriptCommandWorkerFactory;
import com.anrisoftware.sscontrol.workers.text.tokentemplate.TokensTemplateWorkerFactory;
import com.google.inject.Provider;
class HostnameServiceImpl extends GroovyObjectSupport implements Service {
/**
* @version 0.1
*/
private static final long serialVersionUID = 8026832603525631371L;
private final HostnameServiceImplLogger log;
private final Map<String, Provider<Script>> scripts;
private ProfileService profile;
private String hostname;
private final TemplatesFactory templatesFactory;
@Inject
private TokensTemplateWorkerFactory tokensTemplateWorkerFactory;
@Inject
private ScriptCommandWorkerFactory scriptCommandWorkerFactory;
@Inject
HostnameServiceImpl(HostnameServiceImplLogger logger,
Map<String, Provider<Script>> scripts, TemplatesFactory templates,
@Named("hostname-service-properties") Properties properties) {
this.log = logger;
this.scripts = scripts;
this.templatesFactory = templates;
}
public Object hostname(Closure<?> closure) {
return this;
}
public Object set_hostname(String name) {
log.checkHostname(this, name);
hostname = name;
log.hostnameSet(this, name);
return this;
}
public String getHostname() {
return hostname;
}
@Override
public String getName() {
return NAME;
}
public void setProfile(ProfileService newProfile) {
profile = newProfile;
log.profileSet(this, newProfile);
}
public ProfileService getProfile() {
return profile;
}
@Override
public Service call() throws ServiceException {
String name = profile.getProfileName();
Script script = scripts.get(name).get();
Map<Class<?>, Object> workers = getWorkers();
script.setProperty("workers", workers);
script.setProperty("templatesFactory", templatesFactory);
script.setProperty("system", profile.getEntry("system"));
script.setProperty("profile", profile.getEntry(NAME));
script.setProperty("service", this);
script.setProperty("name", name);
script.run();
return this;
}
private Map<Class<?>, Object> getWorkers() {
Map<Class<?>, Object> workers = new HashMap<Class<?>, Object>();
workers.put(TokensTemplateWorkerFactory.class,
tokensTemplateWorkerFactory);
workers.put(ScriptCommandWorkerFactory.class,
scriptCommandWorkerFactory);
return workers;
}
@Override
public String toString() {
return new ToStringBuilder(this).toString();
}
}
| Add javadoc, returns the profile name in debug to-string | sscontrol-hostname/src/main/java/com/anrisoftware/sscontrol/hostname/service/HostnameServiceImpl.java | Add javadoc, returns the profile name in debug to-string |
|
Java | agpl-3.0 | 7b6ff9e701079cb31165563909a6a63461a6a4ce | 0 | aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.smoketest;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.google.common.collect.Iterables;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NodeListPageIT extends OpenNMSSeleniumTestCase {
@Before
public void setUp() throws Exception {
deleteTestRequisition();
createLocation("Pittsboro");
createLocation("Fulda");
createNode("loc1node1", "Pittsboro");
createNode("loc1node2", "Pittsboro");
createNode("loc2node1", "Fulda");
createNode("loc2node2", "Fulda");
nodePage();
}
@After
public void tearDown() throws Exception {
deleteTestRequisition();
deleteLocation("Pittsboro");
deleteLocation("Fulda");
}
private void deleteLocation(final String location) throws Exception {
sendDelete("/rest/monitoringLocations/" + location);
}
private void createLocation(final String location) throws Exception {
sendPost("/rest/monitoringLocations", "<location location-name=\"" + location + "\" monitoring-area=\"" + location + "\"/>", 201);
}
private void createNode(final String foreignId, final String location) throws Exception {
final String node = "<node type=\"A\" label=\"TestMachine " + foreignId + "\" foreignSource=\""+ REQUISITION_NAME +"\" foreignId=\"" + foreignId + "\">" +
"<labelSource>H</labelSource>" +
"<sysContact>The Owner</sysContact>" +
"<sysDescription>" +
"Darwin TestMachine 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun 9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386" +
"</sysDescription>" +
"<sysLocation>DevJam</sysLocation>" +
"<sysName>TestMachine" + foreignId + "</sysName>" +
"<sysObjectId>.1.3.6.1.4.1.8072.3.2.255</sysObjectId>" +
"<location>" + location + "</location>" +
"</node>";
sendPost("/rest/nodes", node, 201);
}
@Test
public void testAllTextIsPresent() throws Exception {
findElementByXpath("//h3//span[text()='Nodes']");
findElementByXpath("//ol[@class=\"breadcrumb\"]//li[text()='Node List']");
}
@Test
public void testAllLinks() throws InterruptedException {
findElementByLink("Show interfaces").click();
findElementByXpath("//h3[text()='Nodes and their interfaces']");
findElementByLink("Hide interfaces");
}
@Test
public void testAvailableLocations() throws Exception {
// We use hasItems() instead of containsInAnyOrder() at some points because other tests do
// not properly clean up their created nodes ans locations.
// Check if default selection is 'all locations' and all locations are listed
findElementByXpath("//select[@id='monitoringLocation']//option[text()='All locations' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//select[@id='monitoringLocation']//option")), WebElement::getText),
hasItems("All locations",
"Pittsboro",
"Fulda"));
// Check the default lists all nodes
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
hasItems("TestMachine loc1node1",
"TestMachine loc1node2",
"TestMachine loc2node1",
"TestMachine loc2node2"));
// Check switching to first location
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Pittsboro']").click();
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Pittsboro' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
containsInAnyOrder("TestMachine loc1node1",
"TestMachine loc1node2"));
// Check switching to second location
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Fulda']").click();
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Fulda' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
containsInAnyOrder("TestMachine loc2node1",
"TestMachine loc2node2"));
// Check switching to unfiltered
findElementByXpath("//select[@id='monitoringLocation']//option[text()='All locations']").click();
findElementByXpath("//select[@id='monitoringLocation']//option[text()='All locations' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
hasItems("TestMachine loc1node1",
"TestMachine loc1node2",
"TestMachine loc2node1",
"TestMachine loc2node2"));
}
}
| smoke-test/src/test/java/org/opennms/smoketest/NodeListPageIT.java | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.smoketest;
import java.lang.Exception;
import com.google.common.collect.Iterables;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NodeListPageIT extends OpenNMSSeleniumTestCase {
@Before
public void setUp() throws Exception {
deleteTestRequisition();
createLocation("Pittsboro");
createLocation("Fulda");
createNode("loc1node1", "Pittsboro");
createNode("loc1node2", "Pittsboro");
createNode("loc2node1", "Fulda");
createNode("loc2node2", "Fulda");
nodePage();
}
@After
public void tearDown() throws Exception {
deleteTestRequisition();
deleteLocation("Pittsboro");
deleteLocation("Fulda");
}
private void deleteLocation(final String location) throws Exception {
sendDelete("/rest/monitoringLocations/" + location);
}
private void createLocation(final String location) throws Exception {
sendPost("/rest/monitoringLocations", "<location location-name=\"" + location + "\" monitoring-area=\"" + location + "\"/>", 201);
}
private void createNode(final String foreignId, final String location) throws Exception {
final String node = "<node type=\"A\" label=\"TestMachine " + foreignId + "\" foreignSource=\""+ REQUISITION_NAME +"\" foreignId=\"" + foreignId + "\">" +
"<labelSource>H</labelSource>" +
"<sysContact>The Owner</sysContact>" +
"<sysDescription>" +
"Darwin TestMachine 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun 9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386" +
"</sysDescription>" +
"<sysLocation>DevJam</sysLocation>" +
"<sysName>TestMachine" + foreignId + "</sysName>" +
"<sysObjectId>.1.3.6.1.4.1.8072.3.2.255</sysObjectId>" +
"<location>" + location + "</location>" +
"</node>";
sendPost("/rest/nodes", node, 201);
}
@Test
public void testAllTextIsPresent() throws Exception {
findElementByXpath("//h3//span[text()='Nodes']");
findElementByXpath("//ol[@class=\"breadcrumb\"]//li[text()='Node List']");
}
@Test
public void testAllLinks() throws InterruptedException {
findElementByLink("Show interfaces").click();
findElementByXpath("//h3[text()='Nodes and their interfaces']");
findElementByLink("Hide interfaces");
}
@Test
public void testAvailableLocations() throws Exception {
// Check if default selection is 'all locations' and all locations are listed
findElementByXpath("//select[@id='monitoringLocation']//option[text()='All locations' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//select[@id='monitoringLocation']//option")), WebElement::getText),
containsInAnyOrder("All locations",
"Pittsboro",
"Fulda"));
// Check the default lists all nodes
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
containsInAnyOrder("TestMachine loc1node1",
"TestMachine loc1node2",
"TestMachine loc2node1",
"TestMachine loc2node2"));
// Check switching to first location
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Pittsboro']").click();
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Pittsboro' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
containsInAnyOrder("TestMachine loc1node1",
"TestMachine loc1node2"));
// Check switching to second location
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Fulda']").click();
findElementByXpath("//select[@id='monitoringLocation']//option[text()='Fulda' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
containsInAnyOrder("TestMachine loc2node1",
"TestMachine loc2node2"));
// Check switching to unfiltered
findElementByXpath("//select[@id='monitoringLocation']//option[text()='All locations']").click();
findElementByXpath("//select[@id='monitoringLocation']//option[text()='All locations' and @selected]");
assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText),
containsInAnyOrder("TestMachine loc1node1",
"TestMachine loc1node2",
"TestMachine loc2node1",
"TestMachine loc2node2"));
}
}
| HZN-316: Fixed smoke-test to be less error-prone
| smoke-test/src/test/java/org/opennms/smoketest/NodeListPageIT.java | HZN-316: Fixed smoke-test to be less error-prone |
|
Java | lgpl-2.1 | 4521adf89059d5600e241ba9c8a2fdc9a2c8a1b4 | 0 | xwiki/xwiki-commons,xwiki/xwiki-commons | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.velocity.tools;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import net.sf.json.JSON;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
/**
* Unit tests for {@link JSONTool}.
*
* @version $Id$
* @since 4.0M2
*/
public class JSONToolTest
{
public static class MockBean
{
public boolean isEnabled()
{
return true;
}
public int getAge()
{
return 28;
}
public double getGrade()
{
return 9.48;
}
public String getName()
{
return "XWiki";
}
public List<String> getItems()
{
return Arrays.asList("one");
}
public Map<String, String> getParameters()
{
return Collections.singletonMap("foo", "bar");
}
@Transient
public String getTransientProperty()
{
return "transient";
}
}
/**
* The object being tested.
*/
private JSONTool tool = new JSONTool();
@Test
public void testSerializeNull()
{
Assert.assertEquals("null", this.tool.serialize(null));
}
@Test
public void testSerializeMap()
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("bool", false);
map.put("int", 13);
map.put("double", 0.78);
map.put("string", "foo");
map.put("array", new int[] { 9, 8 });
map.put("list", Arrays.asList("one", "two"));
map.put("map", Collections.singletonMap("level2", true));
map.put("null", "null key value");
String json = this.tool.serialize(map);
// We can't predict the order in the map.
Assert.assertTrue(json.contains("\"bool\":false"));
Assert.assertTrue(json.contains("\"int\":13"));
Assert.assertTrue(json.contains("\"double\":0.78"));
Assert.assertTrue(json.contains("\"string\":\"foo\""));
Assert.assertTrue(json.contains("\"array\":[9,8]"));
Assert.assertTrue(json.contains("\"list\":[\"one\",\"two\"]"));
Assert.assertTrue(json.contains("\"map\":{\"level2\":true}"));
Assert.assertTrue(json.contains("\"null\":\"null key value\""));
}
@Test
public void testSerializeList()
{
Assert.assertEquals("[1,2]", this.tool.serialize(Arrays.asList(1, 2)));
Assert.assertEquals("[1.3,2.4]", this.tool.serialize(new double[] { 1.3, 2.4 }));
}
@Test
public void testSerializeNumber()
{
Assert.assertEquals("27", this.tool.serialize(27));
Assert.assertEquals("2.7", this.tool.serialize(2.7));
}
@Test
public void testSerializeBoolean()
{
Assert.assertEquals("false", this.tool.serialize(false));
Assert.assertEquals("true", this.tool.serialize(true));
}
@Test
public void testSerializeString()
{
Assert.assertEquals("\"\\\"te'st\\\"\"", this.tool.serialize("\"te'st\""));
}
@Test
public void testSerializeBean()
{
String json = this.tool.serialize(new MockBean());
// We can't predict the order in the map.
Assert.assertTrue(json.contains("\"age\":28"));
Assert.assertTrue(json.contains("\"enabled\":true"));
Assert.assertTrue(json.contains("\"grade\":9.48"));
Assert.assertTrue(json.contains("\"items\":[\"one\"]"));
Assert.assertTrue(json.contains("\"name\":\"XWiki\""));
Assert.assertTrue(json.contains("\"parameters\":{\"foo\":\"bar\"}"));
Assert.assertFalse(json.contains("\"transientProperty\":\"transient\""));
}
@Test
public void testParseArray()
{
JSON json = this.tool.parse("[1,2,3]");
Assert.assertTrue(json.isArray());
Assert.assertEquals(3, json.size());
}
@Test
public void testParseEmptyArray()
{
JSON json = this.tool.parse("[]");
Assert.assertTrue(json.isArray());
Assert.assertTrue(json.isEmpty());
Assert.assertEquals(0, json.size());
}
@Test
public void testParseMap()
{
JSONObject json = (JSONObject) this.tool.parse("{\"a\" : 1, \"b\": [1], \"c\": true}");
Assert.assertFalse(json.isArray());
Assert.assertFalse(json.isEmpty());
Assert.assertEquals(3, json.size());
Assert.assertTrue(json.getBoolean("c"));
}
@Test
public void testParseEmptyMap()
{
JSONObject json = (JSONObject) this.tool.parse("{}");
Assert.assertFalse(json.isArray());
Assert.assertTrue(json.isEmpty());
Assert.assertEquals(0, json.size());
}
@Test
public void testParseNull()
{
Assert.assertTrue(this.tool.parse(null) instanceof JSONNull);
}
@Test
public void testParseEmptyString()
{
Assert.assertNull(this.tool.parse(""));
}
@Test
public void testParseInvalidJSON()
{
Assert.assertNull(this.tool.parse("This is not the JSON you are looking for..."));
}
@Test
public void serializeOrgJsonObjectWorks()
{
List<String> variants = new ArrayList<>(2);
variants.add("{\"a\":\"b\",\"c\":true}");
variants.add("{\"c\":true,\"a\":\"b\"}");
org.json.JSONObject object = new org.json.JSONObject();
object.put("a", "b");
object.put("c", true);
// Assert.assertEquals(variants.get(0), this.tool.serialize(object));
Assert.assertTrue(variants.contains(this.tool.serialize(object)));
}
@Test
public void serializeNestedOrgJsonObjectWorks()
{
List<String> variants = new ArrayList<>(2);
variants.add("{\"before\":[\"nothing\"],\"json\":{\"a\":\"b\",\"c\":true},\"after\":42}");
variants.add("{\"before\":[\"nothing\"],\"json\":{\"c\":true,\"a\":\"b\"},\"after\":42}");
org.json.JSONObject object = new org.json.JSONObject();
object.put("a", "b");
object.put("c", true);
Map<String, Object> map = new LinkedHashMap<>();
map.put("before", Collections.singletonList("nothing"));
map.put("json", object);
map.put("after", 42);
// Assert.assertEquals(variants.get(0), this.tool.serialize(map));
Assert.assertTrue(variants.contains(this.tool.serialize(map)));
}
@Test
public void serializeOrgJsonArrayWorks()
{
org.json.JSONArray array = new org.json.JSONArray();
array.put("a");
array.put(42);
array.put(true);
Assert.assertEquals("[\"a\",42,true]", this.tool.serialize(array));
}
@Test
public void serializeNestedOrgJsonArrayWorks()
{
org.json.JSONArray array = new org.json.JSONArray();
array.put("a");
array.put(42);
array.put(true);
Map<String, Object> map = new LinkedHashMap<>();
map.put("before", Collections.singletonList("nothing"));
map.put("json", array);
map.put("after", 42);
Assert.assertEquals("{\"before\":[\"nothing\"],\"json\":[\"a\",42,true],\"after\":42}", this.tool.serialize(map));
}
}
| xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/tools/JSONToolTest.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.velocity.tools;
import java.beans.Transient;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import net.sf.json.JSON;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
/**
* Unit tests for {@link JSONTool}.
*
* @version $Id$
* @since 4.0M2
*/
public class JSONToolTest
{
public static class MockBean
{
public boolean isEnabled()
{
return true;
}
public int getAge()
{
return 28;
}
public double getGrade()
{
return 9.48;
}
public String getName()
{
return "XWiki";
}
public List<String> getItems()
{
return Arrays.asList("one");
}
public Map<String, String> getParameters()
{
return Collections.singletonMap("foo", "bar");
}
@Transient
public String getTransientProperty()
{
return "transient";
}
}
/**
* The object being tested.
*/
private JSONTool tool = new JSONTool();
@Test
public void testSerializeNull()
{
Assert.assertEquals("null", this.tool.serialize(null));
}
@Test
public void testSerializeMap()
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("bool", false);
map.put("int", 13);
map.put("double", 0.78);
map.put("string", "foo");
map.put("array", new int[] { 9, 8 });
map.put("list", Arrays.asList("one", "two"));
map.put("map", Collections.singletonMap("level2", true));
map.put("null", "null key value");
String json = this.tool.serialize(map);
// We can't predict the order in the map.
Assert.assertTrue(json.contains("\"bool\":false"));
Assert.assertTrue(json.contains("\"int\":13"));
Assert.assertTrue(json.contains("\"double\":0.78"));
Assert.assertTrue(json.contains("\"string\":\"foo\""));
Assert.assertTrue(json.contains("\"array\":[9,8]"));
Assert.assertTrue(json.contains("\"list\":[\"one\",\"two\"]"));
Assert.assertTrue(json.contains("\"map\":{\"level2\":true}"));
Assert.assertTrue(json.contains("\"null\":\"null key value\""));
}
@Test
public void testSerializeList()
{
Assert.assertEquals("[1,2]", this.tool.serialize(Arrays.asList(1, 2)));
Assert.assertEquals("[1.3,2.4]", this.tool.serialize(new double[] { 1.3, 2.4 }));
}
@Test
public void testSerializeNumber()
{
Assert.assertEquals("27", this.tool.serialize(27));
Assert.assertEquals("2.7", this.tool.serialize(2.7));
}
@Test
public void testSerializeBoolean()
{
Assert.assertEquals("false", this.tool.serialize(false));
Assert.assertEquals("true", this.tool.serialize(true));
}
@Test
public void testSerializeString()
{
Assert.assertEquals("\"\\\"te'st\\\"\"", this.tool.serialize("\"te'st\""));
}
@Test
public void testSerializeBean()
{
String json = this.tool.serialize(new MockBean());
// We can't predict the order in the map.
Assert.assertTrue(json.contains("\"age\":28"));
Assert.assertTrue(json.contains("\"enabled\":true"));
Assert.assertTrue(json.contains("\"grade\":9.48"));
Assert.assertTrue(json.contains("\"items\":[\"one\"]"));
Assert.assertTrue(json.contains("\"name\":\"XWiki\""));
Assert.assertTrue(json.contains("\"parameters\":{\"foo\":\"bar\"}"));
Assert.assertFalse(json.contains("\"transientProperty\":\"transient\""));
}
@Test
public void testParseArray()
{
JSON json = this.tool.parse("[1,2,3]");
Assert.assertTrue(json.isArray());
Assert.assertEquals(3, json.size());
}
@Test
public void testParseEmptyArray()
{
JSON json = this.tool.parse("[]");
Assert.assertTrue(json.isArray());
Assert.assertTrue(json.isEmpty());
Assert.assertEquals(0, json.size());
}
@Test
public void testParseMap()
{
JSONObject json = (JSONObject) this.tool.parse("{\"a\" : 1, \"b\": [1], \"c\": true}");
Assert.assertFalse(json.isArray());
Assert.assertFalse(json.isEmpty());
Assert.assertEquals(3, json.size());
Assert.assertTrue(json.getBoolean("c"));
}
@Test
public void testParseEmptyMap()
{
JSONObject json = (JSONObject) this.tool.parse("{}");
Assert.assertFalse(json.isArray());
Assert.assertTrue(json.isEmpty());
Assert.assertEquals(0, json.size());
}
@Test
public void testParseNull()
{
Assert.assertTrue(this.tool.parse(null) instanceof JSONNull);
}
@Test
public void testParseEmptyString()
{
Assert.assertNull(this.tool.parse(""));
}
@Test
public void testParseInvalidJSON()
{
Assert.assertNull(this.tool.parse("This is not the JSON you are looking for..."));
}
}
| [misc] Added some tests
| xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/tools/JSONToolTest.java | [misc] Added some tests |
|
Java | lgpl-2.1 | 28d5a089de85a67015270b497097dd95851256a5 | 0 | jolie/jolie,jolie/jolie,jolie/jolie | /***************************************************************************
* Copyright (C) 2011 by Fabrizio Montesi <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 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 Library 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. *
* *
* For details about the authors of this software, see the AUTHORS file. *
***************************************************************************/
package jolie.lang.parse;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import jolie.lang.Constants;
import jolie.lang.Constants.ExecutionMode;
import jolie.lang.parse.ast.AddAssignStatement;
import jolie.lang.parse.ast.AssignStatement;
import jolie.lang.parse.ast.CompareConditionNode;
import jolie.lang.parse.ast.CompensateStatement;
import jolie.lang.parse.ast.CorrelationSetInfo;
import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationVariableInfo;
import jolie.lang.parse.ast.CurrentHandlerStatement;
import jolie.lang.parse.ast.DeepCopyStatement;
import jolie.lang.parse.ast.DefinitionCallStatement;
import jolie.lang.parse.ast.DefinitionNode;
import jolie.lang.parse.ast.DivideAssignStatement;
import jolie.lang.parse.ast.DocumentationComment;
import jolie.lang.parse.ast.EmbeddedServiceNode;
import jolie.lang.parse.ast.ExecutionInfo;
import jolie.lang.parse.ast.ExitStatement;
import jolie.lang.parse.ast.ForEachArrayItemStatement;
import jolie.lang.parse.ast.ForEachSubNodeStatement;
import jolie.lang.parse.ast.ForStatement;
import jolie.lang.parse.ast.IfStatement;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.InstallFixedVariableExpressionNode;
import jolie.lang.parse.ast.InstallStatement;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.InterfaceExtenderDefinition;
import jolie.lang.parse.ast.LinkInStatement;
import jolie.lang.parse.ast.LinkOutStatement;
import jolie.lang.parse.ast.MultiplyAssignStatement;
import jolie.lang.parse.ast.NDChoiceStatement;
import jolie.lang.parse.ast.NotificationOperationStatement;
import jolie.lang.parse.ast.NullProcessStatement;
import jolie.lang.parse.ast.OLSyntaxNode;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OneWayOperationStatement;
import jolie.lang.parse.ast.OutputPortInfo;
import jolie.lang.parse.ast.ParallelStatement;
import jolie.lang.parse.ast.PointerStatement;
import jolie.lang.parse.ast.PostDecrementStatement;
import jolie.lang.parse.ast.PostIncrementStatement;
import jolie.lang.parse.ast.PreDecrementStatement;
import jolie.lang.parse.ast.PreIncrementStatement;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.ProvideUntilStatement;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationStatement;
import jolie.lang.parse.ast.RunStatement;
import jolie.lang.parse.ast.Scope;
import jolie.lang.parse.ast.SequenceStatement;
import jolie.lang.parse.ast.SolicitResponseOperationStatement;
import jolie.lang.parse.ast.SpawnStatement;
import jolie.lang.parse.ast.SubtractAssignStatement;
import jolie.lang.parse.ast.SynchronizedStatement;
import jolie.lang.parse.ast.ThrowStatement;
import jolie.lang.parse.ast.TypeCastExpressionNode;
import jolie.lang.parse.ast.UndefStatement;
import jolie.lang.parse.ast.ValueVectorSizeExpressionNode;
import jolie.lang.parse.ast.VariablePathNode;
import jolie.lang.parse.ast.WhileStatement;
import jolie.lang.parse.ast.courier.CourierChoiceStatement;
import jolie.lang.parse.ast.courier.CourierDefinitionNode;
import jolie.lang.parse.ast.courier.NotificationForwardStatement;
import jolie.lang.parse.ast.courier.SolicitResponseForwardStatement;
import jolie.lang.parse.ast.expression.AndConditionNode;
import jolie.lang.parse.ast.expression.ConstantBoolExpression;
import jolie.lang.parse.ast.expression.ConstantDoubleExpression;
import jolie.lang.parse.ast.expression.ConstantIntegerExpression;
import jolie.lang.parse.ast.expression.ConstantLongExpression;
import jolie.lang.parse.ast.expression.ConstantStringExpression;
import jolie.lang.parse.ast.expression.FreshValueExpressionNode;
import jolie.lang.parse.ast.expression.InlineTreeExpressionNode;
import jolie.lang.parse.ast.expression.InstanceOfExpressionNode;
import jolie.lang.parse.ast.expression.IsTypeExpressionNode;
import jolie.lang.parse.ast.expression.NotExpressionNode;
import jolie.lang.parse.ast.expression.OrConditionNode;
import jolie.lang.parse.ast.expression.ProductExpressionNode;
import jolie.lang.parse.ast.expression.SumExpressionNode;
import jolie.lang.parse.ast.expression.VariableExpressionNode;
import jolie.lang.parse.ast.expression.VoidExpressionNode;
import jolie.lang.parse.ast.types.TypeChoiceDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.lang.parse.context.ParsingContext;
import jolie.util.Pair;
/**
*
* @author Fabrizio Montesi
*/
public class TypeChecker implements OLVisitor
{
private class FlaggedVariablePathNode extends VariablePathNode
{
private final boolean isFresh;
public FlaggedVariablePathNode( VariablePathNode path, boolean isFresh )
{
super( path.context(), path.type() );
this.path().addAll( path.path() );
this.isFresh = isFresh;
}
public boolean isFresh()
{
return isFresh;
}
}
private class TypingResult
{
private final VariablePathSet< VariablePathNode > neededCorrPaths;
private final VariablePathSet< FlaggedVariablePathNode > providedCorrPaths;
private final VariablePathSet< VariablePathNode > neededVarPaths;
private final VariablePathSet< VariablePathNode > providedVarPaths;
private final Set< String > sessionOperations;
private String startingOperation = null;
private final VariablePathSet< VariablePathNode > invalidatedVarPaths;
public TypingResult()
{
neededCorrPaths = new VariablePathSet();
providedCorrPaths = new VariablePathSet();
neededVarPaths = new VariablePathSet();
providedVarPaths = new VariablePathSet();
invalidatedVarPaths = new VariablePathSet();
sessionOperations = new HashSet<>();
}
public void registerOperationInput( String operation, boolean isStartingOperation )
{
if ( isStartingOperation ) {
startingOperation = operation;
} else {
sessionOperations.add( operation );
}
}
public void registerOperations( TypingResult other )
{
if ( this.startingOperation == null ) {
this.startingOperation = other.startingOperation;
}
sessionOperations.addAll( other.sessionOperations );
}
public void provide( VariablePathNode path, boolean isFresh )
{
if ( path.isCSet() ) {
providedCorrPaths.add( new FlaggedVariablePathNode( path, isFresh ) );
} else {
providedVarPaths.add( path );
}
}
public void provide( FlaggedVariablePathNode path )
{
if ( path.isCSet() ) {
providedCorrPaths.add( path );
} else {
providedVarPaths.add( path );
}
}
public void provide( VariablePathNode path )
{
if ( path instanceof FlaggedVariablePathNode ) {
provide( (FlaggedVariablePathNode) path );
} else {
provide( path, false );
}
}
public void need( VariablePathNode path )
{
if ( path.isCSet() ) {
neededCorrPaths.add( path );
} else {
neededVarPaths.add( path );
}
}
public void needAll( TypingResult other )
{
for( VariablePathNode path : other.neededCorrPaths ) {
need( path );
}
for( VariablePathNode path : other.neededVarPaths ) {
need( path );
}
}
public void provideAll( TypingResult other )
{
for( VariablePathNode path : other.providedCorrPaths ) {
provide( path );
}
for( VariablePathNode path : other.providedVarPaths ) {
provide( path );
}
}
public void provideAll( VariablePathSet< ? extends VariablePathNode > other )
{
for( VariablePathNode path : other ) {
provide( path );
}
}
public void needAll( VariablePathSet< ? extends VariablePathNode > other )
{
for( VariablePathNode path : other ) {
need( path );
}
}
public void invalidateAll( TypingResult other )
{
for( VariablePathNode path : other.invalidatedVarPaths ) {
invalidate( path );
}
}
public void invalidate( VariablePathNode path )
{
invalidatedVarPaths.add( path );
providedVarPaths.remove( path );
}
public void removeUnsharedProvided( TypingResult other )
{
List< VariablePathNode > toBeRemoved = new LinkedList<>();
for( VariablePathNode path : providedVarPaths ) {
if ( !other.providedVarPaths.contains( path ) ) {
toBeRemoved.add( path );
}
}
for( VariablePathNode path : toBeRemoved ) {
providedVarPaths.remove( path );
}
}
}
private final Program program;
private boolean insideInit = false;
private final CorrelationFunctionInfo correlationFunctionInfo;
private final ExecutionMode executionMode;
private TypingResult typingResult;
private TypingResult entryTyping;
private static final Logger logger = Logger.getLogger( "JOLIE" );
private boolean valid = true;
private final Map< String, TypingResult > definitionTyping = new HashMap<>();
private boolean sessionStarter = false;
public TypeChecker( Program program, ExecutionMode executionMode, CorrelationFunctionInfo correlationFunctionInfo )
{
this.program = program;
this.executionMode = executionMode;
this.correlationFunctionInfo = correlationFunctionInfo;
}
private void error( OLSyntaxNode node, String message )
{
valid = false;
if ( node != null ) {
ParsingContext context = node.context();
logger.severe( context.sourceName() + ":" + context.line() + ": " + message );
} else {
logger.severe( message );
}
}
private boolean isDefinedBefore( VariablePathNode path )
{
if ( entryTyping.providedVarPaths.contains( path ) || entryTyping.providedCorrPaths.contains( path ) ) {
return true;
}
return false;
}
public boolean check()
{
check( program, new TypingResult() );
typingResult = definitionTyping.get( "main" );
if ( typingResult == null ) {
error( program, "Cannot find the main entry point" );
} else {
checkMainTyping();
}
return valid;
}
private void checkMainTyping()
{
TypingResult initTyping = definitionTyping.get( "init" );
if ( initTyping != null ) {
addInitTypingToMain();
}
for( VariablePathNode path : typingResult.neededCorrPaths ) {
error( path, "Correlation path " + path.toPrettyString() + " is not initialised before usage." );
}
for( VariablePathNode path : typingResult.neededVarPaths ) {
error( path, "Variable " + path.toPrettyString() + " is not initialised before using it to initialise a correlation variable." );
}
VariablePathNode path;
boolean isCorrelationSetFresh;
for( CorrelationSetInfo cset : correlationFunctionInfo.correlationSets() ) {
isCorrelationSetFresh = false;
for( CorrelationVariableInfo cvar : cset.variables() ) {
path = new VariablePathNode( cvar.correlationVariablePath().context(), VariablePathNode.Type.CSET );
path.path().add( new Pair<>(
new ConstantStringExpression( cset.context(), Constants.CSETS ),
new ConstantIntegerExpression( cset.context(), 0 )
) );
path.path().addAll( cvar.correlationVariablePath().path() );
FlaggedVariablePathNode flaggedPath = typingResult.providedCorrPaths.getContained( path );
if ( flaggedPath == null ) { // The two cases could be merged in a single if-then-else condition, but they are logically different.
isCorrelationSetFresh = true; // We can set this because the correlation set is not used at all.
break;
} else if ( flaggedPath.isFresh() ) {
isCorrelationSetFresh = true;
break;
}
}
if ( !isCorrelationSetFresh ) {
error( cset, "Every correlation set must have at least one fresh value (maybe you are not using new?)." );
}
}
}
private void addInitTypingToMain()
{
TypingResult right = typingResult;
typingResult = definitionTyping.get( "init" );
for( VariablePathNode path : right.providedCorrPaths ) {
if ( typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables cannot be defined more than one time." );
} else {
typingResult.provide( path );
}
}
for( VariablePathNode path : right.providedVarPaths ) {
typingResult.provide( path );
typingResult.invalidatedVarPaths.remove( path );
}
for( VariablePathNode path : right.neededVarPaths ) {
if ( !typingResult.providedVarPaths.contains( path ) ) {
typingResult.need( path );
}
}
for( VariablePathNode path : right.neededCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
typingResult.need( path );
}
}
typingResult.invalidateAll( right );
}
private TypingResult check( OLSyntaxNode n, TypingResult entryTyping )
{
this.entryTyping = entryTyping;
TypingResult backup = typingResult;
typingResult = new TypingResult();
n.accept( this );
TypingResult ret = typingResult;
typingResult = backup;
return ret;
}
@Override
public void visit( Program n )
{
for( OLSyntaxNode node : n.children() ) {
check( node, new TypingResult() );
}
}
@Override
public void visit( OneWayOperationDeclaration decl )
{}
@Override
public void visit( RequestResponseOperationDeclaration decl )
{}
@Override
public void visit( DefinitionNode n )
{
insideInit = false;
TypingResult entry = null;
switch( n.id() ) {
case "main":
sessionStarter = true;
entry = definitionTyping.get( "init" );
break;
case "init":
insideInit = true;
break;
}
if ( entry == null ) {
entry = new TypingResult();
}
definitionTyping.put( n.id(), check( n.body(), entry ) );
if ( n.id().equals( "init" ) ) {
for( VariablePathNode path : typingResult.providedCorrPaths ) {
error( path, "Correlation variables can not be initialised in the init procedure." );
}
}
}
@Override
public void visit( ParallelStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
TypingResult entry = entryTyping;
typingResult = check( n.children().get( 0 ), entry );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
right = check( n.children().get( i ), entry );
for( VariablePathNode path : right.providedCorrPaths ) {
if ( typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables can not be defined more than one time." );
} else {
typingResult.provide( path );
}
}
typingResult.provideAll( right.providedVarPaths );
typingResult.needAll( right );
typingResult.invalidateAll( right );
typingResult.registerOperations( right );
}
}
@Override
public void visit( SequenceStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
typingResult.provideAll( entryTyping );
typingResult = check( n.children().get( 0 ), typingResult );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
right = check( n.children().get( i ), typingResult );
for( VariablePathNode path : right.providedCorrPaths ) {
if ( typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables can not be defined more than one time." );
} else {
typingResult.provide( path );
}
}
for( VariablePathNode path : right.providedVarPaths ) {
typingResult.provide( path );
typingResult.invalidatedVarPaths.remove( path );
}
for( VariablePathNode path : right.neededVarPaths ) {
if ( !typingResult.providedVarPaths.contains( path ) ) {
typingResult.need( path );
}
}
for( VariablePathNode path : right.neededCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
typingResult.need( path );
}
}
typingResult.invalidateAll( right );
typingResult.registerOperations( right );
}
}
@Override
public void visit( NDChoiceStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
List< TypingResult > branchTypings = new LinkedList<>();
boolean origSessionStarter = sessionStarter;
TypingResult entry = entryTyping;
SequenceStatement seq;
seq = new SequenceStatement( n.context() );
seq.addChild( n.children().get( 0 ).key() );
seq.addChild( n.children().get( 0 ).value() );
typingResult = check( seq, entry );
branchTypings.add( typingResult );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
sessionStarter = origSessionStarter;
seq = new SequenceStatement( n.context() );
seq.addChild( n.children().get( i ).key() );
seq.addChild( n.children().get( i ).value() );
right = check( seq, entry );
branchTypings.add( right );
typingResult.needAll( right );
typingResult.invalidateAll( right );
if ( !origSessionStarter ) {
for( VariablePathNode path : typingResult.providedCorrPaths ) {
if ( !right.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every branch." );
}
}
for( VariablePathNode path : right.providedCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every branch." );
}
}
typingResult.registerOperations( right );
}
typingResult.removeUnsharedProvided( right );
sessionStarter = false;
}
if ( origSessionStarter ) {
for( TypingResult top : branchTypings ) {
for( TypingResult branch : branchTypings ) {
if ( top != branch && branch.sessionOperations.contains( top.startingOperation ) ) {
error( program, "Operation " + top.startingOperation + " can not be used both as a starter and in the body of another session branch." );
}
}
}
}
sessionStarter = false;
}
@Override
public void visit( OneWayOperationStatement n )
{
if ( executionMode == ExecutionMode.SINGLE ) {
return;
}
typingResult.registerOperationInput( n.id(), sessionStarter );
if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) {
error( n, "Input operations can not receive on a correlation variable" );
}
CorrelationSetInfo cset = correlationFunctionInfo.operationCorrelationSetMap().get( n.id() );
if ( !sessionStarter && !insideInit ) {
if ( cset == null || cset.variables().isEmpty() ) {
error( n, "No correlation set defined for operation " + n.id() );
}
}
if ( cset != null ) {
for( CorrelationSetInfo.CorrelationVariableInfo cvar : cset.variables() ) {
VariablePathNode path = new VariablePathNode( cset.context(), VariablePathNode.Type.CSET );
path.path().add(new Pair<>(
new ConstantStringExpression( cset.context(), Constants.CSETS ),
new ConstantIntegerExpression( cset.context(), 0 )
) );
path.path().addAll( cvar.correlationVariablePath().path() );
if ( sessionStarter ) {
typingResult.provide( path, true );
} else {
typingResult.need( path );
}
}
}
sessionStarter = false;
}
@Override
public void visit( RequestResponseOperationStatement n )
{
if ( executionMode == ExecutionMode.SINGLE ) {
return;
}
typingResult.registerOperationInput( n.id(), sessionStarter );
if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) {
error( n, "Input operations can not receive on a correlation variable" );
}
CorrelationSetInfo cset = correlationFunctionInfo.operationCorrelationSetMap().get( n.id() );
if ( !sessionStarter && !insideInit ) {
if ( cset == null || cset.variables().isEmpty() ) {
error( n, "No correlation set defined for operation " + n.id() );
}
}
if ( cset != null ) {
for( CorrelationSetInfo.CorrelationVariableInfo cvar : cset.variables() ) {
VariablePathNode path = new VariablePathNode( cset.context(), VariablePathNode.Type.CSET );
path.path().add(new Pair<>(
new ConstantStringExpression( cset.context(), Constants.CSETS ),
new ConstantIntegerExpression( cset.context(), 0 )
) );
path.path().addAll( cvar.correlationVariablePath().path() );
if ( sessionStarter ) {
typingResult.provide( path, true );
} else {
typingResult.need( path );
}
}
}
sessionStarter = false;
TypingResult internalProcessTyping = check( n.process(), entryTyping );
typingResult.needAll( internalProcessTyping );
typingResult.provideAll( internalProcessTyping );
typingResult.registerOperations( internalProcessTyping );
}
@Override
public void visit( NotificationOperationStatement n )
{}
@Override
public void visit( SolicitResponseOperationStatement n )
{
if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) {
error( n, "Solicit-response statements can not receive on a correlation variable" );
}
}
@Override
public void visit( FreshValueExpressionNode n )
{}
@Override
public void visit( LinkInStatement n )
{}
@Override
public void visit( LinkOutStatement n )
{}
@Override
public void visit( AssignStatement n )
{
if ( n.variablePath().isStatic() ) {
if ( n.expression() instanceof ConstantIntegerExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantDoubleExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantBoolExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantLongExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantStringExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PostDecrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PostIncrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PreDecrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PreIncrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof VariableExpressionNode ) {
VariablePathNode rightPath = ((VariableExpressionNode)n.expression()).variablePath();
if ( rightPath.isStatic() && isDefinedBefore( rightPath ) ) {
typingResult.provide( n.variablePath() );
} else if ( n.variablePath().isCSet() ) {
error( n, "Variable " + rightPath.toPrettyString() + " may be undefined before being used for defining correlation variable " + n.variablePath().toPrettyString() );
}
} else if ( n.expression() instanceof FreshValueExpressionNode ) {
typingResult.provide( n.variablePath(), true );
} else if ( n.variablePath().isCSet() ) {
error( n, "Correlation variables must either be initialised with createSecureToken@SecurityUtils, a variable or a constant." );
}
}
}
@Override
public void visit( AddAssignStatement n )
{}
@Override
public void visit( SubtractAssignStatement n )
{}
@Override
public void visit( MultiplyAssignStatement n )
{}
@Override
public void visit( DivideAssignStatement n )
{}
@Override
public void visit( IfStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
TypingResult entry = entryTyping;
typingResult = check( n.children().get( 0 ).value(), entry );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
right = check( n.children().get( i ).value(), entry );
typingResult.needAll( right );
typingResult.registerOperations( right );
typingResult.invalidateAll( right );
for( VariablePathNode path : typingResult.providedCorrPaths ) {
if ( !right.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
for( VariablePathNode path : right.providedCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
typingResult.removeUnsharedProvided( right );
}
if ( n.elseProcess() != null ) {
right = check( n.elseProcess(), entry );
typingResult.needAll( right );
typingResult.registerOperations( right );
typingResult.invalidateAll( right );
for( VariablePathNode path : typingResult.providedCorrPaths ) {
if ( !right.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
for( VariablePathNode path : right.providedCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
typingResult.removeUnsharedProvided( right );
}
}
@Override
public void visit( InstanceOfExpressionNode n )
{}
@Override
public void visit( DefinitionCallStatement n )
{
typingResult = definitionTyping.get( n.id() );
if ( typingResult == null ) {
typingResult = new TypingResult();
error( n, "Can not find definition " + n.id() );
}
}
@Override
public void visit( InlineTreeExpressionNode n )
{}
@Override
public void visit( WhileStatement n )
{
typingResult = check( n.body(), entryTyping );
if ( !typingResult.providedCorrPaths.isEmpty() ) {
error( n, "Initialising correlation variables in while loops is forbidden." );
}
typingResult.providedVarPaths.clear();
}
@Override
public void visit( OrConditionNode n )
{}
@Override
public void visit( AndConditionNode n )
{}
@Override
public void visit( NotExpressionNode n )
{}
@Override
public void visit( CompareConditionNode n )
{}
@Override
public void visit( ConstantIntegerExpression n )
{}
@Override
public void visit( ConstantLongExpression n )
{}
@Override
public void visit( ConstantBoolExpression n )
{}
@Override
public void visit( ConstantDoubleExpression n )
{}
@Override
public void visit( ConstantStringExpression n )
{}
@Override
public void visit( ProductExpressionNode n )
{}
@Override
public void visit( SumExpressionNode n )
{}
@Override
public void visit( VariableExpressionNode n )
{}
@Override
public void visit( NullProcessStatement n )
{}
@Override
public void visit( Scope n )
{
typingResult = check( n.body(), entryTyping );
}
@Override
public void visit( InstallStatement n )
{ // TODO check code inside install
}
@Override
public void visit( CompensateStatement n )
{}
@Override
public void visit( ThrowStatement n )
{}
@Override
public void visit( ExitStatement n )
{}
@Override
public void visit( ExecutionInfo n )
{}
@Override
public void visit( CorrelationSetInfo n )
{}
@Override
public void visit( InputPortInfo n )
{}
@Override
public void visit( OutputPortInfo n )
{}
@Override
public void visit( PointerStatement n )
{
typingResult.invalidate( n.rightPath() );
typingResult.invalidate( n.leftPath() );
}
@Override
public void visit( DeepCopyStatement n )
{
if ( n.rightExpression() instanceof VariableExpressionNode ) {
// TODO: check whether to invalidate all variable paths in other expression cases
typingResult.invalidate( ((VariableExpressionNode) n.rightExpression()).variablePath() );
}
typingResult.invalidate( n.leftPath() );
}
@Override
public void visit( RunStatement n )
{}
@Override
public void visit( UndefStatement n )
{
typingResult.invalidate( n.variablePath() );
}
@Override
public void visit( ValueVectorSizeExpressionNode n )
{}
@Override
public void visit( PreIncrementStatement n )
{}
@Override
public void visit( PostIncrementStatement n )
{}
@Override
public void visit( PreDecrementStatement n )
{}
@Override
public void visit( PostDecrementStatement n )
{}
@Override
public void visit( ForStatement n )
{
typingResult = check( n.body(), entryTyping );
if ( !typingResult.providedCorrPaths.isEmpty() ) {
error( n, "Initialising correlation variables in while loops is forbidden." );
}
typingResult.providedVarPaths.clear();
}
@Override
public void visit( ForEachSubNodeStatement n )
{
typingResult = check( n.body(), entryTyping );
if ( !typingResult.providedCorrPaths.isEmpty() ) {
error( n, "Initialising correlation variables in while loops is forbidden." );
}
typingResult.providedVarPaths.clear();
}
@Override
public void visit( ForEachArrayItemStatement n )
{}
@Override
public void visit( SpawnStatement n )
{}
@Override
public void visit( IsTypeExpressionNode n )
{}
@Override
public void visit( TypeCastExpressionNode n )
{}
@Override
public void visit( SynchronizedStatement n )
{
typingResult = check( n.body(), entryTyping );
}
@Override
public void visit( CurrentHandlerStatement n )
{}
@Override
public void visit( EmbeddedServiceNode n )
{}
@Override
public void visit( InstallFixedVariableExpressionNode n )
{}
@Override
public void visit( VariablePathNode n )
{}
@Override
public void visit( TypeInlineDefinition n )
{}
@Override
public void visit( TypeDefinitionLink n )
{}
@Override
public void visit( InterfaceDefinition n )
{}
@Override
public void visit( DocumentationComment n )
{}
@Override
public void visit( InterfaceExtenderDefinition n ) {}
@Override
public void visit( CourierDefinitionNode n ) {}
@Override
public void visit( CourierChoiceStatement n ) {}
@Override
public void visit( NotificationForwardStatement n ) {}
@Override
public void visit( SolicitResponseForwardStatement n ) {}
@Override
public void visit( VoidExpressionNode n ) {}
@Override
public void visit( ProvideUntilStatement n )
{
n.provide().accept( this );
n.until().accept( this );
}
@Override
public void visit(TypeChoiceDefinition n) {
//todo
}
}
| libjolie/src/jolie/lang/parse/TypeChecker.java | /***************************************************************************
* Copyright (C) 2011 by Fabrizio Montesi <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 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 Library 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. *
* *
* For details about the authors of this software, see the AUTHORS file. *
***************************************************************************/
package jolie.lang.parse;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import jolie.lang.Constants;
import jolie.lang.Constants.ExecutionMode;
import jolie.lang.parse.ast.AddAssignStatement;
import jolie.lang.parse.ast.AssignStatement;
import jolie.lang.parse.ast.CompareConditionNode;
import jolie.lang.parse.ast.CompensateStatement;
import jolie.lang.parse.ast.CorrelationSetInfo;
import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationVariableInfo;
import jolie.lang.parse.ast.CurrentHandlerStatement;
import jolie.lang.parse.ast.DeepCopyStatement;
import jolie.lang.parse.ast.DefinitionCallStatement;
import jolie.lang.parse.ast.DefinitionNode;
import jolie.lang.parse.ast.DivideAssignStatement;
import jolie.lang.parse.ast.DocumentationComment;
import jolie.lang.parse.ast.EmbeddedServiceNode;
import jolie.lang.parse.ast.ExecutionInfo;
import jolie.lang.parse.ast.ExitStatement;
import jolie.lang.parse.ast.ForEachArrayItemStatement;
import jolie.lang.parse.ast.ForEachSubNodeStatement;
import jolie.lang.parse.ast.ForStatement;
import jolie.lang.parse.ast.IfStatement;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.InstallFixedVariableExpressionNode;
import jolie.lang.parse.ast.InstallStatement;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.InterfaceExtenderDefinition;
import jolie.lang.parse.ast.LinkInStatement;
import jolie.lang.parse.ast.LinkOutStatement;
import jolie.lang.parse.ast.MultiplyAssignStatement;
import jolie.lang.parse.ast.NDChoiceStatement;
import jolie.lang.parse.ast.NotificationOperationStatement;
import jolie.lang.parse.ast.NullProcessStatement;
import jolie.lang.parse.ast.OLSyntaxNode;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OneWayOperationStatement;
import jolie.lang.parse.ast.OutputPortInfo;
import jolie.lang.parse.ast.ParallelStatement;
import jolie.lang.parse.ast.PointerStatement;
import jolie.lang.parse.ast.PostDecrementStatement;
import jolie.lang.parse.ast.PostIncrementStatement;
import jolie.lang.parse.ast.PreDecrementStatement;
import jolie.lang.parse.ast.PreIncrementStatement;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.ProvideUntilStatement;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationStatement;
import jolie.lang.parse.ast.RunStatement;
import jolie.lang.parse.ast.Scope;
import jolie.lang.parse.ast.SequenceStatement;
import jolie.lang.parse.ast.SolicitResponseOperationStatement;
import jolie.lang.parse.ast.SpawnStatement;
import jolie.lang.parse.ast.SubtractAssignStatement;
import jolie.lang.parse.ast.SynchronizedStatement;
import jolie.lang.parse.ast.ThrowStatement;
import jolie.lang.parse.ast.TypeCastExpressionNode;
import jolie.lang.parse.ast.UndefStatement;
import jolie.lang.parse.ast.ValueVectorSizeExpressionNode;
import jolie.lang.parse.ast.VariablePathNode;
import jolie.lang.parse.ast.WhileStatement;
import jolie.lang.parse.ast.courier.CourierChoiceStatement;
import jolie.lang.parse.ast.courier.CourierDefinitionNode;
import jolie.lang.parse.ast.courier.NotificationForwardStatement;
import jolie.lang.parse.ast.courier.SolicitResponseForwardStatement;
import jolie.lang.parse.ast.expression.AndConditionNode;
import jolie.lang.parse.ast.expression.ConstantBoolExpression;
import jolie.lang.parse.ast.expression.ConstantDoubleExpression;
import jolie.lang.parse.ast.expression.ConstantIntegerExpression;
import jolie.lang.parse.ast.expression.ConstantLongExpression;
import jolie.lang.parse.ast.expression.ConstantStringExpression;
import jolie.lang.parse.ast.expression.FreshValueExpressionNode;
import jolie.lang.parse.ast.expression.InlineTreeExpressionNode;
import jolie.lang.parse.ast.expression.InstanceOfExpressionNode;
import jolie.lang.parse.ast.expression.IsTypeExpressionNode;
import jolie.lang.parse.ast.expression.NotExpressionNode;
import jolie.lang.parse.ast.expression.OrConditionNode;
import jolie.lang.parse.ast.expression.ProductExpressionNode;
import jolie.lang.parse.ast.expression.SumExpressionNode;
import jolie.lang.parse.ast.expression.VariableExpressionNode;
import jolie.lang.parse.ast.expression.VoidExpressionNode;
import jolie.lang.parse.ast.types.TypeChoiceDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.lang.parse.context.ParsingContext;
import jolie.util.Pair;
/**
*
* @author Fabrizio Montesi
*/
public class TypeChecker implements OLVisitor
{
private class FlaggedVariablePathNode extends VariablePathNode
{
private final boolean isFresh;
public FlaggedVariablePathNode( VariablePathNode path, boolean isFresh )
{
super( path.context(), path.type() );
this.path().addAll( path.path() );
this.isFresh = isFresh;
}
public boolean isFresh()
{
return isFresh;
}
}
private class TypingResult
{
private final VariablePathSet< VariablePathNode > neededCorrPaths;
private final VariablePathSet< FlaggedVariablePathNode > providedCorrPaths;
private final VariablePathSet< VariablePathNode > neededVarPaths;
private final VariablePathSet< VariablePathNode > providedVarPaths;
private final Set< String > sessionOperations;
private String startingOperation = null;
private final VariablePathSet< VariablePathNode > invalidatedVarPaths;
public TypingResult()
{
neededCorrPaths = new VariablePathSet();
providedCorrPaths = new VariablePathSet();
neededVarPaths = new VariablePathSet();
providedVarPaths = new VariablePathSet();
invalidatedVarPaths = new VariablePathSet();
sessionOperations = new HashSet<>();
}
public void registerOperationInput( String operation, boolean isStartingOperation )
{
if ( isStartingOperation ) {
startingOperation = operation;
} else {
sessionOperations.add( operation );
}
}
public void registerOperations( TypingResult other )
{
if ( this.startingOperation == null ) {
this.startingOperation = other.startingOperation;
}
sessionOperations.addAll( other.sessionOperations );
}
public void provide( VariablePathNode path, boolean isFresh )
{
if ( path.isCSet() ) {
providedCorrPaths.add( new FlaggedVariablePathNode( path, isFresh ) );
} else {
providedVarPaths.add( path );
}
}
public void provide( FlaggedVariablePathNode path )
{
if ( path.isCSet() ) {
providedCorrPaths.add( path );
} else {
providedVarPaths.add( path );
}
}
public void provide( VariablePathNode path )
{
if ( path instanceof FlaggedVariablePathNode ) {
provide( (FlaggedVariablePathNode) path );
} else {
provide( path, false );
}
}
public void need( VariablePathNode path )
{
if ( path.isCSet() ) {
neededCorrPaths.add( path );
} else {
neededVarPaths.add( path );
}
}
public void needAll( TypingResult other )
{
for( VariablePathNode path : other.neededCorrPaths ) {
need( path );
}
for( VariablePathNode path : other.neededVarPaths ) {
need( path );
}
}
public void provideAll( TypingResult other )
{
for( VariablePathNode path : other.providedCorrPaths ) {
provide( path );
}
for( VariablePathNode path : other.providedVarPaths ) {
provide( path );
}
}
public void provideAll( VariablePathSet< ? extends VariablePathNode > other )
{
for( VariablePathNode path : other ) {
provide( path );
}
}
public void needAll( VariablePathSet< ? extends VariablePathNode > other )
{
for( VariablePathNode path : other ) {
need( path );
}
}
public void invalidateAll( TypingResult other )
{
for( VariablePathNode path : other.invalidatedVarPaths ) {
invalidate( path );
}
}
public void invalidate( VariablePathNode path )
{
invalidatedVarPaths.add( path );
providedVarPaths.remove( path );
}
public void removeUnsharedProvided( TypingResult other )
{
List< VariablePathNode > toBeRemoved = new LinkedList<>();
for( VariablePathNode path : providedVarPaths ) {
if ( !other.providedVarPaths.contains( path ) ) {
toBeRemoved.add( path );
}
}
for( VariablePathNode path : toBeRemoved ) {
providedVarPaths.remove( path );
}
}
}
private final Program program;
private boolean insideInit = false;
private final CorrelationFunctionInfo correlationFunctionInfo;
private final ExecutionMode executionMode;
private TypingResult typingResult;
private TypingResult entryTyping;
private static final Logger logger = Logger.getLogger( "JOLIE" );
private boolean valid = true;
private final Map< String, TypingResult > definitionTyping = new HashMap<>();
private boolean sessionStarter = false;
public TypeChecker( Program program, ExecutionMode executionMode, CorrelationFunctionInfo correlationFunctionInfo )
{
this.program = program;
this.executionMode = executionMode;
this.correlationFunctionInfo = correlationFunctionInfo;
}
private void error( OLSyntaxNode node, String message )
{
valid = false;
if ( node != null ) {
ParsingContext context = node.context();
logger.severe( context.sourceName() + ":" + context.line() + ": " + message );
} else {
logger.severe( message );
}
}
private boolean isDefinedBefore( VariablePathNode path )
{
if ( entryTyping.providedVarPaths.contains( path ) || entryTyping.providedCorrPaths.contains( path ) ) {
return true;
}
return false;
}
public boolean check()
{
check( program, new TypingResult() );
typingResult = definitionTyping.get( "main" );
if ( typingResult == null ) {
error( program, "Cannot find the main entry point" );
} else {
checkMainTyping();
}
return valid;
}
private void checkMainTyping()
{
TypingResult initTyping = definitionTyping.get( "init" );
if ( initTyping != null ) {
addInitTypingToMain();
}
for( VariablePathNode path : typingResult.neededCorrPaths ) {
error( path, "Correlation path " + path.toPrettyString() + " is not initialised before usage." );
}
for( VariablePathNode path : typingResult.neededVarPaths ) {
error( path, "Variable " + path.toPrettyString() + " is not initialised before using it to initialise a correlation variable." );
}
VariablePathNode path;
boolean isCorrelationSetFresh;
for( CorrelationSetInfo cset : correlationFunctionInfo.correlationSets() ) {
isCorrelationSetFresh = false;
for( CorrelationVariableInfo cvar : cset.variables() ) {
path = new VariablePathNode( cvar.correlationVariablePath().context(), VariablePathNode.Type.CSET );
path.path().add( new Pair<>(
new ConstantStringExpression( cset.context(), Constants.CSETS ),
new ConstantIntegerExpression( cset.context(), 0 )
) );
path.path().addAll( cvar.correlationVariablePath().path() );
FlaggedVariablePathNode flaggedPath = typingResult.providedCorrPaths.getContained( path );
if ( flaggedPath == null ) { // The two cases could be merged in a single if-then-else condition, but they are logically different.
isCorrelationSetFresh = true; // We can set this because the correlation set is not used at all.
break;
} else if ( flaggedPath.isFresh() ) {
isCorrelationSetFresh = true;
break;
}
}
if ( !isCorrelationSetFresh ) {
error( cset, "Every correlation set must have at least one fresh value (maybe you are not using new?)." );
}
}
}
private void addInitTypingToMain()
{
TypingResult right = typingResult;
typingResult = definitionTyping.get( "init" );
for( VariablePathNode path : right.providedCorrPaths ) {
if ( typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables can not be defined more than one time." );
} else {
typingResult.provide( path );
}
}
for( VariablePathNode path : right.providedVarPaths ) {
typingResult.provide( path );
typingResult.invalidatedVarPaths.remove( path );
}
for( VariablePathNode path : right.neededVarPaths ) {
if ( !typingResult.providedVarPaths.contains( path ) ) {
typingResult.need( path );
}
}
for( VariablePathNode path : right.neededCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
typingResult.need( path );
}
}
typingResult.invalidateAll( right );
}
private TypingResult check( OLSyntaxNode n, TypingResult entryTyping )
{
this.entryTyping = entryTyping;
TypingResult backup = typingResult;
typingResult = new TypingResult();
n.accept( this );
TypingResult ret = typingResult;
typingResult = backup;
return ret;
}
@Override
public void visit( Program n )
{
for( OLSyntaxNode node : n.children() ) {
check( node, new TypingResult() );
}
}
@Override
public void visit( OneWayOperationDeclaration decl )
{}
@Override
public void visit( RequestResponseOperationDeclaration decl )
{}
@Override
public void visit( DefinitionNode n )
{
insideInit = false;
TypingResult entry = null;
switch( n.id() ) {
case "main":
sessionStarter = true;
entry = definitionTyping.get( "init" );
break;
case "init":
insideInit = true;
break;
}
if ( entry == null ) {
entry = new TypingResult();
}
definitionTyping.put( n.id(), check( n.body(), entry ) );
if ( n.id().equals( "init" ) ) {
for( VariablePathNode path : typingResult.providedCorrPaths ) {
error( path, "Correlation variables can not be initialised in the init procedure." );
}
}
}
@Override
public void visit( ParallelStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
TypingResult entry = entryTyping;
typingResult = check( n.children().get( 0 ), entry );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
right = check( n.children().get( i ), entry );
for( VariablePathNode path : right.providedCorrPaths ) {
if ( typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables can not be defined more than one time." );
} else {
typingResult.provide( path );
}
}
typingResult.provideAll( right.providedVarPaths );
typingResult.needAll( right );
typingResult.invalidateAll( right );
typingResult.registerOperations( right );
}
}
@Override
public void visit( SequenceStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
typingResult.provideAll( entryTyping );
typingResult = check( n.children().get( 0 ), typingResult );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
right = check( n.children().get( i ), typingResult );
for( VariablePathNode path : right.providedCorrPaths ) {
if ( typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables can not be defined more than one time." );
} else {
typingResult.provide( path );
}
}
for( VariablePathNode path : right.providedVarPaths ) {
typingResult.provide( path );
typingResult.invalidatedVarPaths.remove( path );
}
for( VariablePathNode path : right.neededVarPaths ) {
if ( !typingResult.providedVarPaths.contains( path ) ) {
typingResult.need( path );
}
}
for( VariablePathNode path : right.neededCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
typingResult.need( path );
}
}
typingResult.invalidateAll( right );
typingResult.registerOperations( right );
}
}
@Override
public void visit( NDChoiceStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
List< TypingResult > branchTypings = new LinkedList<>();
boolean origSessionStarter = sessionStarter;
TypingResult entry = entryTyping;
SequenceStatement seq;
seq = new SequenceStatement( n.context() );
seq.addChild( n.children().get( 0 ).key() );
seq.addChild( n.children().get( 0 ).value() );
typingResult = check( seq, entry );
branchTypings.add( typingResult );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
sessionStarter = origSessionStarter;
seq = new SequenceStatement( n.context() );
seq.addChild( n.children().get( i ).key() );
seq.addChild( n.children().get( i ).value() );
right = check( seq, entry );
branchTypings.add( right );
typingResult.needAll( right );
typingResult.invalidateAll( right );
if ( !origSessionStarter ) {
for( VariablePathNode path : typingResult.providedCorrPaths ) {
if ( !right.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every branch." );
}
}
for( VariablePathNode path : right.providedCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every branch." );
}
}
typingResult.registerOperations( right );
}
typingResult.removeUnsharedProvided( right );
sessionStarter = false;
}
if ( origSessionStarter ) {
for( TypingResult top : branchTypings ) {
for( TypingResult branch : branchTypings ) {
if ( top != branch && branch.sessionOperations.contains( top.startingOperation ) ) {
error( program, "Operation " + top.startingOperation + " can not be used both as a starter and in the body of another session branch." );
}
}
}
}
sessionStarter = false;
}
@Override
public void visit( OneWayOperationStatement n )
{
if ( executionMode == ExecutionMode.SINGLE ) {
return;
}
typingResult.registerOperationInput( n.id(), sessionStarter );
if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) {
error( n, "Input operations can not receive on a correlation variable" );
}
CorrelationSetInfo cset = correlationFunctionInfo.operationCorrelationSetMap().get( n.id() );
if ( !sessionStarter && !insideInit ) {
if ( cset == null || cset.variables().isEmpty() ) {
error( n, "No correlation set defined for operation " + n.id() );
}
}
if ( cset != null ) {
for( CorrelationSetInfo.CorrelationVariableInfo cvar : cset.variables() ) {
VariablePathNode path = new VariablePathNode( cset.context(), VariablePathNode.Type.CSET );
path.path().add(new Pair<>(
new ConstantStringExpression( cset.context(), Constants.CSETS ),
new ConstantIntegerExpression( cset.context(), 0 )
) );
path.path().addAll( cvar.correlationVariablePath().path() );
if ( sessionStarter ) {
typingResult.provide( path, true );
} else {
typingResult.need( path );
}
}
}
sessionStarter = false;
}
@Override
public void visit( RequestResponseOperationStatement n )
{
if ( executionMode == ExecutionMode.SINGLE ) {
return;
}
typingResult.registerOperationInput( n.id(), sessionStarter );
if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) {
error( n, "Input operations can not receive on a correlation variable" );
}
CorrelationSetInfo cset = correlationFunctionInfo.operationCorrelationSetMap().get( n.id() );
if ( !sessionStarter && !insideInit ) {
if ( cset == null || cset.variables().isEmpty() ) {
error( n, "No correlation set defined for operation " + n.id() );
}
}
if ( cset != null ) {
for( CorrelationSetInfo.CorrelationVariableInfo cvar : cset.variables() ) {
VariablePathNode path = new VariablePathNode( cset.context(), VariablePathNode.Type.CSET );
path.path().add(new Pair<>(
new ConstantStringExpression( cset.context(), Constants.CSETS ),
new ConstantIntegerExpression( cset.context(), 0 )
) );
path.path().addAll( cvar.correlationVariablePath().path() );
if ( sessionStarter ) {
typingResult.provide( path, true );
} else {
typingResult.need( path );
}
}
}
sessionStarter = false;
TypingResult internalProcessTyping = check( n.process(), entryTyping );
typingResult.needAll( internalProcessTyping );
typingResult.provideAll( internalProcessTyping );
typingResult.registerOperations( internalProcessTyping );
}
@Override
public void visit( NotificationOperationStatement n )
{}
@Override
public void visit( SolicitResponseOperationStatement n )
{
if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) {
error( n, "Solicit-response statements can not receive on a correlation variable" );
}
}
@Override
public void visit( FreshValueExpressionNode n )
{}
@Override
public void visit( LinkInStatement n )
{}
@Override
public void visit( LinkOutStatement n )
{}
@Override
public void visit( AssignStatement n )
{
if ( n.variablePath().isStatic() ) {
if ( n.expression() instanceof ConstantIntegerExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantDoubleExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantBoolExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantLongExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof ConstantStringExpression ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PostDecrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PostIncrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PreDecrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof PreIncrementStatement ) {
typingResult.provide( n.variablePath() );
} else if ( n.expression() instanceof VariableExpressionNode ) {
VariablePathNode rightPath = ((VariableExpressionNode)n.expression()).variablePath();
if ( rightPath.isStatic() && isDefinedBefore( rightPath ) ) {
typingResult.provide( n.variablePath() );
} else if ( n.variablePath().isCSet() ) {
error( n, "Variable " + rightPath.toPrettyString() + " may be undefined before being used for defining correlation variable " + n.variablePath().toPrettyString() );
}
} else if ( n.expression() instanceof FreshValueExpressionNode ) {
typingResult.provide( n.variablePath(), true );
} else if ( n.variablePath().isCSet() ) {
error( n, "Correlation variables must either be initialised with createSecureToken@SecurityUtils, a variable or a constant." );
}
}
}
@Override
public void visit( AddAssignStatement n )
{}
@Override
public void visit( SubtractAssignStatement n )
{}
@Override
public void visit( MultiplyAssignStatement n )
{}
@Override
public void visit( DivideAssignStatement n )
{}
@Override
public void visit( IfStatement n )
{
if ( n.children().isEmpty() ) {
return;
}
TypingResult entry = entryTyping;
typingResult = check( n.children().get( 0 ).value(), entry );
TypingResult right;
for( int i = 1; i < n.children().size(); i++ ) {
right = check( n.children().get( i ).value(), entry );
typingResult.needAll( right );
typingResult.registerOperations( right );
typingResult.invalidateAll( right );
for( VariablePathNode path : typingResult.providedCorrPaths ) {
if ( !right.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
for( VariablePathNode path : right.providedCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
typingResult.removeUnsharedProvided( right );
}
if ( n.elseProcess() != null ) {
right = check( n.elseProcess(), entry );
typingResult.needAll( right );
typingResult.registerOperations( right );
typingResult.invalidateAll( right );
for( VariablePathNode path : typingResult.providedCorrPaths ) {
if ( !right.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
for( VariablePathNode path : right.providedCorrPaths ) {
if ( !typingResult.providedCorrPaths.contains( path ) ) {
error( path, "Correlation variables must be initialized in every if-then-else branch." );
}
}
typingResult.removeUnsharedProvided( right );
}
}
@Override
public void visit( InstanceOfExpressionNode n )
{}
@Override
public void visit( DefinitionCallStatement n )
{
typingResult = definitionTyping.get( n.id() );
if ( typingResult == null ) {
typingResult = new TypingResult();
error( n, "Can not find definition " + n.id() );
}
}
@Override
public void visit( InlineTreeExpressionNode n )
{}
@Override
public void visit( WhileStatement n )
{
typingResult = check( n.body(), entryTyping );
if ( !typingResult.providedCorrPaths.isEmpty() ) {
error( n, "Initialising correlation variables in while loops is forbidden." );
}
typingResult.providedVarPaths.clear();
}
@Override
public void visit( OrConditionNode n )
{}
@Override
public void visit( AndConditionNode n )
{}
@Override
public void visit( NotExpressionNode n )
{}
@Override
public void visit( CompareConditionNode n )
{}
@Override
public void visit( ConstantIntegerExpression n )
{}
@Override
public void visit( ConstantLongExpression n )
{}
@Override
public void visit( ConstantBoolExpression n )
{}
@Override
public void visit( ConstantDoubleExpression n )
{}
@Override
public void visit( ConstantStringExpression n )
{}
@Override
public void visit( ProductExpressionNode n )
{}
@Override
public void visit( SumExpressionNode n )
{}
@Override
public void visit( VariableExpressionNode n )
{}
@Override
public void visit( NullProcessStatement n )
{}
@Override
public void visit( Scope n )
{
typingResult = check( n.body(), entryTyping );
}
@Override
public void visit( InstallStatement n )
{ // TODO check code inside install
}
@Override
public void visit( CompensateStatement n )
{}
@Override
public void visit( ThrowStatement n )
{}
@Override
public void visit( ExitStatement n )
{}
@Override
public void visit( ExecutionInfo n )
{}
@Override
public void visit( CorrelationSetInfo n )
{}
@Override
public void visit( InputPortInfo n )
{}
@Override
public void visit( OutputPortInfo n )
{}
@Override
public void visit( PointerStatement n )
{
typingResult.invalidate( n.rightPath() );
typingResult.invalidate( n.leftPath() );
}
@Override
public void visit( DeepCopyStatement n )
{
if ( n.rightExpression() instanceof VariableExpressionNode ) {
// TODO: check whether to invalidate all variable paths in other expression cases
typingResult.invalidate( ((VariableExpressionNode) n.rightExpression()).variablePath() );
}
typingResult.invalidate( n.leftPath() );
}
@Override
public void visit( RunStatement n )
{}
@Override
public void visit( UndefStatement n )
{
typingResult.invalidate( n.variablePath() );
}
@Override
public void visit( ValueVectorSizeExpressionNode n )
{}
@Override
public void visit( PreIncrementStatement n )
{}
@Override
public void visit( PostIncrementStatement n )
{}
@Override
public void visit( PreDecrementStatement n )
{}
@Override
public void visit( PostDecrementStatement n )
{}
@Override
public void visit( ForStatement n )
{
typingResult = check( n.body(), entryTyping );
if ( !typingResult.providedCorrPaths.isEmpty() ) {
error( n, "Initialising correlation variables in while loops is forbidden." );
}
typingResult.providedVarPaths.clear();
}
@Override
public void visit( ForEachSubNodeStatement n )
{
typingResult = check( n.body(), entryTyping );
if ( !typingResult.providedCorrPaths.isEmpty() ) {
error( n, "Initialising correlation variables in while loops is forbidden." );
}
typingResult.providedVarPaths.clear();
}
@Override
public void visit( ForEachArrayItemStatement n )
{}
@Override
public void visit( SpawnStatement n )
{}
@Override
public void visit( IsTypeExpressionNode n )
{}
@Override
public void visit( TypeCastExpressionNode n )
{}
@Override
public void visit( SynchronizedStatement n )
{
typingResult = check( n.body(), entryTyping );
}
@Override
public void visit( CurrentHandlerStatement n )
{}
@Override
public void visit( EmbeddedServiceNode n )
{}
@Override
public void visit( InstallFixedVariableExpressionNode n )
{}
@Override
public void visit( VariablePathNode n )
{}
@Override
public void visit( TypeInlineDefinition n )
{}
@Override
public void visit( TypeDefinitionLink n )
{}
@Override
public void visit( InterfaceDefinition n )
{}
@Override
public void visit( DocumentationComment n )
{}
@Override
public void visit( InterfaceExtenderDefinition n ) {}
@Override
public void visit( CourierDefinitionNode n ) {}
@Override
public void visit( CourierChoiceStatement n ) {}
@Override
public void visit( NotificationForwardStatement n ) {}
@Override
public void visit( SolicitResponseForwardStatement n ) {}
@Override
public void visit( VoidExpressionNode n ) {}
@Override
public void visit( ProvideUntilStatement n )
{
n.provide().accept( this );
n.until().accept( this );
}
@Override
public void visit(TypeChoiceDefinition n) {
//todo
}
}
| Update TypeChecker.java (#183)
Former-commit-id: 041f5d9bdb6008aaf6e58a7d98d6a0f2d5e86b96 | libjolie/src/jolie/lang/parse/TypeChecker.java | Update TypeChecker.java (#183) |
|
Java | lgpl-2.1 | e7c0687417d84393e02683cc95d5693d554fb5fd | 0 | exedio/copernica,exedio/copernica,exedio/copernica | /*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope.pattern;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import com.exedio.cope.BooleanAttribute;
import com.exedio.cope.DataAttribute;
import com.exedio.cope.Feature;
import com.exedio.cope.StringAttribute;
import com.exedio.cope.TestmodelTest;
import com.exedio.cope.testmodel.HttpEntityItem;
public class HttpEntityTest extends TestmodelTest
{
// TODO test various combinations of internal, external implicit, and external explicit source
private HttpEntityItem item;
private final byte[] data = new byte[]{-86,122,-8,23};
private final byte[] data2 = new byte[]{-97,35,-126,86,19,-8};
private final byte[] dataEmpty = new byte[]{};
public void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(item = new HttpEntityItem());
}
private void assertExtension(final String mimeMajor, final String mimeMinor, final String extension)
throws IOException
{
item.setFile(stream(data2), mimeMajor, mimeMinor);
assertEquals(mimeMajor, item.getFileMimeMajor());
assertEquals(mimeMinor, item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(extension));
}
public void testData() throws IOException
{
assertEqualsUnmodifiable(Arrays.asList(new Feature[]{
item.file,
item.file.getData(),
item.file.getMimeMajor(),
item.file.getMimeMinor(),
item.image,
item.image.getData(),
item.image.getMimeMinor(),
item.photo,
item.photo.getData(),
item.photo.getExists(),
}), item.TYPE.getFeatures());
// file
assertEquals(null, item.file.getFixedMimeMajor());
assertEquals(null, item.file.getFixedMimeMinor());
final DataAttribute fileData = item.file.getData();
assertSame(item.TYPE, fileData.getType());
assertSame("fileData", fileData.getName());
assertSame(item.file, HttpEntity.get(fileData));
final StringAttribute fileMajor = item.file.getMimeMajor();
assertSame(item.TYPE, fileMajor.getType());
assertEquals("fileMajor", fileMajor.getName());
final StringAttribute fileMinor = item.file.getMimeMinor();
assertSame(item.TYPE, fileMinor.getType());
assertEquals("fileMinor", fileMinor.getName());
assertEquals(null, item.file.getExists());
assertTrue(item.file.isNull(item));
assertEquals(null, item.getFileData());
assertEquals(-1, item.file.getDataLength(item));
assertEquals(-1, item.file.getDataLastModified(item));
assertEquals(null, item.getFileMimeMajor());
assertEquals(null, item.getFileMimeMinor());
assertEquals(null, item.getFileURL());
final Date beforeData = new Date();
item.setFile(stream(data), "fileMajor", "fileMinor");
final Date afterData = new Date();
assertTrue(!item.file.isNull(item));
assertData(data, item.getFileData());
assertEquals(data.length, item.file.getDataLength(item));
assertWithin(1000, beforeData, afterData, new Date(item.file.getDataLastModified(item)));
assertEquals("fileMajor", item.getFileMimeMajor());
assertEquals("fileMinor", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".fileMajor.fileMinor"));
final Date beforeData2 = new Date();
item.setFile(stream(data2), "fileMajor2", "fileMinor2");
final Date afterData2 = new Date();
assertTrue(!item.file.isNull(item));
assertData(data2, item.getFileData());
assertEquals(data2.length, item.file.getDataLength(item));
assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item)));
assertEquals("fileMajor2", item.getFileMimeMajor());
assertEquals("fileMinor2", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".fileMajor2.fileMinor2"));
assertExtension("image", "jpeg", ".jpg");
assertExtension("image", "pjpeg", ".jpg");
assertExtension("image", "png", ".png");
assertExtension("image", "gif", ".gif");
assertExtension("text", "html", ".html");
assertExtension("text", "plain", ".txt");
assertExtension("text", "css", ".css");
final Date beforeDataEmpty = new Date();
item.setFile(stream(dataEmpty), "emptyMajor", "emptyMinor");
final Date afterDataEmpty = new Date();
assertTrue(!item.file.isNull(item));
assertData(dataEmpty, item.getFileData());
assertEquals(0, item.file.getDataLength(item));
assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item)));
assertEquals("emptyMajor", item.getFileMimeMajor());
assertEquals("emptyMinor", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".emptyMajor.emptyMinor"));
item.setFile(null, null, null);
assertTrue(item.file.isNull(item));
assertEquals(-1, item.file.getDataLength(item));
assertEquals(-1, item.file.getDataLastModified(item));
assertEquals(null, item.getFileData());
assertEquals(null, item.getFileMimeMajor());
assertEquals(null, item.getFileMimeMinor());
assertEquals(null, item.getFileURL());
// image
assertEquals("image", item.image.getFixedMimeMajor());
assertEquals(null, item.image.getFixedMimeMinor());
final DataAttribute imageData = item.image.getData();
assertSame(item.TYPE, imageData.getType());
assertSame("imageData", imageData.getName());
assertSame(item.image, HttpEntity.get(imageData));
assertEquals(null, item.image.getMimeMajor());
final StringAttribute imageMinor = item.image.getMimeMinor();
assertSame(item.TYPE, imageMinor.getType());
assertEquals("imageMinor", imageMinor.getName());
assertEquals(null, item.image.getExists());
assertTrue(item.image.isNull(item));
assertEquals(null, item.getImageData());
assertEquals(-1, item.image.getDataLength(item));
assertEquals(null, item.getImageMimeMajor());
assertEquals(null, item.getImageMimeMinor());
assertEquals(null, item.getImageURL());
item.setImage(stream(data), "imageMinor");
assertTrue(!item.image.isNull(item));
assertData(data, item.getImageData());
assertEquals(data.length, item.image.getDataLength(item));
assertEquals("image", item.getImageMimeMajor());
assertEquals("imageMinor", item.getImageMimeMinor());
//System.out.println(item.getImageURL());
assertTrue(item.getImageURL().endsWith(".image.imageMinor"));
item.setImage(stream(data2), "jpeg");
assertTrue(!item.image.isNull(item));
assertData(data2, item.getImageData());
assertEquals(data2.length, item.image.getDataLength(item));
assertEquals("image", item.getImageMimeMajor());
assertEquals("jpeg", item.getImageMimeMinor());
//System.out.println(item.getImageURL());
assertTrue(item.getImageURL().endsWith(".jpg"));
item.setImage(null, null);
assertTrue(item.image.isNull(item));
assertEquals(null, item.getImageData());
assertEquals(-1, item.image.getDataLength(item));
assertEquals(null, item.getImageMimeMajor());
assertEquals(null, item.getImageMimeMinor());
assertEquals(null, item.getImageURL());
// photo
assertEquals("image", item.photo.getFixedMimeMajor());
assertEquals("jpeg", item.photo.getFixedMimeMinor());
final DataAttribute photoData = item.photo.getData();
assertSame(item.TYPE, photoData.getType());
assertSame("photoData", photoData.getName());
assertSame(item.photo, HttpEntity.get(photoData));
assertEquals(null, item.photo.getMimeMajor());
assertEquals(null, item.photo.getMimeMinor());
final BooleanAttribute photoExists = item.photo.getExists();
assertSame(item.TYPE, photoExists.getType());
assertSame("photoExists", photoExists.getName());
assertTrue(item.photo.isNull(item));
assertEquals(null, item.getPhotoData());
assertEquals(-1, item.photo.getDataLength(item));
assertEquals(null, item.getPhotoMimeMajor());
assertEquals(null, item.getPhotoMimeMinor());
assertEquals(null, item.getPhotoURL());
item.setPhoto(stream(data));
assertTrue(!item.photo.isNull(item));
assertData(data, item.getPhotoData());
assertEquals(data.length, item.photo.getDataLength(item));
assertEquals("image", item.getPhotoMimeMajor());
assertEquals("jpeg", item.getPhotoMimeMinor());
//System.out.println(item.getPhotoURL());
assertTrue(item.getPhotoURL().endsWith(".jpg"));
item.setPhoto(stream(data2));
assertTrue(!item.photo.isNull(item));
assertData(data2, item.getPhotoData());
assertEquals(data2.length, item.photo.getDataLength(item));
assertEquals("image", item.getPhotoMimeMajor());
assertEquals("jpeg", item.getPhotoMimeMinor());
//System.out.println(item.getPhotoURL());
assertTrue(item.getPhotoURL().endsWith(".jpg"));
item.setPhoto(null);
assertTrue(item.photo.isNull(item));
assertEquals(null, item.getPhotoData());
assertEquals(-1, item.photo.getDataLength(item));
assertEquals(null, item.getPhotoMimeMajor());
assertEquals(null, item.getPhotoMimeMinor());
assertEquals(null, item.getPhotoURL());
}
}
| lib/testsrc/com/exedio/cope/pattern/HttpEntityTest.java | /*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope.pattern;
import java.io.IOException;
import java.util.Date;
import com.exedio.cope.BooleanAttribute;
import com.exedio.cope.DataAttribute;
import com.exedio.cope.StringAttribute;
import com.exedio.cope.TestmodelTest;
import com.exedio.cope.testmodel.HttpEntityItem;
public class HttpEntityTest extends TestmodelTest
{
// TODO test various combinations of internal, external implicit, and external explicit source
private HttpEntityItem item;
private final byte[] data = new byte[]{-86,122,-8,23};
private final byte[] data2 = new byte[]{-97,35,-126,86,19,-8};
private final byte[] dataEmpty = new byte[]{};
public void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(item = new HttpEntityItem());
}
private void assertExtension(final String mimeMajor, final String mimeMinor, final String extension)
throws IOException
{
item.setFile(stream(data2), mimeMajor, mimeMinor);
assertEquals(mimeMajor, item.getFileMimeMajor());
assertEquals(mimeMinor, item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(extension));
}
public void testData() throws IOException
{
// TODO: test item.TYPE.getPatterns
// file
assertEquals(null, item.file.getFixedMimeMajor());
assertEquals(null, item.file.getFixedMimeMinor());
final DataAttribute fileData = item.file.getData();
assertSame(item.TYPE, fileData.getType());
assertSame("fileData", fileData.getName());
assertSame(item.file, HttpEntity.get(fileData));
final StringAttribute fileMajor = item.file.getMimeMajor();
assertSame(item.TYPE, fileMajor.getType());
assertEquals("fileMajor", fileMajor.getName());
final StringAttribute fileMinor = item.file.getMimeMinor();
assertSame(item.TYPE, fileMinor.getType());
assertEquals("fileMinor", fileMinor.getName());
assertEquals(null, item.file.getExists());
assertTrue(item.file.isNull(item));
assertEquals(null, item.getFileData());
assertEquals(-1, item.file.getDataLength(item));
assertEquals(-1, item.file.getDataLastModified(item));
assertEquals(null, item.getFileMimeMajor());
assertEquals(null, item.getFileMimeMinor());
assertEquals(null, item.getFileURL());
final Date beforeData = new Date();
item.setFile(stream(data), "fileMajor", "fileMinor");
final Date afterData = new Date();
assertTrue(!item.file.isNull(item));
assertData(data, item.getFileData());
assertEquals(data.length, item.file.getDataLength(item));
assertWithin(1000, beforeData, afterData, new Date(item.file.getDataLastModified(item)));
assertEquals("fileMajor", item.getFileMimeMajor());
assertEquals("fileMinor", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".fileMajor.fileMinor"));
final Date beforeData2 = new Date();
item.setFile(stream(data2), "fileMajor2", "fileMinor2");
final Date afterData2 = new Date();
assertTrue(!item.file.isNull(item));
assertData(data2, item.getFileData());
assertEquals(data2.length, item.file.getDataLength(item));
assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item)));
assertEquals("fileMajor2", item.getFileMimeMajor());
assertEquals("fileMinor2", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".fileMajor2.fileMinor2"));
assertExtension("image", "jpeg", ".jpg");
assertExtension("image", "pjpeg", ".jpg");
assertExtension("image", "png", ".png");
assertExtension("image", "gif", ".gif");
assertExtension("text", "html", ".html");
assertExtension("text", "plain", ".txt");
assertExtension("text", "css", ".css");
final Date beforeDataEmpty = new Date();
item.setFile(stream(dataEmpty), "emptyMajor", "emptyMinor");
final Date afterDataEmpty = new Date();
assertTrue(!item.file.isNull(item));
assertData(dataEmpty, item.getFileData());
assertEquals(0, item.file.getDataLength(item));
assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item)));
assertEquals("emptyMajor", item.getFileMimeMajor());
assertEquals("emptyMinor", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".emptyMajor.emptyMinor"));
item.setFile(null, null, null);
assertTrue(item.file.isNull(item));
assertEquals(-1, item.file.getDataLength(item));
assertEquals(-1, item.file.getDataLastModified(item));
assertEquals(null, item.getFileData());
assertEquals(null, item.getFileMimeMajor());
assertEquals(null, item.getFileMimeMinor());
assertEquals(null, item.getFileURL());
// image
assertEquals("image", item.image.getFixedMimeMajor());
assertEquals(null, item.image.getFixedMimeMinor());
final DataAttribute imageData = item.image.getData();
assertSame(item.TYPE, imageData.getType());
assertSame("imageData", imageData.getName());
assertSame(item.image, HttpEntity.get(imageData));
assertEquals(null, item.image.getMimeMajor());
final StringAttribute imageMinor = item.image.getMimeMinor();
assertSame(item.TYPE, imageMinor.getType());
assertEquals("imageMinor", imageMinor.getName());
assertEquals(null, item.image.getExists());
assertTrue(item.image.isNull(item));
assertEquals(null, item.getImageData());
assertEquals(-1, item.image.getDataLength(item));
assertEquals(null, item.getImageMimeMajor());
assertEquals(null, item.getImageMimeMinor());
assertEquals(null, item.getImageURL());
item.setImage(stream(data), "imageMinor");
assertTrue(!item.image.isNull(item));
assertData(data, item.getImageData());
assertEquals(data.length, item.image.getDataLength(item));
assertEquals("image", item.getImageMimeMajor());
assertEquals("imageMinor", item.getImageMimeMinor());
//System.out.println(item.getImageURL());
assertTrue(item.getImageURL().endsWith(".image.imageMinor"));
item.setImage(stream(data2), "jpeg");
assertTrue(!item.image.isNull(item));
assertData(data2, item.getImageData());
assertEquals(data2.length, item.image.getDataLength(item));
assertEquals("image", item.getImageMimeMajor());
assertEquals("jpeg", item.getImageMimeMinor());
//System.out.println(item.getImageURL());
assertTrue(item.getImageURL().endsWith(".jpg"));
item.setImage(null, null);
assertTrue(item.image.isNull(item));
assertEquals(null, item.getImageData());
assertEquals(-1, item.image.getDataLength(item));
assertEquals(null, item.getImageMimeMajor());
assertEquals(null, item.getImageMimeMinor());
assertEquals(null, item.getImageURL());
// photo
assertEquals("image", item.photo.getFixedMimeMajor());
assertEquals("jpeg", item.photo.getFixedMimeMinor());
final DataAttribute photoData = item.photo.getData();
assertSame(item.TYPE, photoData.getType());
assertSame("photoData", photoData.getName());
assertSame(item.photo, HttpEntity.get(photoData));
assertEquals(null, item.photo.getMimeMajor());
assertEquals(null, item.photo.getMimeMinor());
final BooleanAttribute photoExists = item.photo.getExists();
assertSame(item.TYPE, photoExists.getType());
assertSame("photoExists", photoExists.getName());
assertTrue(item.photo.isNull(item));
assertEquals(null, item.getPhotoData());
assertEquals(-1, item.photo.getDataLength(item));
assertEquals(null, item.getPhotoMimeMajor());
assertEquals(null, item.getPhotoMimeMinor());
assertEquals(null, item.getPhotoURL());
item.setPhoto(stream(data));
assertTrue(!item.photo.isNull(item));
assertData(data, item.getPhotoData());
assertEquals(data.length, item.photo.getDataLength(item));
assertEquals("image", item.getPhotoMimeMajor());
assertEquals("jpeg", item.getPhotoMimeMinor());
//System.out.println(item.getPhotoURL());
assertTrue(item.getPhotoURL().endsWith(".jpg"));
item.setPhoto(stream(data2));
assertTrue(!item.photo.isNull(item));
assertData(data2, item.getPhotoData());
assertEquals(data2.length, item.photo.getDataLength(item));
assertEquals("image", item.getPhotoMimeMajor());
assertEquals("jpeg", item.getPhotoMimeMinor());
//System.out.println(item.getPhotoURL());
assertTrue(item.getPhotoURL().endsWith(".jpg"));
item.setPhoto(null);
assertTrue(item.photo.isNull(item));
assertEquals(null, item.getPhotoData());
assertEquals(-1, item.photo.getDataLength(item));
assertEquals(null, item.getPhotoMimeMajor());
assertEquals(null, item.getPhotoMimeMinor());
assertEquals(null, item.getPhotoURL());
}
}
| test Type#getFeatures()
git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@2968 e7d4fc99-c606-0410-b9bf-843393a9eab7
| lib/testsrc/com/exedio/cope/pattern/HttpEntityTest.java | test Type#getFeatures() |
|
Java | apache-2.0 | 19a7f1a2df0a88e6c2328fcf364e7734cf430b54 | 0 | fhoeben/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures,fhoeben/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures,fhoeben/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures,fhoeben/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures | package nl.hsac.fitnesse.fixture.slim;
import fitnesse.slim.Converter;
import fitnesse.slim.converters.ConverterRegistry;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MapOfMapsFixture extends SlimTableFixture {
private Map<String, Map<String, Object>> maps;
public MapOfMapsFixture() {
this(true);
}
public MapOfMapsFixture(boolean expandPeriodsInNamesToNestedMaps) {
expandPeriodsInNamesToNestedMaps(expandPeriodsInNamesToNestedMaps);
}
@Override
protected List<List<String>> doTableImpl(List<List<String>> table) {
int numberOfRows = table.size();
List<List<String>> result = new ArrayList<>(numberOfRows);
if (!table.isEmpty()) {
List<String> header = table.get(0);
int colCount = header.size();
maps = new LinkedHashMap<>();
for (List<String> row : table) {
int rowCounter = result.size();
List<String> resultRow = new ArrayList<>(colCount);
if (rowCounter == 0) {
handleHeader(resultRow, header);
} else if (rowCounter == numberOfRows - 1) {
handleBottomRow(resultRow, header, row);
} else {
handleRow(resultRow, header, row);
}
result.add(resultRow);
}
}
return result;
}
protected Map<String, Map<String, Object>> getMaps() {
return maps;
}
protected void handleHeader(List<String> resultRow, List<String> header) {
for (int i = 1; i < header.size(); i++) {
String headerCell = header.get(i);
maps.put(headerCell, new LinkedHashMap<>());
}
}
protected void handleBottomRow(List<String> resultRow, List<String> header, List<String> row) {
String firstCell = row.get(0);
if (StringUtils.isEmpty(firstCell)) {
resultRow.add("");
} else if (assignSymbolIfApplicable(firstCell, maps)) {
resultRow.add("pass");
}
if (resultRow.isEmpty()) {
handleRow(resultRow, header, row);
} else {
for (int i = 1; i < header.size() && i < row.size(); i++) {
String cell = row.get(i);
String columnName = header.get(i);
Map<String, Object> map = maps.get(columnName);
if (assignSymbolIfApplicable(cell, map)) {
resultRow.add("pass");
} else {
resultRow.add("fail:expected symbol assignment");
}
}
}
}
protected void handleRow(List<String> resultRow, List<String> header, List<String> row) {
String key = null;
for (int i = 0; i < row.size(); i++) {
if (i == 0) {
key = row.get(i);
} else {
String headerCell = header.get(i);
Map<String, Object> map = maps.get(headerCell);
String cell = row.get(i);
cell = replaceSymbolsInString(cell);
Object value = parseValue(cell);
getMapHelper().setValueForIn(value, key, map);
}
}
}
protected Object parseValue(String cell) {
Object result = cell;
try {
Converter<Map> converter = getConverter(cell);
if (converter != null) {
result = converter.fromString(cell);
}
} catch (Throwable t) {
System.err.println("Unable to parse cell value: " + cell);
t.printStackTrace();
}
return result;
}
protected Converter<Map> getConverter(String cell) {
Converter<Map> converter = null;
if (cell.startsWith("<table class=\"hash_table\">")
&& cell.endsWith("</table>")) {
converter = ConverterRegistry.getConverterForClass(Map.class);
}
return converter;
}
}
| src/main/java/nl/hsac/fitnesse/fixture/slim/MapOfMapsFixture.java | package nl.hsac.fitnesse.fixture.slim;
import fitnesse.slim.Converter;
import fitnesse.slim.converters.ConverterRegistry;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MapOfMapsFixture extends SlimTableFixture {
private Map<String, Map<String, Object>> maps;
public MapOfMapsFixture() {
this(true);
}
public MapOfMapsFixture(boolean expandPeriodsInNamesToNestedMaps) {
expandPeriodsInNamesToNestedMaps(expandPeriodsInNamesToNestedMaps);
}
@Override
protected List<List<String>> doTableImpl(List<List<String>> table) {
int numberOfRows = table.size();
List<List<String>> result = new ArrayList<>(numberOfRows);
if (!table.isEmpty()) {
List<String> header = table.get(0);
int colCount = header.size();
maps = new LinkedHashMap<>();
for (List<String> row : table) {
int rowCounter = result.size();
List<String> resultRow = new ArrayList<>(colCount);
if (rowCounter == 0) {
handleHeader(resultRow, header);
} else if (rowCounter == numberOfRows - 1) {
handleBottomRow(resultRow, header, row);
} else {
handleRow(resultRow, header, row);
}
result.add(resultRow);
}
}
return result;
}
protected void handleHeader(List<String> resultRow, List<String> header) {
for (int i = 1; i < header.size(); i++) {
String headerCell = header.get(i);
maps.put(headerCell, new LinkedHashMap<>());
}
}
protected void handleBottomRow(List<String> resultRow, List<String> header, List<String> row) {
String firstCell = row.get(0);
if (StringUtils.isEmpty(firstCell)) {
resultRow.add("");
} else if (assignSymbolIfApplicable(firstCell, maps)) {
resultRow.add("pass");
}
if (resultRow.isEmpty()) {
handleRow(resultRow, header, row);
} else {
for (int i = 1; i < header.size() && i < row.size(); i++) {
String cell = row.get(i);
String columnName = header.get(i);
Map<String, Object> map = maps.get(columnName);
if (assignSymbolIfApplicable(cell, map)) {
resultRow.add("pass");
} else {
resultRow.add("fail:expected symbol assignment");
}
}
}
}
protected void handleRow(List<String> resultRow, List<String> header, List<String> row) {
String key = null;
for (int i = 0; i < row.size(); i++) {
if (i == 0) {
key = row.get(i);
} else {
String headerCell = header.get(i);
Map<String, Object> map = maps.get(headerCell);
String cell = row.get(i);
cell = replaceSymbolsInString(cell);
Object value = parseValue(cell);
getMapHelper().setValueForIn(value, key, map);
}
}
}
protected Object parseValue(String cell) {
Object result = cell;
try {
Converter<Map> converter = getConverter(cell);
if (converter != null) {
result = converter.fromString(cell);
}
} catch (Throwable t) {
System.err.println("Unable to parse cell value: " + cell);
t.printStackTrace();
}
return result;
}
protected Converter<Map> getConverter(String cell) {
Converter<Map> converter = null;
if (cell.startsWith("<table class=\"hash_table\">")
&& cell.endsWith("</table>")) {
converter = ConverterRegistry.getConverterForClass(Map.class);
}
return converter;
}
}
| Allow subclass access to maps
| src/main/java/nl/hsac/fitnesse/fixture/slim/MapOfMapsFixture.java | Allow subclass access to maps |
|
Java | apache-2.0 | 782e9447698a5b197dbe1e2d5bcd32e61e912f29 | 0 | ngaut/omid,satishpatil2k13/HBASE_OMID,satishpatil2k13/Alan_Gates-OMID-HBase,yonigottesman/incubator-omid,ngaut/omid,satishpatil2k13/HBASE_OMID,yahoo/omid,satishpatil2k13/Alan_Gates-OMID-HBase,yonigottesman/incubator-omid,yahoo/omid | /**
* Copyright (c) 2011 Yahoo! 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.yahoo.omid.tso;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yahoo.omid.replication.SharedMessageBuffer.ReadingBuffer;
import com.yahoo.omid.tso.messages.AbortRequest;
import com.yahoo.omid.tso.messages.AbortedTransactionReport;
import com.yahoo.omid.tso.messages.CommitQueryRequest;
import com.yahoo.omid.tso.messages.CommitQueryResponse;
import com.yahoo.omid.tso.messages.CommitRequest;
import com.yahoo.omid.tso.messages.CommitResponse;
import com.yahoo.omid.tso.messages.FullAbortRequest;
import com.yahoo.omid.tso.messages.LargestDeletedTimestampReport;
import com.yahoo.omid.tso.messages.TimestampRequest;
import com.yahoo.omid.tso.messages.TimestampResponse;
import com.yahoo.omid.tso.metrics.StatusOracleMetrics;
import com.yahoo.omid.tso.persistence.LoggerAsyncCallback.AddRecordCallback;
import com.yahoo.omid.tso.persistence.LoggerException;
import com.yahoo.omid.tso.persistence.LoggerException.Code;
import com.yahoo.omid.tso.persistence.LoggerProtocol;
import com.yammer.metrics.core.TimerContext;
/**
* ChannelHandler for the TSO Server
*/
public class TSOHandler extends SimpleChannelHandler {
private static final Log LOG = LogFactory.getLog(TSOHandler.class);
/**
* Bytes monitor
*/
public static final AtomicInteger transferredBytes = new AtomicInteger();
// public static int transferredBytes = 0;
public static int abortCount = 0;
public static int hitCount = 0;
public static long queries = 0;
/**
* Channel Group
*/
private ChannelGroup channelGroup = null;
private Map<Channel, ReadingBuffer> messageBuffersMap = new HashMap<Channel, ReadingBuffer>();
/**
* Timestamp Oracle
*/
private TimestampOracle timestampOracle = null;
/**
* The wrapper for the shared state of TSO
*/
private TSOState sharedState;
private StatusOracleMetrics metrics;
private FlushThread flushThread;
private ScheduledExecutorService scheduledExecutor;
private ScheduledFuture<?> flushFuture;
private ExecutorService executor;
/**
* Constructor
*
* @param channelGroup
*/
public TSOHandler(ChannelGroup channelGroup, TSOState state) {
this.channelGroup = channelGroup;
this.timestampOracle = state.getSO();
this.sharedState = state;
this.metrics = new StatusOracleMetrics();
}
public void start() {
this.flushThread = new FlushThread();
this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
t.setDaemon(true);
t.setName("flusher");
return t;
}
});
this.flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
this.executor = Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("aborts-snapshotter").build());
}
/**
* Returns the number of transferred bytes
*
* @return the number of transferred bytes
*/
public static long getTransferredBytes() {
return transferredBytes.longValue();
}
/**
* If write of a message was not possible before, we can do it here
*/
@Override
public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) {
}
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channelGroup.add(ctx.getChannel());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
synchronized (sharedMsgBufLock) {
sharedState.sharedMessageBuffer.removeReadingBuffer(ctx);
}
}
/**
* Handle receieved messages
*/
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
Object msg = e.getMessage();
if (msg instanceof TimestampRequest) {
handle((TimestampRequest) msg, ctx);
return;
} else if (msg instanceof CommitRequest) {
handle((CommitRequest) msg, ctx);
return;
} else if (msg instanceof AbortRequest) {
handle((AbortRequest) msg, ctx);
return;
} else if (msg instanceof FullAbortRequest) {
handle((FullAbortRequest) msg, ctx);
return;
} else if (msg instanceof CommitQueryRequest) {
handle((CommitQueryRequest) msg, ctx);
return;
}
}
public void handle(AbortRequest msg, ChannelHandlerContext ctx) {
synchronized (sharedState) {
if (msg.startTimestamp < sharedState.largestDeletedTimestamp) {
LOG.warn("Too old starttimestamp, already aborted: ST " + msg.startTimestamp + " MAX "
+ sharedState.largestDeletedTimestamp);
return;
}
if (!sharedState.uncommited.isUncommitted(msg.startTimestamp)) {
long commitTS = sharedState.hashmap.getCommittedTimestamp(msg.startTimestamp);
if (commitTS == 0) {
LOG.error("Transaction " + msg.startTimestamp + " has already been aborted");
} else {
LOG.error("Transaction " + msg.startTimestamp + " has already been committed with ts " + commitTS);
}
return; // TODO something better to do?
}
DataOutputStream toWAL = sharedState.toWAL;
try {
toWAL.writeByte(LoggerProtocol.ABORT);
toWAL.writeLong(msg.startTimestamp);
} catch (IOException e) {
e.printStackTrace();
}
abortCount++;
metrics.selfAborted();
sharedState.processAbort(msg.startTimestamp);
synchronized (sharedMsgBufLock) {
queueHalfAbort(msg.startTimestamp);
}
}
}
/**
* Handle the TimestampRequest message
*/
public void handle(TimestampRequest msg, ChannelHandlerContext ctx) {
metrics.begin();
TimerContext timer = metrics.startBeginProcessing();
long timestamp;
synchronized (sharedState) {
try {
timestamp = timestampOracle.next(sharedState.toWAL);
sharedState.uncommited.start(timestamp);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
ReadingBuffer buffer;
Channel channel = ctx.getChannel();
boolean bootstrap = false;
synchronized (messageBuffersMap) {
buffer = messageBuffersMap.get(ctx.getChannel());
if (buffer == null) {
synchronized (sharedMsgBufLock) {
bootstrap = true;
buffer = sharedState.sharedMessageBuffer.getReadingBuffer(ctx);
messageBuffersMap.put(channel, buffer);
channelGroup.add(channel);
LOG.warn("Channel connected: " + messageBuffersMap.size());
}
}
}
if (bootstrap) {
synchronized (sharedState) {
synchronized (sharedMsgBufLock) {
channel.write(buffer.getZipperState());
buffer.initializeIndexes();
}
}
channel.write(new LargestDeletedTimestampReport(sharedState.largestDeletedTimestamp));
for (AbortedTransaction halfAborted : sharedState.hashmap.halfAborted) {
channel.write(new AbortedTransactionReport(halfAborted.getStartTimestamp()));
}
}
ChannelBuffer cb;
ChannelFuture future = Channels.future(channel);
synchronized (sharedMsgBufLock) {
cb = buffer.flush(future);
}
Channels.write(ctx, future, cb);
Channels.write(channel, new TimestampResponse(timestamp));
timer.stop();
}
ChannelBuffer cb = ChannelBuffers.buffer(10);
private volatile boolean finish;
public static long waitTime = 0;
public static long commitTime = 0;
public static long checkTime = 0;
private Object sharedMsgBufLock = new Object();
private Object callbackLock = new Object();
private AddRecordCallback noCallback = new AddRecordCallback() {
@Override
public void addRecordComplete(int rc, Object ctx) {
}
};
private Runnable createAbortedSnaphostTask = new Runnable() {
@Override
public void run() {
createAbortedSnapshot();
}
};
public void createAbortedSnapshot() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream toWAL = new DataOutputStream(baos);
long snapshot = sharedState.hashmap.getAndIncrementAbortedSnapshot();
try {
toWAL.writeByte(LoggerProtocol.SNAPSHOT);
toWAL.writeLong(snapshot);
for (AbortedTransaction aborted : sharedState.hashmap.halfAborted) {
// ignore aborted transactions from last snapshot
if (aborted.getSnapshot() < snapshot) {
toWAL.writeByte(LoggerProtocol.ABORT);
toWAL.writeLong(aborted.getStartTimestamp());
}
}
} catch (IOException e) {
// can't happen
throw new RuntimeException(e);
}
sharedState.addRecord(baos.toByteArray(), noCallback, null);
}
/**
* Handle the CommitRequest message
*/
public void handle(CommitRequest msg, ChannelHandlerContext ctx) {
TimerContext timerProcessing = metrics.startCommitProcessing();
TimerContext timerLatency = metrics.startCommitLatency();
CommitResponse reply = new CommitResponse(msg.startTimestamp);
ByteArrayOutputStream baos = sharedState.baos;
DataOutputStream toWAL = sharedState.toWAL;
synchronized (sharedState) {
// 0. check if it should abort
if (msg.startTimestamp < timestampOracle.first()) {
reply.committed = false;
LOG.warn("Aborting transaction after restarting TSO");
} else if (msg.startTimestamp <= sharedState.largestDeletedTimestamp) {
if (msg.rows.length == 0) {
// read only, it has already been put in half aborted list
// we let it commit, but we mark it as fully aborted
// since it is read only, it doesn't matter
processFullAbort(msg.startTimestamp);
} else {
// Too old
reply.committed = false;// set as abort
LOG.warn("Too old starttimestamp: ST " + msg.startTimestamp + " MAX "
+ sharedState.largestDeletedTimestamp);
}
} else if (!sharedState.uncommited.isUncommitted(msg.startTimestamp)) {
long commitTS = sharedState.hashmap.getCommittedTimestamp(msg.startTimestamp);
if (commitTS == 0) {
LOG.error("Transaction " + msg.startTimestamp + " has already been aborted");
} else {
LOG.error("Transaction " + msg.startTimestamp + " has already been committed with ts " + commitTS);
}
return; // TODO something better to do?
} else {
// 1. check the write-write conflicts
for (RowKey r : msg.rows) {
long value;
value = sharedState.hashmap.getLatestWriteForRow(r.hashCode());
if (value != 0 && value > msg.startTimestamp) {
reply.committed = false;// set as abort
break;
} else if (value == 0 && sharedState.largestDeletedTimestamp > msg.startTimestamp) {
// then it could have been committed after start
// timestamp but deleted by recycling
LOG.warn("Old transaction {Start timestamp " + msg.startTimestamp
+ "} {Largest deleted timestamp " + sharedState.largestDeletedTimestamp + "}");
reply.committed = false;// set as abort
break;
}
}
}
if (reply.committed) {
metrics.commited();
// 2. commit
try {
long commitTimestamp = timestampOracle.next(toWAL);
sharedState.uncommited.commit(msg.startTimestamp);
reply.commitTimestamp = commitTimestamp;
if (msg.rows.length > 0) {
if (LOG.isTraceEnabled()) {
LOG.trace("Adding commit to WAL");
}
toWAL.writeByte(LoggerProtocol.COMMIT);
toWAL.writeLong(msg.startTimestamp);
toWAL.writeLong(commitTimestamp);
long oldLargestDeletedTimestamp = sharedState.largestDeletedTimestamp;
for (RowKey r : msg.rows) {
sharedState.hashmap.putLatestWriteForRow(r.hashCode(), commitTimestamp);
}
sharedState.largestDeletedTimestamp = sharedState.hashmap.getLargestDeletedTimestamp();
sharedState.processCommit(msg.startTimestamp, commitTimestamp);
if (sharedState.largestDeletedTimestamp > oldLargestDeletedTimestamp) {
toWAL.writeByte(LoggerProtocol.LARGESTDELETEDTIMESTAMP);
toWAL.writeLong(sharedState.largestDeletedTimestamp);
Set<Long> toAbort = sharedState.uncommited
.raiseLargestDeletedTransaction(sharedState.largestDeletedTimestamp);
if (LOG.isWarnEnabled() && !toAbort.isEmpty()) {
LOG.warn("Slow transactions after raising max: " + toAbort.size());
}
metrics.oldAborted(toAbort.size());
synchronized (sharedMsgBufLock) {
for (Long id : toAbort) {
sharedState.addExistingAbort(id);
queueHalfAbort(id);
}
queueLargestIncrease(sharedState.largestDeletedTimestamp);
}
}
if (sharedState.largestDeletedTimestamp > sharedState.previousLargestDeletedTimestamp
+ TSOState.MAX_ITEMS) {
// schedule snapshot
executor.submit(createAbortedSnaphostTask);
sharedState.previousLargestDeletedTimestamp = sharedState.largestDeletedTimestamp;
}
synchronized (sharedMsgBufLock) {
queueCommit(msg.startTimestamp, commitTimestamp);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else { // add it to the aborted list
abortCount++;
metrics.aborted();
try {
toWAL.writeByte(LoggerProtocol.ABORT);
toWAL.writeLong(msg.startTimestamp);
} catch (IOException e) {
e.printStackTrace();
}
sharedState.processAbort(msg.startTimestamp);
synchronized (sharedMsgBufLock) {
queueHalfAbort(msg.startTimestamp);
}
}
TSOHandler.transferredBytes.incrementAndGet();
ChannelandMessage cam = new ChannelandMessage(ctx, reply, timerLatency);
sharedState.nextBatch.add(cam);
if (sharedState.baos.size() >= TSOState.BATCH_SIZE) {
if (LOG.isTraceEnabled()) {
LOG.trace("Going to add record of size " + sharedState.baos.size());
}
// sharedState.lh.asyncAddEntry(baos.toByteArray(), this,
// sharedState.nextBatch);
sharedState.addRecord(baos.toByteArray(), new AddRecordCallback() {
@Override
public void addRecordComplete(int rc, Object ctx) {
if (rc != Code.OK) {
LOG.warn("Write failed: " + LoggerException.getMessage(rc));
} else {
synchronized (callbackLock) {
@SuppressWarnings("unchecked")
ArrayList<ChannelandMessage> theBatch = (ArrayList<ChannelandMessage>) ctx;
for (ChannelandMessage cam : theBatch) {
Channels.write(cam.ctx, Channels.succeededFuture(cam.ctx.getChannel()), cam.msg);
cam.timer.stop();
}
}
}
}
}, sharedState.nextBatch);
sharedState.nextBatch = new ArrayList<ChannelandMessage>(sharedState.nextBatch.size() + 5);
sharedState.baos.reset();
}
}
timerProcessing.stop();
}
/**
* Handle the CommitQueryRequest message
*/
public void handle(CommitQueryRequest msg, ChannelHandlerContext ctx) {
metrics.query();
CommitQueryResponse reply = new CommitQueryResponse(msg.startTimestamp);
reply.queryTimestamp = msg.queryTimestamp;
synchronized (sharedState) {
queries++;
// 1. check the write-write conflicts
long value;
value = sharedState.hashmap.getCommittedTimestamp(msg.queryTimestamp);
if (value != 0) { // it exists
reply.commitTimestamp = value;
reply.committed = value < msg.startTimestamp;// set as abort
} else if (sharedState.hashmap.isHalfAborted(msg.queryTimestamp))
reply.committed = false;
else if (sharedState.uncommited.isUncommitted(msg.queryTimestamp))
reply.committed = false;
else
reply.retry = true;
// else if (sharedState.largestDeletedTimestamp >=
// msg.queryTimestamp)
// reply.committed = true;
// TODO retry needed? isnt it just fully aborted?
ctx.getChannel().write(reply);
// We send the message directly. If after a failure the state is
// inconsistent we'll detect it
}
}
public void flush() {
synchronized (sharedState) {
if (LOG.isTraceEnabled()) {
LOG.trace("Adding record, size: " + sharedState.baos.size());
}
sharedState.addRecord(sharedState.baos.toByteArray(), new AddRecordCallback() {
@Override
public void addRecordComplete(int rc, Object ctx) {
if (rc != Code.OK) {
LOG.warn("Write failed: " + LoggerException.getMessage(rc));
} else {
synchronized (callbackLock) {
@SuppressWarnings("unchecked")
ArrayList<ChannelandMessage> theBatch = (ArrayList<ChannelandMessage>) ctx;
for (ChannelandMessage cam : theBatch) {
Channels.write(cam.ctx, Channels.succeededFuture(cam.ctx.getChannel()), cam.msg);
cam.timer.stop();
}
}
}
}
}, sharedState.nextBatch);
sharedState.nextBatch = new ArrayList<ChannelandMessage>(sharedState.nextBatch.size() + 5);
sharedState.baos.reset();
if (flushFuture.cancel(false)) {
flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
}
}
}
public class FlushThread implements Runnable {
@Override
public void run() {
if (finish) {
return;
}
if (sharedState.nextBatch.size() > 0) {
synchronized (sharedState) {
if (sharedState.nextBatch.size() > 0) {
if (LOG.isTraceEnabled()) {
LOG.trace("Flushing log batch.");
}
flush();
}
}
}
flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
}
}
private void queueCommit(long startTimestamp, long commitTimestamp) {
sharedState.sharedMessageBuffer.writeCommit(startTimestamp, commitTimestamp);
}
private void queueHalfAbort(long startTimestamp) {
sharedState.sharedMessageBuffer.writeHalfAbort(startTimestamp);
}
private void queueFullAbort(long startTimestamp) {
sharedState.sharedMessageBuffer.writeFullAbort(startTimestamp);
}
private void queueLargestIncrease(long largestTimestamp) {
sharedState.sharedMessageBuffer.writeLargestIncrease(largestTimestamp);
}
/**
* Handle the FullAbortReport message
*/
public void handle(FullAbortRequest msg, ChannelHandlerContext ctx) {
processFullAbort(msg.startTimestamp);
}
private void processFullAbort(long timestamp) {
synchronized (sharedState) {
DataOutputStream toWAL = sharedState.toWAL;
try {
toWAL.writeByte(LoggerProtocol.FULLABORT);
toWAL.writeLong(timestamp);
} catch (IOException e) {
LOG.error("Unexpected exception while writing to WAL", e);
}
metrics.cleanedAbort();
sharedState.processFullAbort(timestamp);
}
synchronized (sharedMsgBufLock) {
queueFullAbort(timestamp);
}
}
/*
* Wrapper for Channel and Message
*/
public static class ChannelandMessage {
ChannelHandlerContext ctx;
TSOMessage msg;
TimerContext timer;
ChannelandMessage(ChannelHandlerContext c, TSOMessage m, TimerContext t) {
ctx = c;
msg = m;
timer = t;
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
LOG.warn("TSOHandler: Unexpected exception from downstream.", e.getCause());
Channels.close(e.getChannel());
}
public void stop() {
finish = true;
scheduledExecutor.shutdown();
executor.shutdown();
}
}
| src/main/java/com/yahoo/omid/tso/TSOHandler.java | /**
* Copyright (c) 2011 Yahoo! 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.yahoo.omid.tso;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yahoo.omid.replication.SharedMessageBuffer.ReadingBuffer;
import com.yahoo.omid.tso.messages.AbortRequest;
import com.yahoo.omid.tso.messages.AbortedTransactionReport;
import com.yahoo.omid.tso.messages.CommitQueryRequest;
import com.yahoo.omid.tso.messages.CommitQueryResponse;
import com.yahoo.omid.tso.messages.CommitRequest;
import com.yahoo.omid.tso.messages.CommitResponse;
import com.yahoo.omid.tso.messages.FullAbortRequest;
import com.yahoo.omid.tso.messages.LargestDeletedTimestampReport;
import com.yahoo.omid.tso.messages.TimestampRequest;
import com.yahoo.omid.tso.messages.TimestampResponse;
import com.yahoo.omid.tso.metrics.StatusOracleMetrics;
import com.yahoo.omid.tso.persistence.LoggerAsyncCallback.AddRecordCallback;
import com.yahoo.omid.tso.persistence.LoggerException;
import com.yahoo.omid.tso.persistence.LoggerException.Code;
import com.yahoo.omid.tso.persistence.LoggerProtocol;
import com.yammer.metrics.core.TimerContext;
/**
* ChannelHandler for the TSO Server
*/
public class TSOHandler extends SimpleChannelHandler {
private static final Log LOG = LogFactory.getLog(TSOHandler.class);
/**
* Bytes monitor
*/
public static final AtomicInteger transferredBytes = new AtomicInteger();
// public static int transferredBytes = 0;
public static int abortCount = 0;
public static int hitCount = 0;
public static long queries = 0;
/**
* Channel Group
*/
private ChannelGroup channelGroup = null;
private Map<Channel, ReadingBuffer> messageBuffersMap = new HashMap<Channel, ReadingBuffer>();
/**
* Timestamp Oracle
*/
private TimestampOracle timestampOracle = null;
/**
* The wrapper for the shared state of TSO
*/
private TSOState sharedState;
private StatusOracleMetrics metrics;
private FlushThread flushThread;
private ScheduledExecutorService scheduledExecutor;
private ScheduledFuture<?> flushFuture;
private ExecutorService executor;
/**
* Constructor
*
* @param channelGroup
*/
public TSOHandler(ChannelGroup channelGroup, TSOState state) {
this.channelGroup = channelGroup;
this.timestampOracle = state.getSO();
this.sharedState = state;
this.metrics = new StatusOracleMetrics();
}
public void start() {
this.flushThread = new FlushThread();
this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
t.setDaemon(true);
t.setName("flusher");
return t;
}
});
this.flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
this.executor = Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("aborts-snapshotter").build());
}
/**
* Returns the number of transferred bytes
*
* @return the number of transferred bytes
*/
public static long getTransferredBytes() {
return transferredBytes.longValue();
}
/**
* If write of a message was not possible before, we can do it here
*/
@Override
public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) {
}
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channelGroup.add(ctx.getChannel());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
synchronized (sharedMsgBufLock) {
sharedState.sharedMessageBuffer.removeReadingBuffer(ctx);
}
}
/**
* Handle receieved messages
*/
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
Object msg = e.getMessage();
if (msg instanceof TimestampRequest) {
handle((TimestampRequest) msg, ctx);
return;
} else if (msg instanceof CommitRequest) {
handle((CommitRequest) msg, ctx);
return;
} else if (msg instanceof AbortRequest) {
handle((AbortRequest) msg, ctx);
return;
} else if (msg instanceof FullAbortRequest) {
handle((FullAbortRequest) msg, ctx);
return;
} else if (msg instanceof CommitQueryRequest) {
handle((CommitQueryRequest) msg, ctx);
return;
}
}
public void handle(AbortRequest msg, ChannelHandlerContext ctx) {
synchronized (sharedState) {
if (!sharedState.uncommited.isUncommitted(msg.startTimestamp)) {
long commitTS = sharedState.hashmap.getCommittedTimestamp(msg.startTimestamp);
if (commitTS == 0) {
LOG.error("Transaction " + msg.startTimestamp + " has already been aborted");
} else {
LOG.error("Transaction " + msg.startTimestamp + " has already been committed with ts " + commitTS);
}
return; // TODO something better to do?
}
DataOutputStream toWAL = sharedState.toWAL;
try {
toWAL.writeByte(LoggerProtocol.ABORT);
toWAL.writeLong(msg.startTimestamp);
} catch (IOException e) {
e.printStackTrace();
}
abortCount++;
metrics.selfAborted();
sharedState.processAbort(msg.startTimestamp);
synchronized (sharedMsgBufLock) {
queueHalfAbort(msg.startTimestamp);
}
}
}
/**
* Handle the TimestampRequest message
*/
public void handle(TimestampRequest msg, ChannelHandlerContext ctx) {
metrics.begin();
TimerContext timer = metrics.startBeginProcessing();
long timestamp;
synchronized (sharedState) {
try {
timestamp = timestampOracle.next(sharedState.toWAL);
sharedState.uncommited.start(timestamp);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
ReadingBuffer buffer;
Channel channel = ctx.getChannel();
boolean bootstrap = false;
synchronized (messageBuffersMap) {
buffer = messageBuffersMap.get(ctx.getChannel());
if (buffer == null) {
synchronized (sharedMsgBufLock) {
bootstrap = true;
buffer = sharedState.sharedMessageBuffer.getReadingBuffer(ctx);
messageBuffersMap.put(channel, buffer);
channelGroup.add(channel);
LOG.warn("Channel connected: " + messageBuffersMap.size());
}
}
}
if (bootstrap) {
synchronized (sharedState) {
synchronized (sharedMsgBufLock) {
channel.write(buffer.getZipperState());
buffer.initializeIndexes();
}
}
channel.write(new LargestDeletedTimestampReport(sharedState.largestDeletedTimestamp));
for (AbortedTransaction halfAborted : sharedState.hashmap.halfAborted) {
channel.write(new AbortedTransactionReport(halfAborted.getStartTimestamp()));
}
}
ChannelBuffer cb;
ChannelFuture future = Channels.future(channel);
synchronized (sharedMsgBufLock) {
cb = buffer.flush(future);
}
Channels.write(ctx, future, cb);
Channels.write(channel, new TimestampResponse(timestamp));
timer.stop();
}
ChannelBuffer cb = ChannelBuffers.buffer(10);
private volatile boolean finish;
public static long waitTime = 0;
public static long commitTime = 0;
public static long checkTime = 0;
private Object sharedMsgBufLock = new Object();
private Object callbackLock = new Object();
private AddRecordCallback noCallback = new AddRecordCallback() {
@Override
public void addRecordComplete(int rc, Object ctx) {
}
};
private Runnable createAbortedSnaphostTask = new Runnable() {
@Override
public void run() {
createAbortedSnapshot();
}
};
public void createAbortedSnapshot() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream toWAL = new DataOutputStream(baos);
long snapshot = sharedState.hashmap.getAndIncrementAbortedSnapshot();
try {
toWAL.writeByte(LoggerProtocol.SNAPSHOT);
toWAL.writeLong(snapshot);
for (AbortedTransaction aborted : sharedState.hashmap.halfAborted) {
// ignore aborted transactions from last snapshot
if (aborted.getSnapshot() < snapshot) {
toWAL.writeByte(LoggerProtocol.ABORT);
toWAL.writeLong(aborted.getStartTimestamp());
}
}
} catch (IOException e) {
// can't happen
throw new RuntimeException(e);
}
sharedState.addRecord(baos.toByteArray(), noCallback, null);
}
/**
* Handle the CommitRequest message
*/
public void handle(CommitRequest msg, ChannelHandlerContext ctx) {
TimerContext timerProcessing = metrics.startCommitProcessing();
TimerContext timerLatency = metrics.startCommitLatency();
CommitResponse reply = new CommitResponse(msg.startTimestamp);
ByteArrayOutputStream baos = sharedState.baos;
DataOutputStream toWAL = sharedState.toWAL;
synchronized (sharedState) {
// 0. check if it should abort
if (msg.startTimestamp < timestampOracle.first()) {
reply.committed = false;
LOG.warn("Aborting transaction after restarting TSO");
} else if (msg.startTimestamp <= sharedState.largestDeletedTimestamp) {
if (msg.rows.length == 0) {
// read only, it has already been put in half aborted list
// we let it commit, but we mark it as fully aborted
// since it is read only, it doesn't matter
processFullAbort(msg.startTimestamp);
} else {
// Too old
reply.committed = false;// set as abort
LOG.warn("Too old starttimestamp: ST " + msg.startTimestamp + " MAX "
+ sharedState.largestDeletedTimestamp);
}
} else if (!sharedState.uncommited.isUncommitted(msg.startTimestamp)) {
long commitTS = sharedState.hashmap.getCommittedTimestamp(msg.startTimestamp);
if (commitTS == 0) {
LOG.error("Transaction " + msg.startTimestamp + " has already been aborted");
} else {
LOG.error("Transaction " + msg.startTimestamp + " has already been committed with ts " + commitTS);
}
return; // TODO something better to do?
} else {
// 1. check the write-write conflicts
for (RowKey r : msg.rows) {
long value;
value = sharedState.hashmap.getLatestWriteForRow(r.hashCode());
if (value != 0 && value > msg.startTimestamp) {
reply.committed = false;// set as abort
break;
} else if (value == 0 && sharedState.largestDeletedTimestamp > msg.startTimestamp) {
// then it could have been committed after start
// timestamp but deleted by recycling
LOG.warn("Old transaction {Start timestamp " + msg.startTimestamp
+ "} {Largest deleted timestamp " + sharedState.largestDeletedTimestamp + "}");
reply.committed = false;// set as abort
break;
}
}
}
if (reply.committed) {
metrics.commited();
// 2. commit
try {
long commitTimestamp = timestampOracle.next(toWAL);
sharedState.uncommited.commit(msg.startTimestamp);
reply.commitTimestamp = commitTimestamp;
if (msg.rows.length > 0) {
if (LOG.isTraceEnabled()) {
LOG.trace("Adding commit to WAL");
}
toWAL.writeByte(LoggerProtocol.COMMIT);
toWAL.writeLong(msg.startTimestamp);
toWAL.writeLong(commitTimestamp);
long oldLargestDeletedTimestamp = sharedState.largestDeletedTimestamp;
for (RowKey r : msg.rows) {
sharedState.hashmap.putLatestWriteForRow(r.hashCode(), commitTimestamp);
}
sharedState.largestDeletedTimestamp = sharedState.hashmap.getLargestDeletedTimestamp();
sharedState.processCommit(msg.startTimestamp, commitTimestamp);
if (sharedState.largestDeletedTimestamp > oldLargestDeletedTimestamp) {
toWAL.writeByte(LoggerProtocol.LARGESTDELETEDTIMESTAMP);
toWAL.writeLong(sharedState.largestDeletedTimestamp);
Set<Long> toAbort = sharedState.uncommited
.raiseLargestDeletedTransaction(sharedState.largestDeletedTimestamp);
if (LOG.isWarnEnabled() && !toAbort.isEmpty()) {
LOG.warn("Slow transactions after raising max: " + toAbort.size());
}
metrics.oldAborted(toAbort.size());
synchronized (sharedMsgBufLock) {
for (Long id : toAbort) {
sharedState.addExistingAbort(id);
queueHalfAbort(id);
}
queueLargestIncrease(sharedState.largestDeletedTimestamp);
}
}
if (sharedState.largestDeletedTimestamp > sharedState.previousLargestDeletedTimestamp
+ TSOState.MAX_ITEMS) {
// schedule snapshot
executor.submit(createAbortedSnaphostTask);
sharedState.previousLargestDeletedTimestamp = sharedState.largestDeletedTimestamp;
}
synchronized (sharedMsgBufLock) {
queueCommit(msg.startTimestamp, commitTimestamp);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else { // add it to the aborted list
abortCount++;
metrics.aborted();
try {
toWAL.writeByte(LoggerProtocol.ABORT);
toWAL.writeLong(msg.startTimestamp);
} catch (IOException e) {
e.printStackTrace();
}
sharedState.processAbort(msg.startTimestamp);
synchronized (sharedMsgBufLock) {
queueHalfAbort(msg.startTimestamp);
}
}
TSOHandler.transferredBytes.incrementAndGet();
ChannelandMessage cam = new ChannelandMessage(ctx, reply, timerLatency);
sharedState.nextBatch.add(cam);
if (sharedState.baos.size() >= TSOState.BATCH_SIZE) {
if (LOG.isTraceEnabled()) {
LOG.trace("Going to add record of size " + sharedState.baos.size());
}
// sharedState.lh.asyncAddEntry(baos.toByteArray(), this,
// sharedState.nextBatch);
sharedState.addRecord(baos.toByteArray(), new AddRecordCallback() {
@Override
public void addRecordComplete(int rc, Object ctx) {
if (rc != Code.OK) {
LOG.warn("Write failed: " + LoggerException.getMessage(rc));
} else {
synchronized (callbackLock) {
@SuppressWarnings("unchecked")
ArrayList<ChannelandMessage> theBatch = (ArrayList<ChannelandMessage>) ctx;
for (ChannelandMessage cam : theBatch) {
Channels.write(cam.ctx, Channels.succeededFuture(cam.ctx.getChannel()), cam.msg);
cam.timer.stop();
}
}
}
}
}, sharedState.nextBatch);
sharedState.nextBatch = new ArrayList<ChannelandMessage>(sharedState.nextBatch.size() + 5);
sharedState.baos.reset();
}
}
timerProcessing.stop();
}
/**
* Handle the CommitQueryRequest message
*/
public void handle(CommitQueryRequest msg, ChannelHandlerContext ctx) {
metrics.query();
CommitQueryResponse reply = new CommitQueryResponse(msg.startTimestamp);
reply.queryTimestamp = msg.queryTimestamp;
synchronized (sharedState) {
queries++;
// 1. check the write-write conflicts
long value;
value = sharedState.hashmap.getCommittedTimestamp(msg.queryTimestamp);
if (value != 0) { // it exists
reply.commitTimestamp = value;
reply.committed = value < msg.startTimestamp;// set as abort
} else if (sharedState.hashmap.isHalfAborted(msg.queryTimestamp))
reply.committed = false;
else if (sharedState.uncommited.isUncommitted(msg.queryTimestamp))
reply.committed = false;
else
reply.retry = true;
// else if (sharedState.largestDeletedTimestamp >=
// msg.queryTimestamp)
// reply.committed = true;
// TODO retry needed? isnt it just fully aborted?
ctx.getChannel().write(reply);
// We send the message directly. If after a failure the state is
// inconsistent we'll detect it
}
}
public void flush() {
synchronized (sharedState) {
if (LOG.isTraceEnabled()) {
LOG.trace("Adding record, size: " + sharedState.baos.size());
}
sharedState.addRecord(sharedState.baos.toByteArray(), new AddRecordCallback() {
@Override
public void addRecordComplete(int rc, Object ctx) {
if (rc != Code.OK) {
LOG.warn("Write failed: " + LoggerException.getMessage(rc));
} else {
synchronized (callbackLock) {
@SuppressWarnings("unchecked")
ArrayList<ChannelandMessage> theBatch = (ArrayList<ChannelandMessage>) ctx;
for (ChannelandMessage cam : theBatch) {
Channels.write(cam.ctx, Channels.succeededFuture(cam.ctx.getChannel()), cam.msg);
cam.timer.stop();
}
}
}
}
}, sharedState.nextBatch);
sharedState.nextBatch = new ArrayList<ChannelandMessage>(sharedState.nextBatch.size() + 5);
sharedState.baos.reset();
if (flushFuture.cancel(false)) {
flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
}
}
}
public class FlushThread implements Runnable {
@Override
public void run() {
if (finish) {
return;
}
if (sharedState.nextBatch.size() > 0) {
synchronized (sharedState) {
if (sharedState.nextBatch.size() > 0) {
if (LOG.isTraceEnabled()) {
LOG.trace("Flushing log batch.");
}
flush();
}
}
}
flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
}
}
private void queueCommit(long startTimestamp, long commitTimestamp) {
sharedState.sharedMessageBuffer.writeCommit(startTimestamp, commitTimestamp);
}
private void queueHalfAbort(long startTimestamp) {
sharedState.sharedMessageBuffer.writeHalfAbort(startTimestamp);
}
private void queueFullAbort(long startTimestamp) {
sharedState.sharedMessageBuffer.writeFullAbort(startTimestamp);
}
private void queueLargestIncrease(long largestTimestamp) {
sharedState.sharedMessageBuffer.writeLargestIncrease(largestTimestamp);
}
/**
* Handle the FullAbortReport message
*/
public void handle(FullAbortRequest msg, ChannelHandlerContext ctx) {
processFullAbort(msg.startTimestamp);
}
private void processFullAbort(long timestamp) {
synchronized (sharedState) {
DataOutputStream toWAL = sharedState.toWAL;
try {
toWAL.writeByte(LoggerProtocol.FULLABORT);
toWAL.writeLong(timestamp);
} catch (IOException e) {
LOG.error("Unexpected exception while writing to WAL", e);
}
metrics.cleanedAbort();
sharedState.processFullAbort(timestamp);
}
synchronized (sharedMsgBufLock) {
queueFullAbort(timestamp);
}
}
/*
* Wrapper for Channel and Message
*/
public static class ChannelandMessage {
ChannelHandlerContext ctx;
TSOMessage msg;
TimerContext timer;
ChannelandMessage(ChannelHandlerContext c, TSOMessage m, TimerContext t) {
ctx = c;
msg = m;
timer = t;
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
LOG.warn("TSOHandler: Unexpected exception from downstream.", e.getCause());
Channels.close(e.getChannel());
}
public void stop() {
finish = true;
scheduledExecutor.shutdown();
executor.shutdown();
}
}
| Check for old aborts
| src/main/java/com/yahoo/omid/tso/TSOHandler.java | Check for old aborts |
|
Java | apache-2.0 | b8590eac01ae57ee143d5660f1c27e9cf58d0b10 | 0 | saketkumar95/zulip-android,prati0100/zulip-android,Sam1301/zulip-android,vishwesh3/zulip-android,saketkumar95/zulip-android,zulip/zulip-android,abhaymaniyar/zulip-android,prati0100/zulip-android,abhaymaniyar/zulip-android,Sam1301/zulip-android | package com.zulip.android.activities;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.ccil.cowan.tagsoup.HTMLSchema;
import org.ccil.cowan.tagsoup.Parser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zulip.android.util.CustomHtmlToSpannedConverter;
import com.zulip.android.filters.NarrowFilterPM;
import com.zulip.android.filters.NarrowFilterStream;
import com.zulip.android.filters.NarrowListener;
import com.zulip.android.R;
import com.zulip.android.ZulipApp;
import com.zulip.android.models.Message;
import com.zulip.android.models.MessageType;
import com.zulip.android.models.Stream;
import com.zulip.android.networking.GravatarAsyncFetchTask;
/**
* Adapter which stores Messages in a view, and generates LinearLayouts for
* consumption by the ListView which displays the view.
*/
public class MessageAdapter extends ArrayAdapter<Message> {
private static final HTMLSchema schema = new HTMLSchema();
private @ColorInt int mDefaultStreamHeaderColor;
private @ColorInt int mDefaultHuddleHeaderColor;
private @ColorInt int mDefaultStreamMessageColor;
private @ColorInt int mDefaultHuddleMessageColor;
public MessageAdapter(Context context, List<Message> objects) {
super(context, 0, objects);
mDefaultStreamHeaderColor = ContextCompat.getColor(context, R.color.stream_header);
mDefaultStreamMessageColor = ContextCompat.getColor(context, R.color.stream_body);
mDefaultHuddleHeaderColor = ContextCompat.getColor(context, R.color.huddle_header);
mDefaultHuddleMessageColor = ContextCompat.getColor(context, R.color.huddle_body);
}
public View getView(int position, View convertView, ViewGroup group) {
final ZulipActivity context = (ZulipActivity) this.getContext();
final Message message = getItem(position);
LinearLayout tile;
if (convertView == null || !(convertView.getClass().equals(LinearLayout.class))) {
// We didn't get passed a tile, so construct a new one.
// In the future, we should inflate from a layout here.
LayoutInflater inflater = ((Activity) this.getContext()).getLayoutInflater();
tile = (LinearLayout) inflater.inflate(R.layout.message_tile, group, false);
} else {
tile = (LinearLayout) convertView;
}
LinearLayout envelopeTile = (LinearLayout) tile.findViewById(R.id.envelopeTile);
TextView display_recipient = (TextView) tile.findViewById(R.id.displayRecipient);
ImageView muteImageView = (ImageView) tile.findViewById(R.id.muteMessageImage);
if (message.getType() != MessageType.STREAM_MESSAGE) {
envelopeTile.setBackgroundColor(mDefaultHuddleHeaderColor);
} else {
Stream stream = message.getStream();
@ColorInt int color = stream == null ? mDefaultStreamHeaderColor : stream.getColor();
envelopeTile.setBackgroundColor(color);
}
if (message.getType() != MessageType.STREAM_MESSAGE) {
display_recipient.setText(context.getString(R.string.huddle_text, message.getDisplayRecipient(context.app)));
display_recipient.setTextColor(Color.WHITE);
display_recipient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getContext() instanceof NarrowListener) {
((NarrowListener) getContext()).onNarrow(new NarrowFilterPM(
Arrays.asList(message.getRecipients((ZulipApp.get())))));
}
}
});
} else {
display_recipient.setText(message.getDisplayRecipient(context.app));
display_recipient.setTextColor(Color.BLACK);
display_recipient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getContext() instanceof NarrowListener) {
((NarrowListener) getContext()).onNarrow(new NarrowFilterStream(message.getStream(), null));
}
}
});
if (getContext() instanceof NarrowListener) {
if (context.app.isTopicMute(message)) muteImageView.setVisibility(View.VISIBLE);
else muteImageView.setVisibility(View.GONE);
}
}
TextView sep = (TextView) tile.findViewById(R.id.sep);
TextView instance = (TextView) tile.findViewById(R.id.instance);
if (message.getType() != MessageType.STREAM_MESSAGE) {
instance.setVisibility(View.GONE);
sep.setVisibility(View.GONE);
instance.setOnClickListener(null);
} else {
instance.setVisibility(View.VISIBLE);
sep.setVisibility(View.VISIBLE);
instance.setText(message.getSubject());
instance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getContext() instanceof NarrowListener) {
((NarrowListener) getContext()).onNarrow(new NarrowFilterStream(message.getStream(), message.getSubject()));
((NarrowListener) getContext()).onNarrowFillSendBox(message);
}
}
});
}
LinearLayout messageTile = (LinearLayout) tile.findViewById(R.id.messageTile);
if (message.getType() != MessageType.STREAM_MESSAGE) {
messageTile.setBackgroundColor(mDefaultHuddleMessageColor);
} else {
messageTile.setBackgroundColor(mDefaultStreamMessageColor);
}
TextView senderName = (TextView) tile.findViewById(R.id.senderName);
senderName.setText(message.getSender().getName());
TextView contentView = (TextView) tile.findViewById(R.id.contentView);
Spanned formattedMessage = formatContent(message.getFormattedContent(),
context.app);
while (formattedMessage.length() != 0
&& formattedMessage.charAt(formattedMessage.length() - 1) == '\n') {
formattedMessage = (Spanned) formattedMessage.subSequence(0,
formattedMessage.length() - 2);
}
contentView.setText(formattedMessage);
contentView.setMovementMethod(LinkMovementMethod.getInstance());
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = context.getSupportFragmentManager();
ComposeDialog dialog;
if (message.getType() == MessageType.STREAM_MESSAGE) {
dialog = ComposeDialog.newInstance(message.getType(),
message.getStream().getName(),
message.getSubject(), null);
} else {
dialog = ComposeDialog.newInstance(message.getType(), null,
null, message.getReplyTo(context.app));
}
dialog.show(fm, "fragment_compose");
}
});
TextView timestamp = (TextView) tile.findViewById(R.id.timestamp);
if (DateUtils.isToday(message.getTimestamp().getTime())) {
timestamp.setText(DateUtils.formatDateTime(context, message
.getTimestamp().getTime(), DateUtils.FORMAT_SHOW_TIME));
} else {
timestamp.setText(DateUtils.formatDateTime(context, message
.getTimestamp().getTime(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_MONTH
| DateUtils.FORMAT_SHOW_TIME));
}
ImageView gravatar = (ImageView) tile.findViewById(R.id.gravatar);
Bitmap gravatar_img = context.getGravatars().get(message.getSender().getEmail());
if (gravatar_img != null) {
// Gravatar already exists for this image, set the ImageView to it
gravatar.setImageBitmap(gravatar_img);
} else {
// Go get the Bitmap
URL url = GravatarAsyncFetchTask.sizedURL(context, message.getSender().getAvatarURL(), 35);
GravatarAsyncFetchTask task = new GravatarAsyncFetchTask(context, gravatar, message.getSender());
task.loadBitmap(context, url, gravatar, message.getSender());
}
tile.setTag(R.id.messageID, message.getID());
return tile;
}
/**
* Copied from Html.fromHtml
*
* @param source HTML to be formatted
* @param app
* @return Span
*/
public static Spanned formatContent(String source, ZulipApp app) {
final Context context = app.getApplicationContext();
final float density = context.getResources().getDisplayMetrics().density;
Parser parser = new Parser();
try {
parser.setProperty(Parser.schemaProperty, schema);
} catch (org.xml.sax.SAXNotRecognizedException e) {
// Should not happen.
throw new RuntimeException(e);
} catch (org.xml.sax.SAXNotSupportedException e) {
// Should not happen.
throw new RuntimeException(e);
}
Html.ImageGetter emojiGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int lastIndex = -1;
if (source != null) {
lastIndex = source.lastIndexOf('/');
}
if (lastIndex != -1) {
String filename = source.substring(lastIndex + 1);
try {
Drawable drawable = Drawable.createFromStream(context
.getAssets().open("emoji/" + filename),
"emoji/" + filename);
// scaling down by half to fit well in message
double scaleFactor = 0.5;
drawable.setBounds(0, 0,
(int) (drawable.getIntrinsicWidth()
* scaleFactor * density),
(int) (drawable.getIntrinsicHeight()
* scaleFactor * density));
return drawable;
} catch (IOException e) {
Log.e("MessageAdapter", e.getMessage());
}
}
return null;
}
};
CustomHtmlToSpannedConverter converter = new CustomHtmlToSpannedConverter(
source, null, null, parser, emojiGetter, app.getServerURI());
return converter.convert();
}
public long getItemId(int position) {
return this.getItem(position).getID();
}
}
| app/src/main/java/com/zulip/android/activities/MessageAdapter.java | package com.zulip.android.activities;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.ccil.cowan.tagsoup.HTMLSchema;
import org.ccil.cowan.tagsoup.Parser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zulip.android.util.CustomHtmlToSpannedConverter;
import com.zulip.android.filters.NarrowFilterPM;
import com.zulip.android.filters.NarrowFilterStream;
import com.zulip.android.filters.NarrowListener;
import com.zulip.android.R;
import com.zulip.android.ZulipApp;
import com.zulip.android.models.Message;
import com.zulip.android.models.MessageType;
import com.zulip.android.models.Stream;
import com.zulip.android.networking.GravatarAsyncFetchTask;
/**
* Adapter which stores Messages in a view, and generates LinearLayouts for
* consumption by the ListView which displays the view.
*/
public class MessageAdapter extends ArrayAdapter<Message> {
private static final HTMLSchema schema = new HTMLSchema();
private @ColorInt int mDefaultStreamHeaderColor;
private @ColorInt int mDefaultHuddleHeaderColor;
private @ColorInt int mDefaultStreamMessageColor;
private @ColorInt int mDefaultHuddleMessageColor;
public MessageAdapter(Context context, List<Message> objects) {
super(context, 0, objects);
mDefaultStreamHeaderColor = ContextCompat.getColor(context, R.color.stream_header);
mDefaultStreamMessageColor = ContextCompat.getColor(context, R.color.stream_body);
mDefaultHuddleHeaderColor = ContextCompat.getColor(context, R.color.huddle_header);
mDefaultHuddleMessageColor = ContextCompat.getColor(context, R.color.huddle_body);
}
public View getView(int position, View convertView, ViewGroup group) {
final ZulipActivity context = (ZulipActivity) this.getContext();
final Message message = getItem(position);
LinearLayout tile;
if (convertView == null || !(convertView.getClass().equals(LinearLayout.class))) {
// We didn't get passed a tile, so construct a new one.
// In the future, we should inflate from a layout here.
LayoutInflater inflater = ((Activity) this.getContext()).getLayoutInflater();
tile = (LinearLayout) inflater.inflate(R.layout.message_tile, group, false);
} else {
tile = (LinearLayout) convertView;
}
LinearLayout envelopeTile = (LinearLayout) tile.findViewById(R.id.envelopeTile);
TextView display_recipient = (TextView) tile.findViewById(R.id.displayRecipient);
ImageView muteImageView = (ImageView) tile.findViewById(R.id.muteMessageImage);
if (message.getType() != MessageType.STREAM_MESSAGE) {
envelopeTile.setBackgroundColor(mDefaultHuddleHeaderColor);
} else {
Stream stream = message.getStream();
@ColorInt int color = stream == null ? mDefaultStreamHeaderColor : stream.getColor();
envelopeTile.setBackgroundColor(color);
}
if (message.getType() != MessageType.STREAM_MESSAGE) {
display_recipient.setText(context.getString(R.string.huddle_text, message.getDisplayRecipient(context.app)));
display_recipient.setTextColor(Color.WHITE);
display_recipient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getContext() instanceof NarrowListener) {
((NarrowListener) getContext()).onNarrow(new NarrowFilterPM(
Arrays.asList(message.getRecipients((ZulipApp.get())))));
}
}
});
} else {
display_recipient.setText(message.getDisplayRecipient(context.app));
display_recipient.setTextColor(Color.BLACK);
display_recipient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getContext() instanceof NarrowListener) {
((NarrowListener) getContext()).onNarrow(new NarrowFilterStream(message.getStream(), null));
}
}
});
if (getContext() instanceof NarrowListener) {
if (context.app.isTopicMute(message)) muteImageView.setVisibility(View.VISIBLE);
else muteImageView.setVisibility(View.GONE);
}
}
TextView sep = (TextView) tile.findViewById(R.id.sep);
TextView instance = (TextView) tile.findViewById(R.id.instance);
if (message.getType() != MessageType.STREAM_MESSAGE) {
instance.setVisibility(View.GONE);
sep.setVisibility(View.GONE);
instance.setOnClickListener(null);
} else {
instance.setVisibility(View.VISIBLE);
sep.setVisibility(View.VISIBLE);
instance.setText(message.getSubject());
instance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getContext() instanceof NarrowListener) {
((NarrowListener) getContext()).onNarrow(new NarrowFilterStream(message.getStream(), message.getSubject()));
}
}
});
}
LinearLayout messageTile = (LinearLayout) tile.findViewById(R.id.messageTile);
if (message.getType() != MessageType.STREAM_MESSAGE) {
messageTile.setBackgroundColor(mDefaultHuddleMessageColor);
} else {
messageTile.setBackgroundColor(mDefaultStreamMessageColor);
}
TextView senderName = (TextView) tile.findViewById(R.id.senderName);
senderName.setText(message.getSender().getName());
TextView contentView = (TextView) tile.findViewById(R.id.contentView);
Spanned formattedMessage = formatContent(message.getFormattedContent(),
context.app);
while (formattedMessage.length() != 0
&& formattedMessage.charAt(formattedMessage.length() - 1) == '\n') {
formattedMessage = (Spanned) formattedMessage.subSequence(0,
formattedMessage.length() - 2);
}
contentView.setText(formattedMessage);
contentView.setMovementMethod(LinkMovementMethod.getInstance());
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = context.getSupportFragmentManager();
ComposeDialog dialog;
if (message.getType() == MessageType.STREAM_MESSAGE) {
dialog = ComposeDialog.newInstance(message.getType(),
message.getStream().getName(),
message.getSubject(), null);
} else {
dialog = ComposeDialog.newInstance(message.getType(), null,
null, message.getReplyTo(context.app));
}
dialog.show(fm, "fragment_compose");
}
});
TextView timestamp = (TextView) tile.findViewById(R.id.timestamp);
if (DateUtils.isToday(message.getTimestamp().getTime())) {
timestamp.setText(DateUtils.formatDateTime(context, message
.getTimestamp().getTime(), DateUtils.FORMAT_SHOW_TIME));
} else {
timestamp.setText(DateUtils.formatDateTime(context, message
.getTimestamp().getTime(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_MONTH
| DateUtils.FORMAT_SHOW_TIME));
}
ImageView gravatar = (ImageView) tile.findViewById(R.id.gravatar);
Bitmap gravatar_img = context.getGravatars().get(message.getSender().getEmail());
if (gravatar_img != null) {
// Gravatar already exists for this image, set the ImageView to it
gravatar.setImageBitmap(gravatar_img);
} else {
// Go get the Bitmap
URL url = GravatarAsyncFetchTask.sizedURL(context, message.getSender().getAvatarURL(), 35);
GravatarAsyncFetchTask task = new GravatarAsyncFetchTask(context, gravatar, message.getSender());
task.loadBitmap(context, url, gravatar, message.getSender());
}
tile.setTag(R.id.messageID, message.getID());
return tile;
}
/**
* Copied from Html.fromHtml
*
* @param source HTML to be formatted
* @param app
* @return Span
*/
public static Spanned formatContent(String source, ZulipApp app) {
final Context context = app.getApplicationContext();
final float density = context.getResources().getDisplayMetrics().density;
Parser parser = new Parser();
try {
parser.setProperty(Parser.schemaProperty, schema);
} catch (org.xml.sax.SAXNotRecognizedException e) {
// Should not happen.
throw new RuntimeException(e);
} catch (org.xml.sax.SAXNotSupportedException e) {
// Should not happen.
throw new RuntimeException(e);
}
Html.ImageGetter emojiGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int lastIndex = -1;
if (source != null) {
lastIndex = source.lastIndexOf('/');
}
if (lastIndex != -1) {
String filename = source.substring(lastIndex + 1);
try {
Drawable drawable = Drawable.createFromStream(context
.getAssets().open("emoji/" + filename),
"emoji/" + filename);
// scaling down by half to fit well in message
double scaleFactor = 0.5;
drawable.setBounds(0, 0,
(int) (drawable.getIntrinsicWidth()
* scaleFactor * density),
(int) (drawable.getIntrinsicHeight()
* scaleFactor * density));
return drawable;
} catch (IOException e) {
Log.e("MessageAdapter", e.getMessage());
}
}
return null;
}
};
CustomHtmlToSpannedConverter converter = new CustomHtmlToSpannedConverter(
source, null, null, parser, emojiGetter, app.getServerURI());
return converter.convert();
}
public long getItemId(int position) {
return this.getItem(position).getID();
}
}
| Fill chatBox on click of title.
| app/src/main/java/com/zulip/android/activities/MessageAdapter.java | Fill chatBox on click of title. |
|
Java | apache-2.0 | fe8173e4489e351a3a9c789c883c9d852942965a | 0 | consulo/consulo-gdb | package uk.co.cwspencer.ideagdb.debug;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.xdebugger.frame.XExecutionStack;
import com.intellij.xdebugger.frame.XStackFrame;
import uk.co.cwspencer.gdb.Gdb;
import uk.co.cwspencer.gdb.messages.GdbErrorEvent;
import uk.co.cwspencer.gdb.messages.GdbEvent;
import uk.co.cwspencer.gdb.messages.GdbStackFrame;
import uk.co.cwspencer.gdb.messages.GdbStackTrace;
import uk.co.cwspencer.gdb.messages.GdbThread;
public class GdbExecutionStack extends XExecutionStack
{
private static final Logger m_log =
Logger.getInstance("#uk.co.cwspencer.ideagdb.debug.GdbExecutionStack");
// The GDB instance
private Gdb m_gdb;
// The thread
private GdbThread m_thread;
// The top of the stack
private GdbExecutionStackFrame m_topFrame;
/**
* Constructor.
* @param gdb Handle to the GDB instance.
* @param thread The thread.
*/
public GdbExecutionStack(Gdb gdb, GdbThread thread)
{
super(thread.formatName());
m_gdb = gdb;
m_thread = thread;
// Get the top of the stack
if (thread.frame != null)
{
m_topFrame = new GdbExecutionStackFrame(gdb, m_thread.id, thread.frame);
}
}
/**
* Returns the frame at the top of the stack.
* @return The stack frame.
*/
@Nullable
@Override
public XStackFrame getTopFrame()
{
return m_topFrame;
}
/**
* Gets the stack trace starting at the given index. This passes the request and returns
* immediately; the data is supplied to container asynchronously.
* @param container Container into which the stack frames are inserted.
*/
@Override
public void computeStackFrames(final XStackFrameContainer container)
{
// Just get the whole stack
String command = "-stack-list-frames";
m_gdb.sendCommand(command, new Gdb.GdbEventCallback()
{
@Override
public void onGdbCommandCompleted(GdbEvent event)
{
onGdbStackTraceReady(event, container);
}
});
}
/**
* Callback function for when GDB has responded to our stack trace request.
* @param event The event.
* @param container The container passed to computeStackFrames().
*/
private void onGdbStackTraceReady(GdbEvent event, XStackFrameContainer container)
{
if (event instanceof GdbErrorEvent)
{
container.errorOccurred(((GdbErrorEvent) event).message);
return;
}
if (!(event instanceof GdbStackTrace))
{
container.errorOccurred("Unexpected data received from GDB");
m_log.warn("Unexpected event " + event + " received from -stack-list-frames request");
return;
}
// Inspect the stack trace
GdbStackTrace stackTrace = (GdbStackTrace) event;
if (stackTrace.stack == null || stackTrace.stack.isEmpty())
{
// No data
container.addStackFrames(new ArrayList<XStackFrame>(0), true);
}
// Build a list of GdbExecutionStaceFrames
List<GdbExecutionStackFrame> stack = new ArrayList<GdbExecutionStackFrame>();
for (int i = 0; i < stackTrace.stack.size(); ++i)
{
GdbStackFrame frame = stackTrace.stack.get(i);
stack.add(new GdbExecutionStackFrame(m_gdb, m_thread.id, frame));
}
// Pass the data on
container.addStackFrames(stack, true);
}
}
| src/uk/co/cwspencer/ideagdb/debug/GdbExecutionStack.java | package uk.co.cwspencer.ideagdb.debug;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.xdebugger.frame.XExecutionStack;
import com.intellij.xdebugger.frame.XStackFrame;
import org.jetbrains.annotations.Nullable;
import uk.co.cwspencer.gdb.Gdb;
import uk.co.cwspencer.gdb.messages.GdbErrorEvent;
import uk.co.cwspencer.gdb.messages.GdbEvent;
import uk.co.cwspencer.gdb.messages.GdbStackFrame;
import uk.co.cwspencer.gdb.messages.GdbStackTrace;
import uk.co.cwspencer.gdb.messages.GdbStoppedEvent;
import uk.co.cwspencer.gdb.messages.GdbThread;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GdbExecutionStack extends XExecutionStack
{
private static final Logger m_log =
Logger.getInstance("#uk.co.cwspencer.ideagdb.debug.GdbExecutionStack");
// The GDB instance
private Gdb m_gdb;
// The thread
private GdbThread m_thread;
// The top of the stack
private GdbExecutionStackFrame m_topFrame;
/**
* Constructor.
* @param gdb Handle to the GDB instance.
* @param thread The thread.
*/
public GdbExecutionStack(Gdb gdb, GdbThread thread)
{
super(thread.formatName());
m_gdb = gdb;
m_thread = thread;
// Get the top of the stack
if (thread.frame != null)
{
m_topFrame = new GdbExecutionStackFrame(gdb, m_thread.id, thread.frame);
}
}
/**
* Returns the frame at the top of the stack.
* @return The stack frame.
*/
@Nullable
@Override
public XStackFrame getTopFrame()
{
return m_topFrame;
}
/**
* Gets the stack trace starting at the given index. This passes the request and returns
* immediately; the data is supplied to container asynchronously.
* @param firstFrameIndex The first frame to retrieve, where 0 is the top of the stack.
* @param container Container into which the stack frames are inserted.
*/
@Override
public void computeStackFrames(final int firstFrameIndex, final XStackFrameContainer container)
{
// Just get the whole stack
String command = "-stack-list-frames";
m_gdb.sendCommand(command, new Gdb.GdbEventCallback()
{
@Override
public void onGdbCommandCompleted(GdbEvent event)
{
onGdbStackTraceReady(event, firstFrameIndex, container);
}
});
}
/**
* Callback function for when GDB has responded to our stack trace request.
* @param event The event.
* @param firstFrameIndex The first frame from the list to use.
* @param container The container passed to computeStackFrames().
*/
private void onGdbStackTraceReady(GdbEvent event, int firstFrameIndex,
XStackFrameContainer container)
{
if (event instanceof GdbErrorEvent)
{
container.errorOccurred(((GdbErrorEvent) event).message);
return;
}
if (!(event instanceof GdbStackTrace))
{
container.errorOccurred("Unexpected data received from GDB");
m_log.warn("Unexpected event " + event + " received from -stack-list-frames request");
return;
}
// Inspect the stack trace
GdbStackTrace stackTrace = (GdbStackTrace) event;
if (stackTrace.stack == null || stackTrace.stack.isEmpty())
{
// No data
container.addStackFrames(new ArrayList<XStackFrame>(0), true);
}
// Build a list of GdbExecutionStaceFrames
List<GdbExecutionStackFrame> stack = new ArrayList<GdbExecutionStackFrame>();
for (int i = firstFrameIndex; i < stackTrace.stack.size(); ++i)
{
GdbStackFrame frame = stackTrace.stack.get(i);
stack.add(new GdbExecutionStackFrame(m_gdb, m_thread.id, frame));
}
// Pass the data on
container.addStackFrames(stack, true);
}
}
| compilation
| src/uk/co/cwspencer/ideagdb/debug/GdbExecutionStack.java | compilation |
|
Java | apache-2.0 | 95d7739e0bb37e3eefd087a5bf9204903ae17a3c | 0 | wcm-io/wcm-io-tooling,wcm-io/wcm-io-tooling,wcm-io/wcm-io-tooling | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2017 wcm.io
* %%
* 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.
* #L%
*/
package io.wcm.tooling.commons.packmgr.download;
import static io.wcm.tooling.commons.packmgr.PackageManagerHelper.CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import io.wcm.tooling.commons.packmgr.Logger;
import io.wcm.tooling.commons.packmgr.PackageManagerException;
import io.wcm.tooling.commons.packmgr.PackageManagerHelper;
import io.wcm.tooling.commons.packmgr.PackageManagerProperties;
import io.wcm.tooling.commons.packmgr.install.VendorInstallerFactory;
/**
* Downloads a single AEM content package.
*/
public final class PackageDownloader {
private final PackageManagerProperties props;
private final PackageManagerHelper pkgmgr;
private final Logger log;
/**
* @param props Package manager configuration properties.
* @param log Logger
*/
public PackageDownloader(PackageManagerProperties props, Logger log) {
this.props = props;
this.pkgmgr = new PackageManagerHelper(props, log);
this.log = log;
}
/**
* Download content package from CRX instance.
* @param file Local version of package that should be downloaded.
* @param ouputFilePath Path to download package from AEM instance to.
* @return Downloaded file
*/
public File downloadFile(File file, String ouputFilePath) {
try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) {
log.info("Download " + file.getName() + " from " + props.getPackageManagerUrl());
// 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
HttpPost post = new HttpPost(props.getPackageManagerUrl() + "/.json?cmd=upload");
MultipartEntityBuilder entity = MultipartEntityBuilder.create()
.addBinaryBody("package", file)
.addTextBody("force", "true");
post.setEntity(entity.build());
JSONObject jsonResponse = pkgmgr.executePackageManagerMethodJson(httpClient, post);
boolean success = jsonResponse.optBoolean("success", false);
String msg = jsonResponse.optString("msg", null);
String path = jsonResponse.optString("path", null);
// package already exists - get path from error message and continue
if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && StringUtils.isEmpty(path)) {
path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
success = true;
}
if (!success) {
throw new PackageManagerException("Package path detection failed: " + msg);
}
log.info("Package path is: " + path + " - now rebuilding package...");
// 2nd: build package
HttpPost buildMethod = new HttpPost(props.getPackageManagerUrl() + "/console.html" + path + "?cmd=build");
pkgmgr.executePackageManagerMethodHtmlOutputResponse(httpClient, buildMethod);
// 3rd: download package
String baseUrl = VendorInstallerFactory.getBaseUrl(props.getPackageManagerUrl(), log);
HttpGet downloadMethod = new HttpGet(baseUrl + path);
// execute download
CloseableHttpResponse response = httpClient.execute(downloadMethod);
try {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// get response stream
InputStream responseStream = response.getEntity().getContent();
// delete existing file
File outputFileObject = new File(ouputFilePath);
if (outputFileObject.exists()) {
outputFileObject.delete();
}
// write response file
FileOutputStream fos = new FileOutputStream(outputFileObject);
IOUtils.copy(responseStream, fos);
fos.flush();
responseStream.close();
fos.close();
log.info("Package downloaded to " + outputFileObject.getAbsolutePath());
return outputFileObject;
}
else {
throw new PackageManagerException("Package download failed:\n"
+ EntityUtils.toString(response.getEntity()));
}
}
finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
try {
response.close();
}
catch (IOException ex) {
// ignore
}
}
}
}
catch (FileNotFoundException ex) {
throw new PackageManagerException("File not found: " + file.getAbsolutePath(), ex);
}
catch (IOException ex) {
throw new PackageManagerException("Download operation failed.", ex);
}
}
}
| commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/download/PackageDownloader.java | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2017 wcm.io
* %%
* 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.
* #L%
*/
package io.wcm.tooling.commons.packmgr.download;
import static io.wcm.tooling.commons.packmgr.PackageManagerHelper.CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import io.wcm.tooling.commons.packmgr.Logger;
import io.wcm.tooling.commons.packmgr.PackageManagerException;
import io.wcm.tooling.commons.packmgr.PackageManagerHelper;
import io.wcm.tooling.commons.packmgr.PackageManagerProperties;
/**
* Downloads a single AEM content package.
*/
public final class PackageDownloader {
private final PackageManagerProperties props;
private final PackageManagerHelper pkgmgr;
private final Logger log;
/**
* @param props Package manager configuration properties.
* @param log Logger
*/
public PackageDownloader(PackageManagerProperties props, Logger log) {
this.props = props;
this.pkgmgr = new PackageManagerHelper(props, log);
this.log = log;
}
/**
* Download content package from CRX instance.
* @param file Local version of package that should be downloaded.
* @param ouputFilePath Path to download package from AEM instance to.
* @return Downloaded file
*/
public File downloadFile(File file, String ouputFilePath) {
try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) {
log.info("Download " + file.getName() + " from " + props.getPackageManagerUrl());
// 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
HttpPost post = new HttpPost(props.getPackageManagerUrl() + "/.json?cmd=upload");
MultipartEntityBuilder entity = MultipartEntityBuilder.create()
.addBinaryBody("package", file)
.addTextBody("force", "true");
post.setEntity(entity.build());
JSONObject jsonResponse = pkgmgr.executePackageManagerMethodJson(httpClient, post);
boolean success = jsonResponse.optBoolean("success", false);
String msg = jsonResponse.optString("msg", null);
String path = jsonResponse.optString("path", null);
// package already exists - get path from error message and continue
if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && StringUtils.isEmpty(path)) {
path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
success = true;
}
if (!success) {
throw new PackageManagerException("Package path detection failed: " + msg);
}
log.info("Package path is: " + path + " - now rebuilding package...");
// 2nd: build package
HttpPost buildMethod = new HttpPost(props.getPackageManagerUrl() + "/console.html" + path + "?cmd=build");
pkgmgr.executePackageManagerMethodHtmlOutputResponse(httpClient, buildMethod);
// 3rd: download package
String crxUrl = StringUtils.removeEnd(props.getPackageManagerUrl(), "/crx/packmgr/service");
HttpGet downloadMethod = new HttpGet(crxUrl + path);
// execute download
CloseableHttpResponse response = httpClient.execute(downloadMethod);
try {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// get response stream
InputStream responseStream = response.getEntity().getContent();
// delete existing file
File outputFileObject = new File(ouputFilePath);
if (outputFileObject.exists()) {
outputFileObject.delete();
}
// write response file
FileOutputStream fos = new FileOutputStream(outputFileObject);
IOUtils.copy(responseStream, fos);
fos.flush();
responseStream.close();
fos.close();
log.info("Package downloaded to " + outputFileObject.getAbsolutePath());
return outputFileObject;
}
else {
throw new PackageManagerException("Package download failed:\n"
+ EntityUtils.toString(response.getEntity()));
}
}
finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
try {
response.close();
}
catch (IOException ex) {
// ignore
}
}
}
}
catch (FileNotFoundException ex) {
throw new PackageManagerException("File not found: " + file.getAbsolutePath(), ex);
}
catch (IOException ex) {
throw new PackageManagerException("Download operation failed.", ex);
}
}
}
| reuse VendorInstallerFactory.getBaseUrl to get base url for package downloading
| commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/download/PackageDownloader.java | reuse VendorInstallerFactory.getBaseUrl to get base url for package downloading |
|
Java | apache-2.0 | 7998a96d69f1ee9709be92b77f679783a4764e34 | 0 | clarkparsia/ontop,ConstantB/ontop-spatial,ontop/ontop,ontop/ontop,ghxiao/ontop-spatial,ghxiao/ontop-spatial,srapisarda/ontop,ontop/ontop,ontop/ontop,srapisarda/ontop,ghxiao/ontop-spatial,ConstantB/ontop-spatial,ConstantB/ontop-spatial,ConstantB/ontop-spatial,clarkparsia/ontop,eschwert/ontop,eschwert/ontop,clarkparsia/ontop,srapisarda/ontop,ghxiao/ontop-spatial,srapisarda/ontop,eschwert/ontop,eschwert/ontop,ontop/ontop | package it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht;
import it.unibz.krdb.obda.ontology.Description;
import it.unibz.krdb.obda.ontology.OClass;
import it.unibz.krdb.obda.ontology.OntologyFactory;
import it.unibz.krdb.obda.ontology.Property;
import it.unibz.krdb.obda.ontology.impl.OntologyFactoryImpl;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import org.jgrapht.traverse.DepthFirstIterator;
import org.jgrapht.traverse.GraphIterator;
/**
* Build a DAG with only the named descriptions
*
* */
public class NamedDAGBuilder {
/**
* Constructor for the NamedDAGBuilder
* @param dag the DAG from which we want to maintain only the named descriptions
*/
public static NamedDAGImpl getNamedDAG(DAGImpl dag) {
SimpleDirectedGraph <Description,DefaultEdge> namedDag =
new SimpleDirectedGraph <Description,DefaultEdge>(DefaultEdge.class);
// clone all the vertexes and edges from dag
for (Description v : dag.vertexSet()) {
namedDag.addVertex(v);
}
for (DefaultEdge e : dag.edgeSet()) {
Description s = dag.getEdgeSource(e);
Description t = dag.getEdgeTarget(e);
namedDag.addEdge(s, t, e);
}
OntologyFactory descFactory = OntologyFactoryImpl.getInstance();
// take classes, roles, equivalences map and replacements from the DAG
Set<OClass> namedClasses = dag.getClasses();
Set<Property> property = dag.getRoles();
// clone the equivalences and replacements map
Map<Description, Description> replacements = new HashMap<Description, Description>();
for (Description eliminateNode : dag.getReplacementKeys()) {
Description referent = dag.getReplacementFor(eliminateNode);
replacements.put(eliminateNode, referent);
}
/*
* Test with a reversed graph so that the incoming edges
* represent the parents of the node
*/
DirectedGraph<Description, DefaultEdge> reversed = dag.getReversedDag();
LinkedList<Description> roots = new LinkedList<Description>();
for (Description n : reversed.vertexSet()) {
if ((reversed.incomingEdgesOf(n)).isEmpty()) {
roots.add(n);
}
}
Set<Description> processedNodes = new HashSet<Description>();
for (Description root: roots) {
/*
* A depth first sort from each root of the DAG.
* If the node is named we keep it, otherwise we remove it and
* we connect all its descendants to all its ancestors.
*
*
*/
GraphIterator<Description, DefaultEdge> orderIterator =
new DepthFirstIterator<Description, DefaultEdge>(reversed, root);
while (orderIterator.hasNext())
{
Description node = orderIterator.next();
if (processedNodes.contains(node))
continue;
if (namedClasses.contains(node) || property.contains(node)) {
processedNodes.add(node);
continue;
}
if (node instanceof Property)
{
Property posNode = descFactory.createProperty(((Property)node).getPredicate(), false);
if(processedNodes.contains(posNode))
{
eliminateNode(namedDag, node);
processedNodes.add(node);
continue;
}
}
EquivalenceClass<Description> equivalenceClassInDag = dag.getEquivalenceClass(node);
Set<Description> namedEquivalences;
{
// if there are no equivalent nodes return the node or nothing
if (equivalenceClassInDag == null) {
if (namedClasses.contains(node) || property.contains(node))
namedEquivalences = Collections.singleton(node);
else // empty set if (desc) is not a named class or property
namedEquivalences = Collections.emptySet();
}
else {
namedEquivalences = new LinkedHashSet<Description>();
for (Description vertex : equivalenceClassInDag) {
if (namedClasses.contains(vertex) || property.contains(vertex))
namedEquivalences.add(vertex);
}
}
}
if(!namedEquivalences.isEmpty())
{
Description newReference = namedEquivalences.iterator().next();
replacements.remove(newReference);
namedDag.addVertex(newReference);
if (equivalenceClassInDag != null)
for (Description vertex : equivalenceClassInDag) {
if (!vertex.equals(newReference))
replacements.put(vertex, newReference);
}
/*
* Re-pointing all links to and from the eliminated node to the new
* representative node
*/
for (DefaultEdge incEdge : namedDag.incomingEdgesOf(node)) {
Description source = namedDag.getEdgeSource(incEdge);
namedDag.removeAllEdges(source, node);
if (!source.equals(newReference))
namedDag.addEdge(source, newReference);
}
for (DefaultEdge outEdge : namedDag.outgoingEdgesOf(node)) {
Description target = namedDag.getEdgeTarget(outEdge);
namedDag.removeAllEdges(node, target);
if (!target.equals(newReference))
namedDag.addEdge(newReference, target);
}
namedDag.removeVertex(node);
processedNodes.add(node);
/*remove the invertex*/
if(node instanceof Property)
{
Property posNode = descFactory.createProperty(((Property)node).getPredicate(), false);
eliminateNode(namedDag, posNode);
continue;
}
}
else {
eliminateNode(namedDag, node);
processedNodes.add(node);
}
}
}
NamedDAGImpl dagImpl = new NamedDAGImpl(namedDag, dag, replacements);
return dagImpl;
}
private static void eliminateNode(SimpleDirectedGraph <Description,DefaultEdge> namedDag, Description node) {
Set<DefaultEdge> incomingEdges = new HashSet<DefaultEdge>(
namedDag.incomingEdgesOf(node));
// I do a copy of the dag not to remove edges that I still need to
// consider in the loops
SimpleDirectedGraph <Description,DefaultEdge> copyDAG =
(SimpleDirectedGraph <Description,DefaultEdge>) namedDag.clone();
Set<DefaultEdge> outgoingEdges = new HashSet<DefaultEdge>(
copyDAG.outgoingEdgesOf(node));
for (DefaultEdge incEdge : incomingEdges) {
Description source = namedDag.getEdgeSource(incEdge);
namedDag.removeAllEdges(source, node);
for (DefaultEdge outEdge : outgoingEdges) {
Description target = copyDAG.getEdgeTarget(outEdge);
namedDag.removeAllEdges(node, target);
if (!source.equals(target))
namedDag.addEdge(source, target);
}
}
namedDag.removeVertex(node);
}
}
| reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/dagjgrapht/NamedDAGBuilder.java | package it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht;
import it.unibz.krdb.obda.ontology.Description;
import it.unibz.krdb.obda.ontology.OClass;
import it.unibz.krdb.obda.ontology.OntologyFactory;
import it.unibz.krdb.obda.ontology.Property;
import it.unibz.krdb.obda.ontology.impl.OntologyFactoryImpl;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import org.jgrapht.traverse.DepthFirstIterator;
import org.jgrapht.traverse.GraphIterator;
/**
* Build a DAG with only the named descriptions
*
* */
public class NamedDAGBuilder {
/**
* Constructor for the NamedDAGBuilder
* @param dag the DAG from which we want to maintain only the named descriptions
*/
public static NamedDAGImpl getNamedDAG(DAGImpl dag) {
SimpleDirectedGraph <Description,DefaultEdge> namedDag =
new SimpleDirectedGraph <Description,DefaultEdge>(DefaultEdge.class);
// clone all the vertexes and edges from dag
for (Description v : dag.vertexSet()) {
namedDag.addVertex(v);
}
for (DefaultEdge e : dag.edgeSet()) {
Description s = dag.getEdgeSource(e);
Description t = dag.getEdgeTarget(e);
namedDag.addEdge(s, t, e);
}
OntologyFactory descFactory = OntologyFactoryImpl.getInstance();
// take classes, roles, equivalences map and replacements from the DAG
Set<OClass> namedClasses = dag.getClasses();
Set<Property> property = dag.getRoles();
// clone the equivalences and replacements map
Map<Description, Description> replacements = new HashMap<Description, Description>();
for (Description eliminateNode : dag.getReplacementKeys()) {
Description referent = dag.getReplacementFor(eliminateNode);
replacements.put(eliminateNode, referent);
}
/*
* Test with a reversed graph so that the incoming edges
* represent the parents of the node
*/
DirectedGraph<Description, DefaultEdge> reversed = dag.getReversedDag();
LinkedList<Description> roots = new LinkedList<Description>();
for (Description n : reversed.vertexSet()) {
if ((reversed.incomingEdgesOf(n)).isEmpty()) {
roots.add(n);
}
}
Set<Description> processedNodes = new HashSet<Description>();
for (Description root: roots) {
/*
* A depth first sort from each root of the DAG.
* If the node is named we keep it, otherwise we remove it and
* we connect all its descendants to all its ancestors.
*
*
*/
GraphIterator<Description, DefaultEdge> orderIterator =
new DepthFirstIterator<Description, DefaultEdge>(reversed, root);
while (orderIterator.hasNext())
{
Description node = orderIterator.next();
if(processedNodes.contains(node))
continue;
if (namedClasses.contains(node) || property.contains(node)) {
processedNodes.add(node);
continue;
}
if(node instanceof Property)
{
Property posNode = descFactory.createProperty(((Property)node).getPredicate(), false);
if(processedNodes.contains(posNode))
{
Set<DefaultEdge> incomingEdges = new HashSet<DefaultEdge>(
namedDag.incomingEdgesOf(node));
// I do a copy of the dag not to remove edges that I still need to
// consider in the loops
SimpleDirectedGraph <Description,DefaultEdge> copyDAG =
(SimpleDirectedGraph <Description,DefaultEdge>)namedDag.clone();
Set<DefaultEdge> outgoingEdges = new HashSet<DefaultEdge>(
copyDAG.outgoingEdgesOf(node));
for (DefaultEdge incEdge : incomingEdges) {
Description source = namedDag.getEdgeSource(incEdge);
namedDag.removeAllEdges(source, node);
for (DefaultEdge outEdge : outgoingEdges) {
Description target = copyDAG.getEdgeTarget(outEdge);
namedDag.removeAllEdges(node, target);
if (!source.equals(target))
namedDag.addEdge(source, target);
}
}
namedDag.removeVertex(node);
processedNodes.add(node);
continue;
}
}
EquivalenceClass<Description> equivalenceClassInDag = dag.getEquivalenceClass(node);
Set<Description> namedEquivalences;
{
// if there are no equivalent nodes return the node or nothing
if (equivalenceClassInDag == null) {
if (namedClasses.contains(node) || property.contains(node))
namedEquivalences = Collections.singleton(node);
else // empty set if (desc) is not a named class or property
namedEquivalences = Collections.emptySet();
}
else {
namedEquivalences = new LinkedHashSet<Description>();
for (Description vertex : equivalenceClassInDag) {
if (namedClasses.contains(vertex) || property.contains(vertex))
namedEquivalences.add(vertex);
}
}
}
if(!namedEquivalences.isEmpty())
{
Description newReference = namedEquivalences.iterator().next();
replacements.remove(newReference);
namedDag.addVertex(newReference);
if (equivalenceClassInDag != null)
for (Description vertex : equivalenceClassInDag) {
if (!vertex.equals(newReference))
replacements.put(vertex, newReference);
}
/*
* Re-pointing all links to and from the eliminated node to the new
* representative node
*/
for (DefaultEdge incEdge : namedDag.incomingEdgesOf(node)) {
Description source = namedDag.getEdgeSource(incEdge);
namedDag.removeAllEdges(source, node);
if (!source.equals(newReference))
namedDag.addEdge(source, newReference);
}
for (DefaultEdge outEdge : namedDag.outgoingEdgesOf(node)) {
Description target = namedDag.getEdgeTarget(outEdge);
namedDag.removeAllEdges(node, target);
if (!target.equals(newReference))
namedDag.addEdge(newReference, target);
}
namedDag.removeVertex(node);
processedNodes.add(node);
/*remove the invertex*/
if(node instanceof Property)
{
Property posNode = descFactory.createProperty(((Property)node).getPredicate(), false);
Set<DefaultEdge> incomingEdges = new HashSet<DefaultEdge>(
namedDag.incomingEdgesOf(posNode));
// I do a copy of the dag not to remove edges that I still need to
// consider in the loops
SimpleDirectedGraph <Description,DefaultEdge> copyDAG =
(SimpleDirectedGraph <Description,DefaultEdge>) namedDag.clone();
Set<DefaultEdge> outgoingEdges = new HashSet<DefaultEdge>(
copyDAG.outgoingEdgesOf(posNode));
for (DefaultEdge incEdge : incomingEdges) {
Description source = namedDag.getEdgeSource(incEdge);
namedDag.removeAllEdges(source, posNode);
for (DefaultEdge outEdge : outgoingEdges) {
Description target = copyDAG.getEdgeTarget(outEdge);
namedDag.removeAllEdges(posNode, target);
if (!source.equals(target))
namedDag.addEdge(source, target);
}
}
namedDag.removeVertex(posNode);
continue;
}
}
else {
Set<DefaultEdge> incomingEdges = new HashSet<DefaultEdge>(
namedDag.incomingEdgesOf(node));
// I do a copy of the dag not to remove edges that I still need to
// consider in the loops
SimpleDirectedGraph <Description,DefaultEdge> copyDAG =
(SimpleDirectedGraph <Description,DefaultEdge>) namedDag.clone();
Set<DefaultEdge> outgoingEdges = new HashSet<DefaultEdge>(
copyDAG.outgoingEdgesOf(node));
for (DefaultEdge incEdge : incomingEdges) {
Description source = namedDag.getEdgeSource(incEdge);
namedDag.removeAllEdges(source, node);
for (DefaultEdge outEdge : outgoingEdges) {
Description target = copyDAG.getEdgeTarget(outEdge);
namedDag.removeAllEdges(node, target);
if (!source.equals(target))
namedDag.addEdge(source, target);
}
}
namedDag.removeVertex(node);
processedNodes.add(node);
}
}
}
NamedDAGImpl dagImpl = new NamedDAGImpl(namedDag, dag, replacements);
return dagImpl;
}
}
| NamedDAGBuilder refactoring | reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/dagjgrapht/NamedDAGBuilder.java | NamedDAGBuilder refactoring |
|
Java | apache-2.0 | 338e09ff066e73b9054d46c0f62021456039ecdb | 0 | nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite,nivanov/ignite | /*
* 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.ignite.math.impls.storage.vector;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import org.apache.ignite.internal.util.offheap.GridOffHeapMap;
import org.apache.ignite.internal.util.offheap.GridOffHeapMapFactory;
import org.apache.ignite.math.VectorStorage;
import org.apache.ignite.math.exceptions.UnsupportedOperationException;
/**
* TODO:add description
*/
public class SparseLocalOffHeapVectorStorage implements VectorStorage {
/** Assume 10% density.*/
private static final int INIT_DENSITY = 10;
/** Storage capacity. */
private int size;
/** Local off heap map.*/
private GridOffHeapMap gridOffHeapMap;
/** */
public SparseLocalOffHeapVectorStorage(){
//No-op.
}
/** */
public SparseLocalOffHeapVectorStorage(int cap){
gridOffHeapMap = GridOffHeapMapFactory.unsafeMap(cap / INIT_DENSITY);
size = cap;
}
/** {@inheritDoc} */
@Override public int size() {
return (int) gridOffHeapMap.size();
}
/** {@inheritDoc} */
@Override public double get(int i) {
byte[] bytes = gridOffHeapMap.get(hash(i), intToByteArray(i));
return bytes == null ? 0 : ByteBuffer.wrap(bytes).getDouble();
}
/** {@inheritDoc} */
@Override public void set(int i, double v) {
gridOffHeapMap.put(hash(i), intToByteArray(i), doubleToByteArray(v));
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
throw new UnsupportedOperationException(); // TODO: add externalization support.
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean isSequentialAccess() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isRandomAccess() {
return true;
}
/** {@inheritDoc} */
@Override public boolean isDense() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isArrayBased() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isDistributed() {
return false;
}
/** {@inheritDoc} */
@Override public void destroy() {
gridOffHeapMap.destruct();
}
private int hash(int h){
// Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
// Despite two multiplies, this is often faster than others
// with comparable bit-spread properties.
h ^= h >>> 16;
h *= 0x85ebca6b;
h ^= h >>> 13;
h *= 0xc2b2ae35;
return (h >>> 16) ^ h;
}
private byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
private byte[] doubleToByteArray(double value){
long l = Double.doubleToRawLongBits(value);
return new byte[] {
(byte)((l >> 56) & 0xff),
(byte)((l >> 48) & 0xff),
(byte)((l >> 40) & 0xff),
(byte)((l >> 32) & 0xff),
(byte)((l >> 24) & 0xff),
(byte)((l >> 16) & 0xff),
(byte)((l >> 8) & 0xff),
(byte)((l) & 0xff),
};
}
}
| modules/math/src/main/java/org/apache/ignite/math/impls/storage/vector/SparseLocalOffHeapVectorStorage.java | /*
* 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.ignite.math.impls.storage.vector;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import org.apache.ignite.internal.util.offheap.GridOffHeapMap;
import org.apache.ignite.internal.util.offheap.GridOffHeapMapFactory;
import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMap;
import org.apache.ignite.math.VectorStorage;
import org.apache.ignite.math.exceptions.UnsupportedOperationException;
/**
* TODO:add description
*
* TODO: use {@link GridUnsafeMap}
*/
public class SparseLocalOffHeapVectorStorage implements VectorStorage {
/** Assume 10% density.*/
private static final int INIT_DENSITY = 10;
/** Storage capacity. */
private int size;
/** Local off heap map.*/
private GridOffHeapMap gridOffHeapMap;
/** */
public SparseLocalOffHeapVectorStorage(){
//No-op.
}
/** */
public SparseLocalOffHeapVectorStorage(int cap){
gridOffHeapMap = GridOffHeapMapFactory.unsafeMap(cap / INIT_DENSITY);
size = cap;
}
/** {@inheritDoc} */
@Override public int size() {
return (int) gridOffHeapMap.size();
}
/** {@inheritDoc} */
@Override public double get(int i) {
byte[] bytes = gridOffHeapMap.get(hash(i), intToByteArray(i));
return bytes == null ? 0 : ByteBuffer.wrap(bytes).getDouble();
}
/** {@inheritDoc} */
@Override public void set(int i, double v) {
gridOffHeapMap.put(hash(i), intToByteArray(i), doubleToByteArray(v));
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
throw new UnsupportedOperationException(); // TODO: add externalization support.
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean isSequentialAccess() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isRandomAccess() {
return true;
}
/** {@inheritDoc} */
@Override public boolean isDense() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isArrayBased() {
return false;
}
/** {@inheritDoc} */
@Override public boolean isDistributed() {
return false;
}
/** {@inheritDoc} */
@Override public void destroy() {
gridOffHeapMap.destruct();
}
private int hash(int h){
// Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
// Despite two multiplies, this is often faster than others
// with comparable bit-spread properties.
h ^= h >>> 16;
h *= 0x85ebca6b;
h ^= h >>> 13;
h *= 0xc2b2ae35;
return (h >>> 16) ^ h;
}
private byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
private byte[] doubleToByteArray(double value){
long l = Double.doubleToRawLongBits(value);
return new byte[] {
(byte)((l >> 56) & 0xff),
(byte)((l >> 48) & 0xff),
(byte)((l >> 40) & 0xff),
(byte)((l >> 32) & 0xff),
(byte)((l >> 24) & 0xff),
(byte)((l >> 16) & 0xff),
(byte)((l >> 8) & 0xff),
(byte)((l) & 0xff),
};
}
}
| IGN-6530:
cleanup
| modules/math/src/main/java/org/apache/ignite/math/impls/storage/vector/SparseLocalOffHeapVectorStorage.java | IGN-6530: cleanup |
|
Java | apache-2.0 | 60e99484bbb769e237baa57c7a4c0b5ae99aca4b | 0 | AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support | /*
* Copyright (C) 2012 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 android.support.v4.app;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.GravityCompat;
import android.view.Gravity;
import android.widget.RemoteViews;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Helper for accessing features in {@link android.app.Notification}
* introduced after API level 4 in a backwards compatible fashion.
*/
public class NotificationCompat {
/**
* Use all default values (where applicable).
*/
public static final int DEFAULT_ALL = ~0;
/**
* Use the default notification sound. This will ignore any sound set using
* {@link Builder#setSound}
*
* <p>
* A notification that is noisy is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_SOUND = 1;
/**
* Use the default notification vibrate. This will ignore any vibrate set using
* {@link Builder#setVibrate}. Using phone vibration requires the
* {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
*
* <p>
* A notification that vibrates is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_VIBRATE = 2;
/**
* Use the default notification lights. This will ignore the
* {@link #FLAG_SHOW_LIGHTS} bit, and values set with {@link Builder#setLights}.
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_LIGHTS = 4;
/**
* Use this constant as the value for audioStreamType to request that
* the default stream type for notifications be used. Currently the
* default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
*/
public static final int STREAM_DEFAULT = -1;
/**
* Bit set in the Notification flags field when LEDs should be turned on
* for this notification.
*/
public static final int FLAG_SHOW_LIGHTS = 0x00000001;
/**
* Bit set in the Notification flags field if this notification is in
* reference to something that is ongoing, like a phone call. It should
* not be set if this notification is in reference to something that
* happened at a particular point in time, like a missed phone call.
*/
public static final int FLAG_ONGOING_EVENT = 0x00000002;
/**
* Bit set in the Notification flags field if
* the audio will be repeated until the notification is
* cancelled or the notification window is opened.
*/
public static final int FLAG_INSISTENT = 0x00000004;
/**
* Bit set in the Notification flags field if the notification's sound,
* vibrate and ticker should only be played if the notification is not already showing.
*/
public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008;
/**
* Bit set in the Notification flags field if the notification should be canceled when
* it is clicked by the user.
*/
public static final int FLAG_AUTO_CANCEL = 0x00000010;
/**
* Bit set in the Notification flags field if the notification should not be canceled
* when the user clicks the Clear all button.
*/
public static final int FLAG_NO_CLEAR = 0x00000020;
/**
* Bit set in the Notification flags field if this notification represents a currently
* running service. This will normally be set for you by
* {@link android.app.Service#startForeground}.
*/
public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
/**
* Obsolete flag indicating high-priority notifications; use the priority field instead.
*
* @deprecated Use {@link NotificationCompat.Builder#setPriority(int)} with a positive value.
*/
public static final int FLAG_HIGH_PRIORITY = 0x00000080;
/**
* Bit set in the Notification flags field if this notification is relevant to the current
* device only and it is not recommended that it bridge to other devices.
*/
public static final int FLAG_LOCAL_ONLY = 0x00000100;
/**
* Bit set in the Notification flags field if this notification is the group summary for a
* group of notifications. Grouped notifications may display in a cluster or stack on devices
* which support such rendering. Requires a group key also be set using
* {@link Builder#setGroup}.
*/
public static final int FLAG_GROUP_SUMMARY = 0x00000200;
/**
* Default notification priority for {@link NotificationCompat.Builder#setPriority(int)}.
* If your application does not prioritize its own notifications,
* use this value for all notifications.
*/
public static final int PRIORITY_DEFAULT = 0;
/**
* Lower notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for items that are less important. The UI may choose to show
* these items smaller, or at a different position in the list,
* compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_LOW = -1;
/**
* Lowest notification priority for {@link NotificationCompat.Builder#setPriority(int)};
* these items might not be shown to the user except under
* special circumstances, such as detailed notification logs.
*/
public static final int PRIORITY_MIN = -2;
/**
* Higher notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for more important notifications or alerts. The UI may choose
* to show these items larger, or at a different position in
* notification lists, compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_HIGH = 1;
/**
* Highest notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for your application's most important items that require the user's
* prompt attention or input.
*/
public static final int PRIORITY_MAX = 2;
/**
* Notification extras key: this is the title of the notification,
* as supplied to {@link Builder#setContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE = "android.title";
/**
* Notification extras key: this is the title of the notification when shown in expanded form,
* e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
/**
* Notification extras key: this is the main text payload, as supplied to
* {@link Builder#setContentText(CharSequence)}.
*/
public static final String EXTRA_TEXT = "android.text";
/**
* Notification extras key: this is a third line of text, as supplied to
* {@link Builder#setSubText(CharSequence)}.
*/
public static final String EXTRA_SUB_TEXT = "android.subText";
/**
* Notification extras key: this is a small piece of additional text as supplied to
* {@link Builder#setContentInfo(CharSequence)}.
*/
public static final String EXTRA_INFO_TEXT = "android.infoText";
/**
* Notification extras key: this is a line of summary information intended to be shown
* alongside expanded notifications, as supplied to (e.g.)
* {@link BigTextStyle#setSummaryText(CharSequence)}.
*/
public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
/**
* Notification extras key: this is the longer text shown in the big form of a
* {@link BigTextStyle} notification, as supplied to
* {@link BigTextStyle#bigText(CharSequence)}.
*/
public static final String EXTRA_BIG_TEXT = "android.bigText";
/**
* Notification extras key: this is the resource ID of the notification's main small icon, as
* supplied to {@link Builder#setSmallIcon(int)}.
*/
public static final String EXTRA_SMALL_ICON = "android.icon";
/**
* Notification extras key: this is a bitmap to be used instead of the small icon when showing the
* notification payload, as
* supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON = "android.largeIcon";
/**
* Notification extras key: this is a bitmap to be used instead of the one from
* {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
* shown in its expanded form, as supplied to
* {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
/**
* Notification extras key: this is the progress value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS = "android.progress";
/**
* Notification extras key: this is the maximum value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
/**
* Notification extras key: whether the progress bar is indeterminate, supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown as a count-up timer (specifically a {@link android.widget.Chronometer}) instead
* of a timestamp, as supplied to {@link Builder#setUsesChronometer(boolean)}.
*/
public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown, as supplied to {@link Builder#setShowWhen(boolean)}.
*/
public static final String EXTRA_SHOW_WHEN = "android.showWhen";
/**
* Notification extras key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
* notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
*/
public static final String EXTRA_PICTURE = "android.picture";
/**
* Notification extras key: An array of CharSequences to show in {@link InboxStyle} expanded
* notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
*/
public static final String EXTRA_TEXT_LINES = "android.textLines";
/**
* Notification extras key: A string representing the name of the specific
* {@link android.app.Notification.Style} used to create this notification.
*/
public static final String EXTRA_TEMPLATE = "android.template";
/**
* Notification extras key: An array of people that this notification relates to, specified
* by contacts provider contact URI.
*/
public static final String EXTRA_PEOPLE = "android.people";
/**
* Notification extras key: A
* {@link android.content.ContentUris content URI} pointing to an image that can be displayed
* in the background when the notification is selected. The URI must point to an image stream
* suitable for passing into
* {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
* BitmapFactory.decodeStream}; all other content types will be ignored. The content provider
* URI used for this purpose must require no permissions to read the image data.
*/
public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
/**
* Notification key: A
* {@link android.media.session.MediaSession.Token} associated with a
* {@link android.app.Notification.MediaStyle} notification.
*/
public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
/**
* Notification extras key: the indices of actions to be shown in the compact view,
* as supplied to (e.g.) {@link Notification.MediaStyle#setShowActionsInCompactView(int...)}.
*/
public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
/**
* Value of {@link Notification#color} equal to 0 (also known as
* {@link android.graphics.Color#TRANSPARENT Color.TRANSPARENT}),
* telling the system not to decorate this notification with any special color but instead use
* default colors when presenting this notification.
*/
public static final int COLOR_DEFAULT = Color.TRANSPARENT;
/**
* Notification visibility: Show this notification in its entirety on all lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PUBLIC = 1;
/**
* Notification visibility: Show this notification on all lockscreens, but conceal sensitive or
* private information on secure lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PRIVATE = 0;
/**
* Notification visibility: Do not reveal any part of this notification on a secure lockscreen.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_SECRET = -1;
/**
* Notification category: incoming call (voice or video) or similar synchronous communication request.
*/
public static final String CATEGORY_CALL = NotificationCompatApi21.CATEGORY_CALL;
/**
* Notification category: incoming direct message (SMS, instant message, etc.).
*/
public static final String CATEGORY_MESSAGE = NotificationCompatApi21.CATEGORY_MESSAGE;
/**
* Notification category: asynchronous bulk message (email).
*/
public static final String CATEGORY_EMAIL = NotificationCompatApi21.CATEGORY_EMAIL;
/**
* Notification category: calendar event.
*/
public static final String CATEGORY_EVENT = NotificationCompatApi21.CATEGORY_EVENT;
/**
* Notification category: promotion or advertisement.
*/
public static final String CATEGORY_PROMO = NotificationCompatApi21.CATEGORY_PROMO;
/**
* Notification category: alarm or timer.
*/
public static final String CATEGORY_ALARM = NotificationCompatApi21.CATEGORY_ALARM;
/**
* Notification category: progress of a long-running background operation.
*/
public static final String CATEGORY_PROGRESS = NotificationCompatApi21.CATEGORY_PROGRESS;
/**
* Notification category: social network or sharing update.
*/
public static final String CATEGORY_SOCIAL = NotificationCompatApi21.CATEGORY_SOCIAL;
/**
* Notification category: error in background operation or authentication status.
*/
public static final String CATEGORY_ERROR = NotificationCompatApi21.CATEGORY_ERROR;
/**
* Notification category: media transport control for playback.
*/
public static final String CATEGORY_TRANSPORT = NotificationCompatApi21.CATEGORY_TRANSPORT;
/**
* Notification category: system or device status update. Reserved for system use.
*/
public static final String CATEGORY_SYSTEM = NotificationCompatApi21.CATEGORY_SYSTEM;
/**
* Notification category: indication of running background service.
*/
public static final String CATEGORY_SERVICE = NotificationCompatApi21.CATEGORY_SERVICE;
/**
* Notification category: a specific, timely recommendation for a single thing.
* For example, a news app might want to recommend a news story it believes the user will
* want to read next.
*/
public static final String CATEGORY_RECOMMENDATION =
NotificationCompatApi21.CATEGORY_RECOMMENDATION;
/**
* Notification category: ongoing information about device or contextual status.
*/
public static final String CATEGORY_STATUS = NotificationCompatApi21.CATEGORY_STATUS;
private static final NotificationCompatImpl IMPL;
interface NotificationCompatImpl {
public Notification build(Builder b);
public Bundle getExtras(Notification n);
public int getActionCount(Notification n);
public Action getAction(Notification n, int actionIndex);
public Action[] getActionsFromParcelableArrayList(ArrayList<Parcelable> parcelables);
public ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions);
public String getCategory(Notification n);
public boolean getLocalOnly(Notification n);
public String getGroup(Notification n);
public boolean isGroupSummary(Notification n);
public String getSortKey(Notification n);
}
static class NotificationCompatImplBase implements NotificationCompatImpl {
@Override
public Notification build(Builder b) {
Notification result = b.mNotification;
result.setLatestEventInfo(b.mContext, b.mContentTitle,
b.mContentText, b.mContentIntent);
// translate high priority requests into legacy flag
if (b.mPriority > PRIORITY_DEFAULT) {
result.flags |= FLAG_HIGH_PRIORITY;
}
return result;
}
@Override
public Bundle getExtras(Notification n) {
return null;
}
@Override
public int getActionCount(Notification n) {
return 0;
}
@Override
public Action getAction(Notification n, int actionIndex) {
return null;
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return null;
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions) {
return null;
}
@Override
public String getCategory(Notification n) {
return null;
}
@Override
public boolean getLocalOnly(Notification n) {
return false;
}
@Override
public String getGroup(Notification n) {
return null;
}
@Override
public boolean isGroupSummary(Notification n) {
return false;
}
@Override
public String getSortKey(Notification n) {
return null;
}
}
static class NotificationCompatImplGingerbread extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
Notification result = b.mNotification;
result.setLatestEventInfo(b.mContext, b.mContentTitle,
b.mContentText, b.mContentIntent);
result = NotificationCompatGingerbread.add(result, b.mContext,
b.mContentTitle, b.mContentText, b.mContentIntent, b.mFullScreenIntent);
// translate high priority requests into legacy flag
if (b.mPriority > PRIORITY_DEFAULT) {
result.flags |= FLAG_HIGH_PRIORITY;
}
return result;
}
}
static class NotificationCompatImplHoneycomb extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
return NotificationCompatHoneycomb.add(b.mContext, b.mNotification,
b.mContentTitle, b.mContentText, b.mContentInfo, b.mTickerView,
b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon);
}
}
static class NotificationCompatImplIceCreamSandwich extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
return NotificationCompatIceCreamSandwich.add(b.mContext, b.mNotification,
b.mContentTitle, b.mContentText, b.mContentInfo, b.mTickerView,
b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate);
}
}
static class NotificationCompatImplJellybean extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
NotificationCompatJellybean.Builder builder = new NotificationCompatJellybean.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public Bundle getExtras(Notification n) {
return NotificationCompatJellybean.getExtras(n);
}
@Override
public int getActionCount(Notification n) {
return NotificationCompatJellybean.getActionCount(n);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatJellybean.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatJellybean.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatJellybean.getParcelableArrayListForActions(actions);
}
@Override
public boolean getLocalOnly(Notification n) {
return NotificationCompatJellybean.getLocalOnly(n);
}
@Override
public String getGroup(Notification n) {
return NotificationCompatJellybean.getGroup(n);
}
@Override
public boolean isGroupSummary(Notification n) {
return NotificationCompatJellybean.isGroupSummary(n);
}
@Override
public String getSortKey(Notification n) {
return NotificationCompatJellybean.getSortKey(n);
}
}
static class NotificationCompatImplKitKat extends NotificationCompatImplJellybean {
@Override
public Notification build(Builder b) {
NotificationCompatKitKat.Builder builder = new NotificationCompatKitKat.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly,
b.mPeople, b.mExtras, b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public Bundle getExtras(Notification n) {
return NotificationCompatKitKat.getExtras(n);
}
@Override
public int getActionCount(Notification n) {
return NotificationCompatKitKat.getActionCount(n);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatKitKat.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public boolean getLocalOnly(Notification n) {
return NotificationCompatKitKat.getLocalOnly(n);
}
@Override
public String getGroup(Notification n) {
return NotificationCompatKitKat.getGroup(n);
}
@Override
public boolean isGroupSummary(Notification n) {
return NotificationCompatKitKat.isGroupSummary(n);
}
@Override
public String getSortKey(Notification n) {
return NotificationCompatKitKat.getSortKey(n);
}
}
static class NotificationCompatImplApi20 extends NotificationCompatImplKitKat {
@Override
public Notification build(Builder b) {
NotificationCompatApi20.Builder builder = new NotificationCompatApi20.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mPeople, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatApi20.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatApi20.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatApi20.getParcelableArrayListForActions(actions);
}
@Override
public boolean getLocalOnly(Notification n) {
return NotificationCompatApi20.getLocalOnly(n);
}
@Override
public String getGroup(Notification n) {
return NotificationCompatApi20.getGroup(n);
}
@Override
public boolean isGroupSummary(Notification n) {
return NotificationCompatApi20.isGroupSummary(n);
}
@Override
public String getSortKey(Notification n) {
return NotificationCompatApi20.getSortKey(n);
}
}
static class NotificationCompatImplApi21 extends NotificationCompatImplApi20 {
@Override
public Notification build(Builder b) {
NotificationCompatApi21.Builder builder = new NotificationCompatApi21.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public String getCategory(Notification notif) {
return NotificationCompatApi21.getCategory(notif);
}
}
private static void addActionsToBuilder(NotificationBuilderWithActions builder,
ArrayList<Action> actions) {
for (Action action : actions) {
builder.addAction(action);
}
}
private static void addStyleToBuilderJellybean(NotificationBuilderWithBuilderAccessor builder,
Style style) {
if (style != null) {
if (style instanceof BigTextStyle) {
BigTextStyle bigTextStyle = (BigTextStyle) style;
NotificationCompatJellybean.addBigTextStyle(builder,
bigTextStyle.mBigContentTitle,
bigTextStyle.mSummaryTextSet,
bigTextStyle.mSummaryText,
bigTextStyle.mBigText);
} else if (style instanceof InboxStyle) {
InboxStyle inboxStyle = (InboxStyle) style;
NotificationCompatJellybean.addInboxStyle(builder,
inboxStyle.mBigContentTitle,
inboxStyle.mSummaryTextSet,
inboxStyle.mSummaryText,
inboxStyle.mTexts);
} else if (style instanceof BigPictureStyle) {
BigPictureStyle bigPictureStyle = (BigPictureStyle) style;
NotificationCompatJellybean.addBigPictureStyle(builder,
bigPictureStyle.mBigContentTitle,
bigPictureStyle.mSummaryTextSet,
bigPictureStyle.mSummaryText,
bigPictureStyle.mPicture,
bigPictureStyle.mBigLargeIcon,
bigPictureStyle.mBigLargeIconSet);
}
}
}
static {
if (Build.VERSION.SDK_INT >= 21) {
IMPL = new NotificationCompatImplApi21();
} else if (Build.VERSION.SDK_INT >= 20) {
IMPL = new NotificationCompatImplApi20();
} else if (Build.VERSION.SDK_INT >= 19) {
IMPL = new NotificationCompatImplKitKat();
} else if (Build.VERSION.SDK_INT >= 16) {
IMPL = new NotificationCompatImplJellybean();
} else if (Build.VERSION.SDK_INT >= 14) {
IMPL = new NotificationCompatImplIceCreamSandwich();
} else if (Build.VERSION.SDK_INT >= 11) {
IMPL = new NotificationCompatImplHoneycomb();
} else if (Build.VERSION.SDK_INT >= 9) {
IMPL = new NotificationCompatImplGingerbread();
} else {
IMPL = new NotificationCompatImplBase();
}
}
/**
* Builder class for {@link NotificationCompat} objects. Allows easier control over
* all the flags, as well as help constructing the typical notification layouts.
* <p>
* On platform versions that don't offer expanded notifications, methods that depend on
* expanded notifications have no effect.
* </p>
* <p>
* For example, action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later.
* <p>
* For this reason, you should always ensure that UI controls in a notification are also
* available in an {@link android.app.Activity} in your app, and you should always start that
* {@link android.app.Activity} when users click the notification. To do this, use the
* {@link NotificationCompat.Builder#setContentIntent setContentIntent()}
* method.
* </p>
*
*/
public static class Builder {
/**
* Maximum length of CharSequences accepted by Builder and friends.
*
* <p>
* Avoids spamming the system with overly large strings such as full e-mails.
*/
private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024;
Context mContext;
CharSequence mContentTitle;
CharSequence mContentText;
PendingIntent mContentIntent;
PendingIntent mFullScreenIntent;
RemoteViews mTickerView;
Bitmap mLargeIcon;
CharSequence mContentInfo;
int mNumber;
int mPriority;
boolean mShowWhen = true;
boolean mUseChronometer;
Style mStyle;
CharSequence mSubText;
int mProgressMax;
int mProgress;
boolean mProgressIndeterminate;
String mGroupKey;
boolean mGroupSummary;
String mSortKey;
ArrayList<Action> mActions = new ArrayList<Action>();
boolean mLocalOnly = false;
String mCategory;
Bundle mExtras;
int mColor = COLOR_DEFAULT;
int mVisibility = VISIBILITY_PRIVATE;
Notification mPublicVersion;
Notification mNotification = new Notification();
public ArrayList<String> mPeople;
/**
* Constructor.
*
* Automatically sets the when field to {@link System#currentTimeMillis()
* System.currentTimeMillis()} and the audio stream to the
* {@link Notification#STREAM_DEFAULT}.
*
* @param context A {@link Context} that will be used to construct the
* RemoteViews. The Context will not be held past the lifetime of this
* Builder object.
*/
public Builder(Context context) {
mContext = context;
// Set defaults to match the defaults of a Notification
mNotification.when = System.currentTimeMillis();
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
mPriority = PRIORITY_DEFAULT;
mPeople = new ArrayList<String>();
}
/**
* Set the time that the event occurred. Notifications in the panel are
* sorted by this time.
*/
public Builder setWhen(long when) {
mNotification.when = when;
return this;
}
/**
* Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
* in the content view.
*/
public Builder setShowWhen(boolean show) {
mShowWhen = show;
return this;
}
/**
* Show the {@link Notification#when} field as a stopwatch.
*
* Instead of presenting <code>when</code> as a timestamp, the notification will show an
* automatically updating display of the minutes and seconds since <code>when</code>.
*
* Useful when showing an elapsed time (like an ongoing phone call).
*
* @see android.widget.Chronometer
* @see Notification#when
*/
public Builder setUsesChronometer(boolean b) {
mUseChronometer = b;
return this;
}
/**
* Set the small icon to use in the notification layouts. Different classes of devices
* may return different sizes. See the UX guidelines for more information on how to
* design these icons.
*
* @param icon A resource ID in the application's package of the drawble to use.
*/
public Builder setSmallIcon(int icon) {
mNotification.icon = icon;
return this;
}
/**
* A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
* level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
* LevelListDrawable}.
*
* @param icon A resource ID in the application's package of the drawble to use.
* @param level The level to use for the icon.
*
* @see android.graphics.drawable.LevelListDrawable
*/
public Builder setSmallIcon(int icon, int level) {
mNotification.icon = icon;
mNotification.iconLevel = level;
return this;
}
/**
* Set the title (first row) of the notification, in a standard notification.
*/
public Builder setContentTitle(CharSequence title) {
mContentTitle = limitCharSequenceLength(title);
return this;
}
/**
* Set the text (second row) of the notification, in a standard notification.
*/
public Builder setContentText(CharSequence text) {
mContentText = limitCharSequenceLength(text);
return this;
}
/**
* Set the third line of text in the platform notification template.
* Don't use if you're also using {@link #setProgress(int, int, boolean)};
* they occupy the same location in the standard template.
* <br>
* If the platform does not provide large-format notifications, this method has no effect.
* The third line of text only appears in expanded view.
* <br>
*/
public Builder setSubText(CharSequence text) {
mSubText = limitCharSequenceLength(text);
return this;
}
/**
* Set the large number at the right-hand side of the notification. This is
* equivalent to setContentInfo, although it might show the number in a different
* font size for readability.
*/
public Builder setNumber(int number) {
mNumber = number;
return this;
}
/**
* Set the large text at the right-hand side of the notification.
*/
public Builder setContentInfo(CharSequence info) {
mContentInfo = limitCharSequenceLength(info);
return this;
}
/**
* Set the progress this notification represents, which may be
* represented as a {@link android.widget.ProgressBar}.
*/
public Builder setProgress(int max, int progress, boolean indeterminate) {
mProgressMax = max;
mProgress = progress;
mProgressIndeterminate = indeterminate;
return this;
}
/**
* Supply a custom RemoteViews to use instead of the standard one.
*/
public Builder setContent(RemoteViews views) {
mNotification.contentView = views;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is clicked.
* If you do not supply an intent, you can now add PendingIntents to individual
* views to be launched when clicked by calling {@link RemoteViews#setOnClickPendingIntent
* RemoteViews.setOnClickPendingIntent(int,PendingIntent)}. Be sure to
* read {@link Notification#contentIntent Notification.contentIntent} for
* how to correctly use this.
*/
public Builder setContentIntent(PendingIntent intent) {
mContentIntent = intent;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is cleared by the user
* directly from the notification panel. For example, this intent is sent when the user
* clicks the "Clear all" button, or the individual "X" buttons on notifications. This
* intent is not sent when the application calls
* {@link android.app.NotificationManager#cancel NotificationManager.cancel(int)}.
*/
public Builder setDeleteIntent(PendingIntent intent) {
mNotification.deleteIntent = intent;
return this;
}
/**
* An intent to launch instead of posting the notification to the status bar.
* Only for use with extremely high-priority notifications demanding the user's
* <strong>immediate</strong> attention, such as an incoming phone call or
* alarm clock that the user has explicitly set to a particular time.
* If this facility is used for something else, please give the user an option
* to turn it off and use a normal notification, as this can be extremely
* disruptive.
*
* <p>
* On some platforms, the system UI may choose to display a heads-up notification,
* instead of launching this intent, while the user is using the device.
* </p>
*
* @param intent The pending intent to launch.
* @param highPriority Passing true will cause this notification to be sent
* even if other notifications are suppressed.
*/
public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
mFullScreenIntent = intent;
setFlag(FLAG_HIGH_PRIORITY, highPriority);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives.
*/
public Builder setTicker(CharSequence tickerText) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives, and also a RemoteViews object that may be displayed instead on some
* devices.
*/
public Builder setTicker(CharSequence tickerText, RemoteViews views) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
mTickerView = views;
return this;
}
/**
* Set the large icon that is shown in the ticker and notification.
*/
public Builder setLargeIcon(Bitmap icon) {
mLargeIcon = icon;
return this;
}
/**
* Set the sound to play. It will play on the default stream.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*/
public Builder setSound(Uri sound) {
mNotification.sound = sound;
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
return this;
}
/**
* Set the sound to play. It will play on the stream you supply.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see Notification#STREAM_DEFAULT
* @see AudioManager for the <code>STREAM_</code> constants.
*/
public Builder setSound(Uri sound, int streamType) {
mNotification.sound = sound;
mNotification.audioStreamType = streamType;
return this;
}
/**
* Set the vibration pattern to use.
*
* <p>
* On some platforms, a notification that vibrates is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see android.os.Vibrator for a discussion of the <code>pattern</code>
* parameter.
*/
public Builder setVibrate(long[] pattern) {
mNotification.vibrate = pattern;
return this;
}
/**
* Set the argb value that you would like the LED on the device to blnk, as well as the
* rate. The rate is specified in terms of the number of milliseconds to be on
* and then the number of milliseconds to be off.
*/
public Builder setLights(int argb, int onMs, int offMs) {
mNotification.ledARGB = argb;
mNotification.ledOnMS = onMs;
mNotification.ledOffMS = offMs;
boolean showLights = mNotification.ledOnMS != 0 && mNotification.ledOffMS != 0;
mNotification.flags = (mNotification.flags & ~Notification.FLAG_SHOW_LIGHTS) |
(showLights ? Notification.FLAG_SHOW_LIGHTS : 0);
return this;
}
/**
* Set whether this is an ongoing notification.
*
* <p>Ongoing notifications differ from regular notifications in the following ways:
* <ul>
* <li>Ongoing notifications are sorted above the regular notifications in the
* notification panel.</li>
* <li>Ongoing notifications do not have an 'X' close button, and are not affected
* by the "Clear all" button.
* </ul>
*/
public Builder setOngoing(boolean ongoing) {
setFlag(Notification.FLAG_ONGOING_EVENT, ongoing);
return this;
}
/**
* Set this flag if you would only like the sound, vibrate
* and ticker to be played if the notification is not already showing.
*/
public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
setFlag(Notification.FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
return this;
}
/**
* Setting this flag will make it so the notification is automatically
* canceled when the user clicks it in the panel. The PendingIntent
* set with {@link #setDeleteIntent} will be broadcast when the notification
* is canceled.
*/
public Builder setAutoCancel(boolean autoCancel) {
setFlag(Notification.FLAG_AUTO_CANCEL, autoCancel);
return this;
}
/**
* Set whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* This hint can be set to recommend this notification not be bridged.
*/
public Builder setLocalOnly(boolean b) {
mLocalOnly = b;
return this;
}
/**
* Set the notification category.
*
* <p>Must be one of the predefined notification categories (see the <code>CATEGORY_*</code>
* constants in {@link Notification}) that best describes this notification.
* May be used by the system for ranking and filtering.
*/
public Builder setCategory(String category) {
mCategory = category;
return this;
}
/**
* Set the default notification options that will be used.
* <p>
* The value should be one or more of the following fields combined with
* bitwise-or:
* {@link Notification#DEFAULT_SOUND}, {@link Notification#DEFAULT_VIBRATE},
* {@link Notification#DEFAULT_LIGHTS}.
* <p>
* For all default values, use {@link Notification#DEFAULT_ALL}.
*/
public Builder setDefaults(int defaults) {
mNotification.defaults = defaults;
if ((defaults & Notification.DEFAULT_LIGHTS) != 0) {
mNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
}
return this;
}
private void setFlag(int mask, boolean value) {
if (value) {
mNotification.flags |= mask;
} else {
mNotification.flags &= ~mask;
}
}
/**
* Set the relative priority for this notification.
*
* Priority is an indication of how much of the user's
* valuable attention should be consumed by this
* notification. Low-priority notifications may be hidden from
* the user in certain situations, while the user might be
* interrupted for a higher-priority notification.
* The system sets a notification's priority based on various factors including the
* setPriority value. The effect may differ slightly on different platforms.
*
* @param pri Relative priority for this notification. Must be one of
* the priority constants defined by {@link NotificationCompat}.
* Acceptable values range from {@link
* NotificationCompat#PRIORITY_MIN} (-2) to {@link
* NotificationCompat#PRIORITY_MAX} (2).
*/
public Builder setPriority(int pri) {
mPriority = pri;
return this;
}
/**
* Add a person that is relevant to this notification.
*
* @see Notification#EXTRA_PEOPLE
*/
public Builder addPerson(String handle) {
mPeople.add(handle);
return this;
}
/**
* Set this notification to be part of a group of notifications sharing the same key.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering.
*
* <p>To make this notification the summary for its group, also call
* {@link #setGroupSummary}. A sort order can be specified for group members by using
* {@link #setSortKey}.
* @param groupKey The group key of the group.
* @return this object for method chaining
*/
public Builder setGroup(String groupKey) {
mGroupKey = groupKey;
return this;
}
/**
* Set this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link #setGroup}.
* @param isGroupSummary Whether this notification should be a group summary.
* @return this object for method chaining
*/
public Builder setGroupSummary(boolean isGroupSummary) {
mGroupSummary = isGroupSummary;
return this;
}
/**
* Set a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public Builder setSortKey(String sortKey) {
mSortKey = sortKey;
return this;
}
/**
* Merge additional metadata into this notification.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see Notification#extras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
if (mExtras == null) {
mExtras = new Bundle(extras);
} else {
mExtras.putAll(extras);
}
}
return this;
}
/**
* Set metadata for this notification.
*
* <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
* current contents are copied into the Notification each time {@link #build()} is
* called.
*
* <p>Replaces any existing extras values with those from the provided Bundle.
* Use {@link #addExtras} to merge in metadata instead.
*
* @see Notification#extras
*/
public Builder setExtras(Bundle extras) {
mExtras = extras;
return this;
}
/**
* Get the current metadata Bundle used by this notification Builder.
*
* <p>The returned Bundle is shared with this Builder.
*
* <p>The current contents of this Bundle are copied into the Notification each time
* {@link #build()} is called.
*
* @see Notification#extras
*/
public Bundle getExtras() {
if (mExtras == null) {
mExtras = new Bundle();
}
return mExtras;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param icon Resource ID of a drawable that represents the action.
* @param title Text describing the action.
* @param intent {@link android.app.PendingIntent} to be fired when the action is invoked.
*/
public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
mActions.add(new Action(icon, title, intent));
return this;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param action The action to add.
*/
public Builder addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Add a rich notification style to be applied at build time.
* <br>
* If the platform does not provide rich notification styles, this method has no effect. The
* user will always see the normal notification style.
*
* @param style Object responsible for modifying the notification style.
*/
public Builder setStyle(Style style) {
if (mStyle != style) {
mStyle = style;
if (mStyle != null) {
mStyle.setBuilder(this);
}
}
return this;
}
/**
* Sets {@link Notification#color}.
*
* @param argb The accent color to use
*
* @return The same Builder.
*/
public Builder setColor(int argb) {
mColor = argb;
return this;
}
/**
* Sets {@link Notification#visibility}.
*
* @param visibility One of {@link Notification#VISIBILITY_PRIVATE} (the default),
* {@link Notification#VISIBILITY_PUBLIC}, or
* {@link Notification#VISIBILITY_SECRET}.
*/
public Builder setVisibility(int visibility) {
mVisibility = visibility;
return this;
}
/**
* Supply a replacement Notification whose contents should be shown in insecure contexts
* (i.e. atop the secure lockscreen). See {@link Notification#visibility} and
* {@link #VISIBILITY_PUBLIC}.
*
* @param n A replacement notification, presumably with some or all info redacted.
* @return The same Builder.
*/
public Builder setPublicVersion(Notification n) {
mPublicVersion = n;
return this;
}
/**
* Apply an extender to this notification builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* @deprecated Use {@link #build()} instead.
*/
@Deprecated
public Notification getNotification() {
return IMPL.build(this);
}
/**
* Combine all of the options that have been set and return a new {@link Notification}
* object.
*/
public Notification build() {
return IMPL.build(this);
}
protected static CharSequence limitCharSequenceLength(CharSequence cs) {
if (cs == null) return cs;
if (cs.length() > MAX_CHARSEQUENCE_LENGTH) {
cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH);
}
return cs;
}
}
/**
* An object that can apply a rich notification style to a {@link Notification.Builder}
* object.
* <br>
* If the platform does not provide rich notification styles, methods in this class have no
* effect.
*/
public static abstract class Style {
Builder mBuilder;
CharSequence mBigContentTitle;
CharSequence mSummaryText;
boolean mSummaryTextSet = false;
public void setBuilder(Builder builder) {
if (mBuilder != builder) {
mBuilder = builder;
if (mBuilder != null) {
mBuilder.setStyle(this);
}
}
}
public Notification build() {
Notification notification = null;
if (mBuilder != null) {
notification = mBuilder.build();
}
return notification;
}
}
/**
* Helper class for generating large-format notifications that include a large image attachment.
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notif = new Notification.Builder(mContext)
* .setContentTitle("New photo from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_post)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigPictureStyle()
* .bigPicture(aBigBitmap))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigPictureStyle extends Style {
Bitmap mPicture;
Bitmap mBigLargeIcon;
boolean mBigLargeIconSet;
public BigPictureStyle() {
}
public BigPictureStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigPictureStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigPictureStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the bitmap to be used as the payload for the BigPicture notification.
*/
public BigPictureStyle bigPicture(Bitmap b) {
mPicture = b;
return this;
}
/**
* Override the large icon when the big notification is shown.
*/
public BigPictureStyle bigLargeIcon(Bitmap b) {
mBigLargeIcon = b;
mBigLargeIconSet = true;
return this;
}
}
/**
* Helper class for generating large-format notifications that include a lot of text.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notif = new Notification.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigTextStyle()
* .bigText(aVeryLongString))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigTextStyle extends Style {
CharSequence mBigText;
public BigTextStyle() {
}
public BigTextStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigTextStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigTextStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the longer text to be displayed in the big form of the
* template in place of the content text.
*/
public BigTextStyle bigText(CharSequence cs) {
mBigText = Builder.limitCharSequenceLength(cs);
return this;
}
}
/**
* Helper class for generating large-format notifications that include a list of (up to 5) strings.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification noti = new Notification.Builder()
* .setContentTitle("5 New mails from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.InboxStyle()
* .addLine(str1)
* .addLine(str2)
* .setContentTitle("")
* .setSummaryText("+3 more"))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class InboxStyle extends Style {
ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
public InboxStyle() {
}
public InboxStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public InboxStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public InboxStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Append a line to the digest section of the Inbox notification.
*/
public InboxStyle addLine(CharSequence cs) {
mTexts.add(Builder.limitCharSequenceLength(cs));
return this;
}
}
/**
* Structure to encapsulate a named action that can be shown as part of this notification.
* It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
* selected by the user. Action buttons won't appear on platforms prior to Android 4.1.
* <p>
* Apps should use {@link NotificationCompat.Builder#addAction(int, CharSequence, PendingIntent)}
* or {@link NotificationCompat.Builder#addAction(NotificationCompat.Action)}
* to attach actions.
*/
public static class Action extends NotificationCompatBase.Action {
private final Bundle mExtras;
private final RemoteInput[] mRemoteInputs;
/**
* Small icon representing the action.
*/
public int icon;
/**
* Title of the action.
*/
public CharSequence title;
/**
* Intent to send when the user invokes this action. May be null, in which case the action
* may be rendered in a disabled presentation.
*/
public PendingIntent actionIntent;
public Action(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle(), null);
}
private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
RemoteInput[] remoteInputs) {
this.icon = icon;
this.title = NotificationCompat.Builder.limitCharSequenceLength(title);
this.actionIntent = intent;
this.mExtras = extras != null ? extras : new Bundle();
this.mRemoteInputs = remoteInputs;
}
@Override
protected int getIcon() {
return icon;
}
@Override
protected CharSequence getTitle() {
return title;
}
@Override
protected PendingIntent getActionIntent() {
return actionIntent;
}
/**
* Get additional metadata carried around with this Action.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Get the list of inputs to be collected from the user when this action is sent.
* May return null if no remote inputs were added.
*/
public RemoteInput[] getRemoteInputs() {
return mRemoteInputs;
}
/**
* Builder class for {@link Action} objects.
*/
public static final class Builder {
private final int mIcon;
private final CharSequence mTitle;
private final PendingIntent mIntent;
private final Bundle mExtras;
private ArrayList<RemoteInput> mRemoteInputs;
/**
* Construct a new builder for {@link Action} object.
* @param icon icon to show for this action
* @param title the title of the action
* @param intent the {@link PendingIntent} to fire when users trigger this action
*/
public Builder(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle());
}
/**
* Construct a new builder for {@link Action} object using the fields from an
* {@link Action}.
* @param action the action to read fields from.
*/
public Builder(Action action) {
this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras));
}
private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras) {
mIcon = icon;
mTitle = NotificationCompat.Builder.limitCharSequenceLength(title);
mIntent = intent;
mExtras = extras;
}
/**
* Merge additional metadata into this builder.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see NotificationCompat.Action#getExtras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
mExtras.putAll(extras);
}
return this;
}
/**
* Get the metadata Bundle used by this Builder.
*
* <p>The returned Bundle is shared with this Builder.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Add an input to be collected from the user when this action is sent.
* Response values can be retrieved from the fired intent by using the
* {@link RemoteInput#getResultsFromIntent} function.
* @param remoteInput a {@link RemoteInput} to add to the action
* @return this object for method chaining
*/
public Builder addRemoteInput(RemoteInput remoteInput) {
if (mRemoteInputs == null) {
mRemoteInputs = new ArrayList<RemoteInput>();
}
mRemoteInputs.add(remoteInput);
return this;
}
/**
* Apply an extender to this action builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* Combine all of the options that have been set and return a new {@link Action}
* object.
* @return the built action
*/
public Action build() {
RemoteInput[] remoteInputs = mRemoteInputs != null
? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs);
}
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on an action builder.
*/
public interface Extender {
/**
* Apply this extender to a notification action builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
public Builder extend(Builder builder);
}
/**
* Wearable extender for notification actions. To add extensions to an action,
* create a new {@link NotificationCompat.Action.WearableExtender} object using
* the {@code WearableExtender()} constructor and apply it to a
* {@link NotificationCompat.Action.Builder} using
* {@link NotificationCompat.Action.Builder#extend}.
*
* <pre class="prettyprint">
* NotificationCompat.Action action = new NotificationCompat.Action.Builder(
* R.drawable.archive_all, "Archive all", actionIntent)
* .extend(new NotificationCompat.Action.WearableExtender()
* .setAvailableOffline(false))
* .build();</pre>
*/
public static final class WearableExtender implements Extender {
/** Notification action extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
private static final String KEY_FLAGS = "flags";
// Flags bitwise-ored to mFlags
private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
private int mFlags = DEFAULT_FLAGS;
/**
* Create a {@link NotificationCompat.Action.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
/**
* Create a {@link NotificationCompat.Action.WearableExtender} by reading
* wearable options present in an existing notification action.
* @param action the notification action to inspect.
*/
public WearableExtender(Action action) {
Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
if (wearableBundle != null) {
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
}
}
/**
* Apply wearable extensions to a notification action that is being built. This is
* typically called by the {@link NotificationCompat.Action.Builder#extend}
* method of {@link NotificationCompat.Action.Builder}.
*/
@Override
public Action.Builder extend(Action.Builder builder) {
Bundle wearableBundle = new Bundle();
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mFlags = this.mFlags;
return that;
}
/**
* Set whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public WearableExtender setAvailableOffline(boolean availableOffline) {
setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
return this;
}
/**
* Get whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public boolean isAvailableOffline() {
return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
}
/** @hide */
public static final Factory FACTORY = new Factory() {
@Override
public Action build(int icon, CharSequence title,
PendingIntent actionIntent, Bundle extras,
RemoteInputCompatBase.RemoteInput[] remoteInputs) {
return new Action(icon, title, actionIntent, extras,
(RemoteInput[]) remoteInputs);
}
@Override
public Action[] newArray(int length) {
return new Action[length];
}
};
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on a notification builder.
*/
public interface Extender {
/**
* Apply this extender to a notification builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
public Builder extend(Builder builder);
}
/**
* Helper class to add wearable extensions to notifications.
* <p class="note"> See
* <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
* for Android Wear</a> for more information on how to use this class.
* <p>
* To create a notification with wearable extensions:
* <ol>
* <li>Create a {@link NotificationCompat.Builder}, setting any desired
* properties.
* <li>Create a {@link NotificationCompat.WearableExtender}.
* <li>Set wearable-specific properties using the
* {@code add} and {@code set} methods of {@link NotificationCompat.WearableExtender}.
* <li>Call {@link NotificationCompat.Builder#extend} to apply the extensions to a
* notification.
* <li>Post the notification to the notification
* system with the {@code NotificationManagerCompat.notify(...)} methods
* and not the {@code NotificationManager.notify(...)} methods.
* </ol>
*
* <pre class="prettyprint">
* Notification notif = new NotificationCompat.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .extend(new NotificationCompat.WearableExtender()
* .setContentIcon(R.drawable.new_mail))
* .build();
* NotificationManagerCompat.from(mContext).notify(0, notif);</pre>
*
* <p>Wearable extensions can be accessed on an existing notification by using the
* {@code WearableExtender(Notification)} constructor,
* and then using the {@code get} methods to access values.
*
* <pre class="prettyprint">
* NotificationCompat.WearableExtender wearableExtender =
* new NotificationCompat.WearableExtender(notification);
* List<Notification> pages = wearableExtender.getPages();</pre>
*/
public static final class WearableExtender implements Extender {
/**
* Sentinel value for an action index that is unset.
*/
public static final int UNSET_ACTION_INDEX = -1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification with
* default sizing.
* <p>For custom display notifications created using {@link #setDisplayIntent},
* the default is {@link #SIZE_LARGE}. All other notifications size automatically based
* on their content.
*/
public static final int SIZE_DEFAULT = 0;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with an extra small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_XSMALL = 1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_SMALL = 2;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a medium size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_MEDIUM = 3;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a large size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_LARGE = 4;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* full screen.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_FULL_SCREEN = 5;
/** Notification extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
// Keys within EXTRA_WEARABLE_OPTIONS for wearable options.
private static final String KEY_ACTIONS = "actions";
private static final String KEY_FLAGS = "flags";
private static final String KEY_DISPLAY_INTENT = "displayIntent";
private static final String KEY_PAGES = "pages";
private static final String KEY_BACKGROUND = "background";
private static final String KEY_CONTENT_ICON = "contentIcon";
private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
private static final String KEY_GRAVITY = "gravity";
// Flags bitwise-ored to mFlags
private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
private static final int DEFAULT_CONTENT_ICON_GRAVITY = GravityCompat.END;
private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
private ArrayList<Action> mActions = new ArrayList<Action>();
private int mFlags = DEFAULT_FLAGS;
private PendingIntent mDisplayIntent;
private ArrayList<Notification> mPages = new ArrayList<Notification>();
private Bitmap mBackground;
private int mContentIcon;
private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
private int mContentActionIndex = UNSET_ACTION_INDEX;
private int mCustomSizePreset = SIZE_DEFAULT;
private int mCustomContentHeight;
private int mGravity = DEFAULT_GRAVITY;
/**
* Create a {@link NotificationCompat.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
public WearableExtender(Notification notif) {
Bundle extras = getExtras(notif);
Bundle wearableBundle = extras != null ? extras.getBundle(EXTRA_WEARABLE_EXTENSIONS)
: null;
if (wearableBundle != null) {
Action[] actions = IMPL.getActionsFromParcelableArrayList(
wearableBundle.getParcelableArrayList(KEY_ACTIONS));
if (actions != null) {
Collections.addAll(mActions, actions);
}
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
Notification[] pages = getNotificationArrayFromBundle(
wearableBundle, KEY_PAGES);
if (pages != null) {
Collections.addAll(mPages, pages);
}
mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
DEFAULT_CONTENT_ICON_GRAVITY);
mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
UNSET_ACTION_INDEX);
mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
SIZE_DEFAULT);
mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
}
}
/**
* Apply wearable extensions to a notification that is being built. This is typically
* called by the {@link NotificationCompat.Builder#extend} method of
* {@link NotificationCompat.Builder}.
*/
@Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
Bundle wearableBundle = new Bundle();
if (!mActions.isEmpty()) {
wearableBundle.putParcelableArrayList(KEY_ACTIONS,
IMPL.getParcelableArrayListForActions(mActions.toArray(
new Action[mActions.size()])));
}
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
if (mDisplayIntent != null) {
wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
}
if (!mPages.isEmpty()) {
wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
new Notification[mPages.size()]));
}
if (mBackground != null) {
wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
}
if (mContentIcon != 0) {
wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
}
if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
}
if (mContentActionIndex != UNSET_ACTION_INDEX) {
wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
mContentActionIndex);
}
if (mCustomSizePreset != SIZE_DEFAULT) {
wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
}
if (mCustomContentHeight != 0) {
wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
}
if (mGravity != DEFAULT_GRAVITY) {
wearableBundle.putInt(KEY_GRAVITY, mGravity);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mActions = new ArrayList<Action>(this.mActions);
that.mFlags = this.mFlags;
that.mDisplayIntent = this.mDisplayIntent;
that.mPages = new ArrayList<Notification>(this.mPages);
that.mBackground = this.mBackground;
that.mContentIcon = this.mContentIcon;
that.mContentIconGravity = this.mContentIconGravity;
that.mContentActionIndex = this.mContentActionIndex;
that.mCustomSizePreset = this.mCustomSizePreset;
that.mCustomContentHeight = this.mCustomContentHeight;
that.mGravity = this.mGravity;
return that;
}
/**
* Add a wearable action to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param action the action to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Adds wearable actions to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param actions the actions to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addActions(List<Action> actions) {
mActions.addAll(actions);
return this;
}
/**
* Clear all wearable actions present on this builder.
* @return this object for method chaining.
* @see #addAction
*/
public WearableExtender clearActions() {
mActions.clear();
return this;
}
/**
* Get the wearable actions present on this notification.
*/
public List<Action> getActions() {
return mActions;
}
/**
* Set an intent to launch inside of an activity view when displaying
* this notification. The {@link PendingIntent} provided should be for an activity.
*
* <pre class="prettyprint">
* Intent displayIntent = new Intent(context, MyDisplayActivity.class);
* PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
* 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
* Notification notif = new NotificationCompat.Builder(context)
* .extend(new NotificationCompat.WearableExtender()
* .setDisplayIntent(displayPendingIntent)
* .setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_MEDIUM))
* .build();</pre>
*
* <p>The activity to launch needs to allow embedding, must be exported, and
* should have an empty task affinity. It is also recommended to use the device
* default light theme.
*
* <p>Example AndroidManifest.xml entry:
* <pre class="prettyprint">
* <activity android:name="com.example.MyDisplayActivity"
* android:exported="true"
* android:allowEmbedded="true"
* android:taskAffinity=""
* android:theme="@android:style/Theme.DeviceDefault.Light" /></pre>
*
* @param intent the {@link PendingIntent} for an activity
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getDisplayIntent
*/
public WearableExtender setDisplayIntent(PendingIntent intent) {
mDisplayIntent = intent;
return this;
}
/**
* Get the intent to launch inside of an activity view when displaying this
* notification. This {@code PendingIntent} should be for an activity.
*/
public PendingIntent getDisplayIntent() {
return mDisplayIntent;
}
/**
* Add an additional page of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param page the notification to add as another page
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPage(Notification page) {
mPages.add(page);
return this;
}
/**
* Add additional pages of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param pages a list of notifications
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPages(List<Notification> pages) {
mPages.addAll(pages);
return this;
}
/**
* Clear all additional pages present on this builder.
* @return this object for method chaining.
* @see #addPage
*/
public WearableExtender clearPages() {
mPages.clear();
return this;
}
/**
* Get the array of additional pages of content for displaying this notification. The
* current notification forms the first page, and elements within this array form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
* @return the pages for this notification
*/
public List<Notification> getPages() {
return mPages;
}
/**
* Set a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @param background the background bitmap
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getBackground
*/
public WearableExtender setBackground(Bitmap background) {
mBackground = background;
return this;
}
/**
* Get a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @return the background image
* @see NotificationCompat.WearableExtender#setBackground
*/
public Bitmap getBackground() {
return mBackground;
}
/**
* Set an icon that goes with the content of this notification.
*/
public WearableExtender setContentIcon(int icon) {
mContentIcon = icon;
return this;
}
/**
* Get an icon that goes with the content of this notification.
*/
public int getContentIcon() {
return mContentIcon;
}
/**
* Set the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #setContentIcon
*/
public WearableExtender setContentIconGravity(int contentIconGravity) {
mContentIconGravity = contentIconGravity;
return this;
}
/**
* Get the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #getContentIcon
*/
public int getContentIconGravity() {
return mContentIconGravity;
}
/**
* Set an action from this notification's actions to be clickable with the content of
* this notification. This action will no longer display separately from the
* notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* @param actionIndex The index of the action to hoist onto the current notification page.
* If wearable actions were added to the main notification, this index
* will apply to that list, otherwise it will apply to the regular
* actions list.
*/
public WearableExtender setContentAction(int actionIndex) {
mContentActionIndex = actionIndex;
return this;
}
/**
* Get the index of the notification action, if any, that was specified as being clickable
* with the content of this notification. This action will no longer display separately
* from the notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* <p>If wearable specific actions were added to the main notification, this index will
* apply to that list, otherwise it will apply to the regular actions list.
*
* @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
*/
public int getContentAction() {
return mContentActionIndex;
}
/**
* Set the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public WearableExtender setGravity(int gravity) {
mGravity = gravity;
return this;
}
/**
* Get the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public int getGravity() {
return mGravity;
}
/**
* Set the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. Check the
* documentation for the preset in question. See also
* {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
*/
public WearableExtender setCustomSizePreset(int sizePreset) {
mCustomSizePreset = sizePreset;
return this;
}
/**
* Get the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link #setDisplayIntent}. Check the documentation for the preset in question.
* See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
*/
public int getCustomSizePreset() {
return mCustomSizePreset;
}
/**
* Set the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. See also
* {@link NotificationCompat.WearableExtender#setCustomSizePreset} and
* {@link #getCustomContentHeight}.
*/
public WearableExtender setCustomContentHeight(int height) {
mCustomContentHeight = height;
return this;
}
/**
* Get the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
* {@link #setCustomContentHeight}.
*/
public int getCustomContentHeight() {
return mCustomContentHeight;
}
/**
* Set whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
return this;
}
/**
* Get whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public boolean getStartScrollBottom() {
return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
}
/**
* Set whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public WearableExtender setContentIntentAvailableOffline(
boolean contentIntentAvailableOffline) {
setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
return this;
}
/**
* Get whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public boolean getContentIntentAvailableOffline() {
return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
}
/**
* Set a hint that this notification's icon should not be displayed.
* @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintHideIcon(boolean hintHideIcon) {
setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
return this;
}
/**
* Get a hint that this notification's icon should not be displayed.
* @return {@code true} if this icon should not be displayed, false otherwise.
* The default value is {@code false} if this was never set.
*/
public boolean getHintHideIcon() {
return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
}
/**
* Set a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link #addPage}.
*/
public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
return this;
}
/**
* Get a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link NotificationCompat.WearableExtender#addPage}.
*/
public boolean getHintShowBackgroundOnly() {
return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
}
/**
* Get an array of Notification objects from a parcelable array bundle field.
* Update the bundle to have a typed array so fetches in the future don't need
* to do an array copy.
*/
private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
Parcelable[] array = bundle.getParcelableArray(key);
if (array instanceof Notification[] || array == null) {
return (Notification[]) array;
}
Notification[] typedArray = new Notification[array.length];
for (int i = 0; i < array.length; i++) {
typedArray[i] = (Notification) array[i];
}
bundle.putParcelableArray(key, typedArray);
return typedArray;
}
/**
* Gets the {@link Notification#extras} field from a notification in a backwards
* compatible manner. Extras field was supported from JellyBean (Api level 16)
* forwards. This function will return null on older api levels.
*/
public static Bundle getExtras(Notification notif) {
return IMPL.getExtras(notif);
}
/**
* Get the number of actions in this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
*/
public static int getActionCount(Notification notif) {
return IMPL.getActionCount(notif);
}
/**
* Get an action on this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
* @param notif The notification to inspect.
* @param actionIndex The index of the action to retrieve.
*/
public static Action getAction(Notification notif, int actionIndex) {
return IMPL.getAction(notif, actionIndex);
}
/**
* Get the category of this notification in a backwards compatible
* manner.
* @param notif The notification to inspect.
*/
public static String getCategory(Notification notif) {
return IMPL.getCategory(notif);
}
/**
* Get whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* If this hint is set, it is recommend that this notification not be bridged.
*/
public static boolean getLocalOnly(Notification notif) {
return IMPL.getLocalOnly(notif);
}
/**
* Get the key used to group this notification into a cluster or stack
* with other notifications on devices which support such rendering.
*/
public static String getGroup(Notification notif) {
return IMPL.getGroup(notif);
}
/**
* Get whether this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
* @return Whether this notification is a group summary.
*/
public static boolean isGroupSummary(Notification notif) {
return IMPL.isGroupSummary(notif);
}
/**
* Get a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public static String getSortKey(Notification notif) {
return IMPL.getSortKey(notif);
}
}
| v4/java/android/support/v4/app/NotificationCompat.java | /*
* Copyright (C) 2012 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 android.support.v4.app;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.GravityCompat;
import android.view.Gravity;
import android.widget.RemoteViews;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Helper for accessing features in {@link android.app.Notification}
* introduced after API level 4 in a backwards compatible fashion.
*/
public class NotificationCompat {
/**
* Use all default values (where applicable).
*/
public static final int DEFAULT_ALL = ~0;
/**
* Use the default notification sound. This will ignore any sound set using
* {@link Builder#setSound}
*
* <p>
* A notification that is noisy is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_SOUND = 1;
/**
* Use the default notification vibrate. This will ignore any vibrate set using
* {@link Builder#setVibrate}. Using phone vibration requires the
* {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
*
* <p>
* A notification that vibrates is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_VIBRATE = 2;
/**
* Use the default notification lights. This will ignore the
* {@link #FLAG_SHOW_LIGHTS} bit, and values set with {@link Builder#setLights}.
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_LIGHTS = 4;
/**
* Use this constant as the value for audioStreamType to request that
* the default stream type for notifications be used. Currently the
* default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
*/
public static final int STREAM_DEFAULT = -1;
/**
* Bit set in the Notification flags field when LEDs should be turned on
* for this notification.
*/
public static final int FLAG_SHOW_LIGHTS = 0x00000001;
/**
* Bit set in the Notification flags field if this notification is in
* reference to something that is ongoing, like a phone call. It should
* not be set if this notification is in reference to something that
* happened at a particular point in time, like a missed phone call.
*/
public static final int FLAG_ONGOING_EVENT = 0x00000002;
/**
* Bit set in the Notification flags field if
* the audio will be repeated until the notification is
* cancelled or the notification window is opened.
*/
public static final int FLAG_INSISTENT = 0x00000004;
/**
* Bit set in the Notification flags field if the notification's sound,
* vibrate and ticker should only be played if the notification is not already showing.
*/
public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008;
/**
* Bit set in the Notification flags field if the notification should be canceled when
* it is clicked by the user.
*/
public static final int FLAG_AUTO_CANCEL = 0x00000010;
/**
* Bit set in the Notification flags field if the notification should not be canceled
* when the user clicks the Clear all button.
*/
public static final int FLAG_NO_CLEAR = 0x00000020;
/**
* Bit set in the Notification flags field if this notification represents a currently
* running service. This will normally be set for you by
* {@link android.app.Service#startForeground}.
*/
public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
/**
* Obsolete flag indicating high-priority notifications; use the priority field instead.
*
* @deprecated Use {@link NotificationCompat.Builder#setPriority(int)} with a positive value.
*/
public static final int FLAG_HIGH_PRIORITY = 0x00000080;
/**
* Bit set in the Notification flags field if this notification is relevant to the current
* device only and it is not recommended that it bridge to other devices.
*/
public static final int FLAG_LOCAL_ONLY = 0x00000100;
/**
* Bit set in the Notification flags field if this notification is the group summary for a
* group of notifications. Grouped notifications may display in a cluster or stack on devices
* which support such rendering. Requires a group key also be set using
* {@link Builder#setGroup}.
*/
public static final int FLAG_GROUP_SUMMARY = 0x00000200;
/**
* Default notification priority for {@link NotificationCompat.Builder#setPriority(int)}.
* If your application does not prioritize its own notifications,
* use this value for all notifications.
*/
public static final int PRIORITY_DEFAULT = 0;
/**
* Lower notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for items that are less important. The UI may choose to show
* these items smaller, or at a different position in the list,
* compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_LOW = -1;
/**
* Lowest notification priority for {@link NotificationCompat.Builder#setPriority(int)};
* these items might not be shown to the user except under
* special circumstances, such as detailed notification logs.
*/
public static final int PRIORITY_MIN = -2;
/**
* Higher notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for more important notifications or alerts. The UI may choose
* to show these items larger, or at a different position in
* notification lists, compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_HIGH = 1;
/**
* Highest notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for your application's most important items that require the user's
* prompt attention or input.
*/
public static final int PRIORITY_MAX = 2;
/**
* Notification extras key: this is the title of the notification,
* as supplied to {@link Builder#setContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE = "android.title";
/**
* Notification extras key: this is the title of the notification when shown in expanded form,
* e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
/**
* Notification extras key: this is the main text payload, as supplied to
* {@link Builder#setContentText(CharSequence)}.
*/
public static final String EXTRA_TEXT = "android.text";
/**
* Notification extras key: this is a third line of text, as supplied to
* {@link Builder#setSubText(CharSequence)}.
*/
public static final String EXTRA_SUB_TEXT = "android.subText";
/**
* Notification extras key: this is a small piece of additional text as supplied to
* {@link Builder#setContentInfo(CharSequence)}.
*/
public static final String EXTRA_INFO_TEXT = "android.infoText";
/**
* Notification extras key: this is a line of summary information intended to be shown
* alongside expanded notifications, as supplied to (e.g.)
* {@link BigTextStyle#setSummaryText(CharSequence)}.
*/
public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
/**
* Notification extras key: this is the longer text shown in the big form of a
* {@link BigTextStyle} notification, as supplied to
* {@link BigTextStyle#bigText(CharSequence)}.
*/
public static final String EXTRA_BIG_TEXT = "android.bigText";
/**
* Notification extras key: this is the resource ID of the notification's main small icon, as
* supplied to {@link Builder#setSmallIcon(int)}.
*/
public static final String EXTRA_SMALL_ICON = "android.icon";
/**
* Notification extras key: this is a bitmap to be used instead of the small icon when showing the
* notification payload, as
* supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON = "android.largeIcon";
/**
* Notification extras key: this is a bitmap to be used instead of the one from
* {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
* shown in its expanded form, as supplied to
* {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
/**
* Notification extras key: this is the progress value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS = "android.progress";
/**
* Notification extras key: this is the maximum value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
/**
* Notification extras key: whether the progress bar is indeterminate, supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown as a count-up timer (specifically a {@link android.widget.Chronometer}) instead
* of a timestamp, as supplied to {@link Builder#setUsesChronometer(boolean)}.
*/
public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown, as supplied to {@link Builder#setShowWhen(boolean)}.
*/
public static final String EXTRA_SHOW_WHEN = "android.showWhen";
/**
* Notification extras key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
* notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
*/
public static final String EXTRA_PICTURE = "android.picture";
/**
* Notification extras key: An array of CharSequences to show in {@link InboxStyle} expanded
* notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
*/
public static final String EXTRA_TEXT_LINES = "android.textLines";
/**
* Notification extras key: An array of people that this notification relates to, specified
* by contacts provider contact URI.
*/
public static final String EXTRA_PEOPLE = "android.people";
/**
* Notification extras key: the indices of actions to be shown in the compact view,
* as supplied to (e.g.) {@link Notification.MediaStyle#setShowActionsInCompactView(int...)}.
*/
public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
/**
* Value of {@link Notification#color} equal to 0 (also known as
* {@link android.graphics.Color#TRANSPARENT Color.TRANSPARENT}),
* telling the system not to decorate this notification with any special color but instead use
* default colors when presenting this notification.
*/
public static final int COLOR_DEFAULT = Color.TRANSPARENT;
/**
* Notification visibility: Show this notification in its entirety on all lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PUBLIC = 1;
/**
* Notification visibility: Show this notification on all lockscreens, but conceal sensitive or
* private information on secure lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PRIVATE = 0;
/**
* Notification visibility: Do not reveal any part of this notification on a secure lockscreen.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_SECRET = -1;
/**
* Notification category: incoming call (voice or video) or similar synchronous communication request.
*/
public static final String CATEGORY_CALL = NotificationCompatApi21.CATEGORY_CALL;
/**
* Notification category: incoming direct message (SMS, instant message, etc.).
*/
public static final String CATEGORY_MESSAGE = NotificationCompatApi21.CATEGORY_MESSAGE;
/**
* Notification category: asynchronous bulk message (email).
*/
public static final String CATEGORY_EMAIL = NotificationCompatApi21.CATEGORY_EMAIL;
/**
* Notification category: calendar event.
*/
public static final String CATEGORY_EVENT = NotificationCompatApi21.CATEGORY_EVENT;
/**
* Notification category: promotion or advertisement.
*/
public static final String CATEGORY_PROMO = NotificationCompatApi21.CATEGORY_PROMO;
/**
* Notification category: alarm or timer.
*/
public static final String CATEGORY_ALARM = NotificationCompatApi21.CATEGORY_ALARM;
/**
* Notification category: progress of a long-running background operation.
*/
public static final String CATEGORY_PROGRESS = NotificationCompatApi21.CATEGORY_PROGRESS;
/**
* Notification category: social network or sharing update.
*/
public static final String CATEGORY_SOCIAL = NotificationCompatApi21.CATEGORY_SOCIAL;
/**
* Notification category: error in background operation or authentication status.
*/
public static final String CATEGORY_ERROR = NotificationCompatApi21.CATEGORY_ERROR;
/**
* Notification category: media transport control for playback.
*/
public static final String CATEGORY_TRANSPORT = NotificationCompatApi21.CATEGORY_TRANSPORT;
/**
* Notification category: system or device status update. Reserved for system use.
*/
public static final String CATEGORY_SYSTEM = NotificationCompatApi21.CATEGORY_SYSTEM;
/**
* Notification category: indication of running background service.
*/
public static final String CATEGORY_SERVICE = NotificationCompatApi21.CATEGORY_SERVICE;
/**
* Notification category: a specific, timely recommendation for a single thing.
* For example, a news app might want to recommend a news story it believes the user will
* want to read next.
*/
public static final String CATEGORY_RECOMMENDATION =
NotificationCompatApi21.CATEGORY_RECOMMENDATION;
/**
* Notification category: ongoing information about device or contextual status.
*/
public static final String CATEGORY_STATUS = NotificationCompatApi21.CATEGORY_STATUS;
private static final NotificationCompatImpl IMPL;
interface NotificationCompatImpl {
public Notification build(Builder b);
public Bundle getExtras(Notification n);
public int getActionCount(Notification n);
public Action getAction(Notification n, int actionIndex);
public Action[] getActionsFromParcelableArrayList(ArrayList<Parcelable> parcelables);
public ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions);
public String getCategory(Notification n);
public boolean getLocalOnly(Notification n);
public String getGroup(Notification n);
public boolean isGroupSummary(Notification n);
public String getSortKey(Notification n);
}
static class NotificationCompatImplBase implements NotificationCompatImpl {
@Override
public Notification build(Builder b) {
Notification result = b.mNotification;
result.setLatestEventInfo(b.mContext, b.mContentTitle,
b.mContentText, b.mContentIntent);
// translate high priority requests into legacy flag
if (b.mPriority > PRIORITY_DEFAULT) {
result.flags |= FLAG_HIGH_PRIORITY;
}
return result;
}
@Override
public Bundle getExtras(Notification n) {
return null;
}
@Override
public int getActionCount(Notification n) {
return 0;
}
@Override
public Action getAction(Notification n, int actionIndex) {
return null;
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return null;
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions) {
return null;
}
@Override
public String getCategory(Notification n) {
return null;
}
@Override
public boolean getLocalOnly(Notification n) {
return false;
}
@Override
public String getGroup(Notification n) {
return null;
}
@Override
public boolean isGroupSummary(Notification n) {
return false;
}
@Override
public String getSortKey(Notification n) {
return null;
}
}
static class NotificationCompatImplGingerbread extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
Notification result = b.mNotification;
result.setLatestEventInfo(b.mContext, b.mContentTitle,
b.mContentText, b.mContentIntent);
result = NotificationCompatGingerbread.add(result, b.mContext,
b.mContentTitle, b.mContentText, b.mContentIntent, b.mFullScreenIntent);
// translate high priority requests into legacy flag
if (b.mPriority > PRIORITY_DEFAULT) {
result.flags |= FLAG_HIGH_PRIORITY;
}
return result;
}
}
static class NotificationCompatImplHoneycomb extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
return NotificationCompatHoneycomb.add(b.mContext, b.mNotification,
b.mContentTitle, b.mContentText, b.mContentInfo, b.mTickerView,
b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon);
}
}
static class NotificationCompatImplIceCreamSandwich extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
return NotificationCompatIceCreamSandwich.add(b.mContext, b.mNotification,
b.mContentTitle, b.mContentText, b.mContentInfo, b.mTickerView,
b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate);
}
}
static class NotificationCompatImplJellybean extends NotificationCompatImplBase {
@Override
public Notification build(Builder b) {
NotificationCompatJellybean.Builder builder = new NotificationCompatJellybean.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public Bundle getExtras(Notification n) {
return NotificationCompatJellybean.getExtras(n);
}
@Override
public int getActionCount(Notification n) {
return NotificationCompatJellybean.getActionCount(n);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatJellybean.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatJellybean.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatJellybean.getParcelableArrayListForActions(actions);
}
@Override
public boolean getLocalOnly(Notification n) {
return NotificationCompatJellybean.getLocalOnly(n);
}
@Override
public String getGroup(Notification n) {
return NotificationCompatJellybean.getGroup(n);
}
@Override
public boolean isGroupSummary(Notification n) {
return NotificationCompatJellybean.isGroupSummary(n);
}
@Override
public String getSortKey(Notification n) {
return NotificationCompatJellybean.getSortKey(n);
}
}
static class NotificationCompatImplKitKat extends NotificationCompatImplJellybean {
@Override
public Notification build(Builder b) {
NotificationCompatKitKat.Builder builder = new NotificationCompatKitKat.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly,
b.mPeople, b.mExtras, b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public Bundle getExtras(Notification n) {
return NotificationCompatKitKat.getExtras(n);
}
@Override
public int getActionCount(Notification n) {
return NotificationCompatKitKat.getActionCount(n);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatKitKat.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public boolean getLocalOnly(Notification n) {
return NotificationCompatKitKat.getLocalOnly(n);
}
@Override
public String getGroup(Notification n) {
return NotificationCompatKitKat.getGroup(n);
}
@Override
public boolean isGroupSummary(Notification n) {
return NotificationCompatKitKat.isGroupSummary(n);
}
@Override
public String getSortKey(Notification n) {
return NotificationCompatKitKat.getSortKey(n);
}
}
static class NotificationCompatImplApi20 extends NotificationCompatImplKitKat {
@Override
public Notification build(Builder b) {
NotificationCompatApi20.Builder builder = new NotificationCompatApi20.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mPeople, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatApi20.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatApi20.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatApi20.getParcelableArrayListForActions(actions);
}
@Override
public boolean getLocalOnly(Notification n) {
return NotificationCompatApi20.getLocalOnly(n);
}
@Override
public String getGroup(Notification n) {
return NotificationCompatApi20.getGroup(n);
}
@Override
public boolean isGroupSummary(Notification n) {
return NotificationCompatApi20.isGroupSummary(n);
}
@Override
public String getSortKey(Notification n) {
return NotificationCompatApi20.getSortKey(n);
}
}
static class NotificationCompatImplApi21 extends NotificationCompatImplApi20 {
@Override
public Notification build(Builder b) {
NotificationCompatApi21.Builder builder = new NotificationCompatApi21.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return builder.build();
}
@Override
public String getCategory(Notification notif) {
return NotificationCompatApi21.getCategory(notif);
}
}
private static void addActionsToBuilder(NotificationBuilderWithActions builder,
ArrayList<Action> actions) {
for (Action action : actions) {
builder.addAction(action);
}
}
private static void addStyleToBuilderJellybean(NotificationBuilderWithBuilderAccessor builder,
Style style) {
if (style != null) {
if (style instanceof BigTextStyle) {
BigTextStyle bigTextStyle = (BigTextStyle) style;
NotificationCompatJellybean.addBigTextStyle(builder,
bigTextStyle.mBigContentTitle,
bigTextStyle.mSummaryTextSet,
bigTextStyle.mSummaryText,
bigTextStyle.mBigText);
} else if (style instanceof InboxStyle) {
InboxStyle inboxStyle = (InboxStyle) style;
NotificationCompatJellybean.addInboxStyle(builder,
inboxStyle.mBigContentTitle,
inboxStyle.mSummaryTextSet,
inboxStyle.mSummaryText,
inboxStyle.mTexts);
} else if (style instanceof BigPictureStyle) {
BigPictureStyle bigPictureStyle = (BigPictureStyle) style;
NotificationCompatJellybean.addBigPictureStyle(builder,
bigPictureStyle.mBigContentTitle,
bigPictureStyle.mSummaryTextSet,
bigPictureStyle.mSummaryText,
bigPictureStyle.mPicture,
bigPictureStyle.mBigLargeIcon,
bigPictureStyle.mBigLargeIconSet);
}
}
}
static {
if (Build.VERSION.SDK_INT >= 21) {
IMPL = new NotificationCompatImplApi21();
} else if (Build.VERSION.SDK_INT >= 20) {
IMPL = new NotificationCompatImplApi20();
} else if (Build.VERSION.SDK_INT >= 19) {
IMPL = new NotificationCompatImplKitKat();
} else if (Build.VERSION.SDK_INT >= 16) {
IMPL = new NotificationCompatImplJellybean();
} else if (Build.VERSION.SDK_INT >= 14) {
IMPL = new NotificationCompatImplIceCreamSandwich();
} else if (Build.VERSION.SDK_INT >= 11) {
IMPL = new NotificationCompatImplHoneycomb();
} else if (Build.VERSION.SDK_INT >= 9) {
IMPL = new NotificationCompatImplGingerbread();
} else {
IMPL = new NotificationCompatImplBase();
}
}
/**
* Builder class for {@link NotificationCompat} objects. Allows easier control over
* all the flags, as well as help constructing the typical notification layouts.
* <p>
* On platform versions that don't offer expanded notifications, methods that depend on
* expanded notifications have no effect.
* </p>
* <p>
* For example, action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later.
* <p>
* For this reason, you should always ensure that UI controls in a notification are also
* available in an {@link android.app.Activity} in your app, and you should always start that
* {@link android.app.Activity} when users click the notification. To do this, use the
* {@link NotificationCompat.Builder#setContentIntent setContentIntent()}
* method.
* </p>
*
*/
public static class Builder {
/**
* Maximum length of CharSequences accepted by Builder and friends.
*
* <p>
* Avoids spamming the system with overly large strings such as full e-mails.
*/
private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024;
Context mContext;
CharSequence mContentTitle;
CharSequence mContentText;
PendingIntent mContentIntent;
PendingIntent mFullScreenIntent;
RemoteViews mTickerView;
Bitmap mLargeIcon;
CharSequence mContentInfo;
int mNumber;
int mPriority;
boolean mShowWhen = true;
boolean mUseChronometer;
Style mStyle;
CharSequence mSubText;
int mProgressMax;
int mProgress;
boolean mProgressIndeterminate;
String mGroupKey;
boolean mGroupSummary;
String mSortKey;
ArrayList<Action> mActions = new ArrayList<Action>();
boolean mLocalOnly = false;
String mCategory;
Bundle mExtras;
int mColor = COLOR_DEFAULT;
int mVisibility = VISIBILITY_PRIVATE;
Notification mPublicVersion;
Notification mNotification = new Notification();
public ArrayList<String> mPeople;
/**
* Constructor.
*
* Automatically sets the when field to {@link System#currentTimeMillis()
* System.currentTimeMillis()} and the audio stream to the
* {@link Notification#STREAM_DEFAULT}.
*
* @param context A {@link Context} that will be used to construct the
* RemoteViews. The Context will not be held past the lifetime of this
* Builder object.
*/
public Builder(Context context) {
mContext = context;
// Set defaults to match the defaults of a Notification
mNotification.when = System.currentTimeMillis();
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
mPriority = PRIORITY_DEFAULT;
mPeople = new ArrayList<String>();
}
/**
* Set the time that the event occurred. Notifications in the panel are
* sorted by this time.
*/
public Builder setWhen(long when) {
mNotification.when = when;
return this;
}
/**
* Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
* in the content view.
*/
public Builder setShowWhen(boolean show) {
mShowWhen = show;
return this;
}
/**
* Show the {@link Notification#when} field as a stopwatch.
*
* Instead of presenting <code>when</code> as a timestamp, the notification will show an
* automatically updating display of the minutes and seconds since <code>when</code>.
*
* Useful when showing an elapsed time (like an ongoing phone call).
*
* @see android.widget.Chronometer
* @see Notification#when
*/
public Builder setUsesChronometer(boolean b) {
mUseChronometer = b;
return this;
}
/**
* Set the small icon to use in the notification layouts. Different classes of devices
* may return different sizes. See the UX guidelines for more information on how to
* design these icons.
*
* @param icon A resource ID in the application's package of the drawble to use.
*/
public Builder setSmallIcon(int icon) {
mNotification.icon = icon;
return this;
}
/**
* A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
* level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
* LevelListDrawable}.
*
* @param icon A resource ID in the application's package of the drawble to use.
* @param level The level to use for the icon.
*
* @see android.graphics.drawable.LevelListDrawable
*/
public Builder setSmallIcon(int icon, int level) {
mNotification.icon = icon;
mNotification.iconLevel = level;
return this;
}
/**
* Set the title (first row) of the notification, in a standard notification.
*/
public Builder setContentTitle(CharSequence title) {
mContentTitle = limitCharSequenceLength(title);
return this;
}
/**
* Set the text (second row) of the notification, in a standard notification.
*/
public Builder setContentText(CharSequence text) {
mContentText = limitCharSequenceLength(text);
return this;
}
/**
* Set the third line of text in the platform notification template.
* Don't use if you're also using {@link #setProgress(int, int, boolean)};
* they occupy the same location in the standard template.
* <br>
* If the platform does not provide large-format notifications, this method has no effect.
* The third line of text only appears in expanded view.
* <br>
*/
public Builder setSubText(CharSequence text) {
mSubText = limitCharSequenceLength(text);
return this;
}
/**
* Set the large number at the right-hand side of the notification. This is
* equivalent to setContentInfo, although it might show the number in a different
* font size for readability.
*/
public Builder setNumber(int number) {
mNumber = number;
return this;
}
/**
* Set the large text at the right-hand side of the notification.
*/
public Builder setContentInfo(CharSequence info) {
mContentInfo = limitCharSequenceLength(info);
return this;
}
/**
* Set the progress this notification represents, which may be
* represented as a {@link android.widget.ProgressBar}.
*/
public Builder setProgress(int max, int progress, boolean indeterminate) {
mProgressMax = max;
mProgress = progress;
mProgressIndeterminate = indeterminate;
return this;
}
/**
* Supply a custom RemoteViews to use instead of the standard one.
*/
public Builder setContent(RemoteViews views) {
mNotification.contentView = views;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is clicked.
* If you do not supply an intent, you can now add PendingIntents to individual
* views to be launched when clicked by calling {@link RemoteViews#setOnClickPendingIntent
* RemoteViews.setOnClickPendingIntent(int,PendingIntent)}. Be sure to
* read {@link Notification#contentIntent Notification.contentIntent} for
* how to correctly use this.
*/
public Builder setContentIntent(PendingIntent intent) {
mContentIntent = intent;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is cleared by the user
* directly from the notification panel. For example, this intent is sent when the user
* clicks the "Clear all" button, or the individual "X" buttons on notifications. This
* intent is not sent when the application calls
* {@link android.app.NotificationManager#cancel NotificationManager.cancel(int)}.
*/
public Builder setDeleteIntent(PendingIntent intent) {
mNotification.deleteIntent = intent;
return this;
}
/**
* An intent to launch instead of posting the notification to the status bar.
* Only for use with extremely high-priority notifications demanding the user's
* <strong>immediate</strong> attention, such as an incoming phone call or
* alarm clock that the user has explicitly set to a particular time.
* If this facility is used for something else, please give the user an option
* to turn it off and use a normal notification, as this can be extremely
* disruptive.
*
* <p>
* On some platforms, the system UI may choose to display a heads-up notification,
* instead of launching this intent, while the user is using the device.
* </p>
*
* @param intent The pending intent to launch.
* @param highPriority Passing true will cause this notification to be sent
* even if other notifications are suppressed.
*/
public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
mFullScreenIntent = intent;
setFlag(FLAG_HIGH_PRIORITY, highPriority);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives.
*/
public Builder setTicker(CharSequence tickerText) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives, and also a RemoteViews object that may be displayed instead on some
* devices.
*/
public Builder setTicker(CharSequence tickerText, RemoteViews views) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
mTickerView = views;
return this;
}
/**
* Set the large icon that is shown in the ticker and notification.
*/
public Builder setLargeIcon(Bitmap icon) {
mLargeIcon = icon;
return this;
}
/**
* Set the sound to play. It will play on the default stream.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*/
public Builder setSound(Uri sound) {
mNotification.sound = sound;
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
return this;
}
/**
* Set the sound to play. It will play on the stream you supply.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see Notification#STREAM_DEFAULT
* @see AudioManager for the <code>STREAM_</code> constants.
*/
public Builder setSound(Uri sound, int streamType) {
mNotification.sound = sound;
mNotification.audioStreamType = streamType;
return this;
}
/**
* Set the vibration pattern to use.
*
* <p>
* On some platforms, a notification that vibrates is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see android.os.Vibrator for a discussion of the <code>pattern</code>
* parameter.
*/
public Builder setVibrate(long[] pattern) {
mNotification.vibrate = pattern;
return this;
}
/**
* Set the argb value that you would like the LED on the device to blnk, as well as the
* rate. The rate is specified in terms of the number of milliseconds to be on
* and then the number of milliseconds to be off.
*/
public Builder setLights(int argb, int onMs, int offMs) {
mNotification.ledARGB = argb;
mNotification.ledOnMS = onMs;
mNotification.ledOffMS = offMs;
boolean showLights = mNotification.ledOnMS != 0 && mNotification.ledOffMS != 0;
mNotification.flags = (mNotification.flags & ~Notification.FLAG_SHOW_LIGHTS) |
(showLights ? Notification.FLAG_SHOW_LIGHTS : 0);
return this;
}
/**
* Set whether this is an ongoing notification.
*
* <p>Ongoing notifications differ from regular notifications in the following ways:
* <ul>
* <li>Ongoing notifications are sorted above the regular notifications in the
* notification panel.</li>
* <li>Ongoing notifications do not have an 'X' close button, and are not affected
* by the "Clear all" button.
* </ul>
*/
public Builder setOngoing(boolean ongoing) {
setFlag(Notification.FLAG_ONGOING_EVENT, ongoing);
return this;
}
/**
* Set this flag if you would only like the sound, vibrate
* and ticker to be played if the notification is not already showing.
*/
public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
setFlag(Notification.FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
return this;
}
/**
* Setting this flag will make it so the notification is automatically
* canceled when the user clicks it in the panel. The PendingIntent
* set with {@link #setDeleteIntent} will be broadcast when the notification
* is canceled.
*/
public Builder setAutoCancel(boolean autoCancel) {
setFlag(Notification.FLAG_AUTO_CANCEL, autoCancel);
return this;
}
/**
* Set whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* This hint can be set to recommend this notification not be bridged.
*/
public Builder setLocalOnly(boolean b) {
mLocalOnly = b;
return this;
}
/**
* Set the notification category.
*
* <p>Must be one of the predefined notification categories (see the <code>CATEGORY_*</code>
* constants in {@link Notification}) that best describes this notification.
* May be used by the system for ranking and filtering.
*/
public Builder setCategory(String category) {
mCategory = category;
return this;
}
/**
* Set the default notification options that will be used.
* <p>
* The value should be one or more of the following fields combined with
* bitwise-or:
* {@link Notification#DEFAULT_SOUND}, {@link Notification#DEFAULT_VIBRATE},
* {@link Notification#DEFAULT_LIGHTS}.
* <p>
* For all default values, use {@link Notification#DEFAULT_ALL}.
*/
public Builder setDefaults(int defaults) {
mNotification.defaults = defaults;
if ((defaults & Notification.DEFAULT_LIGHTS) != 0) {
mNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
}
return this;
}
private void setFlag(int mask, boolean value) {
if (value) {
mNotification.flags |= mask;
} else {
mNotification.flags &= ~mask;
}
}
/**
* Set the relative priority for this notification.
*
* Priority is an indication of how much of the user's
* valuable attention should be consumed by this
* notification. Low-priority notifications may be hidden from
* the user in certain situations, while the user might be
* interrupted for a higher-priority notification.
* The system sets a notification's priority based on various factors including the
* setPriority value. The effect may differ slightly on different platforms.
*
* @param pri Relative priority for this notification. Must be one of
* the priority constants defined by {@link NotificationCompat}.
* Acceptable values range from {@link
* NotificationCompat#PRIORITY_MIN} (-2) to {@link
* NotificationCompat#PRIORITY_MAX} (2).
*/
public Builder setPriority(int pri) {
mPriority = pri;
return this;
}
/**
* Add a person that is relevant to this notification.
*
* @see Notification#EXTRA_PEOPLE
*/
public Builder addPerson(String handle) {
mPeople.add(handle);
return this;
}
/**
* Set this notification to be part of a group of notifications sharing the same key.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering.
*
* <p>To make this notification the summary for its group, also call
* {@link #setGroupSummary}. A sort order can be specified for group members by using
* {@link #setSortKey}.
* @param groupKey The group key of the group.
* @return this object for method chaining
*/
public Builder setGroup(String groupKey) {
mGroupKey = groupKey;
return this;
}
/**
* Set this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link #setGroup}.
* @param isGroupSummary Whether this notification should be a group summary.
* @return this object for method chaining
*/
public Builder setGroupSummary(boolean isGroupSummary) {
mGroupSummary = isGroupSummary;
return this;
}
/**
* Set a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public Builder setSortKey(String sortKey) {
mSortKey = sortKey;
return this;
}
/**
* Merge additional metadata into this notification.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see Notification#extras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
if (mExtras == null) {
mExtras = new Bundle(extras);
} else {
mExtras.putAll(extras);
}
}
return this;
}
/**
* Set metadata for this notification.
*
* <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
* current contents are copied into the Notification each time {@link #build()} is
* called.
*
* <p>Replaces any existing extras values with those from the provided Bundle.
* Use {@link #addExtras} to merge in metadata instead.
*
* @see Notification#extras
*/
public Builder setExtras(Bundle extras) {
mExtras = extras;
return this;
}
/**
* Get the current metadata Bundle used by this notification Builder.
*
* <p>The returned Bundle is shared with this Builder.
*
* <p>The current contents of this Bundle are copied into the Notification each time
* {@link #build()} is called.
*
* @see Notification#extras
*/
public Bundle getExtras() {
if (mExtras == null) {
mExtras = new Bundle();
}
return mExtras;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param icon Resource ID of a drawable that represents the action.
* @param title Text describing the action.
* @param intent {@link android.app.PendingIntent} to be fired when the action is invoked.
*/
public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
mActions.add(new Action(icon, title, intent));
return this;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param action The action to add.
*/
public Builder addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Add a rich notification style to be applied at build time.
* <br>
* If the platform does not provide rich notification styles, this method has no effect. The
* user will always see the normal notification style.
*
* @param style Object responsible for modifying the notification style.
*/
public Builder setStyle(Style style) {
if (mStyle != style) {
mStyle = style;
if (mStyle != null) {
mStyle.setBuilder(this);
}
}
return this;
}
/**
* Sets {@link Notification#color}.
*
* @param argb The accent color to use
*
* @return The same Builder.
*/
public Builder setColor(int argb) {
mColor = argb;
return this;
}
/**
* Sets {@link Notification#visibility}.
*
* @param visibility One of {@link Notification#VISIBILITY_PRIVATE} (the default),
* {@link Notification#VISIBILITY_PUBLIC}, or
* {@link Notification#VISIBILITY_SECRET}.
*/
public Builder setVisibility(int visibility) {
mVisibility = visibility;
return this;
}
/**
* Supply a replacement Notification whose contents should be shown in insecure contexts
* (i.e. atop the secure lockscreen). See {@link Notification#visibility} and
* {@link #VISIBILITY_PUBLIC}.
*
* @param n A replacement notification, presumably with some or all info redacted.
* @return The same Builder.
*/
public Builder setPublicVersion(Notification n) {
mPublicVersion = n;
return this;
}
/**
* Apply an extender to this notification builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* @deprecated Use {@link #build()} instead.
*/
@Deprecated
public Notification getNotification() {
return IMPL.build(this);
}
/**
* Combine all of the options that have been set and return a new {@link Notification}
* object.
*/
public Notification build() {
return IMPL.build(this);
}
protected static CharSequence limitCharSequenceLength(CharSequence cs) {
if (cs == null) return cs;
if (cs.length() > MAX_CHARSEQUENCE_LENGTH) {
cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH);
}
return cs;
}
}
/**
* An object that can apply a rich notification style to a {@link Notification.Builder}
* object.
* <br>
* If the platform does not provide rich notification styles, methods in this class have no
* effect.
*/
public static abstract class Style {
Builder mBuilder;
CharSequence mBigContentTitle;
CharSequence mSummaryText;
boolean mSummaryTextSet = false;
public void setBuilder(Builder builder) {
if (mBuilder != builder) {
mBuilder = builder;
if (mBuilder != null) {
mBuilder.setStyle(this);
}
}
}
public Notification build() {
Notification notification = null;
if (mBuilder != null) {
notification = mBuilder.build();
}
return notification;
}
}
/**
* Helper class for generating large-format notifications that include a large image attachment.
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notif = new Notification.Builder(mContext)
* .setContentTitle("New photo from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_post)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigPictureStyle()
* .bigPicture(aBigBitmap))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigPictureStyle extends Style {
Bitmap mPicture;
Bitmap mBigLargeIcon;
boolean mBigLargeIconSet;
public BigPictureStyle() {
}
public BigPictureStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigPictureStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigPictureStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the bitmap to be used as the payload for the BigPicture notification.
*/
public BigPictureStyle bigPicture(Bitmap b) {
mPicture = b;
return this;
}
/**
* Override the large icon when the big notification is shown.
*/
public BigPictureStyle bigLargeIcon(Bitmap b) {
mBigLargeIcon = b;
mBigLargeIconSet = true;
return this;
}
}
/**
* Helper class for generating large-format notifications that include a lot of text.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notif = new Notification.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigTextStyle()
* .bigText(aVeryLongString))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigTextStyle extends Style {
CharSequence mBigText;
public BigTextStyle() {
}
public BigTextStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigTextStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigTextStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the longer text to be displayed in the big form of the
* template in place of the content text.
*/
public BigTextStyle bigText(CharSequence cs) {
mBigText = Builder.limitCharSequenceLength(cs);
return this;
}
}
/**
* Helper class for generating large-format notifications that include a list of (up to 5) strings.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification noti = new Notification.Builder()
* .setContentTitle("5 New mails from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.InboxStyle()
* .addLine(str1)
* .addLine(str2)
* .setContentTitle("")
* .setSummaryText("+3 more"))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class InboxStyle extends Style {
ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
public InboxStyle() {
}
public InboxStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public InboxStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public InboxStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Append a line to the digest section of the Inbox notification.
*/
public InboxStyle addLine(CharSequence cs) {
mTexts.add(Builder.limitCharSequenceLength(cs));
return this;
}
}
/**
* Structure to encapsulate a named action that can be shown as part of this notification.
* It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
* selected by the user. Action buttons won't appear on platforms prior to Android 4.1.
* <p>
* Apps should use {@link NotificationCompat.Builder#addAction(int, CharSequence, PendingIntent)}
* or {@link NotificationCompat.Builder#addAction(NotificationCompat.Action)}
* to attach actions.
*/
public static class Action extends NotificationCompatBase.Action {
private final Bundle mExtras;
private final RemoteInput[] mRemoteInputs;
/**
* Small icon representing the action.
*/
public int icon;
/**
* Title of the action.
*/
public CharSequence title;
/**
* Intent to send when the user invokes this action. May be null, in which case the action
* may be rendered in a disabled presentation.
*/
public PendingIntent actionIntent;
public Action(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle(), null);
}
private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
RemoteInput[] remoteInputs) {
this.icon = icon;
this.title = NotificationCompat.Builder.limitCharSequenceLength(title);
this.actionIntent = intent;
this.mExtras = extras != null ? extras : new Bundle();
this.mRemoteInputs = remoteInputs;
}
@Override
protected int getIcon() {
return icon;
}
@Override
protected CharSequence getTitle() {
return title;
}
@Override
protected PendingIntent getActionIntent() {
return actionIntent;
}
/**
* Get additional metadata carried around with this Action.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Get the list of inputs to be collected from the user when this action is sent.
* May return null if no remote inputs were added.
*/
public RemoteInput[] getRemoteInputs() {
return mRemoteInputs;
}
/**
* Builder class for {@link Action} objects.
*/
public static final class Builder {
private final int mIcon;
private final CharSequence mTitle;
private final PendingIntent mIntent;
private final Bundle mExtras;
private ArrayList<RemoteInput> mRemoteInputs;
/**
* Construct a new builder for {@link Action} object.
* @param icon icon to show for this action
* @param title the title of the action
* @param intent the {@link PendingIntent} to fire when users trigger this action
*/
public Builder(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle());
}
/**
* Construct a new builder for {@link Action} object using the fields from an
* {@link Action}.
* @param action the action to read fields from.
*/
public Builder(Action action) {
this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras));
}
private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras) {
mIcon = icon;
mTitle = NotificationCompat.Builder.limitCharSequenceLength(title);
mIntent = intent;
mExtras = extras;
}
/**
* Merge additional metadata into this builder.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see NotificationCompat.Action#getExtras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
mExtras.putAll(extras);
}
return this;
}
/**
* Get the metadata Bundle used by this Builder.
*
* <p>The returned Bundle is shared with this Builder.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Add an input to be collected from the user when this action is sent.
* Response values can be retrieved from the fired intent by using the
* {@link RemoteInput#getResultsFromIntent} function.
* @param remoteInput a {@link RemoteInput} to add to the action
* @return this object for method chaining
*/
public Builder addRemoteInput(RemoteInput remoteInput) {
if (mRemoteInputs == null) {
mRemoteInputs = new ArrayList<RemoteInput>();
}
mRemoteInputs.add(remoteInput);
return this;
}
/**
* Apply an extender to this action builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* Combine all of the options that have been set and return a new {@link Action}
* object.
* @return the built action
*/
public Action build() {
RemoteInput[] remoteInputs = mRemoteInputs != null
? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs);
}
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on an action builder.
*/
public interface Extender {
/**
* Apply this extender to a notification action builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
public Builder extend(Builder builder);
}
/**
* Wearable extender for notification actions. To add extensions to an action,
* create a new {@link NotificationCompat.Action.WearableExtender} object using
* the {@code WearableExtender()} constructor and apply it to a
* {@link NotificationCompat.Action.Builder} using
* {@link NotificationCompat.Action.Builder#extend}.
*
* <pre class="prettyprint">
* NotificationCompat.Action action = new NotificationCompat.Action.Builder(
* R.drawable.archive_all, "Archive all", actionIntent)
* .extend(new NotificationCompat.Action.WearableExtender()
* .setAvailableOffline(false))
* .build();</pre>
*/
public static final class WearableExtender implements Extender {
/** Notification action extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
private static final String KEY_FLAGS = "flags";
// Flags bitwise-ored to mFlags
private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
private int mFlags = DEFAULT_FLAGS;
/**
* Create a {@link NotificationCompat.Action.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
/**
* Create a {@link NotificationCompat.Action.WearableExtender} by reading
* wearable options present in an existing notification action.
* @param action the notification action to inspect.
*/
public WearableExtender(Action action) {
Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
if (wearableBundle != null) {
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
}
}
/**
* Apply wearable extensions to a notification action that is being built. This is
* typically called by the {@link NotificationCompat.Action.Builder#extend}
* method of {@link NotificationCompat.Action.Builder}.
*/
@Override
public Action.Builder extend(Action.Builder builder) {
Bundle wearableBundle = new Bundle();
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mFlags = this.mFlags;
return that;
}
/**
* Set whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public WearableExtender setAvailableOffline(boolean availableOffline) {
setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
return this;
}
/**
* Get whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public boolean isAvailableOffline() {
return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
}
/** @hide */
public static final Factory FACTORY = new Factory() {
@Override
public Action build(int icon, CharSequence title,
PendingIntent actionIntent, Bundle extras,
RemoteInputCompatBase.RemoteInput[] remoteInputs) {
return new Action(icon, title, actionIntent, extras,
(RemoteInput[]) remoteInputs);
}
@Override
public Action[] newArray(int length) {
return new Action[length];
}
};
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on a notification builder.
*/
public interface Extender {
/**
* Apply this extender to a notification builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
public Builder extend(Builder builder);
}
/**
* Helper class to add wearable extensions to notifications.
* <p class="note"> See
* <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
* for Android Wear</a> for more information on how to use this class.
* <p>
* To create a notification with wearable extensions:
* <ol>
* <li>Create a {@link NotificationCompat.Builder}, setting any desired
* properties.
* <li>Create a {@link NotificationCompat.WearableExtender}.
* <li>Set wearable-specific properties using the
* {@code add} and {@code set} methods of {@link NotificationCompat.WearableExtender}.
* <li>Call {@link NotificationCompat.Builder#extend} to apply the extensions to a
* notification.
* <li>Post the notification to the notification
* system with the {@code NotificationManagerCompat.notify(...)} methods
* and not the {@code NotificationManager.notify(...)} methods.
* </ol>
*
* <pre class="prettyprint">
* Notification notif = new NotificationCompat.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .extend(new NotificationCompat.WearableExtender()
* .setContentIcon(R.drawable.new_mail))
* .build();
* NotificationManagerCompat.from(mContext).notify(0, notif);</pre>
*
* <p>Wearable extensions can be accessed on an existing notification by using the
* {@code WearableExtender(Notification)} constructor,
* and then using the {@code get} methods to access values.
*
* <pre class="prettyprint">
* NotificationCompat.WearableExtender wearableExtender =
* new NotificationCompat.WearableExtender(notification);
* List<Notification> pages = wearableExtender.getPages();</pre>
*/
public static final class WearableExtender implements Extender {
/**
* Sentinel value for an action index that is unset.
*/
public static final int UNSET_ACTION_INDEX = -1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification with
* default sizing.
* <p>For custom display notifications created using {@link #setDisplayIntent},
* the default is {@link #SIZE_LARGE}. All other notifications size automatically based
* on their content.
*/
public static final int SIZE_DEFAULT = 0;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with an extra small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_XSMALL = 1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_SMALL = 2;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a medium size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_MEDIUM = 3;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a large size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_LARGE = 4;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* full screen.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_FULL_SCREEN = 5;
/** Notification extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
// Keys within EXTRA_WEARABLE_OPTIONS for wearable options.
private static final String KEY_ACTIONS = "actions";
private static final String KEY_FLAGS = "flags";
private static final String KEY_DISPLAY_INTENT = "displayIntent";
private static final String KEY_PAGES = "pages";
private static final String KEY_BACKGROUND = "background";
private static final String KEY_CONTENT_ICON = "contentIcon";
private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
private static final String KEY_GRAVITY = "gravity";
// Flags bitwise-ored to mFlags
private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
private static final int DEFAULT_CONTENT_ICON_GRAVITY = GravityCompat.END;
private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
private ArrayList<Action> mActions = new ArrayList<Action>();
private int mFlags = DEFAULT_FLAGS;
private PendingIntent mDisplayIntent;
private ArrayList<Notification> mPages = new ArrayList<Notification>();
private Bitmap mBackground;
private int mContentIcon;
private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
private int mContentActionIndex = UNSET_ACTION_INDEX;
private int mCustomSizePreset = SIZE_DEFAULT;
private int mCustomContentHeight;
private int mGravity = DEFAULT_GRAVITY;
/**
* Create a {@link NotificationCompat.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
public WearableExtender(Notification notif) {
Bundle extras = getExtras(notif);
Bundle wearableBundle = extras != null ? extras.getBundle(EXTRA_WEARABLE_EXTENSIONS)
: null;
if (wearableBundle != null) {
Action[] actions = IMPL.getActionsFromParcelableArrayList(
wearableBundle.getParcelableArrayList(KEY_ACTIONS));
if (actions != null) {
Collections.addAll(mActions, actions);
}
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
Notification[] pages = getNotificationArrayFromBundle(
wearableBundle, KEY_PAGES);
if (pages != null) {
Collections.addAll(mPages, pages);
}
mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
DEFAULT_CONTENT_ICON_GRAVITY);
mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
UNSET_ACTION_INDEX);
mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
SIZE_DEFAULT);
mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
}
}
/**
* Apply wearable extensions to a notification that is being built. This is typically
* called by the {@link NotificationCompat.Builder#extend} method of
* {@link NotificationCompat.Builder}.
*/
@Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
Bundle wearableBundle = new Bundle();
if (!mActions.isEmpty()) {
wearableBundle.putParcelableArrayList(KEY_ACTIONS,
IMPL.getParcelableArrayListForActions(mActions.toArray(
new Action[mActions.size()])));
}
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
if (mDisplayIntent != null) {
wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
}
if (!mPages.isEmpty()) {
wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
new Notification[mPages.size()]));
}
if (mBackground != null) {
wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
}
if (mContentIcon != 0) {
wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
}
if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
}
if (mContentActionIndex != UNSET_ACTION_INDEX) {
wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
mContentActionIndex);
}
if (mCustomSizePreset != SIZE_DEFAULT) {
wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
}
if (mCustomContentHeight != 0) {
wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
}
if (mGravity != DEFAULT_GRAVITY) {
wearableBundle.putInt(KEY_GRAVITY, mGravity);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mActions = new ArrayList<Action>(this.mActions);
that.mFlags = this.mFlags;
that.mDisplayIntent = this.mDisplayIntent;
that.mPages = new ArrayList<Notification>(this.mPages);
that.mBackground = this.mBackground;
that.mContentIcon = this.mContentIcon;
that.mContentIconGravity = this.mContentIconGravity;
that.mContentActionIndex = this.mContentActionIndex;
that.mCustomSizePreset = this.mCustomSizePreset;
that.mCustomContentHeight = this.mCustomContentHeight;
that.mGravity = this.mGravity;
return that;
}
/**
* Add a wearable action to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param action the action to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Adds wearable actions to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param actions the actions to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addActions(List<Action> actions) {
mActions.addAll(actions);
return this;
}
/**
* Clear all wearable actions present on this builder.
* @return this object for method chaining.
* @see #addAction
*/
public WearableExtender clearActions() {
mActions.clear();
return this;
}
/**
* Get the wearable actions present on this notification.
*/
public List<Action> getActions() {
return mActions;
}
/**
* Set an intent to launch inside of an activity view when displaying
* this notification. The {@link PendingIntent} provided should be for an activity.
*
* <pre class="prettyprint">
* Intent displayIntent = new Intent(context, MyDisplayActivity.class);
* PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
* 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
* Notification notif = new NotificationCompat.Builder(context)
* .extend(new NotificationCompat.WearableExtender()
* .setDisplayIntent(displayPendingIntent)
* .setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_MEDIUM))
* .build();</pre>
*
* <p>The activity to launch needs to allow embedding, must be exported, and
* should have an empty task affinity. It is also recommended to use the device
* default light theme.
*
* <p>Example AndroidManifest.xml entry:
* <pre class="prettyprint">
* <activity android:name="com.example.MyDisplayActivity"
* android:exported="true"
* android:allowEmbedded="true"
* android:taskAffinity=""
* android:theme="@android:style/Theme.DeviceDefault.Light" /></pre>
*
* @param intent the {@link PendingIntent} for an activity
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getDisplayIntent
*/
public WearableExtender setDisplayIntent(PendingIntent intent) {
mDisplayIntent = intent;
return this;
}
/**
* Get the intent to launch inside of an activity view when displaying this
* notification. This {@code PendingIntent} should be for an activity.
*/
public PendingIntent getDisplayIntent() {
return mDisplayIntent;
}
/**
* Add an additional page of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param page the notification to add as another page
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPage(Notification page) {
mPages.add(page);
return this;
}
/**
* Add additional pages of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param pages a list of notifications
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPages(List<Notification> pages) {
mPages.addAll(pages);
return this;
}
/**
* Clear all additional pages present on this builder.
* @return this object for method chaining.
* @see #addPage
*/
public WearableExtender clearPages() {
mPages.clear();
return this;
}
/**
* Get the array of additional pages of content for displaying this notification. The
* current notification forms the first page, and elements within this array form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
* @return the pages for this notification
*/
public List<Notification> getPages() {
return mPages;
}
/**
* Set a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @param background the background bitmap
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getBackground
*/
public WearableExtender setBackground(Bitmap background) {
mBackground = background;
return this;
}
/**
* Get a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @return the background image
* @see NotificationCompat.WearableExtender#setBackground
*/
public Bitmap getBackground() {
return mBackground;
}
/**
* Set an icon that goes with the content of this notification.
*/
public WearableExtender setContentIcon(int icon) {
mContentIcon = icon;
return this;
}
/**
* Get an icon that goes with the content of this notification.
*/
public int getContentIcon() {
return mContentIcon;
}
/**
* Set the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #setContentIcon
*/
public WearableExtender setContentIconGravity(int contentIconGravity) {
mContentIconGravity = contentIconGravity;
return this;
}
/**
* Get the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #getContentIcon
*/
public int getContentIconGravity() {
return mContentIconGravity;
}
/**
* Set an action from this notification's actions to be clickable with the content of
* this notification. This action will no longer display separately from the
* notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* @param actionIndex The index of the action to hoist onto the current notification page.
* If wearable actions were added to the main notification, this index
* will apply to that list, otherwise it will apply to the regular
* actions list.
*/
public WearableExtender setContentAction(int actionIndex) {
mContentActionIndex = actionIndex;
return this;
}
/**
* Get the index of the notification action, if any, that was specified as being clickable
* with the content of this notification. This action will no longer display separately
* from the notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* <p>If wearable specific actions were added to the main notification, this index will
* apply to that list, otherwise it will apply to the regular actions list.
*
* @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
*/
public int getContentAction() {
return mContentActionIndex;
}
/**
* Set the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public WearableExtender setGravity(int gravity) {
mGravity = gravity;
return this;
}
/**
* Get the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public int getGravity() {
return mGravity;
}
/**
* Set the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. Check the
* documentation for the preset in question. See also
* {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
*/
public WearableExtender setCustomSizePreset(int sizePreset) {
mCustomSizePreset = sizePreset;
return this;
}
/**
* Get the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link #setDisplayIntent}. Check the documentation for the preset in question.
* See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
*/
public int getCustomSizePreset() {
return mCustomSizePreset;
}
/**
* Set the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. See also
* {@link NotificationCompat.WearableExtender#setCustomSizePreset} and
* {@link #getCustomContentHeight}.
*/
public WearableExtender setCustomContentHeight(int height) {
mCustomContentHeight = height;
return this;
}
/**
* Get the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
* {@link #setCustomContentHeight}.
*/
public int getCustomContentHeight() {
return mCustomContentHeight;
}
/**
* Set whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
return this;
}
/**
* Get whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public boolean getStartScrollBottom() {
return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
}
/**
* Set whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public WearableExtender setContentIntentAvailableOffline(
boolean contentIntentAvailableOffline) {
setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
return this;
}
/**
* Get whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public boolean getContentIntentAvailableOffline() {
return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
}
/**
* Set a hint that this notification's icon should not be displayed.
* @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintHideIcon(boolean hintHideIcon) {
setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
return this;
}
/**
* Get a hint that this notification's icon should not be displayed.
* @return {@code true} if this icon should not be displayed, false otherwise.
* The default value is {@code false} if this was never set.
*/
public boolean getHintHideIcon() {
return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
}
/**
* Set a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link #addPage}.
*/
public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
return this;
}
/**
* Get a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link NotificationCompat.WearableExtender#addPage}.
*/
public boolean getHintShowBackgroundOnly() {
return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
}
/**
* Get an array of Notification objects from a parcelable array bundle field.
* Update the bundle to have a typed array so fetches in the future don't need
* to do an array copy.
*/
private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
Parcelable[] array = bundle.getParcelableArray(key);
if (array instanceof Notification[] || array == null) {
return (Notification[]) array;
}
Notification[] typedArray = new Notification[array.length];
for (int i = 0; i < array.length; i++) {
typedArray[i] = (Notification) array[i];
}
bundle.putParcelableArray(key, typedArray);
return typedArray;
}
/**
* Gets the {@link Notification#extras} field from a notification in a backwards
* compatible manner. Extras field was supported from JellyBean (Api level 16)
* forwards. This function will return null on older api levels.
*/
public static Bundle getExtras(Notification notif) {
return IMPL.getExtras(notif);
}
/**
* Get the number of actions in this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
*/
public static int getActionCount(Notification notif) {
return IMPL.getActionCount(notif);
}
/**
* Get an action on this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
* @param notif The notification to inspect.
* @param actionIndex The index of the action to retrieve.
*/
public static Action getAction(Notification notif, int actionIndex) {
return IMPL.getAction(notif, actionIndex);
}
/**
* Get the category of this notification in a backwards compatible
* manner.
* @param notif The notification to inspect.
*/
public static String getCategory(Notification notif) {
return IMPL.getCategory(notif);
}
/**
* Get whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* If this hint is set, it is recommend that this notification not be bridged.
*/
public static boolean getLocalOnly(Notification notif) {
return IMPL.getLocalOnly(notif);
}
/**
* Get the key used to group this notification into a cluster or stack
* with other notifications on devices which support such rendering.
*/
public static String getGroup(Notification notif) {
return IMPL.getGroup(notif);
}
/**
* Get whether this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
* @return Whether this notification is a group summary.
*/
public static boolean isGroupSummary(Notification notif) {
return IMPL.isGroupSummary(notif);
}
/**
* Get a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public static String getSortKey(Notification notif) {
return IMPL.getSortKey(notif);
}
}
| am 3f632fcd: am f3f73479: am 6b66bba1: Merge "NoCompat: Add missing L extras" into lmp-dev
* commit '3f632fcd56498ba8dfcef158e6a4fb51fc55a48a':
NoCompat: Add missing L extras
| v4/java/android/support/v4/app/NotificationCompat.java | am 3f632fcd: am f3f73479: am 6b66bba1: Merge "NoCompat: Add missing L extras" into lmp-dev |
|
Java | apache-2.0 | 30b56777e48d86cc41e72e63225475dc8134b46a | 0 | helyho/Voovan,helyho/Voovan,helyho/Voovan | package org.voovan.network;
import org.voovan.tools.ByteBufferChannel;
import org.voovan.tools.TByteBuffer;
import org.voovan.tools.TEnv;
import org.voovan.tools.exception.MemoryReleasedException;
import org.voovan.tools.log.Logger;
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* SSL 解析器
* 1.握手信息
* 2.报文信息
*
* @author helyho
* <p>
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class SSLParser {
private SSLEngine engine;
private ByteBuffer appData;
private ByteBuffer netData;
private IoSession session;
boolean handShakeDone = false;
/**
* 构造函数
*
* @param engine SSLEngine对象
* @param session session 对象
*/
public SSLParser(SSLEngine engine, IoSession session) {
this.engine = engine;
this.session = session;
this.appData = buildAppDataBuffer();
this.netData = buildNetDataBuffer();
}
/**
* 判断握手是否完成
*
* @return 握手是否完成
*/
public boolean isHandShakeDone() {
return handShakeDone;
}
/**
* 获取 SSLEngine
*
* @return SSLEngine 对象
*/
public SSLEngine getSSLEngine() {
return engine;
}
public ByteBuffer buildNetDataBuffer() {
SSLSession sslSession = engine.getSession();
int newBufferMax = sslSession.getPacketBufferSize();
return TByteBuffer.allocateDirect(newBufferMax);
}
public ByteBuffer buildAppDataBuffer() {
SSLSession sslSession = engine.getSession();
int newBufferMax = sslSession.getPacketBufferSize();
return TByteBuffer.allocateDirect(newBufferMax);
}
/**
* 清理缓冲区
*/
private void clearBuffer() {
appData.clear();
netData.clear();
}
/**
* 打包并发送数据
*
* @param buffer 需要的数据缓冲区
* @return 返回成功执行的最后一个或者失败的那个 SSLEnginResult
* @throws IOException IO 异常
*/
public synchronized SSLEngineResult warpData(ByteBuffer buffer) throws IOException {
if (session.isConnected()) {
SSLEngineResult engineResult = null;
do {
synchronized (netData) {
if(!TByteBuffer.isReleased(netData)) {
netData.clear();
engineResult = engine.wrap(buffer, netData);
netData.flip();
if (session.isConnected() && engineResult.bytesProduced() > 0 && netData.limit() > 0) {
session.send0(netData);
}
netData.clear();
} else {
return null;
}
}
} while (engineResult.getStatus() == Status.OK && buffer.hasRemaining());
return engineResult;
} else {
return null;
}
}
/**
* 处理握手 Warp;
*
* @return
* @throws IOException
* @throws Exception
*/
private synchronized HandshakeStatus doHandShakeWarp() throws IOException {
int waitCount = 0;
while (true) {
if(!session.isConnected()){
return null;
}
if (waitCount >= session.socketContext().getReadTimeout()) {
throw new SSLHandshakeException("Hand shake on: " + session.remoteAddress() + ":" + session.remotePort() + " timeout");
}
try {
clearBuffer();
appData.flip();
if (warpData(appData) == null) {
return null;
}
//如果有 HandShake Task 则执行
HandshakeStatus handshakeStatus = runDelegatedTasks();
return handshakeStatus;
} catch (SSLException e) {
waitCount++;
TEnv.sleep(1);
continue;
}
}
}
/**
* 解包数据
*
* @param netBuffer 接受解包数据的缓冲区
* @param appBuffer 接受解包后数据的缓冲区
* @throws SSLException SSL 异常
* @return SSLEngineResult 对象
*/
public synchronized SSLEngineResult unwarpData(ByteBuffer netBuffer, ByteBuffer appBuffer) throws SSLException {
if (session.isConnected()) {
SSLEngineResult engineResult = null;
synchronized (appBuffer) {
if(!TByteBuffer.isReleased(appBuffer)) {
engineResult = engine.unwrap(netBuffer, appBuffer);
} else {
return null;
}
}
return engineResult;
} else {
return null;
}
}
/**
* 处理握手 Unwarp;
*
* @return
* @throws IOException
* @throws Exception
*/
private synchronized HandshakeStatus doHandShakeUnwarp() throws IOException {
HandshakeStatus handshakeStatus = null;
SSLEngineResult engineResult = null;
int waitCount = 0;
while (true) {
if(!session.isConnected()){
break;
}
if (waitCount >= session.socketContext().getReadTimeout()) {
throw new SSLHandshakeException("Hand shake on: " + session.remoteAddress() + ":" + session.remotePort() + " timeout");
}
clearBuffer();
ByteBufferChannel byteBufferChannel = session.getByteBufferChannel();
if (byteBufferChannel.isReleased()) {
throw new IOException("Socket is disconnect");
}
if (byteBufferChannel.size() > 0) {
ByteBuffer byteBuffer = byteBufferChannel.getByteBuffer();
engineResult = unwarpData(byteBuffer, appData);
if (engineResult == null) {
return null;
}
byteBufferChannel.compact();
switch (engineResult.getStatus()) {
case OK: {
return engine.getHandshakeStatus();
}
case CLOSED: {
Logger.error(new SSLHandshakeException("Handshake failed: " + engineResult.getStatus()));
session.close();
break;
}
case BUFFER_OVERFLOW: {
break;
}
case BUFFER_UNDERFLOW: {
break;
}
}
if (!session.isConnected()) {
break;
}
}
waitCount++;
TEnv.sleep(1);
}
;
return handshakeStatus == null ? engine.getHandshakeStatus() : handshakeStatus;
}
/**
* 执行委派任务
*
* @throws Exception
*/
private synchronized HandshakeStatus runDelegatedTasks() {
if (handShakeDone == false) {
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
Runnable runnable;
while ((runnable = engine.getDelegatedTask()) != null) {
runnable.run();
}
}
return engine.getHandshakeStatus();
}
return null;
}
public synchronized boolean doHandShake() throws IOException {
engine.beginHandshake();
int handShakeCount = 0;
HandshakeStatus handshakeStatus = engine.getHandshakeStatus();
while (!handShakeDone && handShakeCount < 20) {
handShakeCount++;
if (handshakeStatus == null) {
throw new SSLException("doHandShake: Socket is disconnect");
}
switch (handshakeStatus) {
case NEED_TASK:
handshakeStatus = runDelegatedTasks();
break;
case NEED_WRAP:
handshakeStatus = doHandShakeWarp();
break;
case NEED_UNWRAP:
handshakeStatus = doHandShakeUnwarp();
break;
case FINISHED:
handshakeStatus = engine.getHandshakeStatus();
break;
case NOT_HANDSHAKING:
handShakeDone = true;
break;
default:
break;
}
// TEnv.sleep(1);
}
return handShakeDone;
}
/**
* 读取SSL消息到缓冲区
*
* @param session Socket 会话对象
* @param netByteBufferChannel Socket SSL 加密后的数据
* @param appByteBufferChannel Socket SSL 解密后的数据
* @return 接收数据大小
* @throws IOException IO异常
*/
public synchronized int unWarpByteBufferChannel(IoSession session, ByteBufferChannel netByteBufferChannel,
ByteBufferChannel appByteBufferChannel) throws IOException {
int readSize = 0;
if (session.isConnected() && netByteBufferChannel.size() > 0) {
SSLEngineResult engineResult = null;
try {
while (true) {
appData.clear();
ByteBuffer byteBuffer = netByteBufferChannel.getByteBuffer();
engineResult = unwarpData(byteBuffer, appData);
netByteBufferChannel.compact();
if (engineResult == null) {
throw new SSLException("unWarpByteBufferChannel: Socket is disconnect");
}
appData.flip();
appByteBufferChannel.writeEnd(appData);
if (engineResult != null &&
engineResult.getStatus() == Status.OK &&
byteBuffer.remaining() == 0) {
break;
}
if (engineResult != null &&
(engineResult.getStatus() == Status.BUFFER_OVERFLOW ||
engineResult.getStatus() == Status.BUFFER_UNDERFLOW ||
engineResult.getStatus() == Status.CLOSED)
) {
break;
}
}
}catch (MemoryReleasedException e){
if(!session.isConnected()) {
throw new SSLException("unWarpByteBufferChannel ");
}
}
}
return readSize;
}
public void release() {
TByteBuffer.release(netData);
TByteBuffer.release(appData);
}
public static boolean isHandShakeDone(IoSession session){
if(session==null || session.getSSLParser()==null){
return true;
}else{
return session.getSSLParser().isHandShakeDone();
}
}
}
| Network/src/main/java/org/voovan/network/SSLParser.java | package org.voovan.network;
import org.voovan.tools.ByteBufferChannel;
import org.voovan.tools.TByteBuffer;
import org.voovan.tools.TEnv;
import org.voovan.tools.exception.MemoryReleasedException;
import org.voovan.tools.log.Logger;
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* SSL 解析器
* 1.握手信息
* 2.报文信息
*
* @author helyho
* <p>
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class SSLParser {
private SSLEngine engine;
private ByteBuffer appData;
private ByteBuffer netData;
private IoSession session;
boolean handShakeDone = false;
/**
* 构造函数
*
* @param engine SSLEngine对象
* @param session session 对象
*/
public SSLParser(SSLEngine engine, IoSession session) {
this.engine = engine;
this.session = session;
this.appData = buildAppDataBuffer();
this.netData = buildNetDataBuffer();
}
/**
* 判断握手是否完成
*
* @return 握手是否完成
*/
public boolean isHandShakeDone() {
return handShakeDone;
}
/**
* 获取 SSLEngine
*
* @return SSLEngine 对象
*/
public SSLEngine getSSLEngine() {
return engine;
}
public ByteBuffer buildNetDataBuffer() {
SSLSession sslSession = engine.getSession();
int newBufferMax = sslSession.getPacketBufferSize();
return TByteBuffer.allocateDirect(newBufferMax);
}
public ByteBuffer buildAppDataBuffer() {
SSLSession sslSession = engine.getSession();
int newBufferMax = sslSession.getPacketBufferSize();
return TByteBuffer.allocateDirect(newBufferMax);
}
/**
* 清理缓冲区
*/
private void clearBuffer() {
appData.clear();
netData.clear();
}
/**
* 打包并发送数据
*
* @param buffer 需要的数据缓冲区
* @return 返回成功执行的最后一个或者失败的那个 SSLEnginResult
* @throws IOException IO 异常
*/
public synchronized SSLEngineResult warpData(ByteBuffer buffer) throws IOException {
if (session.isConnected()) {
SSLEngineResult engineResult = null;
do {
synchronized (netData) {
if(!TByteBuffer.isReleased(netData)) {
netData.clear();
engineResult = engine.wrap(buffer, netData);
netData.flip();
if (session.isConnected() && engineResult.bytesProduced() > 0 && netData.limit() > 0) {
session.send0(netData);
}
netData.clear();
} else {
return null;
}
}
} while (engineResult.getStatus() == Status.OK && buffer.hasRemaining());
return engineResult;
} else {
return null;
}
}
/**
* 处理握手 Warp;
*
* @return
* @throws IOException
* @throws Exception
*/
private synchronized HandshakeStatus doHandShakeWarp() throws IOException {
int waitCount = 0;
while (true) {
if (waitCount >= session.socketContext().getReadTimeout() || !session.isConnected()) {
throw new SSLHandshakeException("Hand shake on: " + session.remoteAddress() + ":" + session.remotePort() + " timeout");
}
try {
clearBuffer();
appData.flip();
if (warpData(appData) == null) {
return null;
}
//如果有 HandShake Task 则执行
HandshakeStatus handshakeStatus = runDelegatedTasks();
return handshakeStatus;
} catch (SSLException e) {
waitCount++;
TEnv.sleep(1);
continue;
}
}
}
/**
* 解包数据
*
* @param netBuffer 接受解包数据的缓冲区
* @param appBuffer 接受解包后数据的缓冲区
* @throws SSLException SSL 异常
* @return SSLEngineResult 对象
*/
public synchronized SSLEngineResult unwarpData(ByteBuffer netBuffer, ByteBuffer appBuffer) throws SSLException {
if (session.isConnected()) {
SSLEngineResult engineResult = null;
synchronized (appBuffer) {
if(!TByteBuffer.isReleased(appBuffer)) {
engineResult = engine.unwrap(netBuffer, appBuffer);
} else {
return null;
}
}
return engineResult;
} else {
return null;
}
}
/**
* 处理握手 Unwarp;
*
* @return
* @throws IOException
* @throws Exception
*/
private synchronized HandshakeStatus doHandShakeUnwarp() throws IOException {
HandshakeStatus handshakeStatus = null;
SSLEngineResult engineResult = null;
int waitCount = 0;
while (true) {
if (waitCount >= session.socketContext().getReadTimeout() || !session.isConnected()) {
throw new SSLHandshakeException("Hand shake on: " + session.remoteAddress() + ":" + session.remotePort() + " timeout");
}
clearBuffer();
ByteBufferChannel byteBufferChannel = session.getByteBufferChannel();
if (byteBufferChannel.isReleased()) {
throw new IOException("Socket is disconnect");
}
if (byteBufferChannel.size() > 0) {
ByteBuffer byteBuffer = byteBufferChannel.getByteBuffer();
engineResult = unwarpData(byteBuffer, appData);
if (engineResult == null) {
return null;
}
byteBufferChannel.compact();
switch (engineResult.getStatus()) {
case OK: {
return engine.getHandshakeStatus();
}
case CLOSED: {
Logger.error(new SSLHandshakeException("Handshake failed: " + engineResult.getStatus()));
session.close();
break;
}
case BUFFER_OVERFLOW: {
break;
}
case BUFFER_UNDERFLOW: {
break;
}
}
if (!session.isConnected()) {
break;
}
}
waitCount++;
TEnv.sleep(1);
}
;
return handshakeStatus == null ? engine.getHandshakeStatus() : handshakeStatus;
}
/**
* 执行委派任务
*
* @throws Exception
*/
private synchronized HandshakeStatus runDelegatedTasks() {
if (handShakeDone == false) {
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
Runnable runnable;
while ((runnable = engine.getDelegatedTask()) != null) {
runnable.run();
}
}
return engine.getHandshakeStatus();
}
return null;
}
public synchronized boolean doHandShake() throws IOException {
engine.beginHandshake();
int handShakeCount = 0;
HandshakeStatus handshakeStatus = engine.getHandshakeStatus();
while (!handShakeDone && handShakeCount < 20) {
handShakeCount++;
if (handshakeStatus == null) {
throw new SSLException("doHandShake: Socket is disconnect");
}
switch (handshakeStatus) {
case NEED_TASK:
handshakeStatus = runDelegatedTasks();
break;
case NEED_WRAP:
handshakeStatus = doHandShakeWarp();
break;
case NEED_UNWRAP:
handshakeStatus = doHandShakeUnwarp();
break;
case FINISHED:
handshakeStatus = engine.getHandshakeStatus();
break;
case NOT_HANDSHAKING:
handShakeDone = true;
break;
default:
break;
}
// TEnv.sleep(1);
}
return handShakeDone;
}
/**
* 读取SSL消息到缓冲区
*
* @param session Socket 会话对象
* @param netByteBufferChannel Socket SSL 加密后的数据
* @param appByteBufferChannel Socket SSL 解密后的数据
* @return 接收数据大小
* @throws IOException IO异常
*/
public synchronized int unWarpByteBufferChannel(IoSession session, ByteBufferChannel netByteBufferChannel,
ByteBufferChannel appByteBufferChannel) throws IOException {
int readSize = 0;
if (session.isConnected() && netByteBufferChannel.size() > 0) {
SSLEngineResult engineResult = null;
try {
while (true) {
appData.clear();
ByteBuffer byteBuffer = netByteBufferChannel.getByteBuffer();
engineResult = unwarpData(byteBuffer, appData);
netByteBufferChannel.compact();
if (engineResult == null) {
throw new SSLException("unWarpByteBufferChannel: Socket is disconnect");
}
appData.flip();
appByteBufferChannel.writeEnd(appData);
if (engineResult != null &&
engineResult.getStatus() == Status.OK &&
byteBuffer.remaining() == 0) {
break;
}
if (engineResult != null &&
(engineResult.getStatus() == Status.BUFFER_OVERFLOW ||
engineResult.getStatus() == Status.BUFFER_UNDERFLOW ||
engineResult.getStatus() == Status.CLOSED)
) {
break;
}
}
}catch (MemoryReleasedException e){
if(!session.isConnected()) {
throw new SSLException("unWarpByteBufferChannel ");
}
}
}
return readSize;
}
public void release() {
TByteBuffer.release(netData);
TByteBuffer.release(appData);
}
public static boolean isHandShakeDone(IoSession session){
if(session==null || session.getSSLParser()==null){
return true;
}else{
return session.getSSLParser().isHandShakeDone();
}
}
}
| imp: 修复SSL握手连接断开抛出异常的问题
| Network/src/main/java/org/voovan/network/SSLParser.java | imp: 修复SSL握手连接断开抛出异常的问题 |
|
Java | apache-2.0 | a750fa97f1d4def205c85a3f3da25d348b4b6627 | 0 | blindpirate/gradle,gradle/gradle,gstevey/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle | /*
* Copyright 2013 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 org.gradle.tooling.internal.consumer;
import org.gradle.tooling.CancellationToken;
import org.gradle.tooling.LongRunningOperation;
import org.gradle.tooling.ProgressListener;
import org.gradle.tooling.internal.consumer.parameters.ConsumerOperationParameters;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
public abstract class AbstractLongRunningOperation<T extends AbstractLongRunningOperation<T>> implements LongRunningOperation {
protected final ConnectionParameters connectionParameters;
protected final ConsumerOperationParameters.Builder operationParamsBuilder;
protected AbstractLongRunningOperation(ConnectionParameters parameters) {
connectionParameters = parameters;
operationParamsBuilder = ConsumerOperationParameters.builder();
operationParamsBuilder.setCancellationToken(new DefaultCancellationTokenSource().token());
}
protected abstract T getThis();
protected final ConsumerOperationParameters getConsumerOperationParameters() {
ConnectionParameters connectionParameters = this.connectionParameters;
return operationParamsBuilder.setParameters(connectionParameters).build();
}
public T withArguments(String... arguments) {
operationParamsBuilder.setArguments(arguments);
return getThis();
}
public T setStandardOutput(OutputStream outputStream) {
operationParamsBuilder.setStdout(outputStream);
return getThis();
}
public T setStandardError(OutputStream outputStream) {
operationParamsBuilder.setStderr(outputStream);
return getThis();
}
public T setStandardInput(InputStream inputStream) {
operationParamsBuilder.setStdin(inputStream);
return getThis();
}
public T setColorOutput(boolean colorOutput) {
operationParamsBuilder.setColorOutput(colorOutput);
return getThis();
}
public T setJavaHome(File javaHome) {
operationParamsBuilder.setJavaHome(javaHome);
return getThis();
}
public T setJvmArguments(String... jvmArguments) {
operationParamsBuilder.setJvmArguments(jvmArguments);
return getThis();
}
public T addProgressListener(ProgressListener listener) {
operationParamsBuilder.addProgressListener(listener);
return getThis();
}
public T withCancellationToken(CancellationToken cancellationToken) {
operationParamsBuilder.setCancellationToken(cancellationToken);
return getThis();
}
}
| subprojects/tooling-api/src/main/java/org/gradle/tooling/internal/consumer/AbstractLongRunningOperation.java | /*
* Copyright 2013 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 org.gradle.tooling.internal.consumer;
import com.google.common.base.Preconditions;
import org.gradle.tooling.CancellationToken;
import org.gradle.tooling.LongRunningOperation;
import org.gradle.tooling.ProgressListener;
import org.gradle.tooling.internal.consumer.parameters.ConsumerOperationParameters;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
public abstract class AbstractLongRunningOperation<T extends AbstractLongRunningOperation<T>> implements LongRunningOperation {
protected final ConnectionParameters connectionParameters;
protected final ConsumerOperationParameters.Builder operationParamsBuilder;
protected AbstractLongRunningOperation(ConnectionParameters parameters) {
connectionParameters = parameters;
operationParamsBuilder = ConsumerOperationParameters.builder();
operationParamsBuilder.setCancellationToken(new DefaultCancellationTokenSource().token());
}
protected abstract T getThis();
protected final ConsumerOperationParameters getConsumerOperationParameters() {
ConnectionParameters connectionParameters = this.connectionParameters;
return operationParamsBuilder.setParameters(connectionParameters).build();
}
public T withArguments(String... arguments) {
operationParamsBuilder.setArguments(arguments);
return getThis();
}
public T setStandardOutput(OutputStream outputStream) {
operationParamsBuilder.setStdout(outputStream);
return getThis();
}
public T setStandardError(OutputStream outputStream) {
operationParamsBuilder.setStderr(outputStream);
return getThis();
}
public T setStandardInput(InputStream inputStream) {
operationParamsBuilder.setStdin(inputStream);
return getThis();
}
public T setColorOutput(boolean colorOutput) {
operationParamsBuilder.setColorOutput(colorOutput);
return getThis();
}
public T setJavaHome(File javaHome) {
operationParamsBuilder.setJavaHome(javaHome);
return getThis();
}
public T setJvmArguments(String... jvmArguments) {
operationParamsBuilder.setJvmArguments(jvmArguments);
return getThis();
}
public T addProgressListener(ProgressListener listener) {
operationParamsBuilder.addProgressListener(listener);
return getThis();
}
public T withCancellationToken(CancellationToken cancellationToken) {
operationParamsBuilder.setCancellationToken(cancellationToken);
return getThis();
}
}
| Fix checkstyle
| subprojects/tooling-api/src/main/java/org/gradle/tooling/internal/consumer/AbstractLongRunningOperation.java | Fix checkstyle |
|
Java | apache-2.0 | 4c9ecda562957d26695970e9f5168025cd4a3813 | 0 | wso2/analytics-apim,wso2/analytics-apim,wso2/analytics-apim | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.extension.siddhi.io.mgwfile.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.extension.siddhi.io.mgwfile.MGWFileSourceConstants;
import org.wso2.extension.siddhi.io.mgwfile.dto.MGWFileInfoDTO;
import org.wso2.extension.siddhi.io.mgwfile.exception.MGWFileSourceException;
import org.wso2.extension.siddhi.io.mgwfile.util.MGWFileSourceDBUtil;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* This class contains methods DB access for FileEventAdapter.
*/
public class MGWFileSourceDAO {
private static final Log log = LogFactory.getLog(MGWFileSourceDAO.class);
/**
* Adds a record into the database with uploaded file's information.
*
* @param dto Uploaded File Information represented by {@link MGWFileInfoDTO}
* @param uploadedInputStream Input stream with the uploaded file content
* @throws MGWFileSourceException if there is an error while getting a connection or executing the query
*/
public static void persistUploadedFile(MGWFileInfoDTO dto, InputStream uploadedInputStream)
throws MGWFileSourceException {
Connection connection = null;
boolean autoCommitStatus = false;
PreparedStatement statement = null;
try {
connection = MGWFileSourceDBUtil.getConnection();
autoCommitStatus = connection.getAutoCommit();
connection.setAutoCommit(false);
statement = connection.prepareStatement(MGWFileSourceConstants.INSERT_UPLOADED_FILE_INFO_QUERY);
statement.setString(1, dto.getFileName());
statement.setTimestamp(2, new Timestamp(dto.getTimeStamp()));
statement.setBinaryStream(3, uploadedInputStream);
statement.executeUpdate();
connection.commit();
if (log.isDebugEnabled()) {
log.debug("Persisted Uploaded File info : " + dto.toString());
}
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
log.error("Error occurred while rolling back inserting uploaded information into db transaction,", e1);
}
throw new MGWFileSourceException("Error occurred while inserting uploaded information into database", e);
} finally {
try {
if (connection != null) {
connection.setAutoCommit(autoCommitStatus);
}
} catch (SQLException e) {
log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
}
MGWFileSourceDBUtil.closeAllConnections(statement, connection, null);
}
}
/**
* Returns the next set of files to bre processed by the worker threads.
*
* @param limit number of records to be retrieved
* @return list of {@link MGWFileInfoDTO}
* @throws MGWFileSourceException if there is an error while getting a connection or executing the query
*/
public static List<MGWFileInfoDTO> getNextFilesToProcess(int limit) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement selectStatement = null;
PreparedStatement updateStatement = null;
ResultSet resultSet = null;
boolean autoCommitStatus = false;
List<MGWFileInfoDTO> usageFileList = new ArrayList<>();
try {
connection = MGWFileSourceDBUtil.getConnection();
autoCommitStatus = connection.getAutoCommit();
connection.setAutoCommit(false);
if ((connection.getMetaData().getDriverName()).contains("Oracle")) {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_ORACLE);
} else if (connection.getMetaData().getDatabaseProductName().contains("Microsoft")) {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_MSSQL);
} else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_DB2);
} else {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_DEFAULT);
}
selectStatement.setInt(1, limit);
resultSet = selectStatement.executeQuery();
while (resultSet.next()) {
String fileName = resultSet.getString("FILE_NAME");
long timeStamp = resultSet.getTimestamp("FILE_TIMESTAMP").getTime();
updateStatement = connection
.prepareStatement(MGWFileSourceConstants.UPDATE_FILE_PROCESSING_STARTED_STATUS);
updateStatement.setString(1, fileName);
updateStatement.executeUpdate();
//File content (Blob) is not stored in memory. Will retrieve one by one when processing.
MGWFileInfoDTO dto = new MGWFileInfoDTO(fileName, timeStamp);
usageFileList.add(dto);
if (log.isDebugEnabled()) {
log.debug("Added File to list : " + dto.toString());
}
}
connection.commit();
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
log.error("Error occurred while rolling back getting the next files to process transaction.", e1);
}
throw new MGWFileSourceException("Error occurred while getting the next files to process.", e);
} finally {
try {
if (connection != null) {
connection.setAutoCommit(autoCommitStatus);
}
} catch (SQLException e) {
log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
}
MGWFileSourceDBUtil.closeStatement(updateStatement);
MGWFileSourceDBUtil.closeAllConnections(selectStatement, connection, resultSet);
}
return usageFileList;
}
/**
* Updates the completion of processing a uploaded usage file.
*
* @param dto Processed file represented by {@link MGWFileInfoDTO}
* @throws MGWFileSourceException if there is an error while getting a connection or executing the query
*/
public static void updateCompletion(MGWFileInfoDTO dto) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = MGWFileSourceDBUtil.getConnection();
connection.setAutoCommit(false);
statement = connection.prepareStatement(MGWFileSourceConstants.UPDATE_COMPETITION_QUERY);
statement.setString(1, dto.getFileName());
statement.executeUpdate();
connection.commit();
if (log.isDebugEnabled()) {
log.debug("Updated completion for file : " + dto.toString());
}
} catch (SQLException e) {
throw new MGWFileSourceException("Error occurred while updating the completion state.", e);
} finally {
MGWFileSourceDBUtil.closeAllConnections(statement, connection, null);
}
}
/**
* Get the content of the file based on the file information.
*
* @param dto Processed file represented by {@link MGWFileInfoDTO}
* @return InputStream with the content of the file of null if there is no content
* @throws MGWFileSourceException
*/
public static InputStream getFileContent(MGWFileInfoDTO dto) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
InputStream fileContentInputStream = null;
try {
connection = MGWFileSourceDBUtil.getConnection();
connection.setAutoCommit(false);
statement = connection.prepareStatement(MGWFileSourceConstants.GET_UPLOADED_FILE_CONTENT_QUERY);
statement.setString(1, dto.getFileName());
resultSet = statement.executeQuery();
while (resultSet.next()) {
//Postgres bytea data doesn't support getBlob operation
if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
fileContentInputStream = resultSet.getBinaryStream(MGWFileSourceConstants.API_USAGE_FILE_CONTENT);
} else {
Blob content = resultSet.getBlob(MGWFileSourceConstants.API_USAGE_FILE_CONTENT);
fileContentInputStream = content.getBinaryStream();
}
if (log.isDebugEnabled()) {
log.debug("Added File to list : " + dto.toString());
}
}
if (log.isDebugEnabled()) {
log.debug("Retrieved content of file : " + dto.toString());
}
} catch (SQLException e) {
throw new MGWFileSourceException(
"Error occurred while retrieving the content of the file: " + dto.toString(), e);
} finally {
MGWFileSourceDBUtil.closeAllConnections(statement, connection, resultSet);
}
return fileContentInputStream;
}
/**
* Delete obsolete usage records in the dbG.
*
* @param lastKeptDate up to which files should be retained
* @throws MGWFileSourceException
*/
public static void deleteProcessedOldFiles(Date lastKeptDate) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement delStatement = null;
boolean autoCommitStatus = false;
try {
connection = MGWFileSourceDBUtil.getConnection();
if (!isUsageTableExist(connection)) {
log.debug("Table 'AM_USAGE_UPLOADED_FILES' not found in '" + MGWFileSourceDBUtil.getDatasourceName()
+ "'. Skip publishing usage data assuming Micro GW is not configured.");
return;
}
autoCommitStatus = connection.getAutoCommit();
connection.setAutoCommit(false);
delStatement = connection.prepareStatement(MGWFileSourceConstants.DELETE_OLD_UPLOAD_COMPLETED_FILES);
delStatement.setTimestamp(1, new Timestamp(lastKeptDate.getTime()));
delStatement.executeUpdate();
connection.commit();
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
log.error("Error occurred while rolling back deleting old uploaded files transaction.", e1);
}
throw new MGWFileSourceException("Error occurred while deleting old uploaded files.", e);
} finally {
try {
if (connection != null) {
connection.setAutoCommit(autoCommitStatus);
}
} catch (SQLException e) {
log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
}
MGWFileSourceDBUtil.closeAllConnections(delStatement, connection, null);
}
}
/**
* Check whether given table is exist
*
* @param conn Connection
* @return existence
* @throws SQLException throw if an error occurred
*/
private static boolean isUsageTableExist(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
try {
stmt.execute(MGWFileSourceConstants.TABLE_EXISTENCE_SQL);
return true;
} catch (SQLException e) {
// logging is not required here.
return false;
} finally {
if (stmt != null) {
stmt.close();
}
}
}
}
| components/org.wso2.sp.extension.siddhi.io.mgwfile/src/main/java/org/wso2/extension/siddhi/io/mgwfile/dao/MGWFileSourceDAO.java | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.extension.siddhi.io.mgwfile.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.extension.siddhi.io.mgwfile.MGWFileSourceConstants;
import org.wso2.extension.siddhi.io.mgwfile.dto.MGWFileInfoDTO;
import org.wso2.extension.siddhi.io.mgwfile.exception.MGWFileSourceException;
import org.wso2.extension.siddhi.io.mgwfile.util.MGWFileSourceDBUtil;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* This class contains methods DB access for FileEventAdapter.
*/
public class MGWFileSourceDAO {
private static final Log log = LogFactory.getLog(MGWFileSourceDAO.class);
/**
* Adds a record into the database with uploaded file's information.
*
* @param dto Uploaded File Information represented by {@link MGWFileInfoDTO}
* @param uploadedInputStream Input stream with the uploaded file content
* @throws MGWFileSourceException if there is an error while getting a connection or executing the query
*/
public static void persistUploadedFile(MGWFileInfoDTO dto, InputStream uploadedInputStream)
throws MGWFileSourceException {
Connection connection = null;
boolean autoCommitStatus = false;
PreparedStatement statement = null;
try {
connection = MGWFileSourceDBUtil.getConnection();
autoCommitStatus = connection.getAutoCommit();
connection.setAutoCommit(false);
statement = connection.prepareStatement(MGWFileSourceConstants.INSERT_UPLOADED_FILE_INFO_QUERY);
statement.setString(1, dto.getFileName());
statement.setTimestamp(2, new Timestamp(dto.getTimeStamp()));
statement.setBinaryStream(3, uploadedInputStream);
statement.executeUpdate();
connection.commit();
if (log.isDebugEnabled()) {
log.debug("Persisted Uploaded File info : " + dto.toString());
}
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
log.error("Error occurred while rolling back inserting uploaded information into db transaction,", e1);
}
throw new MGWFileSourceException("Error occurred while inserting uploaded information into database", e);
} finally {
try {
if (connection != null) {
connection.setAutoCommit(autoCommitStatus);
}
} catch (SQLException e) {
log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
}
MGWFileSourceDBUtil.closeAllConnections(statement, connection, null);
}
}
/**
* Returns the next set of files to bre processed by the worker threads.
*
* @param limit number of records to be retrieved
* @return list of {@link MGWFileInfoDTO}
* @throws MGWFileSourceException if there is an error while getting a connection or executing the query
*/
public static List<MGWFileInfoDTO> getNextFilesToProcess(int limit) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement selectStatement = null;
PreparedStatement updateStatement = null;
ResultSet resultSet = null;
boolean autoCommitStatus = false;
List<MGWFileInfoDTO> usageFileList = new ArrayList<>();
try {
connection = MGWFileSourceDBUtil.getConnection();
autoCommitStatus = connection.getAutoCommit();
connection.setAutoCommit(false);
if ((connection.getMetaData().getDriverName()).contains("Oracle")) {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_ORACLE);
} else if (connection.getMetaData().getDatabaseProductName().contains("Microsoft")) {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_MSSQL);
} else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_DB2);
} else {
selectStatement = connection
.prepareStatement(MGWFileSourceConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_DEFAULT);
}
selectStatement.setInt(1, limit);
resultSet = selectStatement .executeQuery();
while (resultSet.next()) {
String fileName = resultSet.getString("FILE_NAME");
long timeStamp = resultSet.getTimestamp("FILE_TIMESTAMP").getTime();
updateStatement = connection
.prepareStatement(MGWFileSourceConstants.UPDATE_FILE_PROCESSING_STARTED_STATUS);
updateStatement.setString(1, fileName);
updateStatement.executeUpdate();
//File content (Blob) is not stored in memory. Will retrieve one by one when processing.
MGWFileInfoDTO dto = new MGWFileInfoDTO(fileName, timeStamp);
usageFileList.add(dto);
if (log.isDebugEnabled()) {
log.debug("Added File to list : " + dto.toString());
}
}
connection.commit();
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
log.error("Error occurred while rolling back getting the next files to process transaction.", e1);
}
throw new MGWFileSourceException("Error occurred while getting the next files to process.", e);
} finally {
try {
if (connection != null) {
connection.setAutoCommit(autoCommitStatus);
}
} catch (SQLException e) {
log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
}
MGWFileSourceDBUtil.closeStatement(updateStatement);
MGWFileSourceDBUtil.closeAllConnections(selectStatement, connection, resultSet);
}
return usageFileList;
}
/**
* Updates the completion of processing a uploaded usage file.
*
* @param dto Processed file represented by {@link MGWFileInfoDTO}
* @throws MGWFileSourceException if there is an error while getting a connection or executing the query
*/
public static void updateCompletion(MGWFileInfoDTO dto) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = MGWFileSourceDBUtil.getConnection();
connection.setAutoCommit(false);
statement = connection.prepareStatement(MGWFileSourceConstants.UPDATE_COMPETITION_QUERY);
statement.setString(1, dto.getFileName());
statement.executeUpdate();
connection.commit();
if (log.isDebugEnabled()) {
log.debug("Updated completion for file : " + dto.toString());
}
} catch (SQLException e) {
throw new MGWFileSourceException("Error occurred while updating the completion state.", e);
} finally {
MGWFileSourceDBUtil.closeAllConnections(statement, connection, null);
}
}
/**
* Get the content of the file based on the file information.
*
* @param dto Processed file represented by {@link MGWFileInfoDTO}
* @return InputStream with the content of the file of null if there is no content
* @throws MGWFileSourceException
*/
public static InputStream getFileContent(MGWFileInfoDTO dto) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
InputStream fileContentInputStream = null;
try {
connection = MGWFileSourceDBUtil.getConnection();
connection.setAutoCommit(false);
statement = connection.prepareStatement(MGWFileSourceConstants.GET_UPLOADED_FILE_CONTENT_QUERY);
statement.setString(1, dto.getFileName());
resultSet = statement.executeQuery();
while (resultSet.next()) {
//Postgres bytea data doesn't support getBlob operation
if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
fileContentInputStream = resultSet.getBinaryStream(MGWFileSourceConstants.API_USAGE_FILE_CONTENT);
} else {
Blob content = resultSet.getBlob(MGWFileSourceConstants.API_USAGE_FILE_CONTENT);
fileContentInputStream = content.getBinaryStream();
}
if (log.isDebugEnabled()) {
log.debug("Added File to list : " + dto.toString());
}
}
if (log.isDebugEnabled()) {
log.debug("Retrieved content of file : " + dto.toString());
}
} catch (SQLException e) {
throw new MGWFileSourceException(
"Error occurred while retrieving the content of the file: " + dto.toString(), e);
} finally {
MGWFileSourceDBUtil.closeAllConnections(statement, connection, resultSet);
}
return fileContentInputStream;
}
/**
* Delete obsolete usage records in the dbG.
*
* @param lastKeptDate up to which files should be retained
* @throws MGWFileSourceException
*/
public static void deleteProcessedOldFiles(Date lastKeptDate) throws MGWFileSourceException {
Connection connection = null;
PreparedStatement delStatement = null;
boolean autoCommitStatus = false;
try {
connection = MGWFileSourceDBUtil.getConnection();
if (!isUsageTableExist(connection)) {
log.debug("Table 'AM_USAGE_UPLOADED_FILES' not found in '" + MGWFileSourceDBUtil.getDatasourceName()
+ "'. Skip publishing usage data assuming Micro GW is not configured.");
return;
}
autoCommitStatus = connection.getAutoCommit();
connection.setAutoCommit(false);
delStatement = connection.prepareStatement(MGWFileSourceConstants.DELETE_OLD_UPLOAD_COMPLETED_FILES);
delStatement.setTimestamp(1, new Timestamp(lastKeptDate.getTime()));
delStatement.executeUpdate();
connection.commit();
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
log.error("Error occurred while rolling back deleting old uploaded files transaction.", e1);
}
throw new MGWFileSourceException("Error occurred while deleting old uploaded files.", e);
} finally {
try {
if (connection != null) {
connection.setAutoCommit(autoCommitStatus);
}
} catch (SQLException e) {
log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
}
MGWFileSourceDBUtil.closeAllConnections(delStatement, connection, null);
}
}
/**
* Check whether given table is exist
*
* @param conn Connection
* @return existence
* @throws SQLException throw if an error occurred
*/
private static boolean isUsageTableExist(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
try {
stmt.execute(MGWFileSourceConstants.TABLE_EXISTENCE_SQL);
return true;
} catch (SQLException e) {
// logging is not required here.
return false;
} finally {
if (stmt != null) {
stmt.close();
}
}
}
}
| Format fix
| components/org.wso2.sp.extension.siddhi.io.mgwfile/src/main/java/org/wso2/extension/siddhi/io/mgwfile/dao/MGWFileSourceDAO.java | Format fix |
|
Java | apache-2.0 | 0caabdbc8c9f1a4d0969124b9e925c4bd013b9f7 | 0 | masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,davinash/geode,smgoller/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,davebarnes97/geode,davinash/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,davinash/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,davinash/geode,smgoller/geode,smgoller/geode,davinash/geode,smgoller/geode,davebarnes97/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,davinash/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,davebarnes97/geode,davebarnes97/geode,davebarnes97/geode,davinash/geode,davebarnes97/geode,smgoller/geode,davebarnes97/geode | /*
* 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.geode.rest.internal.web.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.rest.internal.web.RestFunctionTemplate;
import org.apache.geode.test.junit.categories.RestAPITest;
import org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactory;
@Category(RestAPITest.class)
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)
public class RestAPIsOnGroupsFunctionExecutionDUnitTest extends RestAPITestBase {
@Parameterized.Parameter
public String urlContext;
@Parameterized.Parameters
public static Collection<String> data() {
return Arrays.asList("/geode", "/gemfire-api");
}
private void setupCacheWithGroupsAndFunction() {
restURLs.add(vm0.invoke("createCacheWithGroups",
() -> createCacheWithGroups(vm0.getHost().getHostName(), "g0,gm", urlContext)));
restURLs.add(vm1.invoke("createCacheWithGroups",
() -> createCacheWithGroups(vm1.getHost().getHostName(), "g1", urlContext)));
restURLs.add(vm2.invoke("createCacheWithGroups",
() -> createCacheWithGroups(vm2.getHost().getHostName(), "g0,g1", urlContext)));
vm0.invoke("registerFunction(new OnGroupsFunction())",
() -> FunctionService.registerFunction(new OnGroupsFunction()));
vm1.invoke("registerFunction(new OnGroupsFunction())",
() -> FunctionService.registerFunction(new OnGroupsFunction()));
vm2.invoke("registerFunction(new OnGroupsFunction())",
() -> FunctionService.registerFunction(new OnGroupsFunction()));
}
@Test
public void testonGroupsExecutionOnAllMembers() {
setupCacheWithGroupsAndFunction();
for (int i = 0; i < 10; i++) {
CloseableHttpResponse response =
executeFunctionThroughRestCall("OnGroupsFunction", null, null, null, "g0,g1", null);
assertHttpResponse(response, 200, 3);
}
assertCorrectInvocationCount("OnGroupsFunction", 30, vm0, vm1, vm2);
restURLs.clear();
}
@Test
public void testonGroupsExecutionOnAllMembersWithFilter() {
setupCacheWithGroupsAndFunction();
// Execute function randomly (in iteration) on all available (per VM) REST end-points and verify
// its result
for (int i = 0; i < 10; i++) {
CloseableHttpResponse response =
executeFunctionThroughRestCall("OnGroupsFunction", null, "someKey", null, "g1", null);
assertHttpResponse(response, 500, 0);
}
assertCorrectInvocationCount("OnGroupsFunction", 0, vm0, vm1, vm2);
restURLs.clear();
}
@Test
public void testBasicP2PFunctionSelectedGroup() {
setupCacheWithGroupsAndFunction();
// Step-3 : Execute function randomly (in iteration) on all available (per VM) REST end-points
// and verify its result
for (int i = 0; i < 5; i++) {
CloseableHttpResponse response = executeFunctionThroughRestCall("OnGroupsFunction", null,
null, null, "no%20such%20group", null);
assertHttpResponse(response, 500, 0);
}
assertCorrectInvocationCount("OnGroupsFunction", 0, vm0, vm1, vm2);
for (int i = 0; i < 5; i++) {
CloseableHttpResponse response =
executeFunctionThroughRestCall("OnGroupsFunction", null, null, null, "gm", null);
assertHttpResponse(response, 200, 1);
}
assertCorrectInvocationCount("OnGroupsFunction", 5, vm0, vm1, vm2);
vm0.invoke(() -> resetInvocationCount("OnGroupsFunction"));
vm1.invoke(() -> resetInvocationCount("OnGroupsFunction"));
vm2.invoke(() -> resetInvocationCount("OnGroupsFunction"));
restURLs.clear();
}
@SuppressWarnings("unchecked")
private static class OnGroupsFunction extends RestFunctionTemplate {
static final String Id = "OnGroupsFunction";
@Override
public void execute(FunctionContext context) {
InternalDistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
invocationCount++;
ArrayList<String> l = (ArrayList<String>) context.getArguments();
if (l != null) {
assertThat(Collections.disjoint(l, ds.getDistributedMember().getGroups())).isFalse();
}
context.getResultSender().lastResult(Boolean.TRUE);
}
@Override
public String getId() {
return Id;
}
@Override
public boolean hasResult() {
return true;
}
@Override
public boolean optimizeForWrite() {
return false;
}
@Override
public boolean isHA() {
return false;
}
}
}
| geode-assembly/src/distributedTest/java/org/apache/geode/rest/internal/web/controllers/RestAPIsOnGroupsFunctionExecutionDUnitTest.java | /*
* 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.geode.rest.internal.web.controllers;
import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.rest.internal.web.RestFunctionTemplate;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.junit.categories.RestAPITest;
import org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactory;
@Category({RestAPITest.class})
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)
public class RestAPIsOnGroupsFunctionExecutionDUnitTest extends RestAPITestBase {
@Parameterized.Parameter
public String urlContext;
@Parameterized.Parameters
public static Collection<String> data() {
return Arrays.asList("/geode", "/gemfire-api");
}
private void setupCacheWithGroupsAndFunction() {
restURLs.add(vm0.invoke("createCacheWithGroups",
() -> createCacheWithGroups(vm0.getHost().getHostName(), "g0,gm", urlContext)));
restURLs.add(vm1.invoke("createCacheWithGroups",
() -> createCacheWithGroups(vm1.getHost().getHostName(), "g1", urlContext)));
restURLs.add(vm2.invoke("createCacheWithGroups",
() -> createCacheWithGroups(vm2.getHost().getHostName(), "g0,g1", urlContext)));
vm0.invoke("registerFunction(new OnGroupsFunction())",
() -> FunctionService.registerFunction(new OnGroupsFunction()));
vm1.invoke("registerFunction(new OnGroupsFunction())",
() -> FunctionService.registerFunction(new OnGroupsFunction()));
vm2.invoke("registerFunction(new OnGroupsFunction())",
() -> FunctionService.registerFunction(new OnGroupsFunction()));
}
@Test
public void testonGroupsExecutionOnAllMembers() {
setupCacheWithGroupsAndFunction();
for (int i = 0; i < 10; i++) {
CloseableHttpResponse response =
executeFunctionThroughRestCall("OnGroupsFunction", null, null, null, "g0,g1", null);
assertHttpResponse(response, 200, 3);
}
assertCorrectInvocationCount("OnGroupsFunction", 30, vm0, vm1, vm2);
restURLs.clear();
}
@Test
public void testonGroupsExecutionOnAllMembersWithFilter() {
setupCacheWithGroupsAndFunction();
// Execute function randomly (in iteration) on all available (per VM) REST end-points and verify
// its result
for (int i = 0; i < 10; i++) {
CloseableHttpResponse response =
executeFunctionThroughRestCall("OnGroupsFunction", null, "someKey", null, "g1", null);
assertHttpResponse(response, 500, 0);
}
assertCorrectInvocationCount("OnGroupsFunction", 0, vm0, vm1, vm2);
restURLs.clear();
}
@Test
public void testBasicP2PFunctionSelectedGroup() {
setupCacheWithGroupsAndFunction();
// Step-3 : Execute function randomly (in iteration) on all available (per VM) REST end-points
// and verify its result
for (int i = 0; i < 5; i++) {
CloseableHttpResponse response = executeFunctionThroughRestCall("OnGroupsFunction", null,
null, null, "no%20such%20group", null);
assertHttpResponse(response, 500, 0);
}
assertCorrectInvocationCount("OnGroupsFunction", 0, vm0, vm1, vm2);
for (int i = 0; i < 5; i++) {
CloseableHttpResponse response =
executeFunctionThroughRestCall("OnGroupsFunction", null, null, null, "gm", null);
assertHttpResponse(response, 200, 1);
}
assertCorrectInvocationCount("OnGroupsFunction", 5, vm0, vm1, vm2);
vm0.invoke(() -> resetInvocationCount("OnGroupsFunction"));
vm1.invoke(() -> resetInvocationCount("OnGroupsFunction"));
vm2.invoke(() -> resetInvocationCount("OnGroupsFunction"));
restURLs.clear();
}
private class OnGroupsFunction extends RestFunctionTemplate {
static final String Id = "OnGroupsFunction";
@Override
public void execute(FunctionContext context) {
LogWriterUtils.getLogWriter().fine("SWAP:1:executing OnGroupsFunction:" + invocationCount);
InternalDistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
invocationCount++;
ArrayList<String> l = (ArrayList<String>) context.getArguments();
if (l != null) {
assertFalse(Collections.disjoint(l, ds.getDistributedMember().getGroups()));
}
context.getResultSender().lastResult(Boolean.TRUE);
}
@Override
public String getId() {
return Id;
}
@Override
public boolean hasResult() {
return true;
}
@Override
public boolean optimizeForWrite() {
return false;
}
@Override
public boolean isHA() {
return false;
}
}
}
| GEODE-7407: Fix Test Warnings (#4301)
- Fixed some minor warnings in tests.
- Replaced usages of 'junit.Assert' by 'assertj'. | geode-assembly/src/distributedTest/java/org/apache/geode/rest/internal/web/controllers/RestAPIsOnGroupsFunctionExecutionDUnitTest.java | GEODE-7407: Fix Test Warnings (#4301) |
|
Java | apache-2.0 | 7b84cc60eb7d8e803fa5fe553da91dbf0f587008 | 0 | IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl | package com.b2international.snowowl.snomed.api.impl.validation.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.ihtsdo.drools.domain.Description;
import org.ihtsdo.drools.domain.Relationship;
import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserConcept;
import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserDescription;
import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserRelationship;
public class ValidationConcept implements org.ihtsdo.drools.domain.Concept {
private ISnomedBrowserConcept browserConcept;
private List<Description> descriptions;
private List<Relationship> relationships;
public ValidationConcept(ISnomedBrowserConcept browserConcept) {
this.browserConcept = browserConcept;
String conceptId = browserConcept.getConceptId();
descriptions = new ArrayList<>();
for (ISnomedBrowserDescription browserDescription : browserConcept.getDescriptions()) {
descriptions.add(new ValidationDescription(browserDescription, conceptId));
}
relationships = new ArrayList<>();
for (ISnomedBrowserRelationship browserRelationship : browserConcept.getRelationships()) {
relationships.add(new ValidationRelationship(browserRelationship, conceptId));
}
}
public java.util.Collection<? extends org.ihtsdo.drools.domain.OntologyAxiom> getOntologyAxioms() {
return new HashSet<>();
}
@Override
public String getId() {
return browserConcept.getConceptId();
}
@Override
public boolean isActive() {
return browserConcept.isActive();
}
@Override
public boolean isPublished() {
return browserConcept.getEffectiveTime() != null;
}
@Override
public boolean isReleased() {
return browserConcept.isReleased();
}
@Override
public String getModuleId() {
return browserConcept.getModuleId();
}
@Override
public String getDefinitionStatusId() {
return browserConcept.getDefinitionStatus().getConceptId();
}
@Override
public Collection<Description> getDescriptions() {
return descriptions;
}
@Override
public Collection<Relationship> getRelationships() {
return relationships;
}
}
| snomed/com.b2international.snowowl.snomed.api.impl/src/com/b2international/snowowl/snomed/api/impl/validation/domain/ValidationConcept.java | package com.b2international.snowowl.snomed.api.impl.validation.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.ihtsdo.drools.domain.Description;
import org.ihtsdo.drools.domain.Relationship;
import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserConcept;
import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserDescription;
import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserRelationship;
public class ValidationConcept implements org.ihtsdo.drools.domain.Concept {
private ISnomedBrowserConcept browserConcept;
private List<Description> descriptions;
private List<Relationship> relationships;
public ValidationConcept(ISnomedBrowserConcept browserConcept) {
this.browserConcept = browserConcept;
String conceptId = browserConcept.getConceptId();
descriptions = new ArrayList<>();
for (ISnomedBrowserDescription browserDescription : browserConcept.getDescriptions()) {
descriptions.add(new ValidationDescription(browserDescription, conceptId));
}
relationships = new ArrayList<>();
for (ISnomedBrowserRelationship browserRelationship : browserConcept.getRelationships()) {
relationships.add(new ValidationRelationship(browserRelationship, conceptId));
}
}
@Override
public String getId() {
return browserConcept.getConceptId();
}
@Override
public boolean isActive() {
return browserConcept.isActive();
}
@Override
public boolean isPublished() {
return browserConcept.getEffectiveTime() != null;
}
@Override
public boolean isReleased() {
return browserConcept.isReleased();
}
@Override
public String getModuleId() {
return browserConcept.getModuleId();
}
@Override
public String getDefinitionStatusId() {
return browserConcept.getDefinitionStatus().getConceptId();
}
@Override
public Collection<Description> getDescriptions() {
return descriptions;
}
@Override
public Collection<Relationship> getRelationships() {
return relationships;
}
}
| MAINT-153 Empty set of OntologyAxioms for drools engine compliance.
| snomed/com.b2international.snowowl.snomed.api.impl/src/com/b2international/snowowl/snomed/api/impl/validation/domain/ValidationConcept.java | MAINT-153 Empty set of OntologyAxioms for drools engine compliance. |
|
Java | apache-2.0 | 4e4e4e11e89d9abec50323a8a1242268fb0e1546 | 0 | outskywind/myproject | package org.lotus.algorithm.strings;
import org.junit.Test;
import java.util.Arrays;
/**
* Created by quanchengyun on 2019/10/7.
*/
public class Strings {
public static char[] str= {'a','b','c','d','e','f','g','h'};
private static char[] getStr(){
return Arrays.copyOf(str,str.length);
}
//1.翻转子字符串-----------------------------------------------------------
/**
* 在原字符串中把字符串尾部的m个字符移动到字符串的头部,
* 要求:长度为n的字符串操作时间复杂度为O(n),空间复杂度为O(1)。
* 例如,原字符串为”Ilovebaofeng”,m=7,输出结果为:”baofengIlove”。
*
* : (x~y~)~=y~~x~~=yx
*/
public static void revertChar(char[] str , int m){
//0,n-1
//x= str[0],str[n-1-m] , y = n-1-m+1 , n-1
if(m>=str.length){
System.out.print("invalid param m");
}
revert(str,0,str.length-1-m);
revert(str,str.length-m,str.length-1);
revert(str,0,str.length-1);
System.out.println(str);
}
private static void revert(char[] str , int start ,int end){
int j=start;
int k=end;
while(j < k){
char v = str[j];
str[j]=str[k];
str[k]= v;
j++;
k--;
}
}
@Test
public void testRevert(){
revertChar(getStr(),3);
revertChar(getStr(),4);
revertChar(getStr(),5);
}
/**
*单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。
* 为简单起见,标点符号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I”
* (x~_y~_z~)~ = z~~_y~~_x~~ = z_y_x
*/
private static void revertWord(){
//略
}
//1.end-----------------------------------------------------------------------
//2.最长回文子串问题------------------------------------------------------------
/**
* 1.manacher 算法 ,扩展字符数组填充特殊字符# ,2N-1
* 2. 以i为中心扩展查找
*/
private static void palindromic(char[] str){
char[] extend = new char[str.length*2-1];
for(int i=0,j=0;i<str.length;i++,j++){
extend[j]=str[i];
j++;
if (j<extend.length)
extend[j]='#';
}
int[] mp = new int[extend.length];
int m=0,r=0;
for(int i=0;i<extend.length;i++){
mp[i]= i < r ? Math.min(mp[2*m-i],r-i):1;
while(i-mp[i]>=0 && i+mp[i]<extend.length && extend[i-mp[i]]==extend[i+mp[i]]){
mp[i]++;
}
//i为中心的构成回文,如果i大于等于 r ,那么扩展后 r=i,m=i
if(i+mp[i] > r) {
r=i+mp[i];
m=i;
}
}
//找到最大的那一个
int max=0;
for(int i=0;i<mp.length;i++){
if (mp[i]>mp[max]){
max=i;
}
}
if (mp[max]>1) {
int left = max-mp[max]+1;
int right = max+mp[max]-1;
left = (left+1)/2;
right = (right-1)/2;
for (int i=left;i<=right;i++){
System.out.print(str[i]);
}
}
}
@Test
public void testPalindromic(){
char[] origin = "abcdeffeffedcab".toCharArray();
palindromic(origin);
}
//2. end------------------------------
//3. 字符串hash -------------------------------------
/**
* h(s[i])= s[i]*b^i mod M
* h(s) = h(s[0])+...+ h(s[n])
* h(s[l,r]) = h(s[0,r])-h(s[0,l-1])
* h(s[l,r])=h(s[l-1,r-1]) - h(s[l-1]) + h(s[r]);
* 找出在目标字符串中 target 包含的 模式子串 pattern
*
* O(N+M) 平均时间,极端情况下,O(N*M)
*/
public static int patternMatch( char[] target,char[] pattern){
//计算字符串hash
//前缀hash --Rabin-Karp
if(pattern.length>target.length){
return -1;
}
//缺陷是计算的数字要在一个long 范围内
int b = 233;
int M = 1000000007;
long hashPattern = 0;
long hashTarget = 0;
long bl = 1;
for(int i=1;i<pattern.length;i++){
bl = bl*b;
}
bl=bl%M;
for(int i=0;i<pattern.length;i++){
hashPattern = (hashPattern*b+pattern[i])%M;
hashTarget = (hashTarget*b+target[i])%M;
}
int pos = -1;
for(int i=0;i<target.length-pattern.length;i++){
if (hashPattern == hashTarget){
pos=i;
break;
}
hashTarget = (hashTarget*b - (target[i]*bl*b)%M + target[i+pattern.length])%M;
}
return pos;
}
@Test
public void testPatternMatch(){
char[] target = ("afhkcvaofaaamvakidwvbhadoavbiqqqqhsdlkczovoavaqafbmkginl" +
"ogapipahnfjadnvcxbxdiazdlkfdfeeigdbjvqweqiutfafpvpzvbadbahufu").toCharArray();
char[] pattern = "lkfdf".toCharArray();
int pos = patternMatch(target,pattern);
System.out.println(pos);
}
/*private long hash(char[] str,int dwHashType){
long seed1= 0x7FED7FED;
long seed2= 0xEEEEEEEE;
long[] cryptTable=prepareCryptTable();
int ch;
for (int i=0;i<str.length;i++)
{
ch = str[i];
seed1 = cryptTable[(dwHashType << 8) + ch] ^ (seed1 + seed2);
seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3;
}
return seed1;
}
static long[] prepareCryptTable()
{
long seed = 0x00100001;
int index2=0,index1=0, i=0;
long[] cryptTable = new long[256];
for(index1 = 0; index1 < 256; index1++) {
for(index2 = index1, i = 0; i < 5; i++, index2 += 256)
{
long temp1, temp2;
seed = (seed * 125 + 3) % 0x2AAAAB;
temp1 = (seed & 0xFFFF) << 0x10;
seed = (seed * 125 + 3) % 0x2AAAAB;
temp2 = (seed & 0xFFFF);
cryptTable[index2] = ( temp1 | temp2 );
}
}
return cryptTable;
}*/
//3. end--------------------------------------------
}
| algorithm/src/main/java/org/lotus/algorithm/strings/Strings.java | package org.lotus.algorithm.strings;
import org.junit.Test;
import java.util.Arrays;
/**
* Created by quanchengyun on 2019/10/7.
*/
public class Strings {
public static char[] str= {'a','b','c','d','e','f','g','h'};
private static char[] getStr(){
return Arrays.copyOf(str,str.length);
}
//1.start-----------------------------------------------------------
/**
* 在原字符串中把字符串尾部的m个字符移动到字符串的头部,
* 要求:长度为n的字符串操作时间复杂度为O(n),空间复杂度为O(1)。
* 例如,原字符串为”Ilovebaofeng”,m=7,输出结果为:”baofengIlove”。
*
* : (x~y~)~=y~~x~~=yx
*/
public static void revertChar(char[] str , int m){
//0,n-1
//x= str[0],str[n-1-m] , y = n-1-m+1 , n-1
if(m>=str.length){
System.out.print("invalid param m");
}
revert(str,0,str.length-1-m);
revert(str,str.length-m,str.length-1);
revert(str,0,str.length-1);
System.out.println(str);
}
private static void revert(char[] str , int start ,int end){
int j=start;
int k=end;
while(j < k){
char v = str[j];
str[j]=str[k];
str[k]= v;
j++;
k--;
}
}
@Test
public void testRevert(){
revertChar(getStr(),3);
revertChar(getStr(),4);
revertChar(getStr(),5);
}
/**
*单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。
* 为简单起见,标点符号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I”
* (x~_y~_z~)~ = z~~_y~~_x~~ = z_y_x
*/
private static void revertWord(){
//略
}
//1.end-----------------------------------------------------------
//2.start------------------------------------------------------------
/**
* 最长回文子串问题 ,
* 1.manacher 算法 ,扩展字符数组填充特殊字符# ,2N-1
* 2. 以i为中心扩展查找
*/
private static void palindromic(char[] str){
char[] extend = new char[str.length*2-1];
for(int i=0,j=0;i<str.length;i++,j++){
extend[j]=str[i];
j++;
if (j<extend.length)
extend[j]='#';
}
int[] mp = new int[extend.length];
int m=0,r=0;
for(int i=0;i<extend.length;i++){
mp[i]= i < r ? Math.min(mp[2*m-i],r-i):1;
while(i-mp[i]>=0 && i+mp[i]<extend.length && extend[i-mp[i]]==extend[i+mp[i]]){
mp[i]++;
}
//i为中心的构成回文,如果i大于等于 r ,那么扩展后 r=i,m=i
if(i+mp[i] > r) {
r=i+mp[i]-1;
m=i;
}
}
//找到最大的那一个
int max=0;
for(int i=0;i<mp.length;i++){
if (mp[i]>mp[max]){
max=i;
}
}
if (mp[max]>1) {
int left = max-mp[max]+1;
int right = max+mp[max]-1;
left = (left+1)/2;
right = (right-1)/2;
for (int i=left;i<=right;i++){
System.out.print(str[i]);
}
}
}
@Test
public void testPalindromic(){
char[] origin = "abcdeffeffedcab".toCharArray();
palindromic(origin);
}
//2. end------------------------------
}
| commit
| algorithm/src/main/java/org/lotus/algorithm/strings/Strings.java | commit |
|
Java | bsd-3-clause | 8414399f9daa11d6f189c7d138956e9daa2b43f4 | 0 | alexmilowski/xproclet,alexmilowski/xproclet,alexmilowski/xproclet | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.xproclet.xproc;
import com.xmlcalabash.core.XProcException;
import com.xmlcalabash.io.ReadablePipe;
import com.xmlcalabash.io.WritableDocument;
import com.xmlcalabash.model.RuntimeValue;
import com.xmlcalabash.model.Serialization;
import com.xmlcalabash.runtime.XInput;
import com.xmlcalabash.runtime.XPipeline;
import com.xmlcalabash.util.S9apiUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.sax.SAXSource;
import net.sf.saxon.s9api.Axis;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmItem;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmNodeKind;
import net.sf.saxon.s9api.XdmSequenceIterator;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.CacheDirective;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.engine.header.Header;
import org.restlet.representation.OutputRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.util.Series;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xproclet.server.DocumentLoader;
/**
*
* @author alex
*/
public class XProcHelper {
final static String NS = "http://www.xproclet.org/V/XProc/";
final static String HTTP_NS = "http://www.xproclet.org/V/HTTP/";
final static QName HTTP_NAME = QName.fromClarkName("{"+HTTP_NS+"}http");
final static QName HEADER_NAME = QName.fromClarkName("{"+HTTP_NS+"}header");
final static QName ENTITY_NAME = QName.fromClarkName("{"+HTTP_NS+"}entity");
final static QName ATTRIBUTE_NAME = QName.fromClarkName("{"+HTTP_NS+"}attribute");
final static QName STATUS_NAME = QName.fromClarkName("status");
final static QName NAME_NAME = QName.fromClarkName("name");
final static QName TYPE_NAME = QName.fromClarkName("type");
final static QName VALUE_NAME = QName.fromClarkName("value");
final static QName LAST_MODIFIED_NAME = QName.fromClarkName("last-modified");
public final static String XPROC_CONFIG_ATTR = "xproc.configuration";
final static SimpleDateFormat xsdDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
final static SimpleDateFormat xsdDateFormatWithMilliseconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
static class OptionBinding {
enum Source {
ATTRIBUTES,
HEADERS,
PARAMETERS,
QUERY,
REQUEST
}
QName optionName;
Source source;
String name;
String defaultValue;
OptionBinding(QName optionName,Source source,String name,String defaultValue)
{
this.optionName = optionName;
this.name = name;
this.source = source;
this.defaultValue = defaultValue;
}
}
static class PipeInfo {
enum QueryBind {
NONE,
PARAMETERS,
OPTIONS
}
URI location;
boolean bindResult;
QueryBind bindQuery;
List<OptionBinding> optionBindings;
/*
Map<String,QName> parametersToBind;
Map<String,QName> headersToBind;
Map<String,QName> requestsToBind;
Map<String,QName> attrsToBind;
*/
Map<String,String> optionValues;
List<MediaType> requiredTypes;
MediaType outputType;
PipeInfo(URI location) {
this.location = location;
/*
this.parametersToBind = null;
this.optionValues = null;
this.headersToBind = null;
this.requestsToBind = null;
this.attrsToBind = null;
*/
this.optionBindings = null;
this.bindResult = false;
this.bindQuery = QueryBind.NONE;
this.requiredTypes = new ArrayList<MediaType>();
this.outputType = MediaType.valueOf(MediaType.APPLICATION_XML+";charset=UTF-8");
}
void bindOptionToParameter(String parameterName,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.PARAMETERS,parameterName,defaultValue));
/*
if (parametersToBind==null) {
parametersToBind = new TreeMap<String,QName>();
}
parametersToBind.put(parameterName,name);
*
*/
}
void bindOptionToHeader(String header,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.HEADERS,header,defaultValue));
/*
if (headersToBind==null) {
headersToBind = new TreeMap<String,QName>();
}
headersToBind.put(header,name);
*
*/
}
void bindOption(String name,String value) {
if (optionValues==null) {
optionValues = new TreeMap<String,String>();
}
optionValues.put(name, value);
}
void bindOptionToRequest(String part,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.REQUEST,part,defaultValue));
/*
if (requestsToBind==null) {
requestsToBind = new TreeMap<String,QName>();
}
requestsToBind.put(part,name);
*
*/
}
void bindOptionToAttribute(String attrName,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.ATTRIBUTES,attrName,defaultValue));
/*
if (attrsToBind==null) {
attrsToBind = new TreeMap<String,QName>();
}
attrsToBind.put(attrName,name);
*
*/
}
void bindOptionToQuery(String parameterName,QName name,String defaultValue)
{
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.QUERY,parameterName,defaultValue));
}
}
Context context;
Map<Method,PipeInfo> methodPipelines;
protected XProcCache cache;
List<QName> optionsToBind;
Map<String,QName> headersToBind;
Object contextObject;
File tmpDir;
static boolean equalsName(Element e,String name)
{
return NS.equals(e.getNamespaceURI()) && name.equals(e.getLocalName());
}
public XProcHelper(Context context) {
this.context = context;
try {
cache = (XProcCache)getContext().getAttributes().get(XProcCache.ATTR);
if (cache==null) {
getLogger().warning("No cache "+XProcCache.ATTR+" attribute was found for caching xproc pipeline instances.");
}
} catch (Exception ex) {
getLogger().log(Level.SEVERE,"Cannot retrieve cache from context.",ex);
}
String tmpDir = context.getParameters().getFirstValue(XProcResource.TMPDIR_PARAM);
if (tmpDir!=null) {
if (tmpDir.startsWith("file:")) {
tmpDir = tmpDir.substring(5);
}
this.tmpDir = new File(tmpDir);
if (!this.tmpDir.exists()) {
if (!this.tmpDir.mkdirs()) {
getLogger().severe("Cannot create temporary directory "+tmpDir);
this.tmpDir = null;
}
}
if (this.tmpDir!=null && !this.tmpDir.isDirectory()) {
getLogger().severe("The location "+tmpDir+" is not a directory.");
this.tmpDir = null;
}
} else {
this.tmpDir = null;
}
this.methodPipelines = new TreeMap<Method,PipeInfo>();
contextObject = null;
if ("context".equals(getContext().getParameters().getFirstValue(XProcResource.LOAD_TYPE_PARAM))) {
contextObject = getContext().getAttributes().get(XProcResource.CONTEXT_ATTR);
}
Object o = context.getAttributes().get(XPROC_CONFIG_ATTR);
if (o instanceof List) {
List<Object> configuration = (List<Object>)o;
for (Object item : configuration) {
if (item instanceof Document) {
Document methodDoc = (Document)item;
Element top = methodDoc.getDocumentElement();
if (equalsName(top,"method")) {
String methodName = DocumentLoader.getAttributeValue(top,"name");
String href = DocumentLoader.getAttributeValue(top,"href");
if (methodName!=null && href!=null) {
Method method = Method.valueOf(methodName.trim().toUpperCase());
try {
URI pipeline = resolve(top.getBaseURI()==null ? null : new URI(top.getBaseURI()),href);
if (pipeline==null) {
getLogger().warning("No resolved URI for pipeline method "+methodName);
continue;
}
getLogger().fine("Configuring pipeline "+pipeline+" for method "+methodName);
PipeInfo info = new PipeInfo(pipeline);
if ("true".equals(DocumentLoader.getAttributeValue(top,"bind-output"))) {
getLogger().fine("Binding result for "+method+" on "+pipeline);
info.bindResult = true;
}
String bindQuery = DocumentLoader.getAttributeValue(top,"bind-query");
if ("options".equals(bindQuery)) {
info.bindQuery = PipeInfo.QueryBind.OPTIONS;
} else if ("parameters".equals(bindQuery)) {
info.bindQuery = PipeInfo.QueryBind.PARAMETERS;
}
methodPipelines.put(method,info);
String outputType = DocumentLoader.getAttributeValue(top,"output-type");
if (outputType!=null) {
info.outputType = MediaType.valueOf(outputType);
}
for (Element option : DocumentLoader.getElementsByName(top, new DocumentLoader.Name(NS,"option"))) {
String name = DocumentLoader.getAttributeValue(option,"name");
if (name==null) {
continue;
}
QName optionName = QName.fromClarkName(name);
String source = DocumentLoader.getAttributeValue(option,"source");
String defaultValue = DocumentLoader.getAttributeValue(option,"default");
if (source!=null) {
source = source.trim();
}
String value = DocumentLoader.getAttributeValue(option,"value");
if (value!=null) {
getLogger().fine("Binding "+optionName+" to value: "+value);
info.bindOption(optionName.getClarkName(), value);
} else if ("parameters".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to parameter "+from);
info.bindOptionToParameter(from,optionName,defaultValue);
} else if ("header".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to header "+from);
info.bindOptionToHeader(from,optionName,defaultValue);
} else if ("request".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to request "+from);
info.bindOptionToRequest(from,optionName,defaultValue);
} else if ("attributes".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to attribute "+from);
info.bindOptionToAttribute(from,optionName,defaultValue);
} else if ("query".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to query "+from);
info.bindOptionToQuery(from,optionName,defaultValue);
}
}
for (Element require : DocumentLoader.getElementsByName(top, new DocumentLoader.Name(NS,"require"))) {
String typeName = DocumentLoader.getAttributeValue(require,"content-type");
if (typeName==null) {
continue;
}
MediaType contentType = MediaType.valueOf(typeName);
info.requiredTypes.add(contentType);
}
} catch (URISyntaxException ex) {
getLogger().severe("Bad URI: "+ex.getMessage());
}
}
}
}
}
}
optionsToBind = null;
String [] optionNames = context.getParameters().getValuesArray(XProcResource.OPTION_NAMES_PARAM);
if (optionNames!=null) {
for (int v=0; v<optionNames.length; v++) {
String [] names = optionNames[v].split(",");
for (int i=0; i<names.length; i++) {
QName name = QName.fromClarkName(names[i].trim());
if (optionsToBind==null) {
optionsToBind = new ArrayList<QName>();
}
optionsToBind.add(name);
getLogger().fine("Binding option "+name+" to parameter/attribute.");
}
}
}
headersToBind = null;
optionNames = context.getParameters().getValuesArray(XProcResource.OPTION_HEADER_NAMES_PARAM);
if (optionNames!=null) {
for (int v=0; v<optionNames.length; v++) {
String [] names = optionNames[v].split(",");
for (int i=0; i<names.length; i++) {
String [] parts = names[i].trim().split("=");
QName name = QName.fromClarkName(parts[parts.length==1 ? 0 : 1]);
String header = parts.length==1 ? name.getLocalName() : parts[0];
if (headersToBind==null) {
headersToBind = new TreeMap<String,QName>();
}
headersToBind.put(header,name);
getLogger().fine("Binding option "+name+" to request header.");
}
}
}
}
public XProcCache getCache() {
return cache;
}
public Context getContext() {
return context;
}
public Logger getLogger() {
return context.getLogger();
}
protected URI resolve(URI baseURI,String href)
throws URISyntaxException
{
if (contextObject!=null) {
URL resourceURL = contextObject.getClass().getResource(href);
if (resourceURL==null) {
getLogger().severe("Cannot load reference "+href+" against class "+contextObject.getClass().getName());
return null;
} else {
return resourceURL.toURI();
}
} else {
return baseURI==null ? new URI(href) : baseURI.resolve(href);
}
}
protected String getHeaderValue(String headerName,Request request,Series<Header> headers) {
if (headerName.equals("Host")) {
Reference hostRef = request.getHostRef();
return hostRef==null ? null : hostRef.toString();
} else {
return headers==null ? null : headers.getFirstValue(headerName);
}
}
protected String getParameterValue(String name)
{
return getContext().getParameters().getFirstValue(name);
}
protected String getAttributeValue(Request request,String attributeName)
{
Object o = request.getAttributes().get(attributeName);
if (o!=null) {
return o.toString();
}
o = getContext().getAttributes().get(attributeName);
if (o!=null) {
return o.toString();
}
return null;
}
protected String getRequestValue(Request request, String facetName)
{
if ("path".equals(facetName)) {
return request.getResourceRef().getPath();
} else if ("uri".equals(facetName)) {
return request.getResourceRef().toString();
} else if ("remaining".equals(facetName)) {
String remaining = request.getResourceRef().getRemainingPart();
int q = remaining.indexOf('?');
return q<0 ? remaining : remaining.substring(0,q);
} else if ("query".equals(facetName)) {
return request.getResourceRef().getQuery();
} else if ("base".equals(facetName)) {
Reference baseRef = request.getResourceRef().getBaseRef();
if (baseRef!=null) {
return baseRef.toString();
}
}
return null;
}
protected String getOptionValue(Request request,QName name)
{
String key = name.getLocalName();
if (name.getNamespaceURI()!=null) {
key = name.getClarkName();
}
Object o = request.getAttributes().get(key);
if (o!=null) {
return o.toString();
}
o = getContext().getAttributes().get(key);
if (o!=null) {
return o.toString();
}
return getContext().getParameters().getFirstValue(key);
}
protected void bindOptions(PipeInfo pipeInfo,XPipeline pipeline,Request request) {
boolean isFineLog = getLogger().isLoggable(Level.FINE);
Form query = request.getResourceRef().getQueryAsForm();
Series<Header> headers = (Series<Header>)request.getAttributes().get("org.restlet.http.headers");
if (pipeInfo.optionBindings!=null) {
for (OptionBinding binding : pipeInfo.optionBindings) {
String value = null;
switch (binding.source) {
case ATTRIBUTES:
value = getAttributeValue(request,binding.name);
break;
case HEADERS:
value = getHeaderValue(binding.name,request,headers);
break;
case PARAMETERS:
value = getParameterValue(binding.name);
break;
case QUERY:
value = query.getValues(binding.name);
break;
case REQUEST:
value = getRequestValue(request,binding.name);
break;
}
if (value==null) {
value = binding.defaultValue;
}
if (value!=null) {
if (isFineLog) {
getLogger().fine("Option "+binding.optionName+"="+value+" from "+binding.source);
}
pipeline.passOption(binding.optionName, new RuntimeValue(value));
} else if (isFineLog) {
getLogger().fine("Option "+binding.optionName+" has no value.");
}
}
}
if (optionsToBind!=null) {
for (QName optionName : optionsToBind) {
String value = getOptionValue(request,optionName);
if (value!=null) {
getLogger().fine("Option: "+optionName+"="+value);
pipeline.passOption(optionName, new RuntimeValue(value));
} else {
getLogger().fine("Option: "+optionName+" has no value.");
}
}
}
if (headersToBind!=null) {
for (String headerName : headersToBind.keySet()) {
String value = getHeaderValue(headerName,request,headers);
QName optionName = headersToBind.get(headerName);
if (value!=null) {
if (isFineLog) {
getLogger().fine("Option: "+optionName+"="+value);
}
pipeline.passOption(optionName, new RuntimeValue(value));
} else if (isFineLog) {
getLogger().fine("Option: "+optionName+" has no value.");
}
}
}
if (pipeInfo.optionValues!=null) {
for (String name : pipeInfo.optionValues.keySet()) {
String value = pipeInfo.optionValues.get(name);
QName optionName = QName.fromClarkName(name);
if (isFineLog) {
getLogger().fine("Option: "+optionName+"="+value);
}
pipeline.passOption(optionName,new RuntimeValue(value));
}
}
switch (pipeInfo.bindQuery) {
case OPTIONS:
for (String name : query.getNames()) {
String value = query.getValues(name);
if (isFineLog) {
getLogger().fine("Option: "+name+"="+value);
}
pipeline.passOption(QName.fromClarkName(name),new RuntimeValue(value));
}
break;
case PARAMETERS:
for (String name : query.getNames()) {
String value = query.getValues(name);
if (isFineLog) {
getLogger().fine("Parameter: "+name+"="+value);
}
pipeline.setParameter(QName.fromClarkName(name),new RuntimeValue(value));
}
}
}
public void handle(boolean inputFromRequest,Request request, Response response) {
boolean isFineLog = getLogger().isLoggable(Level.FINE);
if (cache==null) {
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
return;
}
Method requestMethod = request.getMethod();
PipeInfo pipeInfo = methodPipelines.get(requestMethod);
if (pipeInfo==null) {
response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
return;
}
getLogger().info(getLogger().isLoggable(Level.FINE) ? "Using pipeline: "+pipeInfo.location : "");
if (pipeInfo.requiredTypes.size()>0 && request.isEntityAvailable()) {
MediaType contentType = request.getEntity().getMediaType();
boolean matches = false;
for (MediaType type : pipeInfo.requiredTypes) {
if (type.equals(contentType) || type.includes(contentType)) {
matches = true;
break;
}
}
if (!matches) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity(new StringRepresentation("Content type "+contentType+" is not allowed.",MediaType.TEXT_PLAIN));
return;
}
}
XPipelineContext cachedXProc = null;
try {
cachedXProc = cache.get(pipeInfo.location);
} catch (Exception ex) {
getLogger().log(Level.SEVERE,"Cannot load pipeline.",ex);
response.setStatus(Status.SERVER_ERROR_INTERNAL);
return;
}
final XPipelineContext xproc = cachedXProc;
XPipeline pipeline = xproc.getPipeline();
if (pipeline.getOutputs().size()>1) {
// unsupported
getLogger().severe("Multiple outputs are not supported.");
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
cache.release(xproc);
return;
}
String inputPipeName = null;
String parametersPipeName = null;
boolean unknownPipes = false;
for (String pipeName : pipeline.getInputs()) {
XInput inputPipe = pipeline.getInput(pipeName);
if (inputPipeName==null && !inputPipe.getParameters()) {
inputPipeName = pipeName;
} else if (parametersPipeName==null && inputPipe.getParameters()) {
parametersPipeName = pipeName;
} else {
unknownPipes = true;
}
}
File tmpInputFile = null;
if (inputFromRequest) {
// Note: excluded case of no entity and no input ports
if (request.isEntityAvailable() && !unknownPipes && inputPipeName!=null) {
Representation entity = request.getEntity();
MediaType mediaType = entity.getMediaType();
InputSource isource = null;
String xml = null;
if (MediaType.APPLICATION_ALL_XML.includes(mediaType) || MediaType.TEXT_XML.equals(mediaType)) {
try {
isource = new InputSource(entity.getReader());
} catch (IOException ex) {
getLogger().warning("I/O error getting XML input reader: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
} else if (mediaType.equals(MediaType.APPLICATION_WWW_FORM)) {
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<form>\n");
Form form = new Form(entity);
for (String name : form.getNames()) {
String value = form.getValues(name);
xmlBuilder.append("<input name=\"");
xmlBuilder.append(name.replace("\"", """));
xmlBuilder.append("\" value=\"");
xmlBuilder.append(value.replace("\"", """));
xmlBuilder.append("\"/>\n");
}
xmlBuilder.append("</form>");
xml = xmlBuilder.toString();
isource = new InputSource(new StringReader(xml));
} else if (MediaType.TEXT_ALL.includes(mediaType)) {
// TODO: do this more efficiently
try {
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<data xmlns=\"http://www.w3.org/ns/xproc-step\" content-type=\"");
xmlBuilder.append(mediaType.toString());
xmlBuilder.append("\">");
String data = entity.getText().replace("&", "&").replace("<","<");
xmlBuilder.append(data);
xmlBuilder.append("</data>");
xml = xmlBuilder.toString();
isource = new InputSource(new StringReader(xml));
} catch (IOException ex) {
getLogger().warning("I/O error getting text from input: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
} else if (tmpDir!=null) {
try {
tmpInputFile = File.createTempFile("xproc", ".bin", tmpDir);
FileOutputStream out = new FileOutputStream(tmpInputFile);
entity.write(out);
out.close();
} catch (IOException ex) {
getLogger().warning("I/O error getting XML input reader: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<file xmlns=\"http://www.w3.org/ns/xproc-step\" content-type=\"");
xmlBuilder.append(mediaType.toString());
xmlBuilder.append("\" xml:base=\"file:");
xmlBuilder.append(tmpInputFile.getParentFile().getAbsolutePath().replace("\"", """));
xmlBuilder.append("/\" name=\"");
xmlBuilder.append(tmpInputFile.getName().replace("\"", """));
xmlBuilder.append("\"/>");
xml = xmlBuilder.toString();
isource = new InputSource(new StringReader(xml));
} else {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity(new StringRepresentation("Unprocessable input media type "+mediaType));
cache.release(xproc);
return;
}
SAXSource source = new SAXSource(isource);
DocumentBuilder builder = cache.getRuntime().getProcessor().newDocumentBuilder();
try {
XdmNode doc = builder.build(source);
pipeline.clearInputs(inputPipeName);
pipeline.writeTo(inputPipeName,doc);
} catch (SaxonApiException ex) {
getLogger().warning("Syntax error in XML from client: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
} catch (XProcException ex) {
getLogger().warning("Syntax error in XML from client: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
try {
isource.getCharacterStream().close();
} catch (IOException ex) {
getLogger().log(Level.WARNING,"I/O exception on close of client stream.",ex);
}
isource = null;
} else if (!request.isEntityAvailable() && inputPipeName!=null || unknownPipes) {
if (inputPipeName!=null) {
getLogger().severe("Required input not provided to pipeline: "+xproc.location+", port="+xproc.getPipeline().getInputs());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
} else {
// unsupported
getLogger().severe("Input port mismatch: "+xproc.location+", ports="+xproc.getPipeline().getInputs());
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
}
cache.release(xproc);
return;
} else if (request.isEntityAvailable() && inputPipeName==null) {
getLogger().severe("Input not allowed on pipeline: "+xproc.location);
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
} else if (response.isEntityAvailable() && !unknownPipes && inputPipeName!=null) {
Representation entity = response.getEntity();
MediaType mediaType = entity.getMediaType();
InputSource isource = null;
if (!MediaType.APPLICATION_ALL_XML.includes(mediaType) && !MediaType.TEXT_XML.equals(mediaType)) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity(new StringRepresentation("Unprocessable input media type "+mediaType));
cache.release(xproc);
return;
}
try {
isource = new InputSource(entity.getReader());
} catch (IOException ex) {
getLogger().warning("I/O error getting XML input reader: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
SAXSource source = new SAXSource(isource);
DocumentBuilder builder = cache.getRuntime().getProcessor().newDocumentBuilder();
try {
XdmNode doc = builder.build(source);
pipeline.clearInputs(inputPipeName);
pipeline.writeTo(inputPipeName,doc);
} catch (SaxonApiException ex) {
getLogger().warning("Syntax error in XML from client: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
try {
isource.getCharacterStream().close();
} catch (IOException ex) {
getLogger().log(Level.WARNING,"I/O exception on close of client stream.",ex);
}
} else if (!response.isEntityAvailable() && inputPipeName!=null || unknownPipes) { // Note: excluded case of no entity and no input ports
if (inputPipeName!=null) {
getLogger().severe("Required input not provided to pipeline: "+xproc.location+", port="+xproc.getPipeline().getInputs());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
} else if (pipeline.getInputs().isEmpty()) {
getLogger().severe("Input port mismatch: "+xproc.location+", ports="+xproc.getPipeline().getInputs());
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
}
// unsupported
cache.release(xproc);
return;
} else if (response.isEntityAvailable() && inputPipeName==null) {
getLogger().severe("Input not allowed on pipeline: "+xproc.location);
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
// clear the response just in case this is a filter
response.setEntity(null);
bindOptions(pipeInfo,pipeline,request);
// TODO: switch to use finally ... but there are couple of places where the entity releases the pipeline
try {
try {
pipeline.run();
} catch (XProcException ex) {
cache.release(xproc);
getLogger().info("Error running pipeline: ("+ex.getErrorCode()+") "+ex.getMessage());
response.setStatus(Status.SERVER_ERROR_INTERNAL);
return;
}
if (tmpInputFile!=null) {
if (tmpInputFile.exists() && !tmpInputFile.delete()) {
getLogger().warning("Cannot delete temporary input: "+tmpInputFile.getAbsolutePath());
}
}
if (xproc.getPipeline().getOutputs().size()>=1) {
URI location = xproc.location;
cache.release(xproc);
getLogger().warning("Pipeline "+location+" has too many output ports.");
response.setStatus(Status.SERVER_ERROR_INTERNAL);
return;
} else if (xproc.getPipeline().getOutputs().size()==1) {
final String outputPort = xproc.getPipeline().getOutputs().iterator().next();
if (pipeInfo.bindResult) {
getLogger().fine("Binding result of pipeline run...");
response.setStatus(Status.SUCCESS_NO_CONTENT);
Series<Header> responseHeaders = (Series<Header>)response.getAttributes().get("org.restlet.http.headers");
if (responseHeaders==null) {
responseHeaders = new Series<Header>(Header.class);
response.getAttributes().put("org.restlet.http.headers",responseHeaders);
}
final ReadablePipe rpipe = xproc.getPipeline().readFrom(outputPort);
if (rpipe.moreDocuments()) {
XdmNode doc = rpipe.read();
XdmSequenceIterator seq = doc.axisIterator(Axis.CHILD,HTTP_NAME);
if (seq.hasNext()) {
getLogger().fine("Found http to bind...");
XdmNode http = (XdmNode)seq.next();
String status = http.getAttributeValue(STATUS_NAME);
if (status!=null && status.length()>0) {
getLogger().fine(isFineLog ? "Status: "+status : "");
response.setStatus(Status.valueOf(Integer.parseInt(status)));
}
Series<Header> headers = (Series<Header>)request.getAttributes().get("org.restlet.http.headers");
XdmSequenceIterator headerElements = http.axisIterator(Axis.CHILD,HEADER_NAME);
while (headerElements.hasNext()) {
XdmNode headerElement = (XdmNode)headerElements.next();
String name = headerElement.getAttributeValue(NAME_NAME);
if (name!=null && name.length()>0) {
String value = headerElement.getStringValue();
getLogger().fine(isFineLog ? name+": "+value : "");
if ("location".equalsIgnoreCase(name)) {
response.setLocationRef(value);
} else if ("Cache-Control".equalsIgnoreCase(name)) {
List<CacheDirective> directives = response.getCacheDirectives();
if (directives==null) {
directives = new ArrayList<CacheDirective>();
response.setCacheDirectives(directives);
}
String [] parts = value.trim().split("=");
if (parts.length>1) {
directives.add(new CacheDirective(parts[0],parts[1]));
} else {
directives.add(new CacheDirective(parts[0]));
}
} else {
headers.add(name, value);
}
}
}
XdmSequenceIterator attrElements = http.axisIterator(Axis.CHILD,ATTRIBUTE_NAME);
while (attrElements.hasNext()) {
XdmNode attrElement = (XdmNode)attrElements.next();
String name = attrElement.getAttributeValue(NAME_NAME);
String value = attrElement.getAttributeValue(VALUE_NAME);
if (name!=null && value!=null) {
response.getAttributes().put(name,value);
}
}
XdmSequenceIterator entityElements = http.axisIterator(Axis.CHILD,ENTITY_NAME);
boolean doRelease = true;
while (entityElements.hasNext()) {
XdmNode entityElement = (XdmNode)entityElements.next();
String mediaTypeName = entityElement.getAttributeValue(TYPE_NAME);
String lastModifiedValue = entityElement.getAttributeValue(LAST_MODIFIED_NAME);
Date lastModified = null;
if (lastModifiedValue!=null && lastModifiedValue.length()>22) {
//getLogger().info("Parsing date: "+lastModifiedValue);
try {
String dtValue = lastModifiedValue.substring(0,22)+lastModifiedValue.substring(23);
lastModified = xsdDateFormat.parse(dtValue);
} catch (ParseException ex) {
int lastColon = lastModifiedValue.lastIndexOf(':');
String dtValue = lastModifiedValue.substring(0,lastColon)+lastModifiedValue.substring(lastColon+1);
try {
lastModified = xsdDateFormatWithMilliseconds.parse(dtValue);
} catch (ParseException pex) {
Date date = new Date();
getLogger().warning("Cannot parse date '"+lastModifiedValue+"' (sample "+xsdDateFormatWithMilliseconds.format(date)+" or "+xsdDateFormat.format(date)+"): "+pex.getMessage());
}
}
}
MediaType mediaType = mediaTypeName==null || mediaTypeName.length()==0 ? MediaType.TEXT_PLAIN : MediaType.valueOf(mediaTypeName);
boolean entitySet = false;
if (MediaType.APPLICATION_ALL_XML.includes(mediaType) || MediaType.TEXT_XML.equals(mediaType)) {
XdmSequenceIterator children = entityElement.axisIterator(Axis.CHILD);
HashSet<String> exlcudedNamespaces = new HashSet<String>();
exlcudedNamespaces.add(HTTP_NS);
while (children.hasNext()) {
XdmItem item = children.next();
if (!item.isAtomicValue()) {
XdmNode node = (XdmNode)item;
if (node.getNodeKind()==XdmNodeKind.ELEMENT) {
entitySet = true;
final XdmNode documentElement = S9apiUtils.removeNamespaces(cache.getRuntime(), node, exlcudedNamespaces,true);
final Serialization serial = xproc.getPipeline().getSerialization(outputPort);
response.setEntity(new OutputRepresentation(mediaType) {
public void write(OutputStream out)
throws IOException
{
Serialization serial = xproc.getPipeline().getSerialization(outputPort);
WritableDocument outputDoc = new WritableDocument(cache.getRuntime(),null,serial,out);
outputDoc.write(documentElement);
out.flush();
}
public void release() {
cache.release(xproc);
}
});
doRelease = false;
break;
}
}
}
}
if (!entitySet) {
response.setEntity(new StringRepresentation(entityElement.getStringValue(),mediaType));
}
if (lastModified!=null) {
response.getEntity().setModificationDate(lastModified);
}
}
if (doRelease) {
cache.release(xproc);
}
} else {
getLogger().fine("No HTTP binding from pipeline, serializing result...");
// XML to serialize
final XdmNode startDoc = doc;
final String charset = pipeInfo.outputType.getParameters().getFirstValue("charset");
response.setStatus(Status.SUCCESS_OK);
response.setEntity(new OutputRepresentation(pipeInfo.outputType) {
public void write(OutputStream out)
throws IOException
{
Serialization serial = xproc.getPipeline().getSerialization(outputPort);
if (serial==null && charset!=null) {
serial = new Serialization(cache.getRuntime(),null);
}
if (charset!=null) {
serial.setEncoding(charset);
}
WritableDocument outputDoc = new WritableDocument(cache.getRuntime(),null,serial,out);
outputDoc.write(startDoc);
while (rpipe.moreDocuments()) {
try {
XdmNode nextDoc = rpipe.read();
if (nextDoc!=null) {
outputDoc.write(nextDoc);
}
} catch (SaxonApiException ex) {
throw new IOException("Exception while writing output port "+outputPort,ex);
}
}
out.flush();
}
public void release() {
cache.release(xproc);
}
});
}
}
} else {
getLogger().info("pipeInfo.outputType="+pipeInfo.outputType);
final String charset = pipeInfo.outputType.getParameters().getFirstValue("charset");
response.setEntity(new OutputRepresentation(pipeInfo.outputType) {
public void write(OutputStream out)
throws IOException
{
Serialization serial = xproc.getPipeline().getSerialization(outputPort);
if (serial==null && charset!=null) {
serial = new Serialization(cache.getRuntime(),null);
}
if (charset!=null) {
serial.setEncoding(charset);
}
WritableDocument doc = new WritableDocument(cache.getRuntime(),null,serial,out);
ReadablePipe rpipe = xproc.getPipeline().readFrom(outputPort);
while (rpipe.moreDocuments()) {
try {
doc.write(rpipe.read());
} catch (SaxonApiException ex) {
throw new IOException("Exception while writing output port "+outputPort,ex);
}
}
out.flush();
}
public void release() {
cache.release(xproc);
}
});
response.setStatus(Status.SUCCESS_OK);
}
} else {
cache.release(xproc);
response.setStatus(Status.SUCCESS_NO_CONTENT);
}
} catch (SaxonApiException ex) {
cache.release(xproc);
getLogger().info("Error running pipeline: "+ex.getMessage());
response.setStatus(Status.SERVER_ERROR_INTERNAL);
return;
}
}
}
| mod-xproc/src/org/xproclet/xproc/XProcHelper.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.xproclet.xproc;
import com.xmlcalabash.core.XProcException;
import com.xmlcalabash.io.ReadablePipe;
import com.xmlcalabash.io.WritableDocument;
import com.xmlcalabash.model.RuntimeValue;
import com.xmlcalabash.model.Serialization;
import com.xmlcalabash.runtime.XInput;
import com.xmlcalabash.runtime.XPipeline;
import com.xmlcalabash.util.S9apiUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.sax.SAXSource;
import net.sf.saxon.s9api.Axis;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmItem;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmNodeKind;
import net.sf.saxon.s9api.XdmSequenceIterator;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.CacheDirective;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.engine.header.Header;
import org.restlet.representation.OutputRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.util.Series;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xproclet.server.DocumentLoader;
/**
*
* @author alex
*/
public class XProcHelper {
final static String NS = "http://www.xproclet.org/V/XProc/";
final static String HTTP_NS = "http://www.xproclet.org/V/HTTP/";
final static QName HTTP_NAME = QName.fromClarkName("{"+HTTP_NS+"}http");
final static QName HEADER_NAME = QName.fromClarkName("{"+HTTP_NS+"}header");
final static QName ENTITY_NAME = QName.fromClarkName("{"+HTTP_NS+"}entity");
final static QName ATTRIBUTE_NAME = QName.fromClarkName("{"+HTTP_NS+"}attribute");
final static QName STATUS_NAME = QName.fromClarkName("status");
final static QName NAME_NAME = QName.fromClarkName("name");
final static QName TYPE_NAME = QName.fromClarkName("type");
final static QName VALUE_NAME = QName.fromClarkName("value");
final static QName LAST_MODIFIED_NAME = QName.fromClarkName("last-modified");
public final static String XPROC_CONFIG_ATTR = "xproc.configuration";
final static SimpleDateFormat xsdDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
final static SimpleDateFormat xsdDateFormatWithMilliseconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
static class OptionBinding {
enum Source {
ATTRIBUTES,
HEADERS,
PARAMETERS,
QUERY,
REQUEST
}
QName optionName;
Source source;
String name;
String defaultValue;
OptionBinding(QName optionName,Source source,String name,String defaultValue)
{
this.optionName = optionName;
this.name = name;
this.source = source;
this.defaultValue = defaultValue;
}
}
static class PipeInfo {
enum QueryBind {
NONE,
PARAMETERS,
OPTIONS
}
URI location;
boolean bindResult;
QueryBind bindQuery;
List<OptionBinding> optionBindings;
/*
Map<String,QName> parametersToBind;
Map<String,QName> headersToBind;
Map<String,QName> requestsToBind;
Map<String,QName> attrsToBind;
*/
Map<String,String> optionValues;
List<MediaType> requiredTypes;
MediaType outputType;
PipeInfo(URI location) {
this.location = location;
/*
this.parametersToBind = null;
this.optionValues = null;
this.headersToBind = null;
this.requestsToBind = null;
this.attrsToBind = null;
*/
this.optionBindings = null;
this.bindResult = false;
this.bindQuery = QueryBind.NONE;
this.requiredTypes = new ArrayList<MediaType>();
this.outputType = MediaType.valueOf(MediaType.APPLICATION_XML+";charset=UTF-8");
}
void bindOptionToParameter(String parameterName,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.PARAMETERS,parameterName,defaultValue));
/*
if (parametersToBind==null) {
parametersToBind = new TreeMap<String,QName>();
}
parametersToBind.put(parameterName,name);
*
*/
}
void bindOptionToHeader(String header,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.HEADERS,header,defaultValue));
/*
if (headersToBind==null) {
headersToBind = new TreeMap<String,QName>();
}
headersToBind.put(header,name);
*
*/
}
void bindOption(String name,String value) {
if (optionValues==null) {
optionValues = new TreeMap<String,String>();
}
optionValues.put(name, value);
}
void bindOptionToRequest(String part,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.REQUEST,part,defaultValue));
/*
if (requestsToBind==null) {
requestsToBind = new TreeMap<String,QName>();
}
requestsToBind.put(part,name);
*
*/
}
void bindOptionToAttribute(String attrName,QName name,String defaultValue) {
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.ATTRIBUTES,attrName,defaultValue));
/*
if (attrsToBind==null) {
attrsToBind = new TreeMap<String,QName>();
}
attrsToBind.put(attrName,name);
*
*/
}
void bindOptionToQuery(String parameterName,QName name,String defaultValue)
{
if (optionBindings==null) {
optionBindings = new ArrayList<OptionBinding>();
}
optionBindings.add(new OptionBinding(name,OptionBinding.Source.QUERY,parameterName,defaultValue));
}
}
Context context;
Map<Method,PipeInfo> methodPipelines;
protected XProcCache cache;
List<QName> optionsToBind;
Map<String,QName> headersToBind;
Object contextObject;
File tmpDir;
static boolean equalsName(Element e,String name)
{
return NS.equals(e.getNamespaceURI()) && name.equals(e.getLocalName());
}
public XProcHelper(Context context) {
this.context = context;
try {
cache = (XProcCache)getContext().getAttributes().get(XProcCache.ATTR);
if (cache==null) {
getLogger().warning("No cache "+XProcCache.ATTR+" attribute was found for caching xproc pipeline instances.");
}
} catch (Exception ex) {
getLogger().log(Level.SEVERE,"Cannot retrieve cache from context.",ex);
}
String tmpDir = context.getParameters().getFirstValue(XProcResource.TMPDIR_PARAM);
if (tmpDir!=null) {
if (tmpDir.startsWith("file:")) {
tmpDir = tmpDir.substring(5);
}
this.tmpDir = new File(tmpDir);
if (!this.tmpDir.exists()) {
if (!this.tmpDir.mkdirs()) {
getLogger().severe("Cannot create temporary directory "+tmpDir);
this.tmpDir = null;
}
}
if (this.tmpDir!=null && !this.tmpDir.isDirectory()) {
getLogger().severe("The location "+tmpDir+" is not a directory.");
this.tmpDir = null;
}
} else {
this.tmpDir = null;
}
this.methodPipelines = new TreeMap<Method,PipeInfo>();
contextObject = null;
if ("context".equals(getContext().getParameters().getFirstValue(XProcResource.LOAD_TYPE_PARAM))) {
contextObject = getContext().getAttributes().get(XProcResource.CONTEXT_ATTR);
}
Object o = context.getAttributes().get(XPROC_CONFIG_ATTR);
if (o instanceof List) {
List<Object> configuration = (List<Object>)o;
for (Object item : configuration) {
if (item instanceof Document) {
Document methodDoc = (Document)item;
Element top = methodDoc.getDocumentElement();
if (equalsName(top,"method")) {
String methodName = DocumentLoader.getAttributeValue(top,"name");
String href = DocumentLoader.getAttributeValue(top,"href");
if (methodName!=null && href!=null) {
Method method = Method.valueOf(methodName.trim().toUpperCase());
try {
URI pipeline = resolve(top.getBaseURI()==null ? null : new URI(top.getBaseURI()),href);
if (pipeline==null) {
getLogger().warning("No resolved URI for pipeline method "+methodName);
continue;
}
getLogger().fine("Configuring pipeline "+pipeline+" for method "+methodName);
PipeInfo info = new PipeInfo(pipeline);
if ("true".equals(DocumentLoader.getAttributeValue(top,"bind-output"))) {
getLogger().fine("Binding result for "+method+" on "+pipeline);
info.bindResult = true;
}
String bindQuery = DocumentLoader.getAttributeValue(top,"bind-query");
if ("options".equals(bindQuery)) {
info.bindQuery = PipeInfo.QueryBind.OPTIONS;
} else if ("parameters".equals(bindQuery)) {
info.bindQuery = PipeInfo.QueryBind.PARAMETERS;
}
methodPipelines.put(method,info);
String outputType = DocumentLoader.getAttributeValue(top,"output-type");
if (outputType!=null) {
info.outputType = MediaType.valueOf(outputType);
}
for (Element option : DocumentLoader.getElementsByName(top, new DocumentLoader.Name(NS,"option"))) {
String name = DocumentLoader.getAttributeValue(option,"name");
if (name==null) {
continue;
}
QName optionName = QName.fromClarkName(name);
String source = DocumentLoader.getAttributeValue(option,"source");
String defaultValue = DocumentLoader.getAttributeValue(option,"default");
if (source!=null) {
source = source.trim();
}
String value = DocumentLoader.getAttributeValue(option,"value");
if (value!=null) {
getLogger().fine("Binding "+optionName+" to value: "+value);
info.bindOption(optionName.getClarkName(), value);
} else if ("parameters".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to parameter "+from);
info.bindOptionToParameter(from,optionName,defaultValue);
} else if ("header".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to header "+from);
info.bindOptionToHeader(from,optionName,defaultValue);
} else if ("request".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to request "+from);
info.bindOptionToRequest(from,optionName,defaultValue);
} else if ("attributes".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to attribute "+from);
info.bindOptionToAttribute(from,optionName,defaultValue);
} else if ("query".equals(source)) {
String from = DocumentLoader.getAttributeValue(option,"from");
if (from==null || from.length()==0) {
from = optionName.getLocalName();
}
getLogger().fine("Binding "+optionName+" to query "+from);
info.bindOptionToQuery(from,optionName,defaultValue);
}
}
for (Element require : DocumentLoader.getElementsByName(top, new DocumentLoader.Name(NS,"require"))) {
String typeName = DocumentLoader.getAttributeValue(require,"content-type");
if (typeName==null) {
continue;
}
MediaType contentType = MediaType.valueOf(typeName);
info.requiredTypes.add(contentType);
}
} catch (URISyntaxException ex) {
getLogger().severe("Bad URI: "+ex.getMessage());
}
}
}
}
}
}
optionsToBind = null;
String [] optionNames = context.getParameters().getValuesArray(XProcResource.OPTION_NAMES_PARAM);
if (optionNames!=null) {
for (int v=0; v<optionNames.length; v++) {
String [] names = optionNames[v].split(",");
for (int i=0; i<names.length; i++) {
QName name = QName.fromClarkName(names[i].trim());
if (optionsToBind==null) {
optionsToBind = new ArrayList<QName>();
}
optionsToBind.add(name);
getLogger().fine("Binding option "+name+" to parameter/attribute.");
}
}
}
headersToBind = null;
optionNames = context.getParameters().getValuesArray(XProcResource.OPTION_HEADER_NAMES_PARAM);
if (optionNames!=null) {
for (int v=0; v<optionNames.length; v++) {
String [] names = optionNames[v].split(",");
for (int i=0; i<names.length; i++) {
String [] parts = names[i].trim().split("=");
QName name = QName.fromClarkName(parts[parts.length==1 ? 0 : 1]);
String header = parts.length==1 ? name.getLocalName() : parts[0];
if (headersToBind==null) {
headersToBind = new TreeMap<String,QName>();
}
headersToBind.put(header,name);
getLogger().fine("Binding option "+name+" to request header.");
}
}
}
}
public XProcCache getCache() {
return cache;
}
public Context getContext() {
return context;
}
public Logger getLogger() {
return context.getLogger();
}
protected URI resolve(URI baseURI,String href)
throws URISyntaxException
{
if (contextObject!=null) {
URL resourceURL = contextObject.getClass().getResource(href);
if (resourceURL==null) {
getLogger().severe("Cannot load reference "+href+" against class "+contextObject.getClass().getName());
return null;
} else {
return resourceURL.toURI();
}
} else {
return baseURI==null ? new URI(href) : baseURI.resolve(href);
}
}
protected String getHeaderValue(String headerName,Request request,Series<Header> headers) {
if (headerName.equals("Host")) {
Reference hostRef = request.getHostRef();
return hostRef==null ? null : hostRef.toString();
} else {
return headers==null ? null : headers.getFirstValue(headerName);
}
}
protected String getParameterValue(String name)
{
return getContext().getParameters().getFirstValue(name);
}
protected String getAttributeValue(Request request,String attributeName)
{
Object o = request.getAttributes().get(attributeName);
if (o!=null) {
return o.toString();
}
o = getContext().getAttributes().get(attributeName);
if (o!=null) {
return o.toString();
}
return null;
}
protected String getRequestValue(Request request, String facetName)
{
if ("path".equals(facetName)) {
return request.getResourceRef().getPath();
} else if ("uri".equals(facetName)) {
return request.getResourceRef().toString();
} else if ("remaining".equals(facetName)) {
String remaining = request.getResourceRef().getRemainingPart();
int q = remaining.indexOf('?');
return q<0 ? remaining : remaining.substring(0,q);
} else if ("query".equals(facetName)) {
return request.getResourceRef().getQuery();
} else if ("base".equals(facetName)) {
Reference baseRef = request.getResourceRef().getBaseRef();
if (baseRef!=null) {
return baseRef.toString();
}
}
return null;
}
protected String getOptionValue(Request request,QName name)
{
String key = name.getLocalName();
if (name.getNamespaceURI()!=null) {
key = name.getClarkName();
}
Object o = request.getAttributes().get(key);
if (o!=null) {
return o.toString();
}
o = getContext().getAttributes().get(key);
if (o!=null) {
return o.toString();
}
return getContext().getParameters().getFirstValue(key);
}
protected void bindOptions(PipeInfo pipeInfo,XPipeline pipeline,Request request) {
boolean isFineLog = getLogger().isLoggable(Level.FINE);
Form query = request.getResourceRef().getQueryAsForm();
Series<Header> headers = (Series<Header>)request.getAttributes().get("org.restlet.http.headers");
if (pipeInfo.optionBindings!=null) {
for (OptionBinding binding : pipeInfo.optionBindings) {
String value = null;
switch (binding.source) {
case ATTRIBUTES:
value = getAttributeValue(request,binding.name);
break;
case HEADERS:
value = getHeaderValue(binding.name,request,headers);
break;
case PARAMETERS:
value = getParameterValue(binding.name);
break;
case QUERY:
value = query.getValues(binding.name);
break;
case REQUEST:
value = getRequestValue(request,binding.name);
break;
}
if (value==null) {
value = binding.defaultValue;
}
if (value!=null) {
if (isFineLog) {
getLogger().fine("Option "+binding.optionName+"="+value+" from "+binding.source);
}
pipeline.passOption(binding.optionName, new RuntimeValue(value));
} else if (isFineLog) {
getLogger().fine("Option "+binding.optionName+" has no value.");
}
}
}
if (optionsToBind!=null) {
for (QName optionName : optionsToBind) {
String value = getOptionValue(request,optionName);
if (value!=null) {
getLogger().fine("Option: "+optionName+"="+value);
pipeline.passOption(optionName, new RuntimeValue(value));
} else {
getLogger().fine("Option: "+optionName+" has no value.");
}
}
}
if (headersToBind!=null) {
for (String headerName : headersToBind.keySet()) {
String value = getHeaderValue(headerName,request,headers);
QName optionName = headersToBind.get(headerName);
if (value!=null) {
if (isFineLog) {
getLogger().fine("Option: "+optionName+"="+value);
}
pipeline.passOption(optionName, new RuntimeValue(value));
} else if (isFineLog) {
getLogger().fine("Option: "+optionName+" has no value.");
}
}
}
if (pipeInfo.optionValues!=null) {
for (String name : pipeInfo.optionValues.keySet()) {
String value = pipeInfo.optionValues.get(name);
QName optionName = QName.fromClarkName(name);
if (isFineLog) {
getLogger().fine("Option: "+optionName+"="+value);
}
pipeline.passOption(optionName,new RuntimeValue(value));
}
}
switch (pipeInfo.bindQuery) {
case OPTIONS:
for (String name : query.getNames()) {
String value = query.getValues(name);
if (isFineLog) {
getLogger().fine("Option: "+name+"="+value);
}
pipeline.passOption(QName.fromClarkName(name),new RuntimeValue(value));
}
break;
case PARAMETERS:
for (String name : query.getNames()) {
String value = query.getValues(name);
if (isFineLog) {
getLogger().fine("Parameter: "+name+"="+value);
}
pipeline.setParameter(QName.fromClarkName(name),new RuntimeValue(value));
}
}
}
public void handle(boolean inputFromRequest,Request request, Response response) {
boolean isFineLog = getLogger().isLoggable(Level.FINE);
if (cache==null) {
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
return;
}
Method requestMethod = request.getMethod();
PipeInfo pipeInfo = methodPipelines.get(requestMethod);
if (pipeInfo==null) {
response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
return;
}
getLogger().info(getLogger().isLoggable(Level.FINE) ? "Using pipeline: "+pipeInfo.location : "");
if (pipeInfo.requiredTypes.size()>0 && request.isEntityAvailable()) {
MediaType contentType = request.getEntity().getMediaType();
boolean matches = false;
for (MediaType type : pipeInfo.requiredTypes) {
if (type.equals(contentType) || type.includes(contentType)) {
matches = true;
break;
}
}
if (!matches) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity(new StringRepresentation("Content type "+contentType+" is not allowed.",MediaType.TEXT_PLAIN));
return;
}
}
XPipelineContext cachedXProc = null;
try {
cachedXProc = cache.get(pipeInfo.location);
} catch (Exception ex) {
getLogger().log(Level.SEVERE,"Cannot load pipeline.",ex);
response.setStatus(Status.SERVER_ERROR_INTERNAL);
return;
}
final XPipelineContext xproc = cachedXProc;
XPipeline pipeline = xproc.getPipeline();
if (pipeline.getOutputs().size()>1) {
// unsupported
getLogger().severe("Multiple outputs are not supported.");
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
cache.release(xproc);
return;
}
String inputPipeName = null;
String parametersPipeName = null;
boolean unknownPipes = false;
for (String pipeName : pipeline.getInputs()) {
XInput inputPipe = pipeline.getInput(pipeName);
if (inputPipeName==null && !inputPipe.getParameters()) {
inputPipeName = pipeName;
} else if (parametersPipeName==null && inputPipe.getParameters()) {
parametersPipeName = pipeName;
} else {
unknownPipes = true;
}
}
File tmpInputFile = null;
if (inputFromRequest) {
// Note: excluded case of no entity and no input ports
if (request.isEntityAvailable() && !unknownPipes && inputPipeName!=null) {
Representation entity = request.getEntity();
MediaType mediaType = entity.getMediaType();
InputSource isource = null;
String xml = null;
if (MediaType.APPLICATION_ALL_XML.includes(mediaType) || MediaType.TEXT_XML.equals(mediaType)) {
try {
isource = new InputSource(entity.getReader());
} catch (IOException ex) {
getLogger().warning("I/O error getting XML input reader: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
} else if (mediaType.equals(MediaType.APPLICATION_WWW_FORM)) {
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<form>\n");
Form form = new Form(entity);
for (String name : form.getNames()) {
String value = form.getValues(name);
xmlBuilder.append("<input name=\"");
xmlBuilder.append(name.replace("\"", """));
xmlBuilder.append("\" value=\"");
xmlBuilder.append(value.replace("\"", """));
xmlBuilder.append("\"/>\n");
}
xmlBuilder.append("</form>");
xml = xmlBuilder.toString();
isource = new InputSource(new StringReader(xml));
} else if (MediaType.TEXT_ALL.includes(mediaType)) {
// TODO: do this more efficiently
try {
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<data xmlns=\"http://www.w3.org/ns/xproc-step\" content-type=\"");
xmlBuilder.append(mediaType.toString());
xmlBuilder.append("\">");
String data = entity.getText().replace("&", "&").replace("<","<");
xmlBuilder.append(data);
xmlBuilder.append("</data>");
xml = xmlBuilder.toString();
isource = new InputSource(new StringReader(xml));
} catch (IOException ex) {
getLogger().warning("I/O error getting text from input: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
} else if (tmpDir!=null) {
try {
tmpInputFile = File.createTempFile("xproc", ".bin", tmpDir);
FileOutputStream out = new FileOutputStream(tmpInputFile);
entity.write(out);
out.close();
} catch (IOException ex) {
getLogger().warning("I/O error getting XML input reader: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<file xmlns=\"http://www.w3.org/ns/xproc-step\" content-type=\"");
xmlBuilder.append(mediaType.toString());
xmlBuilder.append("\" xml:base=\"file:");
xmlBuilder.append(tmpInputFile.getParentFile().getAbsolutePath().replace("\"", """));
xmlBuilder.append("/\" name=\"");
xmlBuilder.append(tmpInputFile.getName().replace("\"", """));
xmlBuilder.append("\"/>");
xml = xmlBuilder.toString();
isource = new InputSource(new StringReader(xml));
} else {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity(new StringRepresentation("Unprocessable input media type "+mediaType));
cache.release(xproc);
return;
}
SAXSource source = new SAXSource(isource);
DocumentBuilder builder = cache.getRuntime().getProcessor().newDocumentBuilder();
try {
XdmNode doc = builder.build(source);
pipeline.clearInputs(inputPipeName);
pipeline.writeTo(inputPipeName,doc);
} catch (SaxonApiException ex) {
getLogger().warning("Syntax error in XML from client: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
} catch (XProcException ex) {
getLogger().warning("Syntax error in XML from client: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
try {
isource.getCharacterStream().close();
} catch (IOException ex) {
getLogger().log(Level.WARNING,"I/O exception on close of client stream.",ex);
}
isource = null;
} else if (!request.isEntityAvailable() && inputPipeName!=null || unknownPipes) {
if (inputPipeName!=null) {
getLogger().severe("Required input not provided to pipeline: "+xproc.location+", port="+xproc.getPipeline().getInputs());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
} else {
// unsupported
getLogger().severe("Input port mismatch: "+xproc.location+", ports="+xproc.getPipeline().getInputs());
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
}
cache.release(xproc);
return;
} else if (request.isEntityAvailable() && inputPipeName==null) {
getLogger().severe("Input not allowed on pipeline: "+xproc.location);
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
} else if (response.isEntityAvailable() && !unknownPipes && inputPipeName!=null) {
Representation entity = response.getEntity();
MediaType mediaType = entity.getMediaType();
InputSource isource = null;
if (!MediaType.APPLICATION_ALL_XML.includes(mediaType) && !MediaType.TEXT_XML.equals(mediaType)) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
response.setEntity(new StringRepresentation("Unprocessable input media type "+mediaType));
cache.release(xproc);
return;
}
try {
isource = new InputSource(entity.getReader());
} catch (IOException ex) {
getLogger().warning("I/O error getting XML input reader: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
SAXSource source = new SAXSource(isource);
DocumentBuilder builder = cache.getRuntime().getProcessor().newDocumentBuilder();
try {
XdmNode doc = builder.build(source);
pipeline.clearInputs(inputPipeName);
pipeline.writeTo(inputPipeName,doc);
} catch (SaxonApiException ex) {
getLogger().warning("Syntax error in XML from client: "+ex.getMessage());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
try {
isource.getCharacterStream().close();
} catch (IOException ex) {
getLogger().log(Level.WARNING,"I/O exception on close of client stream.",ex);
}
} else if (!response.isEntityAvailable() && inputPipeName!=null || unknownPipes) { // Note: excluded case of no entity and no input ports
if (inputPipeName!=null) {
getLogger().severe("Required input not provided to pipeline: "+xproc.location+", port="+xproc.getPipeline().getInputs());
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
} else if (pipeline.getInputs().isEmpty()) {
getLogger().severe("Input port mismatch: "+xproc.location+", ports="+xproc.getPipeline().getInputs());
response.setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
}
// unsupported
cache.release(xproc);
return;
} else if (response.isEntityAvailable() && inputPipeName==null) {
getLogger().severe("Input not allowed on pipeline: "+xproc.location);
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
cache.release(xproc);
return;
}
// clear the response just in case this is a filter
response.setEntity(null);
bindOptions(pipeInfo,pipeline,request);
// TODO: switch to use finally ... but there are couple of places where the entity releases the pipeline
try {
try {
pipeline.run();
} catch (XProcException ex) {
cache.release(xproc);
getLogger().info("Error running pipeline: ("+ex.getErrorCode()+") "+ex.getMessage());
response.setStatus(Status.SERVER_ERROR_INTERNAL);
return;
}
if (tmpInputFile!=null) {
if (tmpInputFile.exists() && !tmpInputFile.delete()) {
getLogger().warning("Cannot delete temporary input: "+tmpInputFile.getAbsolutePath());
}
}
if (xproc.getPipeline().getOutputs().size()==1) {
final String outputPort = xproc.getPipeline().getOutputs().iterator().next();
if (pipeInfo.bindResult) {
getLogger().fine("Binding result of pipeline run...");
response.setStatus(Status.SUCCESS_NO_CONTENT);
Series<Header> responseHeaders = (Series<Header>)response.getAttributes().get("org.restlet.http.headers");
if (responseHeaders==null) {
responseHeaders = new Series<Header>(Header.class);
response.getAttributes().put("org.restlet.http.headers",responseHeaders);
}
final ReadablePipe rpipe = xproc.getPipeline().readFrom(outputPort);
if (rpipe.moreDocuments()) {
XdmNode doc = rpipe.read();
XdmSequenceIterator seq = doc.axisIterator(Axis.CHILD,HTTP_NAME);
if (seq.hasNext()) {
getLogger().fine("Found http to bind...");
XdmNode http = (XdmNode)seq.next();
String status = http.getAttributeValue(STATUS_NAME);
if (status!=null && status.length()>0) {
getLogger().fine(isFineLog ? "Status: "+status : "");
response.setStatus(Status.valueOf(Integer.parseInt(status)));
}
Series<Header> headers = (Series<Header>)request.getAttributes().get("org.restlet.http.headers");
XdmSequenceIterator headerElements = http.axisIterator(Axis.CHILD,HEADER_NAME);
while (headerElements.hasNext()) {
XdmNode headerElement = (XdmNode)headerElements.next();
String name = headerElement.getAttributeValue(NAME_NAME);
if (name!=null && name.length()>0) {
String value = headerElement.getStringValue();
getLogger().fine(isFineLog ? name+": "+value : "");
if ("location".equalsIgnoreCase(name)) {
response.setLocationRef(value);
} else if ("Cache-Control".equalsIgnoreCase(name)) {
List<CacheDirective> directives = response.getCacheDirectives();
if (directives==null) {
directives = new ArrayList<CacheDirective>();
response.setCacheDirectives(directives);
}
String [] parts = value.trim().split("=");
if (parts.length>1) {
directives.add(new CacheDirective(parts[0],parts[1]));
} else {
directives.add(new CacheDirective(parts[0]));
}
} else {
headers.add(name, value);
}
}
}
XdmSequenceIterator attrElements = http.axisIterator(Axis.CHILD,ATTRIBUTE_NAME);
while (attrElements.hasNext()) {
XdmNode attrElement = (XdmNode)attrElements.next();
String name = attrElement.getAttributeValue(NAME_NAME);
String value = attrElement.getAttributeValue(VALUE_NAME);
if (name!=null && value!=null) {
response.getAttributes().put(name,value);
}
}
XdmSequenceIterator entityElements = http.axisIterator(Axis.CHILD,ENTITY_NAME);
boolean doRelease = true;
while (entityElements.hasNext()) {
XdmNode entityElement = (XdmNode)entityElements.next();
String mediaTypeName = entityElement.getAttributeValue(TYPE_NAME);
String lastModifiedValue = entityElement.getAttributeValue(LAST_MODIFIED_NAME);
Date lastModified = null;
if (lastModifiedValue!=null && lastModifiedValue.length()>22) {
//getLogger().info("Parsing date: "+lastModifiedValue);
try {
String dtValue = lastModifiedValue.substring(0,22)+lastModifiedValue.substring(23);
lastModified = xsdDateFormat.parse(dtValue);
} catch (ParseException ex) {
int lastColon = lastModifiedValue.lastIndexOf(':');
String dtValue = lastModifiedValue.substring(0,lastColon)+lastModifiedValue.substring(lastColon+1);
try {
lastModified = xsdDateFormatWithMilliseconds.parse(dtValue);
} catch (ParseException pex) {
Date date = new Date();
getLogger().warning("Cannot parse date '"+lastModifiedValue+"' (sample "+xsdDateFormatWithMilliseconds.format(date)+" or "+xsdDateFormat.format(date)+"): "+pex.getMessage());
}
}
}
MediaType mediaType = mediaTypeName==null || mediaTypeName.length()==0 ? MediaType.TEXT_PLAIN : MediaType.valueOf(mediaTypeName);
boolean entitySet = false;
if (MediaType.APPLICATION_ALL_XML.includes(mediaType) || MediaType.TEXT_XML.equals(mediaType)) {
XdmSequenceIterator children = entityElement.axisIterator(Axis.CHILD);
HashSet<String> exlcudedNamespaces = new HashSet<String>();
exlcudedNamespaces.add(HTTP_NS);
while (children.hasNext()) {
XdmItem item = children.next();
if (!item.isAtomicValue()) {
XdmNode node = (XdmNode)item;
if (node.getNodeKind()==XdmNodeKind.ELEMENT) {
entitySet = true;
final XdmNode documentElement = S9apiUtils.removeNamespaces(cache.getRuntime(), node, exlcudedNamespaces,true);
final Serialization serial = xproc.getPipeline().getSerialization(outputPort);
response.setEntity(new OutputRepresentation(mediaType) {
public void write(OutputStream out)
throws IOException
{
Serialization serial = xproc.getPipeline().getSerialization(outputPort);
WritableDocument outputDoc = new WritableDocument(cache.getRuntime(),null,serial,out);
outputDoc.write(documentElement);
out.flush();
}
public void release() {
cache.release(xproc);
}
});
doRelease = false;
break;
}
}
}
}
if (!entitySet) {
response.setEntity(new StringRepresentation(entityElement.getStringValue(),mediaType));
}
if (lastModified!=null) {
response.getEntity().setModificationDate(lastModified);
}
}
if (doRelease) {
cache.release(xproc);
}
} else {
getLogger().fine("No HTTP binding from pipeline, serializing result...");
// XML to serialize
final XdmNode startDoc = doc;
final String charset = pipeInfo.outputType.getParameters().getFirstValue("charset");
response.setStatus(Status.SUCCESS_OK);
response.setEntity(new OutputRepresentation(pipeInfo.outputType) {
public void write(OutputStream out)
throws IOException
{
Serialization serial = xproc.getPipeline().getSerialization(outputPort);
if (serial==null && charset!=null) {
serial = new Serialization(cache.getRuntime(),null);
}
if (charset!=null) {
serial.setEncoding(charset);
}
WritableDocument outputDoc = new WritableDocument(cache.getRuntime(),null,serial,out);
outputDoc.write(startDoc);
while (rpipe.moreDocuments()) {
try {
XdmNode nextDoc = rpipe.read();
if (nextDoc!=null) {
outputDoc.write(nextDoc);
}
} catch (SaxonApiException ex) {
throw new IOException("Exception while writing output port "+outputPort,ex);
}
}
out.flush();
}
public void release() {
cache.release(xproc);
}
});
}
}
} else {
getLogger().info("pipeInfo.outputType="+pipeInfo.outputType);
final String charset = pipeInfo.outputType.getParameters().getFirstValue("charset");
response.setEntity(new OutputRepresentation(pipeInfo.outputType) {
public void write(OutputStream out)
throws IOException
{
Serialization serial = xproc.getPipeline().getSerialization(outputPort);
if (serial==null && charset!=null) {
serial = new Serialization(cache.getRuntime(),null);
}
if (charset!=null) {
serial.setEncoding(charset);
}
WritableDocument doc = new WritableDocument(cache.getRuntime(),null,serial,out);
ReadablePipe rpipe = xproc.getPipeline().readFrom(outputPort);
while (rpipe.moreDocuments()) {
try {
doc.write(rpipe.read());
} catch (SaxonApiException ex) {
throw new IOException("Exception while writing output port "+outputPort,ex);
}
}
out.flush();
}
public void release() {
cache.release(xproc);
}
});
response.setStatus(Status.SUCCESS_OK);
}
} else {
cache.release(xproc);
response.setStatus(Status.SUCCESS_NO_CONTENT);
}
} catch (SaxonApiException ex) {
cache.release(xproc);
getLogger().info("Error running pipeline: "+ex.getMessage());
response.setStatus(Status.SERVER_ERROR_INTERNAL);
return;
}
}
}
| added check for more than one output port
| mod-xproc/src/org/xproclet/xproc/XProcHelper.java | added check for more than one output port |
|
Java | mit | 0a7946336d84934d7185ad3979eb070a1f5e797b | 0 | bhm/Cthulhator | package com.bustiblelemons.views.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import com.bustiblelemons.bustiblelibs.R;
/**
* Created by hiv on 29.10.14.
*/
public class RippleImageButton extends ImageButton {
private static GestureDetector gestureDetector;
private int WIDTH;
private int HEIGHT;
private int FRAME_RATE = 10;
private int DURATION = 200;
private int PAINT_ALPHA = 90;
private Handler canvasHandler;
private float radiusMax = 0;
private boolean animationRunning = false;
private int timer = 0;
private int timerEmpty = 0;
private int durationEmpty = -1;
private float x = -1;
private float y = -1;
private int zoomDuration;
private float zoomScale;
private ScaleAnimation scaleAnimation;
private boolean hasToZoom = false;
private boolean isCentered = true;
private int rippleType = 0;
private Paint paint;
private Bitmap originBitmap;
private int rippleColor;
private int ripplePadding;
private Runnable runnable = new Runnable() {
@Override
public void run() {
invalidate();
}
};
private boolean passClickToParent = false;
private boolean clickIssued = false;
private boolean resetCircle = false;
public RippleImageButton(Context context) {
super(context);
init(context, null);
}
public RippleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RippleImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public RippleImageButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
private void init(final Context context, final AttributeSet attrs) {
if (isInEditMode())
return;
if (attrs != null) {
final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RippleView);
rippleColor = typedArray.getColor(R.styleable.RippleView_rv_color, android.R.color.holo_green_light);
rippleType = typedArray.getInt(R.styleable.RippleView_rv_type, rippleType);
hasToZoom = typedArray.getBoolean(R.styleable.RippleView_rv_zoom, hasToZoom);
isCentered = typedArray.getBoolean(R.styleable.RippleView_rv_centered, isCentered);
DURATION = typedArray.getInteger(R.styleable.RippleView_rv_rippleDuration, DURATION);
FRAME_RATE = typedArray.getInteger(R.styleable.RippleView_rv_framerate, FRAME_RATE);
PAINT_ALPHA = typedArray.getInteger(R.styleable.RippleView_rv_alpha, PAINT_ALPHA);
ripplePadding = typedArray.getDimensionPixelSize(R.styleable.RippleView_rv_ripplePadding, 0);
canvasHandler = new Handler();
zoomScale = typedArray.getFloat(R.styleable.RippleView_rv_zoomScale, 1.03f);
zoomDuration = typedArray.getInt(R.styleable.RippleView_rv_zoomDuration, 200);
passClickToParent = typedArray.getBoolean(R.styleable.RippleView_rv_passClickToParent,
passClickToParent);
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(rippleColor);
paint.setAlpha(PAINT_ALPHA);
}
this.setWillNotDraw(false);
initializeGestureDetectors(context);
this.setDrawingCacheEnabled(true);
}
private void initializeGestureDetectors(Context context) {
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (animationRunning) {
if (resetCircle) {
restoreView(canvas);
return;
}
if (DURATION <= timer * FRAME_RATE) {
clickIssued = false;
restoreView(canvas);
return;
} else {
canvasHandler.postDelayed(runnable, FRAME_RATE);
}
if (timer == 0) {
canvas.save();
}
canvas.drawCircle(x, y, (radiusMax * (((float) timer * FRAME_RATE) / DURATION)), paint);
paint.setColor(getResources().getColor(android.R.color.holo_red_light));
if (rippleType == 1 && originBitmap != null && (((float) timer * FRAME_RATE) / DURATION) > 0.4f) {
if (durationEmpty == -1)
durationEmpty = DURATION - timer * FRAME_RATE;
timerEmpty++;
final Bitmap tmpBitmap = getCircleBitmap((int) ((radiusMax) * (((float) timerEmpty * FRAME_RATE) / (durationEmpty))));
canvas.drawBitmap(tmpBitmap, 0, 0, paint);
tmpBitmap.recycle();
}
paint.setColor(rippleColor);
if (rippleType == 1) {
if ((((float) timer * FRAME_RATE) / DURATION) > 0.6f)
paint.setAlpha((int) (PAINT_ALPHA - ((PAINT_ALPHA) * (((float) timerEmpty * FRAME_RATE) / (durationEmpty)))));
else
paint.setAlpha(PAINT_ALPHA);
} else
paint.setAlpha((int) (PAINT_ALPHA - ((PAINT_ALPHA) * (((float) timer * FRAME_RATE) / DURATION))));
timer++;
}
}
private void restoreView(Canvas canvas) {
resetCircle = false;
animationRunning = false;
timer = 0;
durationEmpty = -1;
timerEmpty = 0;
canvas.restore();
invalidate();
}
private boolean hasParent() {
return getParent() != null && (getParent() instanceof View);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
WIDTH = w;
HEIGHT = h;
calculateMaxRadius();
scaleAnimation = new ScaleAnimation(1.0f, zoomScale, 1.0f, zoomScale, w / 2, h / 2);
scaleAnimation.setDuration(zoomDuration);
scaleAnimation.setRepeatMode(Animation.REVERSE);
scaleAnimation.setRepeatCount(1);
}
private void calculateMaxRadius() {
radiusMax = Math.max(WIDTH, HEIGHT);
if (rippleType == 1)
radiusMax /= 2;
radiusMax -= ripplePadding;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!clickIssued) {
clickIssued = true;
this.performClick();
}
if (gestureDetector.onTouchEvent(event) && !animationRunning) {
triggerDrawing(event);
}
return true;
}
private void triggerDrawing(MotionEvent event) {
if (hasToZoom) {
this.startAnimation(scaleAnimation);
}
radiusMax = Math.max(WIDTH, HEIGHT);
if (rippleType != 2) {
radiusMax /= 2;
}
radiusMax -= ripplePadding;
if (isCentered || rippleType == 1) {
this.x = getMeasuredWidth() / 2;
this.y = getMeasuredHeight() / 2;
} else {
this.x = event.getX();
this.y = event.getY();
}
animationRunning = true;
if (rippleType == 1 && originBitmap == null) {
originBitmap = getDrawingCache(true);
}
invalidate();
}
private Bitmap getCircleBitmap(final int radius) {
final Bitmap output = Bitmap.createBitmap(originBitmap.getWidth(), originBitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect((int) (x - radius), (int) (y - radius), (int) (x + radius), (int) (y + radius));
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(x, y, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(originBitmap, rect, rect, paint);
return output;
}
} | bustibleLibs/src/main/java/com/bustiblelemons/views/widget/RippleImageButton.java | package com.bustiblelemons.views.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import com.bustiblelemons.bustiblelibs.R;
/**
* Created by hiv on 29.10.14.
*/
public class RippleImageButton extends ImageButton {
private static GestureDetector gestureDetector;
private static GestureDetector tapUpGestureDetector;
private int WIDTH;
private int HEIGHT;
private int FRAME_RATE = 10;
private int DURATION = 200;
private int PAINT_ALPHA = 90;
private Handler canvasHandler;
private float radiusMax = 0;
private boolean animationRunning = false;
private int timer = 0;
private int timerEmpty = 0;
private int durationEmpty = -1;
private float x = -1;
private float y = -1;
private int zoomDuration;
private float zoomScale;
private ScaleAnimation scaleAnimation;
private boolean hasToZoom = false;
private boolean isCentered = true;
private int rippleType = 0;
private Paint paint;
private Bitmap originBitmap;
private int rippleColor;
private int ripplePadding;
private Runnable runnable = new Runnable() {
@Override
public void run() {
invalidate();
}
};
private boolean passClickToParent = false;
private boolean clickIssued = false;
private boolean resetCircle = false;
public RippleImageButton(Context context) {
super(context);
init(context, null);
}
public RippleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RippleImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public RippleImageButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
private void init(final Context context, final AttributeSet attrs) {
if (isInEditMode())
return;
if (attrs != null) {
final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RippleView);
rippleColor = typedArray.getColor(R.styleable.RippleView_rv_color, android.R.color.holo_green_light);
rippleType = typedArray.getInt(R.styleable.RippleView_rv_type, rippleType);
hasToZoom = typedArray.getBoolean(R.styleable.RippleView_rv_zoom, hasToZoom);
isCentered = typedArray.getBoolean(R.styleable.RippleView_rv_centered, isCentered);
DURATION = typedArray.getInteger(R.styleable.RippleView_rv_rippleDuration, DURATION);
FRAME_RATE = typedArray.getInteger(R.styleable.RippleView_rv_framerate, FRAME_RATE);
PAINT_ALPHA = typedArray.getInteger(R.styleable.RippleView_rv_alpha, PAINT_ALPHA);
ripplePadding = typedArray.getDimensionPixelSize(R.styleable.RippleView_rv_ripplePadding, 0);
canvasHandler = new Handler();
zoomScale = typedArray.getFloat(R.styleable.RippleView_rv_zoomScale, 1.03f);
zoomDuration = typedArray.getInt(R.styleable.RippleView_rv_zoomDuration, 200);
passClickToParent = typedArray.getBoolean(R.styleable.RippleView_rv_passClickToParent,
passClickToParent);
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(rippleColor);
paint.setAlpha(PAINT_ALPHA);
}
this.setWillNotDraw(false);
initializeGestureDetectors(context);
this.setDrawingCacheEnabled(true);
}
private void initializeGestureDetectors(Context context) {
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
});
tapUpGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (animationRunning) {
if (resetCircle) {
restoreView(canvas);
return;
}
if (DURATION <= timer * FRAME_RATE) {
restoreView(canvas);
return;
} else {
canvasHandler.postDelayed(runnable, FRAME_RATE);
}
if (timer == 0) {
canvas.save();
}
canvas.drawCircle(x, y, (radiusMax * (((float) timer * FRAME_RATE) / DURATION)), paint);
paint.setColor(getResources().getColor(android.R.color.holo_red_light));
if (rippleType == 1 && originBitmap != null && (((float) timer * FRAME_RATE) / DURATION) > 0.4f) {
if (durationEmpty == -1)
durationEmpty = DURATION - timer * FRAME_RATE;
timerEmpty++;
final Bitmap tmpBitmap = getCircleBitmap((int) ((radiusMax) * (((float) timerEmpty * FRAME_RATE) / (durationEmpty))));
canvas.drawBitmap(tmpBitmap, 0, 0, paint);
tmpBitmap.recycle();
}
paint.setColor(rippleColor);
if (rippleType == 1) {
if ((((float) timer * FRAME_RATE) / DURATION) > 0.6f)
paint.setAlpha((int) (PAINT_ALPHA - ((PAINT_ALPHA) * (((float) timerEmpty * FRAME_RATE) / (durationEmpty)))));
else
paint.setAlpha(PAINT_ALPHA);
} else
paint.setAlpha((int) (PAINT_ALPHA - ((PAINT_ALPHA) * (((float) timer * FRAME_RATE) / DURATION))));
timer++;
}
}
private void restoreView(Canvas canvas) {
resetCircle = false;
animationRunning = false;
timer = 0;
durationEmpty = -1;
timerEmpty = 0;
canvas.restore();
invalidate();
}
private boolean hasParent() {
return getParent() != null && (getParent() instanceof View);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
WIDTH = w;
HEIGHT = h;
calculateMaxRadius();
scaleAnimation = new ScaleAnimation(1.0f, zoomScale, 1.0f, zoomScale, w / 2, h / 2);
scaleAnimation.setDuration(zoomDuration);
scaleAnimation.setRepeatMode(Animation.REVERSE);
scaleAnimation.setRepeatCount(1);
}
private void calculateMaxRadius() {
radiusMax = Math.max(WIDTH, HEIGHT);
if (rippleType == 1)
radiusMax /= 2;
radiusMax -= ripplePadding;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
triggerDrawing(event);
return true;
case MotionEvent.ACTION_UP:
clickIssued = true;
return this.performClick();
}
return true;
}
private void triggerDrawing(MotionEvent event) {
if (hasToZoom) {
this.startAnimation(scaleAnimation);
}
radiusMax = Math.max(WIDTH, HEIGHT);
if (rippleType != 2) {
radiusMax /= 2;
}
radiusMax -= ripplePadding;
if (isCentered || rippleType == 1) {
this.x = getMeasuredWidth() / 2;
this.y = getMeasuredHeight() / 2;
} else {
this.x = event.getX();
this.y = event.getY();
}
animationRunning = true;
if (rippleType == 1 && originBitmap == null) {
originBitmap = getDrawingCache(true);
}
invalidate();
}
private Bitmap getCircleBitmap(final int radius) {
final Bitmap output = Bitmap.createBitmap(originBitmap.getWidth(), originBitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect((int) (x - radius), (int) (y - radius), (int) (x + radius), (int) (y + radius));
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(x, y, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(originBitmap, rect, rect, paint);
return output;
}
} | rippleimagebutton fire on ACTION_UP
| bustibleLibs/src/main/java/com/bustiblelemons/views/widget/RippleImageButton.java | rippleimagebutton fire on ACTION_UP |
|
Java | mit | aa1b4384a82ed693c1e1cc7bf93263f838322a79 | 0 | mezz/JustEnoughItems,Adaptivity/JustEnoughItems,Adaptivity/JustEnoughItems,mezz/JustEnoughItems | package mezz.jei.plugins.vanilla.ingredients.item;
import com.google.common.base.Joiner;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import mezz.jei.api.ingredients.ISubtypeRegistry;
import mezz.jei.util.ErrorUtil;
import mezz.jei.util.StackHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class ItemStackListFactory {
private static final Logger LOGGER = LogManager.getLogger();
private final ISubtypeRegistry subtypeRegistry;
public ItemStackListFactory(ISubtypeRegistry subtypeRegistry) {
this.subtypeRegistry = subtypeRegistry;
}
public List<ItemStack> create(StackHelper stackHelper) {
final List<ItemStack> itemList = new ArrayList<>();
final Set<String> itemNameSet = new HashSet<>();
for (ItemGroup itemGroup : ItemGroup.GROUPS) {
if (itemGroup == ItemGroup.HOTBAR || itemGroup == ItemGroup.INVENTORY) {
continue;
}
NonNullList<ItemStack> creativeTabItemStacks = NonNullList.create();
try {
itemGroup.fill(creativeTabItemStacks);
} catch (RuntimeException | LinkageError e) {
LOGGER.error("Item Group crashed while getting items." +
"Some items from this group will be missing from the ingredient list. {}", itemGroup, e);
}
for (ItemStack itemStack : creativeTabItemStacks) {
if (itemStack.isEmpty()) {
LOGGER.error("Found an empty itemStack from creative tab: {}", itemGroup);
} else {
addItemStack(stackHelper, itemStack, itemList, itemNameSet);
}
}
}
return itemList;
}
private void addItemStack(StackHelper stackHelper, ItemStack stack, List<ItemStack> itemList, Set<String> itemNameSet) {
final String itemKey;
try {
addFallbackSubtypeInterpreter(stack);
itemKey = stackHelper.getUniqueIdentifierForStack(stack);
} catch (RuntimeException | LinkageError e) {
String stackInfo = ErrorUtil.getItemStackInfo(stack);
LOGGER.error("Couldn't get unique name for itemStack {}", stackInfo, e);
return;
}
if (!itemNameSet.contains(itemKey)) {
itemNameSet.add(itemKey);
itemList.add(stack);
}
}
private void addFallbackSubtypeInterpreter(ItemStack itemStack) {
if (!this.subtypeRegistry.hasSubtypeInterpreter(itemStack)) {
try {
String info = FluidSubtypeInterpreter.INSTANCE.apply(itemStack);
if (!ISubtypeRegistry.ISubtypeInterpreter.NONE.equals(info)) {
this.subtypeRegistry.registerSubtypeInterpreter(itemStack.getItem(), FluidSubtypeInterpreter.INSTANCE);
}
} catch (RuntimeException | LinkageError e) {
String itemStackInfo = ErrorUtil.getItemStackInfo(itemStack);
LOGGER.error("Failed to apply FluidSubtypeInterpreter to ItemStack: {}", itemStackInfo, e);
}
}
}
private static class FluidSubtypeInterpreter implements ISubtypeRegistry.ISubtypeInterpreter {
public static final FluidSubtypeInterpreter INSTANCE = new FluidSubtypeInterpreter();
private FluidSubtypeInterpreter() {
}
@Override
public String apply(ItemStack itemStack) {
return itemStack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).map(capability -> {
IFluidTankProperties[] tankPropertiesList = capability.getTankProperties();
List<String> contentsNames = new ArrayList<>();
for (IFluidTankProperties tankProperties : tankPropertiesList) {
String contentsName = getContentsName(tankProperties);
if (contentsName != null) {
contentsNames.add(contentsName);
} else {
contentsNames.add("empty");
}
}
if (!contentsNames.isEmpty()) {
return Joiner.on(';').join(contentsNames);
}
return ISubtypeRegistry.ISubtypeInterpreter.NONE;
}).orElse(ISubtypeRegistry.ISubtypeInterpreter.NONE);
}
@Nullable
private static String getContentsName(IFluidTankProperties fluidTankProperties) {
FluidStack contents = fluidTankProperties.getContents();
if (contents != null) {
Fluid fluid = contents.getFluid();
if (fluid != null) {
return fluid.getName();
}
}
return null;
}
}
}
| src/main/java/mezz/jei/plugins/vanilla/ingredients/item/ItemStackListFactory.java | package mezz.jei.plugins.vanilla.ingredients.item;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import mezz.jei.api.ingredients.ISubtypeRegistry;
import mezz.jei.util.ErrorUtil;
import mezz.jei.util.StackHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class ItemStackListFactory {
private static final Logger LOGGER = LogManager.getLogger();
private final ISubtypeRegistry subtypeRegistry;
public ItemStackListFactory(ISubtypeRegistry subtypeRegistry) {
this.subtypeRegistry = subtypeRegistry;
}
public List<ItemStack> create(StackHelper stackHelper) {
final List<ItemStack> itemList = new ArrayList<>();
final Set<String> itemNameSet = new HashSet<>();
for (ItemGroup itemGroup : ItemGroup.GROUPS) {
if (itemGroup == ItemGroup.HOTBAR || itemGroup == ItemGroup.INVENTORY) {
continue;
}
NonNullList<ItemStack> creativeTabItemStacks = NonNullList.create();
try {
itemGroup.fill(creativeTabItemStacks);
} catch (RuntimeException | LinkageError e) {
LOGGER.error("Item Group crashed while getting items." +
"Some items from this group will be missing from the ingredient list. {}", itemGroup, e);
}
for (ItemStack itemStack : creativeTabItemStacks) {
if (itemStack.isEmpty()) {
LOGGER.error("Found an empty itemStack from creative tab: {}", itemGroup);
} else {
addItemStack(stackHelper, itemStack, itemList, itemNameSet);
}
}
}
return itemList;
}
private void addItemStack(StackHelper stackHelper, ItemStack stack, List<ItemStack> itemList, Set<String> itemNameSet) {
final String itemKey;
try {
addFallbackSubtypeInterpreter(stack);
itemKey = stackHelper.getUniqueIdentifierForStack(stack);
} catch (RuntimeException | LinkageError e) {
String stackInfo = ErrorUtil.getItemStackInfo(stack);
LOGGER.error("Couldn't get unique name for itemStack {}", stackInfo, e);
return;
}
if (!itemNameSet.contains(itemKey)) {
itemNameSet.add(itemKey);
itemList.add(stack);
}
}
private void addFallbackSubtypeInterpreter(ItemStack itemStack) {
if (!this.subtypeRegistry.hasSubtypeInterpreter(itemStack)) {
try {
String info = FluidSubtypeInterpreter.INSTANCE.apply(itemStack);
if (!ISubtypeRegistry.ISubtypeInterpreter.NONE.equals(info)) {
this.subtypeRegistry.registerSubtypeInterpreter(itemStack.getItem(), FluidSubtypeInterpreter.INSTANCE);
}
} catch (RuntimeException | LinkageError e) {
String itemStackInfo = ErrorUtil.getItemStackInfo(itemStack);
LOGGER.error("Failed to apply FluidSubtypeInterpreter to ItemStack: {}", itemStackInfo, e);
}
}
}
private static class FluidSubtypeInterpreter implements ISubtypeRegistry.ISubtypeInterpreter {
public static final FluidSubtypeInterpreter INSTANCE = new FluidSubtypeInterpreter();
private FluidSubtypeInterpreter() {
}
@Override
public String apply(ItemStack itemStack) {
return itemStack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).map(capability -> {
IFluidTankProperties[] tankPropertiesList = capability.getTankProperties();
StringBuilder info = new StringBuilder();
for (IFluidTankProperties tankProperties : tankPropertiesList) {
String contentsName = getContentsName(tankProperties);
if (contentsName != null) {
info.append(contentsName).append(";");
} else {
info.append("empty").append(";");
}
}
if (info.length() > 0) {
return info.toString();
}
return ISubtypeRegistry.ISubtypeInterpreter.NONE;
}).orElse(ISubtypeRegistry.ISubtypeInterpreter.NONE);
}
@Nullable
private static String getContentsName(IFluidTankProperties fluidTankProperties) {
FluidStack contents = fluidTankProperties.getContents();
if (contents != null) {
Fluid fluid = contents.getFluid();
if (fluid != null) {
return fluid.getName();
}
}
return null;
}
}
}
| clean up fluid container uids
| src/main/java/mezz/jei/plugins/vanilla/ingredients/item/ItemStackListFactory.java | clean up fluid container uids |
|
Java | mit | 55403404ca0fa415c0b2da02b047a77ff6009179 | 0 | ITC205/teamPurple | package datamanagement;
import org.jdom.*;
import java.util.List;
import java.util.HashMap;
public class StudentManager
{
private static StudentManager self = null;
private StudentMap sm;
private HashMap<String, StudentMap> um;
public static StudentManager get()
{
if (self == null)
self = new StudentManager();
return self;
}
private StudentManager()
{
sm = new StudentMap();
um = new HashMap<>();}
public IStudent getStudent(Integer studentId)
{
IStudent is = sm.get(studentId);
return is != null ? is : createStudent(studentId);
}
private Element getStudentElement(Integer studentId)
{
for (Element el : (List<Element>) XMLManager.getXML().getDocument().getRootElement().getChild("studentTable").getChildren("student"))
if (studentId.toString().equals(el.getAttributeValue("sid")))
return el;
return null;
}
private IStudent createStudent(Integer studentId)
{
IStudent is;
Element el = getStudentElement(studentId);
if (el != null) {
StudentUnitRecordList rlist = StudentUnitRecordManager.instance().getRecordsByStudent(studentId);
is = new Student(new Integer(el.getAttributeValue("sid")),el.getAttributeValue("fname"),el.getAttributeValue("lname"),rlist);
sm.put(is.getID(), is);
return is;
}
throw new RuntimeException("DBMD: createStudent : student not in file");
}
private IStudent createStudentProxy(Integer studentId)
{
Element el = getStudentElement(studentId);
if (el != null)
return new StudentProxy(studentId, el.getAttributeValue("fname"), el.getAttributeValue("lname"));
throw new RuntimeException("DBMD: createStudent : student not in file");
}
public StudentMap getStudentsByUnit(String uc)
{
StudentMap s = um.get(uc);
if (s != null) {
return s;
}
s = new StudentMap();
IStudent is;
StudentUnitRecordList ur = StudentUnitRecordManager.instance().getRecordsByUnit(uc);
for (IStudentUnitRecord S : ur) {
is = createStudentProxy(new Integer(S.getStudentID()));
s.put(is.getID(), is);
}
um.put( uc, s);
return s;
}
}
| src/datamanagement/StudentManager.java | package datamanagement;
import org.jdom.*;
import java.util.List;
public class StudentManager
{
private static StudentManager self = null;
private StudentMap sm;
private java.util.HashMap<String, StudentMap> um;
public static StudentManager get()
{
if (self == null)
self = new StudentManager();
return self;
}
private StudentManager()
{
sm = new StudentMap();
um = new java.util.HashMap<>();}
public IStudent getStudent(Integer studentId)
{
IStudent is = sm.get(studentId);
return is != null ? is : createStudent(studentId);
}
private Element getStudentElement(Integer studentId)
{
for (Element el : (List<Element>) XMLManager.getXML().getDocument().getRootElement().getChild("studentTable").getChildren("student"))
if (studentId.toString().equals(el.getAttributeValue("sid")))
return el;
return null;
}
private IStudent createStudent(Integer studentId)
{
IStudent is;
Element el = getStudentElement(studentId);
if (el != null) {
StudentUnitRecordList rlist = StudentUnitRecordManager.instance().getRecordsByStudent(studentId);
is = new Student(new Integer(el.getAttributeValue("sid")),el.getAttributeValue("fname"),el.getAttributeValue("lname"),rlist);
sm.put(is.getID(), is);
return is;
}
throw new RuntimeException("DBMD: createStudent : student not in file");
}
private IStudent createStudentProxy(Integer studentId)
{
Element el = getStudentElement(studentId);
if (el != null)
return new StudentProxy(studentId, el.getAttributeValue("fname"), el.getAttributeValue("lname"));
throw new RuntimeException("DBMD: createStudent : student not in file");
}
public StudentMap getStudentsByUnit(String uc)
{
StudentMap s = um.get(uc);
if (s != null) {
return s;
}
s = new StudentMap();
IStudent is;
StudentUnitRecordList ur = StudentUnitRecordManager.instance().getRecordsByUnit(uc);
for (IStudentUnitRecord S : ur) {
is = createStudentProxy(new Integer(S.getStudentID()));
s.put(is.getID(), is);
}
um.put( uc, s);
return s;
}
}
| StudentManager.java: imported java.util.HashMap
| src/datamanagement/StudentManager.java | StudentManager.java: imported java.util.HashMap |
|
Java | mit | bcaa101b1c78f82c7f38961b37c49459e55b9a8a | 0 | hazendaz/displaytag,hazendaz/displaytag,hazendaz/displaytag,hazendaz/displaytag | package org.displaytag.tags;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.displaytag.decorator.DecoratorFactory;
import org.displaytag.exception.DecoratorInstantiationException;
import org.displaytag.exception.MissingAttributeException;
import org.displaytag.exception.ObjectLookupException;
import org.displaytag.exception.TagStructureException;
import org.displaytag.model.Cell;
import org.displaytag.model.HeaderCell;
import org.displaytag.properties.MediaTypeEnum;
import org.displaytag.util.Href;
import org.displaytag.util.HtmlAttributeMap;
import org.displaytag.util.MultipleHtmlAttribute;
import org.displaytag.util.TagConstants;
/**
* <p>
* This tag works hand in hand with the TableTag to display a list of objects. This describes a column of data in the
* TableTag. There can be any number of columns that make up the list.
* </p>
* <p>
* This tag does no work itself, it is simply a container of information. The TableTag does all the work based on the
* information provided in the attributes of this tag.
* <p>
* @author mraible
* @version $Revision$ ($Author$)
*/
public class ColumnTag extends BodyTagSupport
{
/**
* logger.
*/
private static Log log = LogFactory.getLog(ColumnTag.class);
/**
* html pass-through attributes for cells.
*/
private HtmlAttributeMap attributeMap = new HtmlAttributeMap();
/**
* html pass-through attributes for cell headers.
*/
private HtmlAttributeMap headerAttributeMap = new HtmlAttributeMap();
/**
* the property method that is called to retrieve the information to be displayed in this column. This method is
* called on the current object in the iteration for the given row. The property format is in typical struts format
* for properties (required)
*/
private String property;
/**
* the title displayed for this column. if this is omitted then the property name is used for the title of the
* column (optional).
*/
private String title;
/**
* by default, null values don't appear in the list, by setting viewNulls to 'true', then null values will appear
* as "null" in the list (mostly useful for debugging) (optional).
*/
private boolean nulls;
/**
* is the column sortable?
*/
private boolean sortable;
/**
* if set to true, then any email addresses and URLs found in the content of the column are automatically converted
* into a hypertext link.
*/
private boolean autolink;
/**
* the grouping level (starting at 1 and incrementing) of this column (indicates if successive contain the same
* values, then they should not be displayed). The level indicates that if a lower level no longer matches, then
* the matching for this higher level should start over as well. If this attribute is not included, then no
* grouping is performed. (optional)
*/
private int group = -1;
/**
* if this attribute is provided, then the data that is shown for this column is wrapped inside a <a href>
* tag with the url provided through this attribute. Typically you would use this attribute along with one of the
* struts-like param attributes below to create a dynamic link so that each row creates a different URL based on
* the data that is being viewed. (optional)
*/
private Href href;
/**
* The name of the request parameter that will be dynamically added to the generated href URL. The corresponding
* value is defined by the paramProperty and (optional) paramName attributes, optionally scoped by the paramScope
* attribute. (optional)
*/
private String paramId;
/**
* The name of a JSP bean that is a String containing the value for the request parameter named by paramId (if
* paramProperty is not specified), or a JSP bean whose property getter is called to return a String (if
* paramProperty is specified). The JSP bean is constrained to the bean scope specified by the paramScope property,
* if it is specified. If paramName is omitted, then it is assumed that the current object being iterated on is the
* target bean. (optional)
*/
private String paramName;
/**
* The name of a property of the bean specified by the paramName attribute (or the current object being iterated on
* if paramName is not provided), whose return value must be a String containing the value of the request parameter
* (named by the paramId attribute) that will be dynamically added to this href URL. (optional)
* @deprecated use Expressions in paramName
*/
private String paramProperty;
/**
* The scope within which to search for the bean specified by the paramName attribute. If not specified, all scopes
* are searched. If paramName is not provided, then the current object being iterated on is assumed to be the
* target bean. (optional)
* @deprecated use Expressions in paramName
*/
private String paramScope;
/**
* If this attribute is provided, then the column's displayed is limited to this number of characters. An elipse
* (...) is appended to the end if this column is linked, and the user can mouseover the elipse to get the full
* text. (optional)
*/
private int maxLength;
/**
* If this attribute is provided, then the column's displayed is limited to this number of words. An elipse (...)
* is appended to the end if this column is linked, and the user can mouseover the elipse to get the full text.
* (optional)
*/
private int maxWords;
/**
* a class that should be used to "decorate" the underlying object being displayed. If a decorator is specified for
* the entire table, then this decorator will decorate that decorator. (optional)
*/
private String decorator;
/**
* is the column already sorted?
*/
private boolean alreadySorted;
/**
* The media supported attribute.
*/
private List supportedMedia = Arrays.asList(MediaTypeEnum.ALL);
/**
* setter for the "property" tag attribute.
* @param value attribute value
*/
public void setProperty(String value)
{
this.property = value;
}
/**
* setter for the "title" tag attribute.
* @param value attribute value
*/
public void setTitle(String value)
{
this.title = value;
}
/**
* setter for the "nulls" tag attribute.
* @param value attribute value
*/
public void setNulls(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.nulls = true;
}
}
/**
* setter for the "sortable" tag attribute.
* @param value attribute value
*/
public void setSortable(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.sortable = true;
}
}
/**
* @deprecated use setSortable()
* @param value String
*/
public void setSort(String value)
{
setSortable(value);
}
/**
* setter for the "autolink" tag attribute.
* @param value attribute value
*/
public void setAutolink(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.autolink = true;
}
}
/**
* setter for the "group" tag attribute.
* @param value attribute value
*/
public void setGroup(String value)
{
try
{
this.group = Integer.parseInt(value);
}
catch (NumberFormatException e)
{
// ignore?
log.warn("Invalid \"group\" attribute: value=\"" + value + "\"");
}
}
/**
* setter for the "href" tag attribute.
* @param value attribute value
*/
public void setHref(String value)
{
this.href = new Href(value);
}
/**
* setter for the "paramId" tag attribute.
* @param value attribute value
*/
public void setParamId(String value)
{
this.paramId = value;
}
/**
* setter for the "paramName" tag attribute.
* @param value attribute value
*/
public void setParamName(String value)
{
this.paramName = value;
}
/**
* setter for the "paramProperty" tag attribute.
* @param value attribute value
*/
public void setParamProperty(String value)
{
this.paramProperty = value;
}
/**
* setter for the "paramScope" tag attribute.
* @param value attribute value
*/
public void setParamScope(String value)
{
this.paramScope = value;
}
/**
* setter for the "maxLength" tag attribute.
* @param value attribute value
*/
public void setMaxLength(int value)
{
this.maxLength = value;
}
/**
* setter for the "maxWords" tag attribute.
* @param value attribute value
*/
public void setMaxWords(int value)
{
this.maxWords = value;
}
/**
* setter for the "width" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setWidth(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_WIDTH, value);
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_WIDTH, value);
}
/**
* setter for the "align" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setAlign(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_ALIGN, value);
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_ALIGN, value);
}
/**
* setter for the "background" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setBackground(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_BACKGROUND, value);
}
/**
* setter for the "bgcolor" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setBgcolor(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_BGCOLOR, value);
}
/**
* setter for the "height" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setHeight(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_HEIGHT, value);
}
/**
* setter for the "nowrap" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setNowrap(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_NOWRAP, value);
}
/**
* setter for the "valign" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setValign(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_VALIGN, value);
}
/**
* setter for the "class" tag attribute.
* @param value attribute value
* @deprecated use the "class" attribute
*/
public void setStyleClass(String value)
{
setClass(value);
}
/**
* setter for the "style" tag attribute.
* @param value attribute value
*/
public void setStyle(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_STYLE, value);
}
/**
* setter for the "class" tag attribute.
* @param value attribute value
*/
public void setClass(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
/**
* Adds a css class to the class attribute (html class suports multiple values).
* @param value attribute value
*/
public void addClass(String value)
{
Object classAttributes = this.attributeMap.get(TagConstants.ATTRIBUTE_CLASS);
if (classAttributes == null)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
else
{
((MultipleHtmlAttribute) classAttributes).addAttributeValue(value);
}
}
/**
* setter for the "headerClass" tag attribute.
* @param value attribute value
*/
public void setHeaderClass(String value)
{
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
/**
* setter for the "headerStyleClass" tag attribute.
* @param value attribute value
* @deprecated use setHeaderClass()
*/
public void setHeaderStyleClass(String value)
{
setHeaderClass(value);
}
/**
* setter for the "decorator" tag attribute.
* @param value attribute value
*/
public void setDecorator(String value)
{
this.decorator = value;
}
/**
* Is this column configured for the media type?
* @param mediaType the currentMedia type
* @return true if the column should be displayed for this request
*/
public boolean availableForMedia(MediaTypeEnum mediaType)
{
return this.supportedMedia.contains(mediaType);
}
/**
* Tag setter.
* @param media the space delimited list of supported types
*/
public void setMedia(String media)
{
if (StringUtils.isBlank(media) || media.toLowerCase().indexOf("all") > -1)
{
this.supportedMedia = Arrays.asList(MediaTypeEnum.ALL);
return;
}
this.supportedMedia = new ArrayList();
String[] values = StringUtils.split(media);
for (int i = 0; i < values.length; i++)
{
String value = values[i];
if (!StringUtils.isBlank(value))
{
MediaTypeEnum type = MediaTypeEnum.fromName(value.toLowerCase());
if (type == null)
{ // Should be in a tag validator..
String msg = "Unknown media type \"" + value
+ "\"; media must be one or more values, space separated." + " Possible values are:";
for (int j = 0; j < MediaTypeEnum.ALL.length; j++)
{
MediaTypeEnum mediaTypeEnum = MediaTypeEnum.ALL[j];
msg += " '" + mediaTypeEnum.getName() + "'";
}
throw new IllegalArgumentException(msg + ".");
}
this.supportedMedia.add(type);
}
}
}
/**
* Passes attribute information up to the parent TableTag.
* <p>
* When we hit the end of the tag, we simply let our parent (which better be a TableTag) know what the user wants
* to do with this column. We do that by simple registering this tag with the parent. This tag's only job is to
* hold the configuration information to describe this particular column. The TableTag does all the work.
* </p>
* @return int
* @throws JspException if this tag is being used outside of a <display:list...> tag.
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException
{
MediaTypeEnum currentMediaType = (MediaTypeEnum) this.pageContext.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (currentMediaType != null && !availableForMedia(currentMediaType))
{
if (log.isDebugEnabled())
{
log.debug("skipping column body, currentMediaType=" + currentMediaType);
}
return SKIP_BODY;
}
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
// add column header only once
if (tableTag.isFirstIteration())
{
addHeaderToTable(tableTag);
}
Cell cell;
if (this.property == null)
{
Object cellValue;
if (this.bodyContent != null)
{
String value = this.bodyContent.getString();
if (value == null && this.nulls)
{
value = "";
}
cellValue = value;
}
// BodyContent will be null if the body was not eval'd, eg an empty list.
else if (tableTag.isEmpty())
{
cellValue = Cell.EMPTY_CELL;
}
else
{
throw new MissingAttributeException(getClass(), new String[]{
"property attribute",
"value attribute",
"tag body"});
}
cell = new Cell(cellValue);
}
else
{
cell = Cell.EMPTY_CELL;
}
tableTag.addCell(cell);
cleanUp();
return super.doEndTag();
}
/**
* Adds the current header to the table model calling addColumn in the parent table tag. This method should be
* called only at first iteration.
* @param tableTag parent table tag
* @throws DecoratorInstantiationException for error during column decorator instantiation
* @throws ObjectLookupException for errors in looking up values
*/
private void addHeaderToTable(TableTag tableTag) throws DecoratorInstantiationException, ObjectLookupException
{
HeaderCell headerCell = new HeaderCell();
headerCell.setHeaderAttributes((HtmlAttributeMap) this.headerAttributeMap.clone());
headerCell.setHtmlAttributes((HtmlAttributeMap) this.attributeMap.clone());
headerCell.setTitle(this.title);
headerCell.setSortable(this.sortable);
headerCell.setColumnDecorator(DecoratorFactory.loadColumnDecorator(this.decorator));
headerCell.setBeanPropertyName(this.property);
headerCell.setShowNulls(this.nulls);
headerCell.setMaxLength(this.maxLength);
headerCell.setMaxWords(this.maxWords);
headerCell.setAutoLink(this.autolink);
headerCell.setGroup(this.group);
// href and parameter, create link
if (this.href != null && this.paramId != null)
{
Href colHref = new Href(this.href);
// parameter value is in a different object than the iterated one
if (this.paramName != null || this.paramScope != null)
{
// create a complete string for compatibility with previous version before expression evaluation.
// this approach is optimized for new expressions, not for previous property/scope parameters
StringBuffer expression = new StringBuffer();
// append scope
if (StringUtils.isNotBlank(this.paramScope))
{
expression.append(this.paramScope).append("Scope.");
}
// base bean name
if (this.paramId != null)
{
expression.append(this.paramName);
}
else
{
expression.append(tableTag.getName());
}
// append property
if (StringUtils.isNotBlank(this.paramProperty))
{
expression.append('.').append(this.paramProperty);
}
// evaluate expression.
// note the value is fixed, not based on any object created during iteration
// this is here for compatibility with the old version mainly
Object paramValue = tableTag.evaluateExpression(expression.toString());
// add parameter
colHref.addParameter(this.paramId, paramValue);
}
else
{
//@todo lookup value as a property on the list object. This should not be done here to avoid useless
// work when only a part of the list is displayed
// set id
headerCell.setParamName(this.paramId);
// set property
headerCell.setParamProperty(this.paramProperty);
}
// sets the base href
headerCell.setHref(colHref);
}
tableTag.addColumn(headerCell);
if (log.isDebugEnabled())
{
log.debug("columnTag.addHeaderToTable() :: first iteration - adding header " + headerCell);
}
}
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
public void release()
{
super.release();
}
/**
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
public int doStartTag() throws JspException
{
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
if (tableTag == null)
{
throw new TagStructureException(getClass(), "column", "table");
}
// If the list is empty, do not execute the body; may result in NPE
if (tableTag.isEmpty())
{
return SKIP_BODY;
}
else
{
MediaTypeEnum currentMediaType = (MediaTypeEnum) this.pageContext
.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (!availableForMedia(currentMediaType))
{
return SKIP_BODY;
}
return super.doStartTag();
}
}
/**
* called to clean up instance variables at the end of tag evaluation.
*/
private void cleanUp()
{
this.attributeMap.clear();
this.attributeMap.clear();
this.headerAttributeMap.clear();
this.alreadySorted = false;
// this is required to fix bad tag pooling in tomcat, need to be tested in resin
this.sortable = false;
this.group = -1;
this.title = null;
// fix for tag pooling in tomcat
setBodyContent(null);
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE)
.append("bodyContent", this.bodyContent)
.append("group", this.group)
.append("maxLength", this.maxLength)
.append("decorator", this.decorator)
.append("href", this.href)
.append("title", this.title)
.append("paramScope", this.paramScope)
.append("property", this.property)
.append("paramProperty", this.paramProperty)
.append("headerAttributeMap", this.headerAttributeMap)
.append("paramName", this.paramName)
.append("autolink", this.autolink)
.append("nulls", this.nulls)
.append("maxWords", this.maxWords)
.append("attributeMap", this.attributeMap)
.append("sortable", this.sortable)
.append("paramId", this.paramId)
.append("alreadySorted", this.alreadySorted)
.toString();
}
}
| displaytag/src/main/java/org/displaytag/tags/ColumnTag.java | package org.displaytag.tags;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.displaytag.decorator.DecoratorFactory;
import org.displaytag.exception.DecoratorInstantiationException;
import org.displaytag.exception.MissingAttributeException;
import org.displaytag.exception.ObjectLookupException;
import org.displaytag.exception.TagStructureException;
import org.displaytag.model.Cell;
import org.displaytag.model.HeaderCell;
import org.displaytag.properties.MediaTypeEnum;
import org.displaytag.util.Href;
import org.displaytag.util.HtmlAttributeMap;
import org.displaytag.util.MultipleHtmlAttribute;
import org.displaytag.util.TagConstants;
/**
* <p>
* This tag works hand in hand with the TableTag to display a list of objects. This describes a column of data in the
* TableTag. There can be any number of columns that make up the list.
* </p>
* <p>
* This tag does no work itself, it is simply a container of information. The TableTag does all the work based on the
* information provided in the attributes of this tag.
* <p>
* @author mraible
* @version $Revision$ ($Author$)
*/
public class ColumnTag extends BodyTagSupport
{
/**
* logger.
*/
private static Log log = LogFactory.getLog(ColumnTag.class);
/**
* html pass-through attributes for cells.
*/
private HtmlAttributeMap attributeMap = new HtmlAttributeMap();
/**
* html pass-through attributes for cell headers.
*/
private HtmlAttributeMap headerAttributeMap = new HtmlAttributeMap();
/**
* the property method that is called to retrieve the information to be displayed in this column. This method is
* called on the current object in the iteration for the given row. The property format is in typical struts format
* for properties (required)
*/
private String property;
/**
* the title displayed for this column. if this is omitted then the property name is used for the title of the
* column (optional).
*/
private String title;
/**
* by default, null values don't appear in the list, by setting viewNulls to 'true', then null values will appear
* as "null" in the list (mostly useful for debugging) (optional).
*/
private boolean nulls;
/**
* is the column sortable?
*/
private boolean sortable;
/**
* if set to true, then any email addresses and URLs found in the content of the column are automatically converted
* into a hypertext link.
*/
private boolean autolink;
/**
* the grouping level (starting at 1 and incrementing) of this column (indicates if successive contain the same
* values, then they should not be displayed). The level indicates that if a lower level no longer matches, then
* the matching for this higher level should start over as well. If this attribute is not included, then no
* grouping is performed. (optional)
*/
private int group = -1;
/**
* if this attribute is provided, then the data that is shown for this column is wrapped inside a <a href>
* tag with the url provided through this attribute. Typically you would use this attribute along with one of the
* struts-like param attributes below to create a dynamic link so that each row creates a different URL based on
* the data that is being viewed. (optional)
*/
private Href href;
/**
* The name of the request parameter that will be dynamically added to the generated href URL. The corresponding
* value is defined by the paramProperty and (optional) paramName attributes, optionally scoped by the paramScope
* attribute. (optional)
*/
private String paramId;
/**
* The name of a JSP bean that is a String containing the value for the request parameter named by paramId (if
* paramProperty is not specified), or a JSP bean whose property getter is called to return a String (if
* paramProperty is specified). The JSP bean is constrained to the bean scope specified by the paramScope property,
* if it is specified. If paramName is omitted, then it is assumed that the current object being iterated on is the
* target bean. (optional)
*/
private String paramName;
/**
* The name of a property of the bean specified by the paramName attribute (or the current object being iterated on
* if paramName is not provided), whose return value must be a String containing the value of the request parameter
* (named by the paramId attribute) that will be dynamically added to this href URL. (optional)
* @deprecated use Expressions in paramName
*/
private String paramProperty;
/**
* The scope within which to search for the bean specified by the paramName attribute. If not specified, all scopes
* are searched. If paramName is not provided, then the current object being iterated on is assumed to be the
* target bean. (optional)
* @deprecated use Expressions in paramName
*/
private String paramScope;
/**
* If this attribute is provided, then the column's displayed is limited to this number of characters. An elipse
* (...) is appended to the end if this column is linked, and the user can mouseover the elipse to get the full
* text. (optional)
*/
private int maxLength;
/**
* If this attribute is provided, then the column's displayed is limited to this number of words. An elipse (...)
* is appended to the end if this column is linked, and the user can mouseover the elipse to get the full text.
* (optional)
*/
private int maxWords;
/**
* a class that should be used to "decorate" the underlying object being displayed. If a decorator is specified for
* the entire table, then this decorator will decorate that decorator. (optional)
*/
private String decorator;
/**
* is the column already sorted?
*/
private boolean alreadySorted;
/**
* The media supported attribute.
*/
private List supportedMedia = Arrays.asList(MediaTypeEnum.ALL);
/**
* setter for the "property" tag attribute.
* @param value attribute value
*/
public void setProperty(String value)
{
this.property = value;
}
/**
* setter for the "title" tag attribute.
* @param value attribute value
*/
public void setTitle(String value)
{
this.title = value;
}
/**
* setter for the "nulls" tag attribute.
* @param value attribute value
*/
public void setNulls(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.nulls = true;
}
}
/**
* setter for the "sortable" tag attribute.
* @param value attribute value
*/
public void setSortable(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.sortable = true;
}
}
/**
* @deprecated use setSortable()
* @param value String
*/
public void setSort(String value)
{
setSortable(value);
}
/**
* setter for the "autolink" tag attribute.
* @param value attribute value
*/
public void setAutolink(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.autolink = true;
}
}
/**
* setter for the "group" tag attribute.
* @param value attribute value
*/
public void setGroup(String value)
{
try
{
this.group = Integer.parseInt(value);
}
catch (NumberFormatException e)
{
// ignore?
log.warn("Invalid \"group\" attribute: value=\"" + value + "\"");
}
}
/**
* setter for the "href" tag attribute.
* @param value attribute value
*/
public void setHref(String value)
{
this.href = new Href(value);
}
/**
* setter for the "paramId" tag attribute.
* @param value attribute value
*/
public void setParamId(String value)
{
this.paramId = value;
}
/**
* setter for the "paramName" tag attribute.
* @param value attribute value
*/
public void setParamName(String value)
{
this.paramName = value;
}
/**
* setter for the "paramProperty" tag attribute.
* @param value attribute value
*/
public void setParamProperty(String value)
{
this.paramProperty = value;
}
/**
* setter for the "paramScope" tag attribute.
* @param value attribute value
*/
public void setParamScope(String value)
{
this.paramScope = value;
}
/**
* setter for the "maxLength" tag attribute.
* @param value attribute value
*/
public void setMaxLength(int value)
{
this.maxLength = value;
}
/**
* setter for the "maxWords" tag attribute.
* @param value attribute value
*/
public void setMaxWords(int value)
{
this.maxWords = value;
}
/**
* setter for the "width" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setWidth(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_WIDTH, value);
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_WIDTH, value);
}
/**
* setter for the "align" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setAlign(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_ALIGN, value);
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_ALIGN, value);
}
/**
* setter for the "background" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setBackground(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_BACKGROUND, value);
}
/**
* setter for the "bgcolor" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setBgcolor(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_BGCOLOR, value);
}
/**
* setter for the "height" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setHeight(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_HEIGHT, value);
}
/**
* setter for the "nowrap" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setNowrap(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_NOWRAP, value);
}
/**
* setter for the "valign" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setValign(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_VALIGN, value);
}
/**
* setter for the "class" tag attribute.
* @param value attribute value
* @deprecated use the "class" attribute
*/
public void setStyleClass(String value)
{
setClass(value);
}
/**
* setter for the "style" tag attribute.
* @param value attribute value
*/
public void setStyle(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_STYLE, value);
}
/**
* setter for the "class" tag attribute.
* @param value attribute value
*/
public void setClass(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
/**
* Adds a css class to the class attribute (html class suports multiple values).
* @param value attribute value
*/
public void addClass(String value)
{
Object classAttributes = this.attributeMap.get(TagConstants.ATTRIBUTE_CLASS);
if (classAttributes == null)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
else
{
((MultipleHtmlAttribute) classAttributes).addAttributeValue(value);
}
}
/**
* setter for the "headerClass" tag attribute.
* @param value attribute value
*/
public void setHeaderClass(String value)
{
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
/**
* setter for the "headerStyleClass" tag attribute.
* @param value attribute value
* @deprecated use setHeaderClass()
*/
public void setHeaderStyleClass(String value)
{
setHeaderClass(value);
}
/**
* setter for the "decorator" tag attribute.
* @param value attribute value
*/
public void setDecorator(String value)
{
this.decorator = value;
}
/**
* Is this column configured for the media type?
* @param mediaType the currentMedia type
* @return true if the column should be displayed for this request
*/
public boolean availableForMedia(MediaTypeEnum mediaType)
{
return this.supportedMedia.contains(mediaType);
}
/**
* Tag setter.
* @param media the space delimited list of supported types
*/
public void setMedia(String media)
{
if (StringUtils.isBlank(media) || media.toLowerCase().indexOf("all") > -1)
{
this.supportedMedia = Arrays.asList(MediaTypeEnum.ALL);
return;
}
this.supportedMedia = new ArrayList();
String[] values = StringUtils.split(media);
for (int i = 0; i < values.length; i++)
{
String value = values[i];
if (!StringUtils.isBlank(value))
{
MediaTypeEnum type = MediaTypeEnum.fromName(value.toLowerCase());
if (type == null)
{ // Should be in a tag validator..
String msg = "Unknown media type \"" + value
+ "\"; media must be one or more values, space separated." + " Possible values are:";
for (int j = 0; j < MediaTypeEnum.ALL.length; j++)
{
MediaTypeEnum mediaTypeEnum = MediaTypeEnum.ALL[j];
msg += " '" + mediaTypeEnum.getName() + "'";
}
throw new IllegalArgumentException(msg + ".");
}
this.supportedMedia.add(type);
}
}
}
/**
* Passes attribute information up to the parent TableTag.
* <p>
* When we hit the end of the tag, we simply let our parent (which better be a TableTag) know what the user wants
* to do with this column. We do that by simple registering this tag with the parent. This tag's only job is to
* hold the configuration information to describe this particular column. The TableTag does all the work.
* </p>
* @return int
* @throws JspException if this tag is being used outside of a <display:list...> tag.
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException
{
MediaTypeEnum currentMediaType = (MediaTypeEnum) this.pageContext.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (currentMediaType != null && !availableForMedia(currentMediaType))
{
if (log.isDebugEnabled())
{
log.debug("skipping column body, currentMediaType=" + currentMediaType);
}
return SKIP_BODY;
}
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
// add column header only once
if (tableTag.isFirstIteration())
{
addHeaderToTable(tableTag);
}
Cell cell;
if (this.property == null)
{
Object cellValue;
if (this.bodyContent != null)
{
String value = this.bodyContent.getString();
if (value == null && this.nulls)
{
value = "";
}
cellValue = value;
}
// BodyContent will be null if the body was not eval'd, eg an empty list.
else if (tableTag.isEmpty())
{
cellValue = Cell.EMPTY_CELL;
}
else
{
throw new MissingAttributeException(getClass(), new String[]{
"property attribute",
"value attribute",
"tag body"});
}
cell = new Cell(cellValue);
}
else
{
cell = Cell.EMPTY_CELL;
}
tableTag.addCell(cell);
cleanUp();
return super.doEndTag();
}
/**
* Adds the current header to the table model calling addColumn in the parent table tag. This method should be
* called only at first iteration.
* @param tableTag parent table tag
* @throws DecoratorInstantiationException for error during column decorator instantiation
* @throws ObjectLookupException for errors in looking up values
*/
private void addHeaderToTable(TableTag tableTag) throws DecoratorInstantiationException, ObjectLookupException
{
HeaderCell headerCell = new HeaderCell();
headerCell.setHeaderAttributes((HtmlAttributeMap) this.headerAttributeMap.clone());
headerCell.setHtmlAttributes((HtmlAttributeMap) this.attributeMap.clone());
headerCell.setTitle(this.title);
headerCell.setSortable(this.sortable);
headerCell.setColumnDecorator(DecoratorFactory.loadColumnDecorator(this.decorator));
headerCell.setBeanPropertyName(this.property);
headerCell.setShowNulls(this.nulls);
headerCell.setMaxLength(this.maxLength);
headerCell.setMaxWords(this.maxWords);
headerCell.setAutoLink(this.autolink);
headerCell.setGroup(this.group);
// href and parameter, create link
if (this.href != null && this.paramId != null)
{
Href colHref = new Href(this.href);
// parameter value is in a different object than the iterated one
if (this.paramName != null || this.paramScope != null)
{
// create a complete string for compatibility with previous version before expression evaluation.
// this approach is optimized for new expressions, not for previous property/scope parameters
StringBuffer expression = new StringBuffer();
// append scope
if (StringUtils.isNotBlank(this.paramScope))
{
expression.append(this.paramScope).append("Scope.");
}
// base bean name
if (this.paramId != null)
{
expression.append(this.paramName);
}
else
{
expression.append(tableTag.getName());
}
// append property
if (StringUtils.isNotBlank(this.paramProperty))
{
expression.append('.').append(this.paramProperty);
}
// evaluate expression.
// note the value is fixed, not based on any object created during iteration
// this is here for compatibility with the old version mainly
Object paramValue = tableTag.evaluateExpression(expression.toString());
// add parameter
colHref.addParameter(this.paramId, paramValue);
}
else
{
//@todo lookup value as a property on the list object. This should not be done here to avoid useless
// work when only a part of the list is displayed
// set id
headerCell.setParamName(this.paramId);
// set property
headerCell.setParamProperty(this.paramProperty);
}
// sets the base href
headerCell.setHref(colHref);
}
tableTag.addColumn(headerCell);
if (log.isDebugEnabled())
{
log.debug("columnTag.addHeaderToTable() :: first iteration - adding header " + headerCell);
}
}
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
public void release()
{
super.release();
}
/**
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
public int doStartTag() throws JspException
{
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
if (tableTag == null)
{
throw new TagStructureException(getClass(), "column", "table");
}
// If the list is empty, do not execute the body; may result in NPE
if (tableTag.isEmpty())
{
return SKIP_BODY;
}
else
{
MediaTypeEnum currentMediaType = (MediaTypeEnum) this.pageContext
.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (!availableForMedia(currentMediaType))
{
return SKIP_BODY;
}
return super.doStartTag();
}
}
/**
* called to clean up instance variables at the end of tag evaluation.
*/
private void cleanUp()
{
this.attributeMap.clear();
this.attributeMap.clear();
this.headerAttributeMap.clear();
this.alreadySorted = false;
// fix for tag pooling in tomcat
setBodyContent(null);
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE).append("bodyContent", this.bodyContent).append(
"group", this.group).append("maxLength", this.maxLength).append("decorator", this.decorator).append("href",
this.href).append("title", this.title).append("paramScope", this.paramScope).append("property",
this.property).append("paramProperty", this.paramProperty).append("headerAttributeMap",
this.headerAttributeMap).append("paramName", this.paramName).append("autolink", this.autolink).append(
"nulls", this.nulls).append("maxWords", this.maxWords).append("attributeMap", this.attributeMap).append(
"sortable", this.sortable).append("paramId", this.paramId).append("alreadySorted", this.alreadySorted)
.toString();
}
}
| readding back some ot the parameter clean-up needed for the tag to work properly in tomcat. Need to be tested
| displaytag/src/main/java/org/displaytag/tags/ColumnTag.java | readding back some ot the parameter clean-up needed for the tag to work properly in tomcat. Need to be tested |
|
Java | mit | 3ed63b68e6d45bb0d202a25c1b85e9679c7756d7 | 0 | reapzor/FiloFirmata | package com.bortbort.arduino.FiloFirmata;
import com.bortbort.arduino.FiloFirmata.Messages.Message;
import net.jodah.typetools.TypeResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* SynchronousMessageListener
* Turns an async design for listening and sending messages into a synchronous design allowing
* a message to be sent with the return value being the response message.
*/
abstract class SynchronousMessageListener<T extends Message> extends MessageListener<T> {
private static final Logger log = LoggerFactory.getLogger(SynchronousMessageListener.class);
private static final int RESPONSE_WAIT_TIME = 5000;
private T responseMessage;
private Boolean responseReceived = null;
private final Object lock = new Object();
@Override
public void messageReceived(T message) {
if (responseReceived != null && responseReceived) {
log.warn("Received more than one synchronous message reply!");
}
if (responseReceived == null) {
responseMessage = message;
responseReceived = true;
}
synchronized (lock) {
lock.notify();
}
}
public Boolean getResponseReceived() {
return responseReceived;
}
public Boolean waitForResponse() {
if (responseReceived != null) {
return responseReceived;
}
synchronized (lock) {
try {
lock.wait(RESPONSE_WAIT_TIME);
} catch (InterruptedException e) {
log.warn("Interrupted waiting for synchronous response.");
}
}
if (responseReceived == null) {
log.warn("Timed out waiting for synchronous response.");
responseReceived = false;
}
return responseReceived;
}
public T getResponseMessage() {
waitForResponse();
return responseMessage;
}
}
| src/main/java/com/bortbort/arduino/FiloFirmata/SynchronousMessageListener.java | package com.bortbort.arduino.FiloFirmata;
import com.bortbort.arduino.FiloFirmata.Messages.Message;
import net.jodah.typetools.TypeResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* SynchronousMessageListener
* Turns an async design for listening and sending messages into a synchronous design allowing
* a message to be sent with the return value being the response message.
*/
abstract class SynchronousMessageListener<T extends Message> extends MessageListener<T> {
private static final Logger log = LoggerFactory.getLogger(SynchronousMessageListener.class);
private static final int RESPONSE_WAIT_TIME = 5000;
private T responseMessage;
private Boolean responseReceived = null;
private final Object lock = new Object();
@Override
public void messageReceived(T message) {
if (responseReceived != null && responseReceived) {
log.warn("Received more than one synchronous message reply!");
}
if (responseReceived == null) {
responseMessage = message;
responseReceived = true;
}
synchronized (lock) {
lock.notify();
}
}
public Boolean getResponseReceived() {
return responseReceived;
}
public Boolean waitForResponse() {
synchronized (lock) {
if (responseReceived != null) {
return responseReceived;
}
try {
lock.wait(RESPONSE_WAIT_TIME);
} catch (InterruptedException e) {
log.warn("Interrupted waiting for synchronous response.");
}
}
if (responseReceived == null) {
log.warn("Timed out waiting for synchronous response.");
responseReceived = false;
}
return responseReceived;
}
public T getResponseMessage() {
waitForResponse();
return responseMessage;
}
}
| Take simple check out of critical lock zone
| src/main/java/com/bortbort/arduino/FiloFirmata/SynchronousMessageListener.java | Take simple check out of critical lock zone |
|
Java | epl-1.0 | 6a930a85b6525498e66e43b5e69a27e1c8d87718 | 0 | viatra/VIATRA-Generator,viatra/VIATRA-Generator,viatra/VIATRA-Generator,viatra/VIATRA-Generator | /*******************************************************************************
* Copyright (c) 2010-2017, Andras Szabolcs Nagy and Daniel Varro
* 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:
* Andras Szabolcs Nagy - initial API and implementation
*******************************************************************************/
package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import org.apache.log4j.Logger;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
import org.eclipse.viatra.dse.base.ThreadContext;
import org.eclipse.viatra.dse.objectives.Fitness;
import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper;
import org.eclipse.viatra.dse.solutionstore.SolutionStore;
import org.eclipse.xtend.lib.annotations.AccessorType;
import org.eclipse.xtend.lib.annotations.Accessors;
import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner;
import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration;
import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem;
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult;
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult;
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser;
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DebugConfiguration;
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor;
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration;
import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace;
/**
* This exploration strategy eventually explorers the whole design space but
* goes in the most promising directions first, based on the {@link Fitness}.
*
* There are a few parameter to tune such as
* <ul>
* <li>maximum depth</li>
* <li>continue the exploration from a state that satisfies the hard objectives
* (the default that it will backtrack),</li>
* <li>whether to continue the exploration from the newly explored state if it
* is at least equally good than the previous one or only if it is better
* (default is "at least equally good").</li>
* </ul>
*
*/
public class BestFirstStrategyForModelGeneration implements IStrategy {
// Services and Configuration
private ThreadContext context;
private ReasonerWorkspace workspace;
private ViatraReasonerConfiguration configuration;
private PartialInterpretation2Logic partialInterpretation2Logic = new PartialInterpretation2Logic();
private Comparator<TrajectoryWithFitness> comparator;
private Logger logger = Logger.getLogger(IStrategy.class);
// Running
private PriorityQueue<TrajectoryWithFitness> trajectoiresToExplore;
private SolutionStore solutionStore;
private SolutionStoreWithCopy solutionStoreWithCopy;
private SolutionStoreWithDiversityDescriptor solutionStoreWithDiversityDescriptor;
private volatile boolean isInterrupted = false;
private ModelResult modelResultByInternalSolver = null;
private Random random = new Random();
// Statistics
private int numberOfStatecoderFail = 0;
private int numberOfPrintedModel = 0;
private int numberOfSolverCalls = 0;
public BestFirstStrategyForModelGeneration(
ReasonerWorkspace workspace,
ViatraReasonerConfiguration configuration)
{
this.workspace = workspace;
this.configuration = configuration;
}
public SolutionStoreWithCopy getSolutionStoreWithCopy() {
return solutionStoreWithCopy;
}
public SolutionStoreWithDiversityDescriptor getSolutionStoreWithDiversityDescriptor() {
return solutionStoreWithDiversityDescriptor;
}
public int getNumberOfStatecoderFail() {
return numberOfStatecoderFail;
}
@Override
public void initStrategy(ThreadContext context) {
this.context = context;
this.solutionStore = context.getGlobalContext().getSolutionStore();
this.solutionStoreWithCopy = new SolutionStoreWithCopy();
this.solutionStoreWithDiversityDescriptor = new SolutionStoreWithDiversityDescriptor(configuration.diversityRequirement);
final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper();
this.comparator = new Comparator<TrajectoryWithFitness>() {
@Override
public int compare(TrajectoryWithFitness o1, TrajectoryWithFitness o2) {
return objectiveComparatorHelper.compare(o2.fitness, o1.fitness);
}
};
trajectoiresToExplore = new PriorityQueue<TrajectoryWithFitness>(11, comparator);
}
@Override
public void explore() {
if (!context.checkGlobalConstraints()) {
logger.info("Global contraint is not satisifed in the first state. Terminate.");
return;
}
if (configuration.searchSpaceConstraints.maxDepth == 0) {
logger.info("Maximal depth is reached in the initial solution. Terminate.");
return;
}
final Fitness firstFittness = context.calculateFitness();
checkForSolution(firstFittness);
final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper();
final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]);
TrajectoryWithFitness currentTrajectoryWithFittness = new TrajectoryWithFitness(firstTrajectory, firstFittness);
trajectoiresToExplore.add(currentTrajectoryWithFittness);
mainLoop: while (!isInterrupted) {
if (currentTrajectoryWithFittness == null) {
if (trajectoiresToExplore.isEmpty()) {
logger.debug("State space is fully traversed.");
return;
} else {
currentTrajectoryWithFittness = selectState();
if (logger.isDebugEnabled()) {
logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray()));
logger.debug("New trajectory is chosen: " + currentTrajectoryWithFittness);
}
context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithFittness.trajectory);
}
}
// visualiseCurrentState();
// boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness);
// if(consistencyCheckResult == true) {
// continue mainLoop;
// }
List<Object> activationIds = selectActivation();
Iterator<Object> iterator = activationIds.iterator();
while (!isInterrupted && iterator.hasNext()) {
final Object nextActivation = iterator.next();
// if (!iterator.hasNext()) {
// logger.debug("Last untraversed activation of the state.");
// trajectoiresToExplore.remove(currentTrajectoryWithFittness);
// }
logger.debug("Executing new activation: " + nextActivation);
context.executeAcitvationId(nextActivation);
visualiseCurrentState();
boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness);
if(consistencyCheckResult == true) { continue mainLoop; }
if (context.isCurrentStateAlreadyTraversed()) {
logger.info("The new state is already visited.");
context.backtrack();
} else if (!context.checkGlobalConstraints()) {
logger.debug("Global contraint is not satisifed.");
context.backtrack();
} else {
final Fitness nextFitness = context.calculateFitness();
checkForSolution(nextFitness);
if (context.getDepth() > configuration.searchSpaceConstraints.maxDepth) {
logger.debug("Reached max depth.");
context.backtrack();
continue;
}
TrajectoryWithFitness nextTrajectoryWithFittness = new TrajectoryWithFitness(
context.getTrajectory().toArray(), nextFitness);
trajectoiresToExplore.add(nextTrajectoryWithFittness);
int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFittness.fitness,
nextTrajectoryWithFittness.fitness);
if (compare < 0) {
logger.debug("Better fitness, moving on: " + nextFitness);
currentTrajectoryWithFittness = nextTrajectoryWithFittness;
continue mainLoop;
} else if (compare == 0) {
logger.debug("Equally good fitness, moving on: " + nextFitness);
currentTrajectoryWithFittness = nextTrajectoryWithFittness;
continue mainLoop;
} else {
logger.debug("Worse fitness.");
currentTrajectoryWithFittness = null;
continue mainLoop;
}
}
}
logger.debug("State is fully traversed.");
trajectoiresToExplore.remove(currentTrajectoryWithFittness);
currentTrajectoryWithFittness = null;
}
logger.info("Interrupted.");
}
private List<Object> selectActivation() {
List<Object> activationIds;
try {
activationIds = new ArrayList<Object>(context.getUntraversedActivationIds());
Collections.shuffle(activationIds);
} catch (NullPointerException e) {
numberOfStatecoderFail++;
activationIds = Collections.emptyList();
}
return activationIds;
}
private void checkForSolution(final Fitness fittness) {
if (fittness.isSatisifiesHardObjectives()) {
if (solutionStoreWithDiversityDescriptor.isDifferent(context)) {
solutionStoreWithCopy.newSolution(context);
solutionStoreWithDiversityDescriptor.newSolution(context);
solutionStore.newSolution(context);
logger.debug("Found a solution.");
}
}
}
@Override
public void interruptStrategy() {
isInterrupted = true;
}
private TrajectoryWithFitness selectState() {
int randomNumber = random.nextInt(configuration.randomBacktrackChance);
if (randomNumber == 0) {
int elements = trajectoiresToExplore.size();
int randomElementIndex = random.nextInt(elements);
logger.debug("Randomly backtract to the " + randomElementIndex + " best solution...");
Iterator<TrajectoryWithFitness> iterator = trajectoiresToExplore.iterator();
while (randomElementIndex != 0) {
iterator.next();
randomElementIndex--;
}
TrajectoryWithFitness res = iterator.next();
if (res == null) {
return trajectoiresToExplore.element();
} else {
return res;
}
} else {
return trajectoiresToExplore.element();
}
}
public void visualiseCurrentState() {
PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugCongiguration.partialInterpretatioVisualiser;
if(partialInterpretatioVisualiser != null) {
PartialInterpretation p = (PartialInterpretation) (context.getModel());
int id = ++numberOfPrintedModel;
if (id % configuration.debugCongiguration.partalInterpretationVisualisationFrequency == 0) {
PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p);
visualisation.writeToFile(workspace, String.format("state%09d", id));
}
}
}
protected boolean checkConsistency(TrajectoryWithFitness t) {
LogicReasoner internalIncosnsitencyDetector = configuration.internalConsistencyCheckerConfiguration.internalIncosnsitencyDetector;
if (internalIncosnsitencyDetector!= null) {
int id = ++numberOfSolverCalls;
if (id % configuration.internalConsistencyCheckerConfiguration.incternalConsistencyCheckingFrequency == 0) {
try {
PartialInterpretation interpretation = (PartialInterpretation) (context.getModel());
PartialInterpretation copied = EcoreUtil.copy(interpretation);
this.partialInterpretation2Logic.transformPartialIntepretation2Logic(copied.getProblem(), copied);
LogicProblem newProblem = copied.getProblem();
this.configuration.typeScopes.maxNewElements = interpretation.getMaxNewElements();
this.configuration.typeScopes.minNewElements = interpretation.getMinNewElements();
LogicResult result = internalIncosnsitencyDetector.solve(newProblem, configuration, workspace);
if (result instanceof InconsistencyResult) {
logger.debug("Solver found an Inconsistency!");
removeSubtreeFromQueue(t);
return true;
} else if (result instanceof ModelResult) {
logger.debug("Solver found a model!");
solutionStore.newSolution(context);
this.modelResultByInternalSolver = (ModelResult) result;
return true;
} else {
logger.debug("Failed consistency check.");
return false;
}
} catch (Exception e) {
logger.debug("Problem with internal consistency checking: "+e.getMessage());
e.printStackTrace();
return false;
}
}
}
return false;
}
protected void removeSubtreeFromQueue(TrajectoryWithFitness t) {
PriorityQueue<TrajectoryWithFitness> previous = this.trajectoiresToExplore;
this.trajectoiresToExplore = new PriorityQueue<>(this.comparator);
for (TrajectoryWithFitness trajectoryWithFitness : previous) {
if (!containsAsSubstring(trajectoryWithFitness.trajectory, t.trajectory)) {
this.trajectoiresToExplore.add(trajectoryWithFitness);
} else {
logger.debug("State has been excluded due to inherent inconsistency");
}
}
}
private boolean containsAsSubstring(Object[] full, Object[] substring) {
if (substring.length > full.length) {
return false;
} else if (substring.length == full.length) {
return Arrays.equals(full, substring);
} else {
Object[] part = Arrays.copyOfRange(full, 0, substring.length);
return Arrays.equals(part, substring);
}
}
}
| Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java | /*******************************************************************************
* Copyright (c) 2010-2017, Andras Szabolcs Nagy and Daniel Varro
* 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:
* Andras Szabolcs Nagy - initial API and implementation
*******************************************************************************/
package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import org.apache.log4j.Logger;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
import org.eclipse.viatra.dse.base.ThreadContext;
import org.eclipse.viatra.dse.objectives.Fitness;
import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper;
import org.eclipse.viatra.dse.solutionstore.SolutionStore;
import org.eclipse.xtend.lib.annotations.AccessorType;
import org.eclipse.xtend.lib.annotations.Accessors;
import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner;
import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration;
import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem;
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult;
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult;
import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation;
import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser;
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DebugConfiguration;
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor;
import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration;
import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace;
/**
* This exploration strategy eventually explorers the whole design space but
* goes in the most promising directions first, based on the {@link Fitness}.
*
* There are a few parameter to tune such as
* <ul>
* <li>maximum depth</li>
* <li>continue the exploration from a state that satisfies the hard objectives
* (the default that it will backtrack),</li>
* <li>whether to continue the exploration from the newly explored state if it
* is at least equally good than the previous one or only if it is better
* (default is "at least equally good").</li>
* </ul>
*
*/
public class BestFirstStrategyForModelGeneration implements IStrategy {
// Services and Configuration
private ThreadContext context;
private ReasonerWorkspace workspace;
private ViatraReasonerConfiguration configuration;
private PartialInterpretation2Logic partialInterpretation2Logic = new PartialInterpretation2Logic();
private Comparator<TrajectoryWithFitness> comparator;
private Logger logger = Logger.getLogger(IStrategy.class);
// Running
private PriorityQueue<TrajectoryWithFitness> trajectoiresToExplore;
private SolutionStore solutionStore;
private SolutionStoreWithCopy solutionStoreWithCopy;
private SolutionStoreWithDiversityDescriptor solutionStoreWithDiversityDescriptor;
private boolean isInterrupted = false;
private ModelResult modelResultByInternalSolver = null;
private Random random = new Random();
// Statistics
private int numberOfStatecoderFail = 0;
private int numberOfPrintedModel = 0;
private int numberOfSolverCalls = 0;
public BestFirstStrategyForModelGeneration(
ReasonerWorkspace workspace,
ViatraReasonerConfiguration configuration)
{
this.workspace = workspace;
this.configuration = configuration;
}
public SolutionStoreWithCopy getSolutionStoreWithCopy() {
return solutionStoreWithCopy;
}
public SolutionStoreWithDiversityDescriptor getSolutionStoreWithDiversityDescriptor() {
return solutionStoreWithDiversityDescriptor;
}
public int getNumberOfStatecoderFail() {
return numberOfStatecoderFail;
}
@Override
public void initStrategy(ThreadContext context) {
this.context = context;
this.solutionStore = context.getGlobalContext().getSolutionStore();
this.solutionStoreWithCopy = new SolutionStoreWithCopy();
this.solutionStoreWithDiversityDescriptor = new SolutionStoreWithDiversityDescriptor(configuration.diversityRequirement);
final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper();
this.comparator = new Comparator<TrajectoryWithFitness>() {
@Override
public int compare(TrajectoryWithFitness o1, TrajectoryWithFitness o2) {
return objectiveComparatorHelper.compare(o2.fitness, o1.fitness);
}
};
trajectoiresToExplore = new PriorityQueue<TrajectoryWithFitness>(11, comparator);
}
@Override
public void explore() {
if (!context.checkGlobalConstraints()) {
logger.info("Global contraint is not satisifed in the first state. Terminate.");
return;
}
if (configuration.searchSpaceConstraints.maxDepth == 0) {
logger.info("Maximal depth is reached in the initial solution. Terminate.");
return;
}
final Fitness firstFittness = context.calculateFitness();
checkForSolution(firstFittness);
final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper();
final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]);
TrajectoryWithFitness currentTrajectoryWithFittness = new TrajectoryWithFitness(firstTrajectory, firstFittness);
trajectoiresToExplore.add(currentTrajectoryWithFittness);
mainLoop: while (!isInterrupted) {
if (currentTrajectoryWithFittness == null) {
if (trajectoiresToExplore.isEmpty()) {
logger.debug("State space is fully traversed.");
return;
} else {
currentTrajectoryWithFittness = selectState();
if (logger.isDebugEnabled()) {
logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray()));
logger.debug("New trajectory is chosen: " + currentTrajectoryWithFittness);
}
context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithFittness.trajectory);
}
}
// visualiseCurrentState();
// boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness);
// if(consistencyCheckResult == true) {
// continue mainLoop;
// }
List<Object> activationIds = selectActivation();
Iterator<Object> iterator = activationIds.iterator();
while (!isInterrupted && iterator.hasNext()) {
final Object nextActivation = iterator.next();
// if (!iterator.hasNext()) {
// logger.debug("Last untraversed activation of the state.");
// trajectoiresToExplore.remove(currentTrajectoryWithFittness);
// }
logger.debug("Executing new activation: " + nextActivation);
context.executeAcitvationId(nextActivation);
visualiseCurrentState();
boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness);
if(consistencyCheckResult == true) { continue mainLoop; }
if (context.isCurrentStateAlreadyTraversed()) {
logger.info("The new state is already visited.");
context.backtrack();
} else if (!context.checkGlobalConstraints()) {
logger.debug("Global contraint is not satisifed.");
context.backtrack();
} else {
final Fitness nextFitness = context.calculateFitness();
checkForSolution(nextFitness);
if (context.getDepth() > configuration.searchSpaceConstraints.maxDepth) {
logger.debug("Reached max depth.");
context.backtrack();
continue;
}
TrajectoryWithFitness nextTrajectoryWithFittness = new TrajectoryWithFitness(
context.getTrajectory().toArray(), nextFitness);
trajectoiresToExplore.add(nextTrajectoryWithFittness);
int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFittness.fitness,
nextTrajectoryWithFittness.fitness);
if (compare < 0) {
logger.debug("Better fitness, moving on: " + nextFitness);
currentTrajectoryWithFittness = nextTrajectoryWithFittness;
continue mainLoop;
} else if (compare == 0) {
logger.debug("Equally good fitness, moving on: " + nextFitness);
currentTrajectoryWithFittness = nextTrajectoryWithFittness;
continue mainLoop;
} else {
logger.debug("Worse fitness.");
currentTrajectoryWithFittness = null;
continue mainLoop;
}
}
}
logger.debug("State is fully traversed.");
trajectoiresToExplore.remove(currentTrajectoryWithFittness);
currentTrajectoryWithFittness = null;
}
logger.info("Interrupted.");
}
private List<Object> selectActivation() {
List<Object> activationIds;
try {
activationIds = new ArrayList<Object>(context.getUntraversedActivationIds());
Collections.shuffle(activationIds);
} catch (NullPointerException e) {
numberOfStatecoderFail++;
activationIds = Collections.emptyList();
}
return activationIds;
}
private void checkForSolution(final Fitness fittness) {
if (fittness.isSatisifiesHardObjectives()) {
if (solutionStoreWithDiversityDescriptor.isDifferent(context)) {
solutionStoreWithCopy.newSolution(context);
solutionStoreWithDiversityDescriptor.newSolution(context);
solutionStore.newSolution(context);
logger.debug("Found a solution.");
}
}
}
@Override
public void interruptStrategy() {
isInterrupted = true;
}
private TrajectoryWithFitness selectState() {
int randomNumber = random.nextInt(configuration.randomBacktrackChance);
if (randomNumber == 0) {
int elements = trajectoiresToExplore.size();
int randomElementIndex = random.nextInt(elements);
logger.debug("Randomly backtract to the " + randomElementIndex + " best solution...");
Iterator<TrajectoryWithFitness> iterator = trajectoiresToExplore.iterator();
while (randomElementIndex != 0) {
iterator.next();
randomElementIndex--;
}
TrajectoryWithFitness res = iterator.next();
if (res == null) {
return trajectoiresToExplore.element();
} else {
return res;
}
} else {
return trajectoiresToExplore.element();
}
}
public void visualiseCurrentState() {
PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugCongiguration.partialInterpretatioVisualiser;
if(partialInterpretatioVisualiser != null) {
PartialInterpretation p = (PartialInterpretation) (context.getModel());
int id = ++numberOfPrintedModel;
if (id % configuration.debugCongiguration.partalInterpretationVisualisationFrequency == 0) {
PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p);
visualisation.writeToFile(workspace, String.format("state%09d", id));
}
}
}
protected boolean checkConsistency(TrajectoryWithFitness t) {
LogicReasoner internalIncosnsitencyDetector = configuration.internalConsistencyCheckerConfiguration.internalIncosnsitencyDetector;
if (internalIncosnsitencyDetector!= null) {
int id = ++numberOfSolverCalls;
if (id % configuration.internalConsistencyCheckerConfiguration.incternalConsistencyCheckingFrequency == 0) {
try {
PartialInterpretation interpretation = (PartialInterpretation) (context.getModel());
PartialInterpretation copied = EcoreUtil.copy(interpretation);
this.partialInterpretation2Logic.transformPartialIntepretation2Logic(copied.getProblem(), copied);
LogicProblem newProblem = copied.getProblem();
this.configuration.typeScopes.maxNewElements = interpretation.getMaxNewElements();
this.configuration.typeScopes.minNewElements = interpretation.getMinNewElements();
LogicResult result = internalIncosnsitencyDetector.solve(newProblem, configuration, workspace);
if (result instanceof InconsistencyResult) {
logger.debug("Solver found an Inconsistency!");
removeSubtreeFromQueue(t);
return true;
} else if (result instanceof ModelResult) {
logger.debug("Solver found a model!");
solutionStore.newSolution(context);
this.modelResultByInternalSolver = (ModelResult) result;
return true;
} else {
logger.debug("Failed consistency check.");
return false;
}
} catch (Exception e) {
logger.debug("Problem with internal consistency checking: "+e.getMessage());
e.printStackTrace();
return false;
}
}
}
return false;
}
protected void removeSubtreeFromQueue(TrajectoryWithFitness t) {
PriorityQueue<TrajectoryWithFitness> previous = this.trajectoiresToExplore;
this.trajectoiresToExplore = new PriorityQueue<>(this.comparator);
for (TrajectoryWithFitness trajectoryWithFitness : previous) {
if (!containsAsSubstring(trajectoryWithFitness.trajectory, t.trajectory)) {
this.trajectoiresToExplore.add(trajectoryWithFitness);
} else {
logger.debug("State has been excluded due to inherent inconsistency");
}
}
}
private boolean containsAsSubstring(Object[] full, Object[] substring) {
if (substring.length > full.length) {
return false;
} else if (substring.length == full.length) {
return Arrays.equals(full, substring);
} else {
Object[] part = Arrays.copyOfRange(full, 0, substring.length);
return Arrays.equals(part, substring);
}
}
}
| Set thread stop signal to volatile | Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java | Set thread stop signal to volatile |
|
Java | agpl-3.0 | 38eae2781fe45f8c915e15b52c45385dbd8e9797 | 0 | wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,ngaut/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,ngaut/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,shunwang/sql-layer-1 | /**
* Copyright (C) 2011 Akiban Technologies Inc.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package com.akiban.server.test.mt.mtatomics;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.UserTable;
import com.akiban.ais.model.aisb2.AISBBasedBuilder;
import com.akiban.ais.model.aisb2.NewAISBuilder;
import com.akiban.server.api.dml.scan.CursorId;
import com.akiban.server.api.dml.scan.NewRow;
import com.akiban.server.api.dml.scan.ScanAllRequest;
import com.akiban.server.api.dml.scan.ScanFlag;
import com.akiban.server.api.dml.scan.ScanLimit;
import com.akiban.server.error.InvalidOperationException;
import com.akiban.server.error.OldAISException;
import com.akiban.server.service.ServiceManagerImpl;
import com.akiban.server.test.mt.mtutil.TimePoints;
import com.akiban.server.test.mt.mtutil.TimePointsComparison;
import com.akiban.server.test.mt.mtutil.TimedCallable;
import com.akiban.server.test.mt.mtutil.TimedExceptionCatcher;
import com.akiban.server.test.mt.mtutil.Timing;
import com.akiban.server.test.mt.mtutil.TimedResult;
import com.akiban.server.service.dxl.ConcurrencyAtomicsDXLService;
import com.akiban.server.service.session.Session;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public final class ConcurrentDDLAtomicsMT extends ConcurrentAtomicsBase {
@Test
public void dropTableWhileScanningPK() throws Exception {
final int tableId = tableWithTwoRows();
dropTableWhileScanning(
tableId,
"PRIMARY",
createNewRow(tableId, 1L, "the snowman"),
createNewRow(tableId, 2L, "mr melty")
);
}
@Test
public void dropTableWhileScanningOnIndex() throws Exception {
final int tableId = tableWithTwoRows();
dropTableWhileScanning(
tableId,
"name",
createNewRow(tableId, 2L, "mr melty"),
createNewRow(tableId, 1L, "the snowman")
);
}
private void dropTableWhileScanning(int tableId, String indexName, NewRow... expectedScanRows) throws Exception {
final int SCAN_WAIT = 5000;
int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex(indexName).getIndexId();
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(0, SCAN_WAIT, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("TABLE: DROP>");
ddl().dropTable(session, table);
timePoints.mark("TABLE: <DROP");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"TABLE: DROP>",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"TABLE: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
assertEquals("rows scanned size", expectedScanRows.length, rowsScanned.size());
assertEquals("rows", Arrays.asList(expectedScanRows), rowsScanned);
}
@Test
public void rowConvertedAfterTableDrop() throws Exception {
final String index = "PRIMARY";
final int tableId = tableWithTwoRows();
final int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex(index).getIndexId();
DelayScanCallableBuilder callableBuilder = new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.markFinish(false)
.beforeConversionDelayer(new DelayerFactory() {
@Override
public Delayer delayer(TimePoints timePoints) {
return new Delayer(timePoints, 0, 5000)
.markBefore(1, "SCAN: PAUSE")
.markAfter(1, "SCAN: CONVERTED");
}
});
TimedCallable<List<NewRow>> scanCallable = callableBuilder.get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("TABLE: DROP>");
ddl().dropTable(session, table);
timePoints.mark("TABLE: <DROP");
return null;
}
};
// Has to happen before the table is dropped!
List<NewRow> rowsExpected = Arrays.asList(
createNewRow(tableId, 1L, "the snowman"),
createNewRow(tableId, 2L, "mr melty")
);
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"SCAN: PAUSE",
"TABLE: DROP>",
"SCAN: CONVERTED",
"TABLE: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
assertEquals("rows scanned (in order)", rowsExpected, rowsScanned);
}
@Test
public void scanPKWhileDropping() throws Exception {
scanWhileDropping("PRIMARY");
}
@Test
public void scanIndexWhileDropping() throws Exception {
scanWhileDropping("name");
}
@Test
public void dropShiftsIndexIdWhileScanning() throws Exception {
final int tableId = createTable(SCHEMA, TABLE, "id int not null primary key", "name varchar(32)", "age varchar(2)",
"UNIQUE(name)", "UNIQUE(age)");
writeRows(
createNewRow(tableId, 2, "alpha", 3),
createNewRow(tableId, 1, "bravo", 2),
createNewRow(tableId, 3, "charlie", 1)
// the above are listed in order of index #1 (the name index)
// after that index is dropped, index #1 is age, and that will come in this order:
// (3, charlie 1)
// (1, bravo, 2)
// (2, alpha, 3)
// We'll get to the 2nd index (bravo) when we drop the index, and we want to make sure we don't
// continue scanning with alpha (which would thus badly order name)
);
final TableName tableName = new TableName(SCHEMA, TABLE);
Index nameIndex = ddl().getUserTable(session(), tableName).getIndex("name");
Index ageIndex = ddl().getUserTable(session(), tableName).getIndex("age");
final int nameIndexId = nameIndex.getIndexId();
assertTrue("age index's ID relative to name's", ageIndex.getIndexId() != nameIndexId);
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, nameIndexId)
.topOfLoopDelayer(2, 5000, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
Timing.sleep(2500);
timePoints.mark("DROP: IN");
ddl().dropTableIndexes(session, tableName, Collections.singleton("name"));
timePoints.mark("DROP: OUT");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"DROP: IN",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"DROP: OUT"
);
newRowsOrdered(scanResult.getItem(), 1);
}
/**
* Smoke test of concurrent DDL causing failures. One thread will drop a table; the other one will try to create
* another table while that drop is still going on.
* @throws Exception if something went wrong :)
*/
@Test
public void createTableWhileDroppingAnother() throws Exception {
largeEnoughTable(5000);
final String uniqueTableName = TABLE + "thesnowman";
NewAISBuilder builder = AISBBasedBuilder.create();
builder.userTable(SCHEMA, uniqueTableName).colLong("id", false).pk("id");
final UserTable tableToCreate = builder.ais().getUserTable(SCHEMA, uniqueTableName);
TimedCallable<Void> dropTable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
timePoints.mark("DROP>");
ddl().dropTable(session, new TableName(SCHEMA, TABLE));
timePoints.mark("DROP<");
return null;
}
};
TimedCallable<Void> createTable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
Timing.sleep(2000);
timePoints.mark("ADD>");
try {
ddl().createTable(session, tableToCreate);
timePoints.mark("ADD SUCCEEDED");
} catch (IllegalStateException e) {
timePoints.mark("ADD FAILED");
}
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<Void>> dropFuture = executor.submit(dropTable);
Future<TimedResult<Void>> createFuture = executor.submit(createTable);
TimedResult<Void> dropResult = dropFuture.get();
TimedResult<Void> createResult = createFuture.get();
new TimePointsComparison(dropResult, createResult).verify(
"DROP>",
"ADD>",
"ADD FAILED",
"DROP<"
);
Set<TableName> userTableNames = new HashSet<TableName>();
for (UserTable userTable : ddl().getAIS(session()).getUserTables().values()) {
if (!"akiban_information_schema".equals(userTable.getName().getSchemaName())) {
userTableNames.add(userTable.getName());
}
}
assertEquals(
"user tables at end",
Collections.singleton(new TableName(SCHEMA, TABLE+"parent")),
userTableNames
);
}
private void newRowsOrdered(List<NewRow> rows, final int fieldIndex) {
assertTrue("not enough rows: " + rows, rows.size() > 1);
List<NewRow> ordered = new ArrayList<NewRow>(rows);
Collections.sort(ordered, new Comparator<NewRow>() {
@Override @SuppressWarnings("unchecked")
public int compare(NewRow o1, NewRow o2) {
Object o1Field = o1.getFields().get(fieldIndex);
Object o2Field = o2.getFields().get(fieldIndex);
if (o1Field == null) {
return o2Field == null ? 0 : -1;
}
if (o2Field == null) {
return 1;
}
Comparable o1Comp = (Comparable)o1Field;
Comparable o2Comp = (Comparable)o2Field;
return o1Comp.compareTo(o2Comp);
}
});
}
private void scanWhileDropping(String indexName) throws InvalidOperationException, InterruptedException, ExecutionException {
final int tableId = largeEnoughTable(5000);
final TableName tableName = new TableName(SCHEMA, TABLE);
final int indexId = ddl().getUserTable(session(), tableName).getIndex(indexName).getIndexId();
DelayScanCallableBuilder callableBuilder = new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(1, 100, "SCAN: FIRST")
.initialDelay(2500)
.markFinish(false)
.markOpenCursor(true);
DelayableScanCallable scanCallable = callableBuilder.get();
TimedCallable<Void> dropCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(final TimePoints timePoints, Session session) throws Exception {
ConcurrencyAtomicsDXLService.hookNextDropTable(
session,
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: IN");
}
},
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: OUT");
Timing.sleep(50);
}
}
);
ddl().dropTable(session, tableName); // will take ~5 seconds
assertFalse(
"drop table hook still installed",
ConcurrencyAtomicsDXLService.isDropTableHookInstalled(session)
);
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> updateFuture = executor.submit(dropCallable);
try {
scanFuture.get();
fail("expected an exception!");
} catch (ExecutionException e) {
if (!OldAISException.class.equals(e.getCause().getClass())) {
throw new RuntimeException("Expected a OldAISException!", e.getCause());
}
}
TimedResult<Void> updateResult = updateFuture.get();
new TimePointsComparison(updateResult, TimedResult.ofNull(scanCallable.getTimePoints())).verify(
"DROP: IN",
"(SCAN: OPEN CURSOR)>",
"DROP: OUT",
"SCAN: exception OldAISException"
);
assertTrue("rows weren't empty!", scanCallable.getRows().isEmpty());
}
/**
* Creates a table with enough rows that it takes a while to drop it
* @param msForDropping how long (at least) it should take to drop this table
* @return the table's id
* @throws InvalidOperationException if ever encountered
*/
private int largeEnoughTable(long msForDropping) throws InvalidOperationException {
int rowCount;
long dropTime;
float factor = 1.5f; // after we write N rows, we'll write an additional (factor-1)*N rows as buffer
int parentId = createTable(SCHEMA, TABLE+"parent", "id int not null primary key");
writeRows(
createNewRow(parentId, 1)
);
final String[] childTableDDL = {"id int not null primary key", "pid int", "name varchar(32)", "UNIQUE(name)",
"GROUPING FOREIGN KEY (pid) REFERENCES " +TABLE+"parent(id)"};
do {
int tableId = createTable(SCHEMA, TABLE, childTableDDL);
rowCount = 1;
final long writeStart = System.currentTimeMillis();
while (System.currentTimeMillis() - writeStart < msForDropping) {
writeRows(
createNewRow(tableId, rowCount, Integer.toString(rowCount))
);
++rowCount;
}
for(int i = rowCount; i < (int) factor * rowCount ; ++i) {
writeRows(
createNewRow(tableId, i, Integer.toString(i))
);
}
final long dropStart = System.currentTimeMillis();
ddl().dropTable(session(), new TableName(SCHEMA, TABLE));
dropTime = System.currentTimeMillis() - dropStart;
factor += 0.2;
} while(dropTime < msForDropping);
int tableId = createTable(SCHEMA, TABLE, childTableDDL);
for(int i = 1; i < rowCount ; ++i) {
writeRows(
createNewRow(tableId, i, Integer.toString(i))
);
}
return tableId;
}
@Test
public void dropIndexWhileScanning() throws Exception {
final int tableId = tableWithTwoRows();
final int SCAN_WAIT = 5000;
int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex("name").getIndexId();
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(0, SCAN_WAIT, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("INDEX: DROP>");
ddl().dropTableIndexes(ServiceManagerImpl.newSession(), table, Collections.singleton("name"));
timePoints.mark("INDEX: <DROP");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"INDEX: DROP>",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"INDEX: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
List<NewRow> rowsExpected = Arrays.asList(
createNewRow(tableId, 2L, "mr melty"),
createNewRow(tableId, 1L, "the snowman")
);
assertEquals("rows scanned (in order)", rowsExpected, rowsScanned);
}
@Test
public void scanWhileDroppingIndex() throws Throwable {
final long SCAN_PAUSE_LENGTH = 2500;
final long DROP_START_LENGTH = 1000;
final long DROP_PAUSE_LENGTH = 2500;
final int NUMBER_OF_ROWS = 100;
final int initialTableId = createTable(SCHEMA, TABLE, "id int not null primary key", "age int");
createIndex(SCHEMA, TABLE, "age", "age");
final TableName tableName = new TableName(SCHEMA, TABLE);
for(int i=0; i < NUMBER_OF_ROWS; ++i) {
writeRows(createNewRow(initialTableId, i, i + 1));
}
final Index index = ddl().getUserTable(session(), tableName).getIndex("age");
final Collection<String> indexNameCollection = Collections.singleton(index.getIndexName().getName());
final int tableId = ddl().getTableId(session(), tableName);
TimedCallable<Throwable> dropIndexCallable = new TimedExceptionCatcher() {
@Override
protected void doOrThrow(final TimePoints timePoints, Session session) throws Exception {
Timing.sleep(DROP_START_LENGTH);
timePoints.mark("DROP: PREPARING");
ConcurrencyAtomicsDXLService.hookNextDropIndex(session,
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: IN");
Timing.sleep(DROP_PAUSE_LENGTH);
}
},
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: OUT");
Timing.sleep(DROP_PAUSE_LENGTH);
}
}
);
ddl().dropTableIndexes(session, tableName, indexNameCollection);
assertFalse("drop hook not removed!", ConcurrencyAtomicsDXLService.isDropIndexHookInstalled(session));
}
};
final int localAISGeneration = aisGeneration();
TimedCallable<Throwable> scanCallable = new TimedExceptionCatcher() {
@Override
protected void doOrThrow(TimePoints timePoints, Session session) throws Exception {
timePoints.mark("SCAN: PREPARING");
ScanAllRequest request = new ScanAllRequest(
tableId,
new HashSet<Integer>(Arrays.asList(0, 1)),
index.getIndexId(),
EnumSet.of(ScanFlag.START_AT_BEGINNING, ScanFlag.END_AT_END),
ScanLimit.NONE
);
timePoints.mark("(SCAN: PAUSE)>");
Timing.sleep(SCAN_PAUSE_LENGTH);
timePoints.mark("<(SCAN: PAUSE)");
try {
CursorId cursorId = dml().openCursor(session, localAISGeneration, request);
timePoints.mark("SCAN: cursorID opened");
dml().closeCursor(session, cursorId);
} catch (OldAISException e) {
timePoints.mark("SCAN: OldAISException");
}
}
@Override
protected void handleCaught(TimePoints timePoints, Session session, Throwable t) {
timePoints.mark("SCAN: Unexpected exception " + t.getClass().getSimpleName());
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<Throwable>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Throwable>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<Throwable> scanResult = scanFuture.get();
TimedResult<Throwable> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: PREPARING",
"(SCAN: PAUSE)>",
"DROP: PREPARING",
"DROP: IN",
"<(SCAN: PAUSE)",
"DROP: OUT",
"SCAN: OldAISException"
);
TimedExceptionCatcher.throwIfThrown(scanResult);
TimedExceptionCatcher.throwIfThrown(dropIndexResult);
}
}
| src/test/java/com/akiban/server/test/mt/mtatomics/ConcurrentDDLAtomicsMT.java | /**
* Copyright (C) 2011 Akiban Technologies Inc.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package com.akiban.server.test.mt.mtatomics;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.UserTable;
import com.akiban.server.api.dml.scan.CursorId;
import com.akiban.server.api.dml.scan.NewRow;
import com.akiban.server.api.dml.scan.ScanAllRequest;
import com.akiban.server.api.dml.scan.ScanFlag;
import com.akiban.server.api.dml.scan.ScanLimit;
import com.akiban.server.error.InvalidOperationException;
import com.akiban.server.error.OldAISException;
import com.akiban.server.service.ServiceManagerImpl;
import com.akiban.server.test.mt.mtutil.TimePoints;
import com.akiban.server.test.mt.mtutil.TimePointsComparison;
import com.akiban.server.test.mt.mtutil.TimedCallable;
import com.akiban.server.test.mt.mtutil.TimedExceptionCatcher;
import com.akiban.server.test.mt.mtutil.Timing;
import com.akiban.server.test.mt.mtutil.TimedResult;
import com.akiban.server.service.dxl.ConcurrencyAtomicsDXLService;
import com.akiban.server.service.session.Session;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public final class ConcurrentDDLAtomicsMT extends ConcurrentAtomicsBase {
@Test
public void dropTableWhileScanningPK() throws Exception {
final int tableId = tableWithTwoRows();
dropTableWhileScanning(
tableId,
"PRIMARY",
createNewRow(tableId, 1L, "the snowman"),
createNewRow(tableId, 2L, "mr melty")
);
}
@Test
public void dropTableWhileScanningOnIndex() throws Exception {
final int tableId = tableWithTwoRows();
dropTableWhileScanning(
tableId,
"name",
createNewRow(tableId, 2L, "mr melty"),
createNewRow(tableId, 1L, "the snowman")
);
}
private void dropTableWhileScanning(int tableId, String indexName, NewRow... expectedScanRows) throws Exception {
final int SCAN_WAIT = 5000;
int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex(indexName).getIndexId();
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(0, SCAN_WAIT, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("TABLE: DROP>");
ddl().dropTable(session, table);
timePoints.mark("TABLE: <DROP");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"TABLE: DROP>",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"TABLE: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
assertEquals("rows scanned size", expectedScanRows.length, rowsScanned.size());
assertEquals("rows", Arrays.asList(expectedScanRows), rowsScanned);
}
@Test
public void rowConvertedAfterTableDrop() throws Exception {
final String index = "PRIMARY";
final int tableId = tableWithTwoRows();
final int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex(index).getIndexId();
DelayScanCallableBuilder callableBuilder = new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.markFinish(false)
.beforeConversionDelayer(new DelayerFactory() {
@Override
public Delayer delayer(TimePoints timePoints) {
return new Delayer(timePoints, 0, 5000)
.markBefore(1, "SCAN: PAUSE")
.markAfter(1, "SCAN: CONVERTED");
}
});
TimedCallable<List<NewRow>> scanCallable = callableBuilder.get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("TABLE: DROP>");
ddl().dropTable(session, table);
timePoints.mark("TABLE: <DROP");
return null;
}
};
// Has to happen before the table is dropped!
List<NewRow> rowsExpected = Arrays.asList(
createNewRow(tableId, 1L, "the snowman"),
createNewRow(tableId, 2L, "mr melty")
);
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"SCAN: PAUSE",
"TABLE: DROP>",
"SCAN: CONVERTED",
"TABLE: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
assertEquals("rows scanned (in order)", rowsExpected, rowsScanned);
}
@Test
public void scanPKWhileDropping() throws Exception {
scanWhileDropping("PRIMARY");
}
@Test
public void scanIndexWhileDropping() throws Exception {
scanWhileDropping("name");
}
@Test
public void dropShiftsIndexIdWhileScanning() throws Exception {
final int tableId = createTable(SCHEMA, TABLE, "id int not null primary key", "name varchar(32)", "age varchar(2)",
"UNIQUE(name)", "UNIQUE(age)");
writeRows(
createNewRow(tableId, 2, "alpha", 3),
createNewRow(tableId, 1, "bravo", 2),
createNewRow(tableId, 3, "charlie", 1)
// the above are listed in order of index #1 (the name index)
// after that index is dropped, index #1 is age, and that will come in this order:
// (3, charlie 1)
// (1, bravo, 2)
// (2, alpha, 3)
// We'll get to the 2nd index (bravo) when we drop the index, and we want to make sure we don't
// continue scanning with alpha (which would thus badly order name)
);
final TableName tableName = new TableName(SCHEMA, TABLE);
Index nameIndex = ddl().getUserTable(session(), tableName).getIndex("name");
Index ageIndex = ddl().getUserTable(session(), tableName).getIndex("age");
final int nameIndexId = nameIndex.getIndexId();
assertTrue("age index's ID relative to name's", ageIndex.getIndexId() != nameIndexId);
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, nameIndexId)
.topOfLoopDelayer(2, 5000, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
Timing.sleep(2500);
timePoints.mark("DROP: IN");
ddl().dropTableIndexes(session, tableName, Collections.singleton("name"));
timePoints.mark("DROP: OUT");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"DROP: IN",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"DROP: OUT"
);
newRowsOrdered(scanResult.getItem(), 1);
}
/**
* Smoke test of concurrent DDL causing failures. One thread will drop a table; the other one will try to create
* another table while that drop is still going on.
* @throws Exception if something went wrong :)
*/
@Test
public void createTableWhileDroppingAnother() throws Exception {
largeEnoughTable(5000);
final String uniqueTableName = TABLE + "thesnowman";
TimedCallable<Void> dropTable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
timePoints.mark("DROP>");
ddl().dropTable(session, new TableName(SCHEMA, TABLE));
timePoints.mark("DROP<");
return null;
}
};
TimedCallable<Void> createTable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
Timing.sleep(2000);
timePoints.mark("ADD>");
try {
createTable(SCHEMA, uniqueTableName, "id int not null primary key");
timePoints.mark("ADD SUCCEEDED");
} catch (IllegalStateException e) {
timePoints.mark("ADD FAILED");
}
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<Void>> dropFuture = executor.submit(dropTable);
Future<TimedResult<Void>> createFuture = executor.submit(createTable);
TimedResult<Void> dropResult = dropFuture.get();
TimedResult<Void> createResult = createFuture.get();
new TimePointsComparison(dropResult, createResult).verify(
"DROP>",
"ADD>",
"ADD FAILED",
"DROP<"
);
Set<TableName> userTableNames = new HashSet<TableName>();
for (UserTable userTable : ddl().getAIS(session()).getUserTables().values()) {
if (!"akiban_information_schema".equals(userTable.getName().getSchemaName())) {
userTableNames.add(userTable.getName());
}
}
assertEquals(
"user tables at end",
Collections.singleton(new TableName(SCHEMA, TABLE+"parent")),
userTableNames
);
}
private void newRowsOrdered(List<NewRow> rows, final int fieldIndex) {
assertTrue("not enough rows: " + rows, rows.size() > 1);
List<NewRow> ordered = new ArrayList<NewRow>(rows);
Collections.sort(ordered, new Comparator<NewRow>() {
@Override @SuppressWarnings("unchecked")
public int compare(NewRow o1, NewRow o2) {
Object o1Field = o1.getFields().get(fieldIndex);
Object o2Field = o2.getFields().get(fieldIndex);
if (o1Field == null) {
return o2Field == null ? 0 : -1;
}
if (o2Field == null) {
return 1;
}
Comparable o1Comp = (Comparable)o1Field;
Comparable o2Comp = (Comparable)o2Field;
return o1Comp.compareTo(o2Comp);
}
});
}
private void scanWhileDropping(String indexName) throws InvalidOperationException, InterruptedException, ExecutionException {
final int tableId = largeEnoughTable(5000);
final TableName tableName = new TableName(SCHEMA, TABLE);
final int indexId = ddl().getUserTable(session(), tableName).getIndex(indexName).getIndexId();
DelayScanCallableBuilder callableBuilder = new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(1, 100, "SCAN: FIRST")
.initialDelay(2500)
.markFinish(false)
.markOpenCursor(true);
DelayableScanCallable scanCallable = callableBuilder.get();
TimedCallable<Void> dropCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(final TimePoints timePoints, Session session) throws Exception {
ConcurrencyAtomicsDXLService.hookNextDropTable(
session,
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: IN");
}
},
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: OUT");
Timing.sleep(50);
}
}
);
ddl().dropTable(session, tableName); // will take ~5 seconds
assertFalse(
"drop table hook still installed",
ConcurrencyAtomicsDXLService.isDropTableHookInstalled(session)
);
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> updateFuture = executor.submit(dropCallable);
try {
scanFuture.get();
fail("expected an exception!");
} catch (ExecutionException e) {
if (!OldAISException.class.equals(e.getCause().getClass())) {
throw new RuntimeException("Expected a OldAISException!", e.getCause());
}
}
TimedResult<Void> updateResult = updateFuture.get();
new TimePointsComparison(updateResult, TimedResult.ofNull(scanCallable.getTimePoints())).verify(
"DROP: IN",
"(SCAN: OPEN CURSOR)>",
"DROP: OUT",
"SCAN: exception OldAISException"
);
assertTrue("rows weren't empty!", scanCallable.getRows().isEmpty());
}
/**
* Creates a table with enough rows that it takes a while to drop it
* @param msForDropping how long (at least) it should take to drop this table
* @return the table's id
* @throws InvalidOperationException if ever encountered
*/
private int largeEnoughTable(long msForDropping) throws InvalidOperationException {
int rowCount;
long dropTime;
float factor = 1.5f; // after we write N rows, we'll write an additional (factor-1)*N rows as buffer
int parentId = createTable(SCHEMA, TABLE+"parent", "id int not null primary key");
writeRows(
createNewRow(parentId, 1)
);
final String[] childTableDDL = {"id int not null primary key", "pid int", "name varchar(32)", "UNIQUE(name)",
"GROUPING FOREIGN KEY (pid) REFERENCES " +TABLE+"parent(id)"};
do {
int tableId = createTable(SCHEMA, TABLE, childTableDDL);
rowCount = 1;
final long writeStart = System.currentTimeMillis();
while (System.currentTimeMillis() - writeStart < msForDropping) {
writeRows(
createNewRow(tableId, rowCount, Integer.toString(rowCount))
);
++rowCount;
}
for(int i = rowCount; i < (int) factor * rowCount ; ++i) {
writeRows(
createNewRow(tableId, i, Integer.toString(i))
);
}
final long dropStart = System.currentTimeMillis();
ddl().dropTable(session(), new TableName(SCHEMA, TABLE));
dropTime = System.currentTimeMillis() - dropStart;
factor += 0.2;
} while(dropTime < msForDropping);
int tableId = createTable(SCHEMA, TABLE, childTableDDL);
for(int i = 1; i < rowCount ; ++i) {
writeRows(
createNewRow(tableId, i, Integer.toString(i))
);
}
return tableId;
}
@Test
public void dropIndexWhileScanning() throws Exception {
final int tableId = tableWithTwoRows();
final int SCAN_WAIT = 5000;
int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex("name").getIndexId();
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(0, SCAN_WAIT, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("INDEX: DROP>");
ddl().dropTableIndexes(ServiceManagerImpl.newSession(), table, Collections.singleton("name"));
timePoints.mark("INDEX: <DROP");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"INDEX: DROP>",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"INDEX: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
List<NewRow> rowsExpected = Arrays.asList(
createNewRow(tableId, 2L, "mr melty"),
createNewRow(tableId, 1L, "the snowman")
);
assertEquals("rows scanned (in order)", rowsExpected, rowsScanned);
}
@Test
public void scanWhileDroppingIndex() throws Throwable {
final long SCAN_PAUSE_LENGTH = 2500;
final long DROP_START_LENGTH = 1000;
final long DROP_PAUSE_LENGTH = 2500;
final int NUMBER_OF_ROWS = 100;
final int initialTableId = createTable(SCHEMA, TABLE, "id int not null primary key", "age int");
createIndex(SCHEMA, TABLE, "age", "age");
final TableName tableName = new TableName(SCHEMA, TABLE);
for(int i=0; i < NUMBER_OF_ROWS; ++i) {
writeRows(createNewRow(initialTableId, i, i + 1));
}
final Index index = ddl().getUserTable(session(), tableName).getIndex("age");
final Collection<String> indexNameCollection = Collections.singleton(index.getIndexName().getName());
final int tableId = ddl().getTableId(session(), tableName);
TimedCallable<Throwable> dropIndexCallable = new TimedExceptionCatcher() {
@Override
protected void doOrThrow(final TimePoints timePoints, Session session) throws Exception {
Timing.sleep(DROP_START_LENGTH);
timePoints.mark("DROP: PREPARING");
ConcurrencyAtomicsDXLService.hookNextDropIndex(session,
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: IN");
Timing.sleep(DROP_PAUSE_LENGTH);
}
},
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: OUT");
Timing.sleep(DROP_PAUSE_LENGTH);
}
}
);
ddl().dropTableIndexes(session, tableName, indexNameCollection);
assertFalse("drop hook not removed!", ConcurrencyAtomicsDXLService.isDropIndexHookInstalled(session));
}
};
final int localAISGeneration = aisGeneration();
TimedCallable<Throwable> scanCallable = new TimedExceptionCatcher() {
@Override
protected void doOrThrow(TimePoints timePoints, Session session) throws Exception {
timePoints.mark("SCAN: PREPARING");
ScanAllRequest request = new ScanAllRequest(
tableId,
new HashSet<Integer>(Arrays.asList(0, 1)),
index.getIndexId(),
EnumSet.of(ScanFlag.START_AT_BEGINNING, ScanFlag.END_AT_END),
ScanLimit.NONE
);
timePoints.mark("(SCAN: PAUSE)>");
Timing.sleep(SCAN_PAUSE_LENGTH);
timePoints.mark("<(SCAN: PAUSE)");
try {
CursorId cursorId = dml().openCursor(session, localAISGeneration, request);
timePoints.mark("SCAN: cursorID opened");
dml().closeCursor(session, cursorId);
} catch (OldAISException e) {
timePoints.mark("SCAN: OldAISException");
}
}
@Override
protected void handleCaught(TimePoints timePoints, Session session, Throwable t) {
timePoints.mark("SCAN: Unexpected exception " + t.getClass().getSimpleName());
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<Throwable>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Throwable>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<Throwable> scanResult = scanFuture.get();
TimedResult<Throwable> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: PREPARING",
"(SCAN: PAUSE)>",
"DROP: PREPARING",
"DROP: IN",
"<(SCAN: PAUSE)",
"DROP: OUT",
"SCAN: OldAISException"
);
TimedExceptionCatcher.throwIfThrown(scanResult);
TimedExceptionCatcher.throwIfThrown(dropIndexResult);
}
}
| Fix intermittent failure in MT by creating table outside of thread trying to be sequenced | src/test/java/com/akiban/server/test/mt/mtatomics/ConcurrentDDLAtomicsMT.java | Fix intermittent failure in MT by creating table outside of thread trying to be sequenced |
|
Java | agpl-3.0 | 219673ebfb02c2e1ae60897927131935e6d6978c | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 1c74c038-2e61-11e5-9284-b827eb9e62be | hello.java | 1c6f580a-2e61-11e5-9284-b827eb9e62be | 1c74c038-2e61-11e5-9284-b827eb9e62be | hello.java | 1c74c038-2e61-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | 3f2e3a3ce97b26e6c09118b77214ad617378c295 | 0 | aaronc/jfreechart,aaronc/jfreechart,aaronc/jfreechart | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------
* Regression.java
* ---------------
* (C) Copyright 2002-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Peter Kolb (patch 2795746);
*
* Changes
* -------
* 30-Sep-2002 : Version 1 (DG);
* 18-Aug-2003 : Added 'abstract' (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 29-May-2009 : Added support for polynomial regression, see patch 2795746
* by Peter Kolb (DG);
* 03-Jul-2013 : Use ParamChecks (DG);
*
*/
package org.jfree.data.statistics;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.xy.XYDataset;
/**
* A utility class for fitting regression curves to data.
*/
public abstract class Regression {
/**
* Returns the parameters 'a' and 'b' for an equation y = a + bx, fitted to
* the data using ordinary least squares regression. The result is
* returned as a double[], where result[0] --> a, and result[1] --> b.
*
* @param data the data.
*
* @return The parameters.
*/
public static double[] getOLSRegression(double[][] data) {
int n = data.length;
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = data[i][0];
double y = data[i][1];
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = ybar - result[1] * xbar;
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = a + bx, fitted to
* the data using ordinary least squares regression. The result is returned
* as a double[], where result[0] --> a, and result[1] --> b.
*
* @param data the data.
* @param series the series (zero-based index).
*
* @return The parameters.
*/
public static double[] getOLSRegression(XYDataset data, int series) {
int n = data.getItemCount(series);
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = data.getXValue(series, i);
double y = data.getYValue(series, i);
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = ybar - result[1] * xbar;
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = ax^b, fitted to
* the data using a power regression equation. The result is returned as
* an array, where double[0] --> a, and double[1] --> b.
*
* @param data the data.
*
* @return The parameters.
*/
public static double[] getPowerRegression(double[][] data) {
int n = data.length;
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = Math.log(data[i][0]);
double y = Math.log(data[i][1]);
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = Math.pow(Math.exp(1.0), ybar - result[1] * xbar);
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = ax^b, fitted to
* the data using a power regression equation. The result is returned as
* an array, where double[0] --> a, and double[1] --> b.
*
* @param data the data.
* @param series the series to fit the regression line against.
*
* @return The parameters.
*/
public static double[] getPowerRegression(XYDataset data, int series) {
int n = data.getItemCount(series);
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = Math.log(data.getXValue(series, i));
double y = Math.log(data.getYValue(series, i));
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = Math.pow(Math.exp(1.0), ybar - result[1] * xbar);
return result;
}
/**
* Returns the parameters 'a0', 'a1', 'a2', ..., 'an' for a polynomial
* function of order n, y = a0 + a1 * x + a2 * x^2 + ... + an * x^n,
* fitted to the data using a polynomial regression equation.
* The result is returned as an array with a length of n + 2,
* where double[0] --> a0, double[1] --> a1, .., double[n] --> an.
* and double[n + 1] is the correlation coefficient R2
* Reference: J. D. Faires, R. L. Burden, Numerische Methoden (german
* edition), pp. 243ff and 327ff.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series to fit the regression line against (the series
* must have at least order + 1 non-NaN items).
* @param order the order of the function (> 0).
*
* @return The parameters.
*
* @since 1.0.14
*/
public static double[] getPolynomialRegression(XYDataset dataset,
int series, int order) {
ParamChecks.nullNotPermitted(dataset, "dataset");
int itemCount = dataset.getItemCount(series);
if (itemCount < order + 1) {
throw new IllegalArgumentException("Not enough data.");
}
int validItems = 0;
double[][] data = new double[2][itemCount];
for(int item = 0; item < itemCount; item++){
double x = dataset.getXValue(series, item);
double y = dataset.getYValue(series, item);
if (!Double.isNaN(x) && !Double.isNaN(y)){
data[0][validItems] = x;
data[1][validItems] = y;
validItems++;
}
}
if (validItems < order + 1) {
throw new IllegalArgumentException("Not enough data.");
}
int equations = order + 1;
int coefficients = order + 2;
double[] result = new double[equations + 1];
double[][] matrix = new double[equations][coefficients];
double sumX = 0.0;
double sumY = 0.0;
for(int item = 0; item < validItems; item++){
sumX += data[0][item];
sumY += data[1][item];
for(int eq = 0; eq < equations; eq++){
for(int coe = 0; coe < coefficients - 1; coe++){
matrix[eq][coe] += Math.pow(data[0][item],eq + coe);
}
matrix[eq][coefficients - 1] += data[1][item]
* Math.pow(data[0][item],eq);
}
}
double[][] subMatrix = calculateSubMatrix(matrix);
for (int eq = 1; eq < equations; eq++) {
matrix[eq][0] = 0;
for (int coe = 1; coe < coefficients; coe++) {
matrix[eq][coe] = subMatrix[eq - 1][coe - 1];
}
}
for (int eq = equations - 1; eq > -1; eq--) {
double value = matrix[eq][coefficients - 1];
for (int coe = eq; coe < coefficients -1; coe++) {
value -= matrix[eq][coe] * result[coe];
}
result[eq] = value / matrix[eq][eq];
}
double meanY = sumY / validItems;
double yObsSquare = 0.0;
double yRegSquare = 0.0;
for (int item = 0; item < validItems; item++) {
double yCalc = 0;
for (int eq = 0; eq < equations; eq++) {
yCalc += result[eq] * Math.pow(data[0][item],eq);
}
yRegSquare += Math.pow(yCalc - meanY, 2);
yObsSquare += Math.pow(data[1][item] - meanY, 2);
}
double rSquare = yRegSquare / yObsSquare;
result[equations] = rSquare;
return result;
}
/**
* Returns a matrix with the following features: (1) the number of rows
* and columns is 1 less than that of the original matrix; (2)the matrix
* is triangular, i.e. all elements a (row, column) with column > row are
* zero. This method is used for calculating a polynomial regression.
*
* @param matrix the start matrix.
*
* @return The new matrix.
*/
private static double[][] calculateSubMatrix(double[][] matrix){
int equations = matrix.length;
int coefficients = matrix[0].length;
double[][] result = new double[equations - 1][coefficients - 1];
for (int eq = 1; eq < equations; eq++) {
double factor = matrix[0][0] / matrix[eq][0];
for (int coe = 1; coe < coefficients; coe++) {
result[eq - 1][coe -1] = matrix[0][coe] - matrix[eq][coe]
* factor;
}
}
if (equations == 1) {
return result;
}
// check for zero pivot element
if (result[0][0] == 0) {
boolean found = false;
for (int i = 0; i < result.length; i ++) {
if (result[i][0] != 0) {
found = true;
double[] temp = result[0];
for (int j = 0; j < result[i].length; j++) {
result[0][j] = result[i][j];
}
for (int j = 0; j < temp.length; j++) {
result[i][j] = temp[j];
}
break;
}
}
if (!found) {
System.out.println("Equation has no solution!");
return new double[equations - 1][coefficients - 1];
}
}
double[][] subMatrix = calculateSubMatrix(result);
for (int eq = 1; eq < equations - 1; eq++) {
result[eq][0] = 0;
for (int coe = 1; coe < coefficients - 1; coe++) {
result[eq][coe] = subMatrix[eq - 1][coe - 1];
}
}
return result;
}
}
| source/org/jfree/data/statistics/Regression.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------
* Regression.java
* ---------------
* (C) Copyright 2002-2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Peter Kolb (patch 2795746);
*
* Changes
* -------
* 30-Sep-2002 : Version 1 (DG);
* 18-Aug-2003 : Added 'abstract' (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 29-May-2009 : Added support for polynomial regression, see patch 2795746
* by Peter Kolb (DG);
*
*/
package org.jfree.data.statistics;
import org.jfree.data.xy.XYDataset;
/**
* A utility class for fitting regression curves to data.
*/
public abstract class Regression {
/**
* Returns the parameters 'a' and 'b' for an equation y = a + bx, fitted to
* the data using ordinary least squares regression. The result is
* returned as a double[], where result[0] --> a, and result[1] --> b.
*
* @param data the data.
*
* @return The parameters.
*/
public static double[] getOLSRegression(double[][] data) {
int n = data.length;
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = data[i][0];
double y = data[i][1];
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = ybar - result[1] * xbar;
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = a + bx, fitted to
* the data using ordinary least squares regression. The result is returned
* as a double[], where result[0] --> a, and result[1] --> b.
*
* @param data the data.
* @param series the series (zero-based index).
*
* @return The parameters.
*/
public static double[] getOLSRegression(XYDataset data, int series) {
int n = data.getItemCount(series);
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = data.getXValue(series, i);
double y = data.getYValue(series, i);
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = ybar - result[1] * xbar;
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = ax^b, fitted to
* the data using a power regression equation. The result is returned as
* an array, where double[0] --> a, and double[1] --> b.
*
* @param data the data.
*
* @return The parameters.
*/
public static double[] getPowerRegression(double[][] data) {
int n = data.length;
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = Math.log(data[i][0]);
double y = Math.log(data[i][1]);
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = Math.pow(Math.exp(1.0), ybar - result[1] * xbar);
return result;
}
/**
* Returns the parameters 'a' and 'b' for an equation y = ax^b, fitted to
* the data using a power regression equation. The result is returned as
* an array, where double[0] --> a, and double[1] --> b.
*
* @param data the data.
* @param series the series to fit the regression line against.
*
* @return The parameters.
*/
public static double[] getPowerRegression(XYDataset data, int series) {
int n = data.getItemCount(series);
if (n < 2) {
throw new IllegalArgumentException("Not enough data.");
}
double sumX = 0;
double sumY = 0;
double sumXX = 0;
double sumXY = 0;
for (int i = 0; i < n; i++) {
double x = Math.log(data.getXValue(series, i));
double y = Math.log(data.getYValue(series, i));
sumX += x;
sumY += y;
double xx = x * x;
sumXX += xx;
double xy = x * y;
sumXY += xy;
}
double sxx = sumXX - (sumX * sumX) / n;
double sxy = sumXY - (sumX * sumY) / n;
double xbar = sumX / n;
double ybar = sumY / n;
double[] result = new double[2];
result[1] = sxy / sxx;
result[0] = Math.pow(Math.exp(1.0), ybar - result[1] * xbar);
return result;
}
/**
* Returns the parameters 'a0', 'a1', 'a2', ..., 'an' for a polynomial
* function of order n, y = a0 + a1 * x + a2 * x^2 + ... + an * x^n,
* fitted to the data using a polynomial regression equation.
* The result is returned as an array with a length of n + 2,
* where double[0] --> a0, double[1] --> a1, .., double[n] --> an.
* and double[n + 1] is the correlation coefficient R2
* Reference: J. D. Faires, R. L. Burden, Numerische Methoden (german
* edition), pp. 243ff and 327ff.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series to fit the regression line against (the series
* must have at least order + 1 non-NaN items).
* @param order the order of the function (> 0).
*
* @return The parameters.
*
* @since 1.0.14
*/
public static double[] getPolynomialRegression(XYDataset dataset, int series, int order) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
int itemCount = dataset.getItemCount(series);
if (itemCount < order + 1) {
throw new IllegalArgumentException("Not enough data.");
}
int validItems = 0;
double[][] data = new double[2][itemCount];
for(int item = 0; item < itemCount; item++){
double x = dataset.getXValue(series, item);
double y = dataset.getYValue(series, item);
if (!Double.isNaN(x) && !Double.isNaN(y)){
data[0][validItems] = x;
data[1][validItems] = y;
validItems++;
}
}
if (validItems < order + 1) {
throw new IllegalArgumentException("Not enough data.");
}
int equations = order + 1;
int coefficients = order + 2;
double[] result = new double[equations + 1];
double[][] matrix = new double[equations][coefficients];
double sumX = 0.0;
double sumY = 0.0;
for(int item = 0; item < validItems; item++){
sumX += data[0][item];
sumY += data[1][item];
for(int eq = 0; eq < equations; eq++){
for(int coe = 0; coe < coefficients - 1; coe++){
matrix[eq][coe] += Math.pow(data[0][item],eq + coe);
}
matrix[eq][coefficients - 1] += data[1][item]
* Math.pow(data[0][item],eq);
}
}
double[][] subMatrix = calculateSubMatrix(matrix);
for (int eq = 1; eq < equations; eq++) {
matrix[eq][0] = 0;
for (int coe = 1; coe < coefficients; coe++) {
matrix[eq][coe] = subMatrix[eq - 1][coe - 1];
}
}
for (int eq = equations - 1; eq > -1; eq--) {
double value = matrix[eq][coefficients - 1];
for (int coe = eq; coe < coefficients -1; coe++) {
value -= matrix[eq][coe] * result[coe];
}
result[eq] = value / matrix[eq][eq];
}
double meanY = sumY / validItems;
double yObsSquare = 0.0;
double yRegSquare = 0.0;
for (int item = 0; item < validItems; item++) {
double yCalc = 0;
for (int eq = 0; eq < equations; eq++) {
yCalc += result[eq] * Math.pow(data[0][item],eq);
}
yRegSquare += Math.pow(yCalc - meanY, 2);
yObsSquare += Math.pow(data[1][item] - meanY, 2);
}
double rSquare = yRegSquare / yObsSquare;
result[equations] = rSquare;
return result;
}
/**
* Returns a matrix with the following features: (1) the number of rows
* and columns is 1 less than that of the original matrix; (2)the matrix
* is triangular, i.e. all elements a (row, column) with column > row are
* zero. This method is used for calculating a polynomial regression.
*
* @param matrix the start matrix.
*
* @return The new matrix.
*/
private static double[][] calculateSubMatrix(double[][] matrix){
int equations = matrix.length;
int coefficients = matrix[0].length;
double[][] result = new double[equations - 1][coefficients - 1];
for (int eq = 1; eq < equations; eq++) {
double factor = matrix[0][0] / matrix[eq][0];
for (int coe = 1; coe < coefficients; coe++) {
result[eq - 1][coe -1] = matrix[0][coe] - matrix[eq][coe]
* factor;
}
}
if (equations == 1) {
return result;
}
// check for zero pivot element
if (result[0][0] == 0) {
boolean found = false;
for (int i = 0; i < result.length; i ++) {
if (result[i][0] != 0) {
found = true;
double[] temp = result[0];
for (int j = 0; j < result[i].length; j++) {
result[0][j] = result[i][j];
}
for (int j = 0; j < temp.length; j++) {
result[i][j] = temp[j];
}
break;
}
}
if (!found) {
System.out.println("Equation has no solution!");
return new double[equations - 1][coefficients - 1];
}
}
double[][] subMatrix = calculateSubMatrix(result);
for (int eq = 1; eq < equations - 1; eq++) {
result[eq][0] = 0;
for (int coe = 1; coe < coefficients - 1; coe++) {
result[eq][coe] = subMatrix[eq - 1][coe - 1];
}
}
return result;
}
}
| Use ParamChecks class.
git-svn-id: ca96c60061366ac92493e2142a352bb838ea8caa@2725 4df5dd95-b682-48b0-b31b-748e37b65e73
| source/org/jfree/data/statistics/Regression.java | Use ParamChecks class. |
|
Java | lgpl-2.1 | 520524239c3ac480b14d4d19db3af5b2c94a4a8c | 0 | RockManJoe64/swingx,RockManJoe64/swingx | /*
* $Id$
*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.jdesktop.swingx.test.XTestUtils;
/**
* Test to expose known issues of <code>JXHeader</code>.
* <p>
*
* Ideally, there would be at least one failing test method per open issue in
* the issue tracker. Plus additional failing test methods for not fully
* specified or not yet decided upon features/behaviour.
* <p>
*
* If an issue is fixed and the corresponding methods are passing, they
* should be moved over to the XXTest.
*
* @author Jeanette Winzenburg
*/
public class JXHeaderIssues extends InteractiveTestCase {
/**
* This issue has been fixed, but remains here (otherwise I get a warning
* when running this test. Not sure if this JXHeaderIssues should just be
* removed, or what).
*
* Issue #403-swingx: JXHeader doesn't show custom values.
* <p>
*
* Breaking if values are passed in the constructor.
*/
public void testTitleInContructor() {
String title = "customTitle";
JXHeader header = new JXHeader(title, null);
// sanity: the property is set
assertEquals(title, header.getTitle());
// fishing in the internals ... not really safe, there are 2 labels
JLabel label = null;
for (int i = 0; i < header.getComponentCount(); i++) {
if (header.getComponent(i) instanceof JLabel && !(header.getComponent(i) instanceof JXLabel)) {
label = (JLabel) header.getComponent(i);
break;
}
}
assertEquals("the label's text must be equal to the headers title",
header.getTitle(), label.getText());
}
// ------------------ interactive
/**
* Short description in header produces unexpected line wraps in
* footer.
*
* Note: the frame is not packed to simulate the appframework
* context.
*/
public void interactiveHTMLTextWrapShort() {
JXHeader header = new JXHeader();
header.setTitle("AlbumManager");
String headerLong = "An adaption from JGoodies Binding Tutorial in the context"
+ " of BeansBinding/AppFramework. "
+ "The Tabs show different styles of typical interaction "
+ "setups (in-place editing vs. dialog-editing). ";
String headerShort = "An adaption from JGoodies Binding Tutorial in the context"
+ " of BeansBinding/AppFramework. ";
header.setDescription(headerShort);
header.setIcon(XTestUtils.loadDefaultIcon());
JXHeader footer = new JXHeader();
footer.setTitle("Notes:");
String footerDescription = "<html>"
+ " <ul> "
+ " <li> code: in the jdnc-incubator, section kleopatra, package appframework."
+ " <li> technique: back the view by a shared presentation model "
+ " <li> technique: veto selection change until editing is completed "
+ " <li> issue: selection of tab should be vetoable "
+ " <li> issue: empty selection should disable editing pane "
+ " </ul> " + " </html>";
footer.setDescription(footerDescription);
JComponent panel = new JPanel(new BorderLayout());
panel.add(header, BorderLayout.NORTH);
panel.add(footer, BorderLayout.SOUTH);
JXFrame frame = new JXFrame("html wrapping in SOUTh: short text in NORTH");
frame.add(panel);
frame.setSize(800, 400);
frame.setVisible(true);
}
/**
* Long description in header produces expected line-wrap in footer.
*
* Note: the frame is not packed to simulate the appframework
* context.
*/
public void interactiveHTMLTextWrapLong() {
JXHeader header = new JXHeader();
header.setTitle("AlbumManager");
String headerLong = "An adaption from JGoodies Binding Tutorial in the context"
+ " of BeansBinding/AppFramework. "
+ "The Tabs show different styles of typical interaction "
+ "setups (in-place editing vs. dialog-editing). ";
String headerShort = "An adaption from JGoodies Binding Tutorial in the context"
+ " of BeansBinding/AppFramework. ";
header.setDescription(headerLong);
header.setIcon(XTestUtils.loadDefaultIcon());
JXHeader footer = new JXHeader();
footer.setTitle("Notes:");
String footerDescription = "<html>"
+ " <ul> "
+ " <li> code: in the jdnc-incubator, section kleopatra, package appframework."
+ " <li> technique: back the view by a shared presentation model "
+ " <li> technique: veto selection change until editing is completed "
+ " <li> issue: selection of tab should be vetoable "
+ " <li> issue: empty selection should disable editing pane "
+ " </ul> " + " </html>";
footer.setDescription(footerDescription);
JComponent panel = new JPanel(new BorderLayout());
panel.add(header, BorderLayout.NORTH);
// panel.add(new JScrollPane(table));
panel.add(footer, BorderLayout.SOUTH);
JXFrame frame = new JXFrame("html wrapping in SOUTh: long text in NORTH");
frame.add(panel);
frame.setSize(800, 600);
frame.setVisible(true);
}
/**
* Issue #403-swingx: JXHeader doesn't show custom values.
* <p>
*
* All values are passed in the constructor.
*/
public void interactiveCustomProperties() {
URL url = getClass().getResource("resources/images/wellTop.gif");;
assertNotNull(url);
JPanel p = new JPanel(new BorderLayout());
JXHeader header = new JXHeader("MyTitle", "MyDescription", new ImageIcon(url));
p.add(header);
// added just to better visualize bkg gradient in the JXHeader.
p.add(new JLabel("Reference component"), BorderLayout.SOUTH);
showInFrame(p, "JXHeader with custom properties");
}
/**
* Issue #469-swingx: JXHeader doesn't wrap words in description.<p>
*
* All values are passed in the constructor.
*/
public void interactiveWordWrapping() {
URL url = getClass().getResource("resources/images/wellTop.gif");
assertNotNull(url);
JPanel p = new JPanel(new BorderLayout());
JXHeader header = new JXHeader("MyTitle", "this is a long test with veeeeeeeeeeeeeery looooooong wooooooooooooords", new ImageIcon(url));
p.add(header);
p.setPreferredSize(new Dimension(200,150));
showInFrame(p, "word wrapping JXHeader");
}
public static void main(String args[]) {
JXHeaderIssues test = new JXHeaderIssues();
try {
test.runInteractiveTests();
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
@Override
protected void setUp() throws Exception {
setSystemLF(true);
}
}
| src/test/org/jdesktop/swingx/JXHeaderIssues.java | /*
* $Id$
*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* Test to expose known issues of <code>JXHeader</code>.
* <p>
*
* Ideally, there would be at least one failing test method per open issue in
* the issue tracker. Plus additional failing test methods for not fully
* specified or not yet decided upon features/behaviour.
* <p>
*
* If an issue is fixed and the corresponding methods are passing, they
* should be moved over to the XXTest.
*
* @author Jeanette Winzenburg
*/
public class JXHeaderIssues extends InteractiveTestCase {
/**
* This issue has been fixed, but remains here (otherwise I get a warning
* when running this test. Not sure if this JXHeaderIssues should just be
* removed, or what).
*
* Issue #403-swingx: JXHeader doesn't show custom values.
* <p>
*
* Breaking if values are passed in the constructor.
*/
public void testTitleInContructor() {
String title = "customTitle";
JXHeader header = new JXHeader(title, null);
// sanity: the property is set
assertEquals(title, header.getTitle());
// fishing in the internals ... not really safe, there are 2 labels
JLabel label = null;
for (int i = 0; i < header.getComponentCount(); i++) {
if (header.getComponent(i) instanceof JLabel && !(header.getComponent(i) instanceof JXLabel)) {
label = (JLabel) header.getComponent(i);
break;
}
}
assertEquals("the label's text must be equal to the headers title",
header.getTitle(), label.getText());
}
//------------------ interactive
/**
* Issue #403-swingx: JXHeader doesn't show custom values.<p>
*
* All values are passed in the constructor.
*/
public void interactiveCustomProperties() {
URL url = getClass().getResource("resources/images/wellTop.gif");
assertNotNull(url);
JPanel p = new JPanel(new BorderLayout());
JXHeader header = new JXHeader("MyTitle", "MyDescription", new ImageIcon(url));
p.add(header);
// added just to better visualize bkg gradient in the JXHeader.
p.add(new JLabel("Reference component"), BorderLayout.SOUTH);
showInFrame(p, "JXHeader with custom properties");
}
/**
* Issue #469-swingx: JXHeader doesn't wrap words in description.<p>
*
* All values are passed in the constructor.
*/
public void interactiveWordWrapping() {
URL url = getClass().getResource("resources/images/wellTop.gif");
assertNotNull(url);
JPanel p = new JPanel(new BorderLayout());
JXHeader header = new JXHeader("MyTitle", "this is a long test with veeeeeeeeeeeeeery looooooong wooooooooooooords", new ImageIcon(url));
p.add(header);
p.setPreferredSize(new Dimension(200,150));
showInFrame(p, "word wrapping JXHeader");
}
public static void main(String args[]) {
JXHeaderIssues test = new JXHeaderIssues();
try {
test.runInteractiveTests();
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
}
| JXHeader: added methods to expose unexpected line-wraps
maybe related to #413-swingx?
| src/test/org/jdesktop/swingx/JXHeaderIssues.java | JXHeader: added methods to expose unexpected line-wraps maybe related to #413-swingx? |
|
Java | lgpl-2.1 | 7ad9e99ad771811d241909bc50c33de030c46d0e | 0 | sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror | /*
*
*
* Copyright (C) 2005 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2005 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.search;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* Naive implementation, always return FS directory, do not try to cache or optimize anything,
* recreate if it does not exist
*
*/
public class SimpleIndexSource implements IndexSource {
private File m_indexDirectory;
private boolean m_createDirectory;
private boolean m_createIndex;
private Analyzer m_analyzer;
private int m_maxFieldLength = IndexWriter.DEFAULT_MAX_FIELD_LENGTH;
private int m_minMergeDocs = IndexWriter.DEFAULT_MIN_MERGE_DOCS;
private Directory getDirectory() {
try {
Directory directory = createDirectory(m_indexDirectory, m_createDirectory);
m_createDirectory = false;
return directory;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Overwrite to create different directory
*
* @throws IOException
*/
protected Directory createDirectory(File file, boolean createDirectory) throws IOException {
return FSDirectory.getDirectory(file, createDirectory);
}
public void setIndexDirectoryName(String indexDirectoryName) {
m_indexDirectory = new File(indexDirectoryName);
m_createDirectory = !m_indexDirectory.exists();
m_createIndex = m_createDirectory;
}
public void setAnalyzer(Analyzer analyzer) {
m_analyzer = analyzer;
}
public void setMinMergeDocs(int minMergeDocs) {
m_minMergeDocs = minMergeDocs;
}
public void setMaxFieldLength(int maxFieldLength) {
m_maxFieldLength = maxFieldLength;
}
public void setWriteLockTimeout(long writeLockTimeout) {
IndexWriter.WRITE_LOCK_TIMEOUT = writeLockTimeout;
}
public IndexReader getReader() throws IOException {
ensureIndexExists();
return IndexReader.open(getDirectory());
}
public IndexWriter getWriter(boolean createNew) throws IOException {
IndexWriter writer = new IndexWriter(getDirectory(), m_analyzer, createNew
|| m_createIndex);
writer.maxFieldLength = m_maxFieldLength;
writer.minMergeDocs = m_minMergeDocs;
m_createIndex = false;
return writer;
}
public IndexSearcher getSearcher() throws IOException {
ensureIndexExists();
return new IndexSearcher(getDirectory());
}
private void ensureIndexExists() throws IOException {
if (m_createIndex) {
IndexWriter writer = getWriter(false);
writer.close();
}
}
}
| sipXconfig/neoconf/src/org/sipfoundry/sipxconfig/search/SimpleIndexSource.java | /*
*
*
* Copyright (C) 2005 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2005 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.search;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* Naive implementation, always return FS directory, do not try to cache or optimize anything,
* recreate if it does not exist
*
*/
public class SimpleIndexSource implements IndexSource {
private File m_indexDirectory;
private boolean m_createDirectory;
private boolean m_createIndex;
private Analyzer m_analyzer;
private int m_maxFieldLength = IndexWriter.DEFAULT_MAX_FIELD_LENGTH;
private int m_minMergeDocs = IndexWriter.DEFAULT_MIN_MERGE_DOCS;
private long m_writeLockTimeout = IndexWriter.WRITE_LOCK_TIMEOUT;
private Directory getDirectory() {
try {
Directory directory = createDirectory(m_indexDirectory, m_createDirectory);
m_createDirectory = false;
return directory;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Overwrite to create different directory
*
* @throws IOException
*/
protected Directory createDirectory(File file, boolean createDirectory) throws IOException {
return FSDirectory.getDirectory(file, createDirectory);
}
public void setIndexDirectoryName(String indexDirectoryName) {
m_indexDirectory = new File(indexDirectoryName);
m_createDirectory = !m_indexDirectory.exists();
m_createIndex = m_createDirectory;
}
public void setAnalyzer(Analyzer analyzer) {
m_analyzer = analyzer;
}
public void setMinMergeDocs(int minMergeDocs) {
m_minMergeDocs = minMergeDocs;
}
public void setMaxFieldLength(int maxFieldLength) {
m_maxFieldLength = maxFieldLength;
}
public void setWriteLockTimeout(long writeLockTimeout) {
m_writeLockTimeout = writeLockTimeout;
}
public IndexReader getReader() throws IOException {
ensureIndexExists();
return IndexReader.open(getDirectory());
}
public IndexWriter getWriter(boolean createNew) throws IOException {
IndexWriter writer = new IndexWriter(getDirectory(), m_analyzer, createNew
|| m_createIndex);
writer.maxFieldLength = m_maxFieldLength;
writer.minMergeDocs = m_minMergeDocs;
writer.WRITE_LOCK_TIMEOUT = m_writeLockTimeout;
m_createIndex = false;
return writer;
}
public IndexSearcher getSearcher() throws IOException {
ensureIndexExists();
return new IndexSearcher(getDirectory());
}
private void ensureIndexExists() throws IOException {
if (m_createIndex) {
IndexWriter writer = getWriter(false);
writer.close();
}
}
}
| Fix Eclipse warning: static field access.
git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@5581 a612230a-c5fa-0310-af8b-88eea846685b
| sipXconfig/neoconf/src/org/sipfoundry/sipxconfig/search/SimpleIndexSource.java | Fix Eclipse warning: static field access. |
|
Java | lgpl-2.1 | 75ba4c683390e4fa789455f611b054973f650e42 | 0 | xxv/SimpleContentProvider | package edu.mit.mobile.android.content.example;
import java.util.Random;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class SimpleContentProviderExample extends ListActivity implements OnClickListener {
private ListAdapter mListAdapter;
private static final String[] TITLES = { "Party Rock Anthem", "Give Me Everything",
"Rolling In The Deep", "Last Friday Night (T.G.I.F.)", "Super Bass",
"The Edge Of Glory", "How To Love", "Good Life", "Tonight Tonight", "E.T." };
private static final String[] BODIES = {
"AWESOME!",
"seriously this video was trying WAYYY tooo hard.. it was not at all funny nor amusing, i was getting disgusted by the whole thing.",
"anyone knows whats the name of the remix?", "I enjoy the song though(:",
"what the heck????", "That wuz funny", "i love this video", "best vid eva!!!",
"like kanye west version alot better", "you done an amzing job with the lyrics" };
private final Random mRand = new Random();
/** Called when the activity is first created. */
// the deprecation here is due to the managedQuery() calls. In the latest Android version,
// Loaders should be used.
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getListView().setEmptyView(findViewById(android.R.id.empty));
// The button bar is only needed if there is no action bar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
findViewById(R.id.button_bar).setVisibility(View.GONE);
}
findViewById(R.id.add).setOnClickListener(this);
findViewById(R.id.add_random).setOnClickListener(this);
findViewById(R.id.clear).setOnClickListener(this);
// the column names that data will be loaded from
final String[] from = new String[] { Message.TITLE, Message.BODY };
// the resource IDs that the data will be loaded into
final int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
// the columns to query.
final String[] projection = new String[] { Message._ID, Message.TITLE, Message.BODY };
final String sortOrder = Message.CREATED_DATE + " DESC";
// this makes the actual database query, returning a cursor that can be
// read directly
// or using an Adapter.
final Cursor c = managedQuery(Message.CONTENT_URI, projection, null, null, sortOrder);
// This adapter binds the data from the cursor to the specified view.
// Android provides two simple list views:
// android.R.layout.simple_list_item_2 which has two text views
// and android.R.layout.simple_list_item_1 which has only one
mListAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, from,
to);
// A ListActivity has a simple ListView by default and this tells it
// which adapter to use
setListAdapter(mListAdapter);
registerForContextMenu(getListView());
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// based on the ID provided by the list, reconstruct the message URI
final Uri message = ContentUris.withAppendedId(Message.CONTENT_URI, id);
// Once we have the message URI, one can simply call the VIEW action on it:
final Intent viewMessage = new Intent(Intent.ACTION_VIEW, message);
startActivity(viewMessage);
// Android will see which activity or activities are capable of VIEWing a message
// item by looking through the Manifest to find the right Activity for the given
// content MIME type and action. If more than one activity is found, it will prompt
// the user and ask which Activity they would like to use for this type.
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.item_context, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (final ClassCastException e) {
return false;
}
final Uri itemUri = ContentUris.withAppendedId(Message.CONTENT_URI, info.id);
switch (item.getItemId()) {
case R.id.view:
startActivity(new Intent(Intent.ACTION_VIEW, itemUri));
return true;
case R.id.edit:
startActivity(new Intent(Intent.ACTION_EDIT, itemUri));
return true;
case R.id.delete:
deleteItem(itemUri);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// load the action bar / menu bar
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
createNewItem();
return true;
case R.id.add_random:
addItem();
return true;
case R.id.clear:
clearAllItems();
return true;
case R.id.add_many:
addManyItems();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Starts a new activity to prompt the user with the contents of a new item.
*/
private void createNewItem() {
// the URI must be specified here, so we know what needs have a new item.
startActivity(new Intent(Intent.ACTION_INSERT, Message.CONTENT_URI));
}
/**
* Generates and adds a random item.
*/
private void addItem() {
// place your content inside a ContentValues object.
final ContentValues cv = new ContentValues();
cv.put(Message.TITLE, TITLES[mRand.nextInt(TITLES.length)]);
cv.put(Message.BODY, BODIES[mRand.nextInt(BODIES.length)]);
// the URI of the newly created item is returned. Feel free to do whatever
// you wish with this URI, as this is the public interface to the content.
final Uri newItem = getContentResolver().insert(Message.CONTENT_URI, cv);
if (newItem == null) {
Toast.makeText(this, "Error inserting item. insert() returned null", Toast.LENGTH_LONG)
.show();
}
}
/**
* Adds a bunch of items to the database. This interactively demonstrates the use of
* {@link ContentResolver#bulkInsert(Uri, ContentValues[])}.
*/
private void addManyItems() {
final int total = 100;
final ContentValues manyCv[] = new ContentValues[total];
for (int i = 0; i < total; i++) {
// place your content inside a ContentValues object.
final ContentValues cv = new ContentValues();
cv.put(Message.TITLE, TITLES[mRand.nextInt(TITLES.length)]);
cv.put(Message.BODY, BODIES[mRand.nextInt(BODIES.length)]);
manyCv[i] = cv;
}
final int count = getContentResolver().bulkInsert(Message.CONTENT_URI, manyCv);
Toast.makeText(this, count + " items added", Toast.LENGTH_SHORT).show();
}
/**
* Deletes the selected item from the database.
*/
private void deleteItem(Uri item) {
// the second two arguments are null here, as the row is specified using the URI
final int count = getContentResolver().delete(item, null, null);
Toast.makeText(this, count + " rows deleted", Toast.LENGTH_SHORT).show();
}
/**
* Deletes all the items from the database.
*/
private void clearAllItems() {
// Specify the dir URI, along with null in the where and selectionArgs
// to delete everything.
deleteItem(Message.CONTENT_URI);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
createNewItem();
break;
case R.id.add_random:
addItem();
break;
case R.id.clear:
clearAllItems();
break;
}
}
} | example/src/edu/mit/mobile/android/content/example/SimpleContentProviderExample.java | package edu.mit.mobile.android.content.example;
import java.util.Random;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class SimpleContentProviderExample extends ListActivity implements OnClickListener {
private ListAdapter mListAdapter;
private static final String[] TITLES = { "Party Rock Anthem", "Give Me Everything",
"Rolling In The Deep", "Last Friday Night (T.G.I.F.)", "Super Bass",
"The Edge Of Glory", "How To Love", "Good Life", "Tonight Tonight", "E.T." };
private static final String[] BODIES = {
"AWESOME!",
"seriously this video was trying WAYYY tooo hard.. it was not at all funny nor amusing, i was getting disgusted by the whole thing.",
"anyone knows whats the name of the remix?", "I enjoy the song though(:",
"what the heck????", "That wuz funny", "i love this video", "best vid eva!!!",
"like kanye west version alot better", "you done an amzing job with the lyrics" };
private final Random mRand = new Random();
/** Called when the activity is first created. */
// the deprecation here is due to the managedQuery() calls. In the latest Android version,
// Loaders should be used.
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getListView().setEmptyView(findViewById(android.R.id.empty));
// The button bar is only needed if there is no action bar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
findViewById(R.id.button_bar).setVisibility(View.GONE);
}
findViewById(R.id.add).setOnClickListener(this);
findViewById(R.id.add_random).setOnClickListener(this);
findViewById(R.id.clear).setOnClickListener(this);
// the column names that data will be loaded from
final String[] from = new String[] { Message.TITLE, Message.BODY };
// the resource IDs that the data will be loaded into
final int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
// the columns to query.
final String[] projection = new String[] { Message._ID, Message.TITLE, Message.BODY };
final String sortOrder = Message.CREATED_DATE + " DESC";
// this makes the actual database query, returning a cursor that can be
// read directly
// or using an Adapter.
final Cursor c = managedQuery(Message.CONTENT_URI, projection, null, null, sortOrder);
// This adapter binds the data from the cursor to the specified view.
// Android provides two simple list views:
// android.R.layout.simple_list_item_2 which has two text views
// and android.R.layout.simple_list_item_1 which has only one
mListAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, from,
to);
// A ListActivity has a simple ListView by default and this tells it
// which adapter to use
setListAdapter(mListAdapter);
registerForContextMenu(getListView());
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// based on the ID provided by the list, reconstruct the message URI
final Uri message = ContentUris.withAppendedId(Message.CONTENT_URI, id);
// Once we have the message URI, one can simply call the VIEW action on it:
final Intent viewMessage = new Intent(Intent.ACTION_VIEW, message);
startActivity(viewMessage);
// Android will see which activit(y|ies) are capable of VIEWing a message
// item by looking through the Manifest to find the right Activity for the given
// content MIME type and action. If more than one activity is found, it will prompt
// the user and ask which Activity they would like to use for this type.
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.item_context, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (final ClassCastException e) {
return false;
}
final Uri itemUri = ContentUris.withAppendedId(Message.CONTENT_URI, info.id);
switch (item.getItemId()) {
case R.id.view:
startActivity(new Intent(Intent.ACTION_VIEW, itemUri));
return true;
case R.id.edit:
startActivity(new Intent(Intent.ACTION_EDIT, itemUri));
return true;
case R.id.delete:
deleteItem(itemUri);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// load the action bar / menu bar
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
createNewItem();
return true;
case R.id.add_random:
addItem();
return true;
case R.id.clear:
clearAllItems();
return true;
case R.id.add_many:
addManyItems();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Starts a new activity to prompt the user with the contents of a new item.
*/
private void createNewItem() {
// the URI must be specified here, so we know what needs have a new item.
startActivity(new Intent(Intent.ACTION_INSERT, Message.CONTENT_URI));
}
/**
* Generates and adds a random item.
*/
private void addItem() {
// place your content inside a ContentValues object.
final ContentValues cv = new ContentValues();
cv.put(Message.TITLE, TITLES[mRand.nextInt(TITLES.length)]);
cv.put(Message.BODY, BODIES[mRand.nextInt(BODIES.length)]);
// the URI of the newly created item is returned. Feel free to do whatever
// you wish with this URI, as this is the public interface to the content.
final Uri newItem = getContentResolver().insert(Message.CONTENT_URI, cv);
if (newItem == null) {
Toast.makeText(this, "Error inserting item. insert() returned null", Toast.LENGTH_LONG)
.show();
}
}
private void addManyItems() {
final int total = 100;
final ContentValues manyCv[] = new ContentValues[total];
for (int i = 0; i < total; i++) {
// place your content inside a ContentValues object.
final ContentValues cv = new ContentValues();
cv.put(Message.TITLE, TITLES[mRand.nextInt(TITLES.length)]);
cv.put(Message.BODY, BODIES[mRand.nextInt(BODIES.length)]);
manyCv[i] = cv;
}
final int count = getContentResolver().bulkInsert(Message.CONTENT_URI, manyCv);
Toast.makeText(this, count + " items added", Toast.LENGTH_SHORT).show();
}
/**
* Deletes all the items from the database.
*/
private void deleteItem(Uri item) {
// the second two arguments are null here, as the row is specified using the URI
final int count = getContentResolver().delete(item, null, null);
Toast.makeText(this, count + " rows deleted", Toast.LENGTH_SHORT).show();
}
/**
* Deletes all the items from the database.
*/
private void clearAllItems() {
// delete() with null in the where and selectionArgs parameters will
// delete all the content.
deleteItem(Message.CONTENT_URI);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
createNewItem();
break;
case R.id.add_random:
addItem();
break;
case R.id.clear:
clearAllItems();
break;
}
}
} | Improves main activity documentation
| example/src/edu/mit/mobile/android/content/example/SimpleContentProviderExample.java | Improves main activity documentation |
|
Java | apache-2.0 | c97a18ad13951b055e8cb13040a135b4fa30c409 | 0 | apache/commons-math,apache/commons-math,sdinot/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus,sdinot/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,sdinot/hipparchus,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus | /*
* 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.
*/
/**
* This package provides algorithms that minimize the residuals
* between observations and model values.
* The {@link org.apache.commons.math3.fitting.leastsquares.AbstractLeastSquaresOptimizer
* non-linear least-squares optimizers} minimize the distance (called
* <em>cost</em> or <em>χ<sup>2</sup></em>) between model and
* observations.
*
* <br/>
* Algorithms in this category need access to a <em>model function</em>
* (represented by a {@link org.apache.commons.math3.analysis.MultivariateVectorFunction
* MultivariateVectorFunction}).
* Such a model predicts a set of values which the algorithm tries to match
* with a set of given set of {@link org.apache.commons.math3.fitting.leastsquares.WithTarget
* observed values}.
* <br/>
* The algorithms implemented in this package also require that the user
* specifies the Jacobian matrix of the model (represented by a
* {@link org.apache.commons.math3.analysis.MultivariateMatrixFunction
* MultivariateMatrixFunction}).
*/
package org.apache.commons.math3.fitting.leastsquares;
| src/main/java/org/apache/commons/math3/fitting/leastsquares/package-info.java | /*
* 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.
*/
/**
* This package provides algorithms that minimize the residuals
* between observations and model values.
* The {@link org.apache.commons.math3.fitting.leastsquares.AbstractLeastSquaresOptimizer
* non-linear least-squares optimizers} minimize the distance (called <em>cost</em> or
* <em>χ<sup>2</sup></em>) between model and observations.
*
* <br/>
* Algorithms in this category need access to a <em>model function</em>
* (represented by a {@link org.apache.commons.math3.analysis.MultivariateVectorFunction
* MultivariateVectorFunction}).
* Such a model predicts a set of values which the algorithm tries to match with a set
* of given set of {@link WithTarget observed values}.
* <br/>
* The algorithms implemented in this package also require that the user specifies the
* Jacobian matrix of the model (represented by a
* {@link org.apache.commons.math3.analysis.MultivariateMatrixFunction
* MultivariateMatrixFunction}).
*/
package org.apache.commons.math3.fitting.leastsquares;
| Javadoc.
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1509235 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/math3/fitting/leastsquares/package-info.java | Javadoc. |
|
Java | apache-2.0 | c94ea1c4d1dcec3bdd2aefcbf073873b458adf9b | 0 | saki4510t/libcommon,saki4510t/libcommon | package com.serenegiant.mediastore;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2019 saki [email protected]
*
* 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.
*/
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.TextView;
import com.serenegiant.common.R;
import com.serenegiant.utils.ThreadPool;
import java.io.IOException;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import static com.serenegiant.mediastore.MediaStoreUtils.*;
/**
* MediaStoreの静止画・動画一覧をRecyclerViewで表示するためのRecyclerView.Adapter実装
* 実データではなくサムネイルを表示する
* MediaStoreAdapterのRecyclerView.Adapter版
*/
public class MediaStoreRecyclerAdapter
extends RecyclerView.Adapter<MediaStoreRecyclerAdapter.ViewHolder> {
private static final boolean DEBUG = false; // FIXME 実働時はfalseにすること
private static final String TAG = MediaStoreRecyclerAdapter.class.getSimpleName();
/**
* MediaStoreRecyclerAdapterでアイテムを選択したときのコールバックリスナー
*/
public interface MediaStoreRecyclerAdapterListener {
/**
* アイテムをクリックした
* @param parent
* @param view
* @param item
*/
public void onItemClick(@NonNull RecyclerView.Adapter<?> parent,
@NonNull View view, @NonNull final MediaInfo item);
/**
* アイテムを長押しした
* @param parent
* @param view
* @param item
* @return
*/
public boolean onItemLongClick(@NonNull RecyclerView.Adapter<?> parent,
@NonNull View view, @NonNull final MediaInfo item);
}
private final LayoutInflater mInflater;
private final int mLayoutId;
private final ContentResolver mCr;
private final MyAsyncQueryHandler mQueryHandler;
private final ThumbnailCache mThumbnailCache;
private final int mGroupId = hashCode();
private final MediaInfo info = new MediaInfo();
private final Handler mUIHandler = new Handler(Looper.getMainLooper());
private boolean mDataValid;
// private int mRowIDColumn;
private ChangeObserver mChangeObserver;
private DataSetObserver mDataSetObserver;
private Cursor mCursor;
private String mSelection;
private String[] mSelectionArgs = null;
private String mSortOrder = null;
@Nullable
private RecyclerView mRecycleView;
@Nullable
private MediaStoreRecyclerAdapterListener mListener;
private boolean mShowTitle = false;
private int mMediaType = MEDIA_ALL;
private int mThumbnailWidth = 200, mThumbnailHeight = 200;
/**
* コンストラクタ
* @param context
* @param itemLayout
*/
public MediaStoreRecyclerAdapter(@NonNull final Context context,
@LayoutRes final int itemLayout) {
super();
if (DEBUG) Log.v(TAG, "コンストラクタ:");
mInflater = LayoutInflater.from(context);
mLayoutId = itemLayout;
mCr = context.getContentResolver();
mQueryHandler = new MyAsyncQueryHandler(mCr, this);
mThumbnailCache = new ThumbnailCache(context);
ThreadPool.preStartAllCoreThreads();
refresh();
}
@Override
protected void finalize() throws Throwable {
try {
changeCursor(null);
} finally {
super.finalize();
}
}
@Override
public void onAttachedToRecyclerView(@NonNull final RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
if (DEBUG) Log.v(TAG, "onAttachedToRecyclerView:");
mRecycleView = recyclerView;
}
@Override
public void onDetachedFromRecyclerView(@NonNull final RecyclerView recyclerView) {
if (DEBUG) Log.v(TAG, "onDetachedFromRecyclerView:");
mRecycleView = null;
super.onDetachedFromRecyclerView(recyclerView);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
final View view = mInflater.inflate(mLayoutId, parent, false);
view.setOnClickListener(mOnClickListener);
view.setOnLongClickListener(mOnLongClickListener);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
setInfo(holder, getMediaInfo(position, info));
}
@Override
public int getItemCount() {
if (mDataValid && mCursor != null) {
return mCursor.getCount();
} else {
return 0;
}
}
/**
* 指定したpositionにあるデータを保持したMediaInfoを取得する
* @param position
* @return
*/
@NonNull
public MediaInfo getItem(final int position) {
return getMediaInfo(position, null);
}
//--------------------------------------------------------------------------------
public void setListener(final MediaStoreRecyclerAdapterListener listener) {
if (DEBUG) Log.v(TAG, "setListener:" + listener);
mListener = listener;
}
public void notifyDataSetInvalidated() {
if (DEBUG) Log.v(TAG, "notifyDataSetInvalidated:");
// mDataSetObservable.notifyInvalidated();
}
public void refresh() {
if (DEBUG) Log.v(TAG, "refresh:");
mQueryHandler.requery();
}
/**
* サムネイルのサイズを設定
* 0を指定したときは96x96(MediaStore.Images.Thumbnails.MICRO_KIND)になる
* @param size
*/
public void setThumbnailSize(final int size) {
setThumbnailSize(size, size);
}
/**
* サムネイルのサイズを設定
* 0を指定したときは96x96(MediaStore.Images.Thumbnails.MICRO_KIND)になる
* @param width
* @param height
*/
public void setThumbnailSize(final int width, final int height) {
if (DEBUG) Log.v(TAG, String.format("setThumbnailSize:(%dx%d)", width, height));
if ((mThumbnailWidth != width) || (mThumbnailHeight != height)) {
mThumbnailWidth = width;
mThumbnailHeight = height;
mThumbnailCache.clear(mGroupId);
onContentChanged();
}
}
/**
* タイトルを表示するかどうかを設定
* @param showTitle
*/
public void setShowTitle(final boolean showTitle) {
if (DEBUG) Log.v(TAG, "setShowTitle:" + showTitle);
if (mShowTitle != showTitle) {
mShowTitle = showTitle;
onContentChanged();
}
}
/**
* タイトルを表示するかどうかを取得
* @return
*/
public boolean getShowTitle() {
return mShowTitle;
}
/**
* 表示するメディ他の種類を取得
* @return
*/
public int getMediaType() {
return mMediaType % MEDIA_TYPE_NUM;
}
/**
* 表示するメディアの種類を設定
* @param media_type
*/
public void setMediaType(final int media_type) {
if (mMediaType != (media_type % MEDIA_TYPE_NUM)) {
mMediaType = media_type % MEDIA_TYPE_NUM;
onContentChanged();
}
}
//--------------------------------------------------------------------------------
@NonNull
private synchronized MediaInfo getMediaInfo(
final int position, @Nullable final MediaInfo info) {
final MediaInfo _info = info != null ? info : new MediaInfo();
if (mCursor == null) {
mCursor = mCr.query(
QUERY_URI, PROJ_MEDIA,
mSelection, mSelectionArgs, mSortOrder);
}
if (mCursor.moveToPosition(position)) {
_info.loadFromCursor(mCursor);
}
return _info;
}
protected void onContentChanged() {
mQueryHandler.requery();
}
protected void changeCursor(@Nullable final Cursor cursor) {
if (DEBUG) Log.v(TAG, "changeCursor:" + cursor);
final Cursor old = swapCursor(cursor);
if ((old != null) && !old.isClosed()) {
old.close();
}
}
/**
* 指定したpositionを示すCursorら返す
* @param position
* @return
*/
@Nullable
protected Cursor getCursor(final int position) {
if (mDataValid && mCursor != null) {
mCursor.moveToPosition(position);
return mCursor;
} else {
return null;
}
}
/**
* カーソルを交換
* @param newCursor
* @return
*/
protected Cursor swapCursor(final Cursor newCursor) {
if (DEBUG) Log.v(TAG, "swapCursor:" + newCursor);
if (newCursor == mCursor) {
return null;
}
Cursor oldCursor = mCursor;
if (oldCursor != null) {
if (mChangeObserver != null) {
oldCursor.unregisterContentObserver(mChangeObserver);
}
if (mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
}
mCursor = newCursor;
if (newCursor != null) {
if (mChangeObserver != null) {
newCursor.registerContentObserver(mChangeObserver);
}
if (mDataSetObserver != null) {
newCursor.registerDataSetObserver(mDataSetObserver);
}
// mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
// notify the observers about the new cursor
notifyDataSetChanged();
} else {
// mRowIDColumn = -1;
mDataValid = false;
// notify the observers about the lack of a data set
notifyDataSetInvalidated();
}
return oldCursor;
}
/**
* ContentResolverへ非同期で問い合わせを行うためのAsyncQueryHandler実装
*/
private static final class MyAsyncQueryHandler extends AsyncQueryHandler {
@NonNull
private final MediaStoreRecyclerAdapter mAdapter;
/**
* コンストラクタ
* @param cr
* @param adapter
*/
public MyAsyncQueryHandler(
@NonNull final ContentResolver cr,
@NonNull final MediaStoreRecyclerAdapter adapter) {
super(cr);
if (DEBUG) Log.v(TAG, "MyAsyncQueryHandler:");
mAdapter = adapter;
}
public void requery() {
synchronized (mAdapter) {
if (mAdapter.mCursor != null) {
mAdapter.mCursor.close();
mAdapter.mCursor = null;
}
mAdapter.mSelection = SELECTIONS[mAdapter.mMediaType % MEDIA_TYPE_NUM];
mAdapter.mSelectionArgs = null;
startQuery(0, mAdapter, QUERY_URI, PROJ_MEDIA,
mAdapter.mSelection, mAdapter.mSelectionArgs, mAdapter.mSortOrder);
}
}
@Override
protected void onQueryComplete(final int token,
final Object cookie, final Cursor cursor) {
super.onQueryComplete(token, cookie, cursor); // this is empty method
if (DEBUG) Log.v(TAG, "MyAsyncQueryHandler#onQueryComplete:");
final Cursor oldCursor = mAdapter.swapCursor(cursor);
if ((oldCursor != null) && !oldCursor.isClosed())
oldCursor.close();
}
} // MyAsyncQueryHandler
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(mUIHandler);
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
refresh();
}
}
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
mDataValid = true;
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
mDataValid = false;
notifyDataSetInvalidated();
}
}
protected final View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (DEBUG) Log.v(TAG, "onClick:" + v);
if ((mRecycleView != null) && mRecycleView.isEnabled()) {
if (v instanceof Checkable) {
((Checkable)v).setChecked(true);
mUIHandler.postDelayed(new Runnable() {
@Override
public void run() {
((Checkable)v).setChecked(false);
}
}, 100);
}
if (mListener != null) {
final MediaInfo info = (MediaInfo) v.getTag(R.id.info);
if (info != null) {
try {
mListener.onItemClick(
MediaStoreRecyclerAdapter.this, v, info);
} catch (final Exception e) {
Log.w(TAG, e);
}
} else if (DEBUG) {
Log.d(TAG, "MediaInfo not attached!");
}
}
} else {
Log.w(TAG, "onClick:mRecycleView=" + mRecycleView);
}
}
};
protected final View.OnLongClickListener mOnLongClickListener
= new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
if (DEBUG) Log.v(TAG, "onLongClick:" + v);
if (((mRecycleView != null) && mRecycleView.isEnabled())
&& (mListener != null)) {
final MediaInfo info = (MediaInfo) v.getTag(R.id.info);
if (info != null) {
try {
return mListener.onItemLongClick(
MediaStoreRecyclerAdapter.this, v, info);
} catch (final Exception e) {
Log.w(TAG, e);
}
}
}
return false;
}
};
//--------------------------------------------------------------------------------
/**
* サムネイルを非同期で取得するためのDrawable
*/
private class ThumbnailLoaderDrawable extends LoaderDrawable {
public ThumbnailLoaderDrawable(final ContentResolver cr,
final int width, final int height) {
super(cr, width, height);
}
@Override
protected ImageLoader createImageLoader() {
return new ThumbnailLoader(this);
}
@Override
protected Bitmap checkCache(final int groupId, final long id) {
return mThumbnailCache.get(groupId, id);
}
}
/**
* ThumbnailLoaderDrawableのための非同期読み込みヘルパークラス
*/
private class ThumbnailLoader extends ImageLoader {
public ThumbnailLoader(final ThumbnailLoaderDrawable parent) {
super(parent);
}
@Override
protected Bitmap loadBitmap(@NonNull final ContentResolver cr,
final int mediaType, final int groupId, final long id,
final int requestWidth, final int requestHeight) {
Bitmap result = null;
try {
switch (mediaType) {
case MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE:
result = mThumbnailCache.getImageThumbnail(cr,
groupId, id, requestWidth, requestHeight);
break;
case MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO:
result = mThumbnailCache.getVideoThumbnail(cr,
groupId, id, requestWidth, requestHeight);
break;
}
} catch (final IOException e) {
Log.w(TAG, e);
}
return result;
}
}
//--------------------------------------------------------------------------------
private void setInfo(@NonNull final ViewHolder holder,
final MediaInfo info) {
// if (DEBUG) Log.v(TAG, "setInfo:" + info);
holder.info = info;
holder.itemView.setTag(R.id.info, info);
// ローカルキャッシュ
final ImageView iv = holder.mImageView;
final TextView tv = holder.mTitleView;
if (iv != null) {
Drawable drawable = iv.getDrawable();
if (!(drawable instanceof LoaderDrawable)) {
drawable = new ThumbnailLoaderDrawable(mCr, mThumbnailWidth, mThumbnailHeight);
iv.setImageDrawable(drawable);
}
((LoaderDrawable)drawable).startLoad(
mCursor.getInt(PROJ_INDEX_MEDIA_TYPE), mGroupId, mCursor.getLong(PROJ_INDEX_ID));
}
if (tv != null) {
tv.setVisibility(mShowTitle ? View.VISIBLE : View.GONE);
if (mShowTitle) {
tv.setText(info.title);
}
}
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTitleView;
private ImageView mImageView;
private MediaInfo info;
public ViewHolder(@NonNull final View v) {
super(v);
if (v instanceof TextView) {
mTitleView = (TextView)v;
mImageView = null;
} else if (v instanceof ImageView) {
mTitleView = null;
mImageView = (ImageView)v;
} else {
mTitleView = v.findViewById(R.id.title);
mImageView = v.findViewById(R.id.thumbnail);
}
}
}
}
| common/src/main/java/com/serenegiant/mediastore/MediaStoreRecyclerAdapter.java | package com.serenegiant.mediastore;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2019 saki [email protected]
*
* 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.
*/
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.TextView;
import com.serenegiant.common.R;
import com.serenegiant.utils.ThreadPool;
import java.io.IOException;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import static com.serenegiant.mediastore.MediaStoreUtils.*;
/**
* MediaStoreの静止画・動画一覧をRecyclerViewで表示するためのRecyclerView.Adapter実装
* 実データではなくサムネイルを表示する
* MediaStoreAdapterのRecyclerView.Adapter版
*/
public class MediaStoreRecyclerAdapter
extends RecyclerView.Adapter<MediaStoreRecyclerAdapter.ViewHolder> {
private static final boolean DEBUG = false; // FIXME 実働時はfalseにすること
private static final String TAG = MediaStoreRecyclerAdapter.class.getSimpleName();
/**
* MediaStoreRecyclerAdapterでアイテムを選択したときのコールバックリスナー
*/
public interface MediaStoreRecyclerAdapterListener {
/**
* アイテムをクリックした
* @param parent
* @param view
* @param item
*/
public void onItemClick(@NonNull RecyclerView.Adapter<?> parent,
@NonNull View view, @NonNull final MediaInfo item);
/**
* アイテムを長押しした
* @param parent
* @param view
* @param item
* @return
*/
public boolean onItemLongClick(@NonNull RecyclerView.Adapter<?> parent,
@NonNull View view, @NonNull final MediaInfo item);
}
private final LayoutInflater mInflater;
private final int mLayoutId;
private final ContentResolver mCr;
private final MyAsyncQueryHandler mQueryHandler;
private final ThumbnailCache mThumbnailCache;
private final int mGroupId = hashCode();
private final MediaInfo info = new MediaInfo();
private final Handler mUIHandler = new Handler(Looper.getMainLooper());
private boolean mDataValid;
// private int mRowIDColumn;
private ChangeObserver mChangeObserver;
private DataSetObserver mDataSetObserver;
private Cursor mCursor;
private String mSelection;
private String[] mSelectionArgs = null;
@Nullable
private RecyclerView mRecycleView;
@Nullable
private MediaStoreRecyclerAdapterListener mListener;
private boolean mShowTitle = false;
private int mMediaType = MEDIA_ALL;
private int mThumbnailWidth = 200, mThumbnailHeight = 200;
/**
* コンストラクタ
* @param context
* @param itemLayout
*/
public MediaStoreRecyclerAdapter(@NonNull final Context context,
@LayoutRes final int itemLayout) {
super();
if (DEBUG) Log.v(TAG, "コンストラクタ:");
mInflater = LayoutInflater.from(context);
mLayoutId = itemLayout;
mCr = context.getContentResolver();
mQueryHandler = new MyAsyncQueryHandler(mCr, this);
mThumbnailCache = new ThumbnailCache(context);
ThreadPool.preStartAllCoreThreads();
refresh();
}
@Override
protected void finalize() throws Throwable {
try {
changeCursor(null);
} finally {
super.finalize();
}
}
@Override
public void onAttachedToRecyclerView(@NonNull final RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
if (DEBUG) Log.v(TAG, "onAttachedToRecyclerView:");
mRecycleView = recyclerView;
}
@Override
public void onDetachedFromRecyclerView(@NonNull final RecyclerView recyclerView) {
if (DEBUG) Log.v(TAG, "onDetachedFromRecyclerView:");
mRecycleView = null;
super.onDetachedFromRecyclerView(recyclerView);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
final View view = mInflater.inflate(mLayoutId, parent, false);
view.setOnClickListener(mOnClickListener);
view.setOnLongClickListener(mOnLongClickListener);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
setInfo(holder, getMediaInfo(position, info));
}
@Override
public int getItemCount() {
if (mDataValid && mCursor != null) {
return mCursor.getCount();
} else {
return 0;
}
}
/**
* 指定したpositionにあるデータを保持したMediaInfoを取得する
* @param position
* @return
*/
@NonNull
public MediaInfo getItem(final int position) {
return getMediaInfo(position, null);
}
//--------------------------------------------------------------------------------
public void setListener(final MediaStoreRecyclerAdapterListener listener) {
if (DEBUG) Log.v(TAG, "setListener:" + listener);
mListener = listener;
}
public void notifyDataSetInvalidated() {
if (DEBUG) Log.v(TAG, "notifyDataSetInvalidated:");
// mDataSetObservable.notifyInvalidated();
}
public void refresh() {
if (DEBUG) Log.v(TAG, "refresh:");
mQueryHandler.requery();
}
/**
* サムネイルのサイズを設定
* 0を指定したときは96x96(MediaStore.Images.Thumbnails.MICRO_KIND)になる
* @param size
*/
public void setThumbnailSize(final int size) {
setThumbnailSize(size, size);
}
/**
* サムネイルのサイズを設定
* 0を指定したときは96x96(MediaStore.Images.Thumbnails.MICRO_KIND)になる
* @param width
* @param height
*/
public void setThumbnailSize(final int width, final int height) {
if (DEBUG) Log.v(TAG, String.format("setThumbnailSize:(%dx%d)", width, height));
if ((mThumbnailWidth != width) || (mThumbnailHeight != height)) {
mThumbnailWidth = width;
mThumbnailHeight = height;
mThumbnailCache.clear(mGroupId);
onContentChanged();
}
}
/**
* タイトルを表示するかどうかを設定
* @param showTitle
*/
public void setShowTitle(final boolean showTitle) {
if (DEBUG) Log.v(TAG, "setShowTitle:" + showTitle);
if (mShowTitle != showTitle) {
mShowTitle = showTitle;
onContentChanged();
}
}
/**
* タイトルを表示するかどうかを取得
* @return
*/
public boolean getShowTitle() {
return mShowTitle;
}
/**
* 表示するメディ他の種類を取得
* @return
*/
public int getMediaType() {
return mMediaType % MEDIA_TYPE_NUM;
}
/**
* 表示するメディアの種類を設定
* @param media_type
*/
public void setMediaType(final int media_type) {
if (mMediaType != (media_type % MEDIA_TYPE_NUM)) {
mMediaType = media_type % MEDIA_TYPE_NUM;
onContentChanged();
}
}
//--------------------------------------------------------------------------------
@NonNull
private synchronized MediaInfo getMediaInfo(
final int position, @Nullable final MediaInfo info) {
final MediaInfo _info = info != null ? info : new MediaInfo();
if (mCursor == null) {
mCursor = mCr.query(
QUERY_URI, PROJ_MEDIA,
mSelection, mSelectionArgs, null);
}
if (mCursor.moveToPosition(position)) {
_info.loadFromCursor(mCursor);
}
return _info;
}
protected void onContentChanged() {
mQueryHandler.requery();
}
protected void changeCursor(@Nullable final Cursor cursor) {
if (DEBUG) Log.v(TAG, "changeCursor:" + cursor);
final Cursor old = swapCursor(cursor);
if ((old != null) && !old.isClosed()) {
old.close();
}
}
/**
* 指定したpositionを示すCursorら返す
* @param position
* @return
*/
@Nullable
protected Cursor getCursor(final int position) {
if (mDataValid && mCursor != null) {
mCursor.moveToPosition(position);
return mCursor;
} else {
return null;
}
}
/**
* カーソルを交換
* @param newCursor
* @return
*/
protected Cursor swapCursor(final Cursor newCursor) {
if (DEBUG) Log.v(TAG, "swapCursor:" + newCursor);
if (newCursor == mCursor) {
return null;
}
Cursor oldCursor = mCursor;
if (oldCursor != null) {
if (mChangeObserver != null) {
oldCursor.unregisterContentObserver(mChangeObserver);
}
if (mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
}
mCursor = newCursor;
if (newCursor != null) {
if (mChangeObserver != null) {
newCursor.registerContentObserver(mChangeObserver);
}
if (mDataSetObserver != null) {
newCursor.registerDataSetObserver(mDataSetObserver);
}
// mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
// notify the observers about the new cursor
notifyDataSetChanged();
} else {
// mRowIDColumn = -1;
mDataValid = false;
// notify the observers about the lack of a data set
notifyDataSetInvalidated();
}
return oldCursor;
}
/**
* ContentResolverへ非同期で問い合わせを行うためのAsyncQueryHandler実装
*/
private static final class MyAsyncQueryHandler extends AsyncQueryHandler {
@NonNull
private final MediaStoreRecyclerAdapter mAdapter;
/**
* コンストラクタ
* @param cr
* @param adapter
*/
public MyAsyncQueryHandler(
@NonNull final ContentResolver cr,
@NonNull final MediaStoreRecyclerAdapter adapter) {
super(cr);
if (DEBUG) Log.v(TAG, "MyAsyncQueryHandler:");
mAdapter = adapter;
}
public void requery() {
synchronized (mAdapter) {
if (mAdapter.mCursor != null) {
mAdapter.mCursor.close();
mAdapter.mCursor = null;
}
mAdapter.mSelection = SELECTIONS[mAdapter.mMediaType % MEDIA_TYPE_NUM];
mAdapter.mSelectionArgs = null;
startQuery(0, mAdapter, QUERY_URI, PROJ_MEDIA,
mAdapter.mSelection, mAdapter.mSelectionArgs, null);
}
}
@Override
protected void onQueryComplete(final int token,
final Object cookie, final Cursor cursor) {
super.onQueryComplete(token, cookie, cursor); // this is empty method
if (DEBUG) Log.v(TAG, "MyAsyncQueryHandler#onQueryComplete:");
final Cursor oldCursor = mAdapter.swapCursor(cursor);
if ((oldCursor != null) && !oldCursor.isClosed())
oldCursor.close();
}
} // MyAsyncQueryHandler
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(mUIHandler);
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
refresh();
}
}
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
mDataValid = true;
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
mDataValid = false;
notifyDataSetInvalidated();
}
}
protected final View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (DEBUG) Log.v(TAG, "onClick:" + v);
if ((mRecycleView != null) && mRecycleView.isEnabled()) {
if (v instanceof Checkable) {
((Checkable)v).setChecked(true);
mUIHandler.postDelayed(new Runnable() {
@Override
public void run() {
((Checkable)v).setChecked(false);
}
}, 100);
}
if (mListener != null) {
final MediaInfo info = (MediaInfo) v.getTag(R.id.info);
if (info != null) {
try {
mListener.onItemClick(
MediaStoreRecyclerAdapter.this, v, info);
} catch (final Exception e) {
Log.w(TAG, e);
}
} else if (DEBUG) {
Log.d(TAG, "MediaInfo not attached!");
}
}
} else {
Log.w(TAG, "onClick:mRecycleView=" + mRecycleView);
}
}
};
protected final View.OnLongClickListener mOnLongClickListener
= new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
if (DEBUG) Log.v(TAG, "onLongClick:" + v);
if (((mRecycleView != null) && mRecycleView.isEnabled())
&& (mListener != null)) {
final MediaInfo info = (MediaInfo) v.getTag(R.id.info);
if (info != null) {
try {
return mListener.onItemLongClick(
MediaStoreRecyclerAdapter.this, v, info);
} catch (final Exception e) {
Log.w(TAG, e);
}
}
}
return false;
}
};
//--------------------------------------------------------------------------------
/**
* サムネイルを非同期で取得するためのDrawable
*/
private class ThumbnailLoaderDrawable extends LoaderDrawable {
public ThumbnailLoaderDrawable(final ContentResolver cr,
final int width, final int height) {
super(cr, width, height);
}
@Override
protected ImageLoader createImageLoader() {
return new ThumbnailLoader(this);
}
@Override
protected Bitmap checkCache(final int groupId, final long id) {
return mThumbnailCache.get(groupId, id);
}
}
/**
* ThumbnailLoaderDrawableのための非同期読み込みヘルパークラス
*/
private class ThumbnailLoader extends ImageLoader {
public ThumbnailLoader(final ThumbnailLoaderDrawable parent) {
super(parent);
}
@Override
protected Bitmap loadBitmap(@NonNull final ContentResolver cr,
final int mediaType, final int groupId, final long id,
final int requestWidth, final int requestHeight) {
Bitmap result = null;
try {
switch (mediaType) {
case MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE:
result = mThumbnailCache.getImageThumbnail(cr,
groupId, id, requestWidth, requestHeight);
break;
case MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO:
result = mThumbnailCache.getVideoThumbnail(cr,
groupId, id, requestWidth, requestHeight);
break;
}
} catch (final IOException e) {
Log.w(TAG, e);
}
return result;
}
}
//--------------------------------------------------------------------------------
private void setInfo(@NonNull final ViewHolder holder,
final MediaInfo info) {
// if (DEBUG) Log.v(TAG, "setInfo:" + info);
holder.info = info;
holder.itemView.setTag(R.id.info, info);
// ローカルキャッシュ
final ImageView iv = holder.mImageView;
final TextView tv = holder.mTitleView;
if (iv != null) {
Drawable drawable = iv.getDrawable();
if (!(drawable instanceof LoaderDrawable)) {
drawable = new ThumbnailLoaderDrawable(mCr, mThumbnailWidth, mThumbnailHeight);
iv.setImageDrawable(drawable);
}
((LoaderDrawable)drawable).startLoad(
mCursor.getInt(PROJ_INDEX_MEDIA_TYPE), mGroupId, mCursor.getLong(PROJ_INDEX_ID));
}
if (tv != null) {
tv.setVisibility(mShowTitle ? View.VISIBLE : View.GONE);
if (mShowTitle) {
tv.setText(info.title);
}
}
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTitleView;
private ImageView mImageView;
private MediaInfo info;
public ViewHolder(@NonNull final View v) {
super(v);
if (v instanceof TextView) {
mTitleView = (TextView)v;
mImageView = null;
} else if (v instanceof ImageView) {
mTitleView = null;
mImageView = (ImageView)v;
} else {
mTitleView = v.findViewById(R.id.title);
mImageView = v.findViewById(R.id.thumbnail);
}
}
}
}
| sortOrder用変数を追加(今は常時nullなので無効)
| common/src/main/java/com/serenegiant/mediastore/MediaStoreRecyclerAdapter.java | sortOrder用変数を追加(今は常時nullなので無効) |
|
Java | apache-2.0 | cdde8f9c11eb6d66f18a7aef450e45dba61b39a5 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.annotator.intentions;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiType;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.codeInspection.GroovyFix;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint;
import static com.intellij.psi.util.PointersKt.createSmartPointer;
/**
* @author Maxim.Medvedev
*/
public class CreateFieldFromConstructorLabelFix extends GroovyFix {
private final CreateFieldFix myFix;
private final SmartPsiElementPointer<GrNamedArgument> myNamedArgumentPointer;
public CreateFieldFromConstructorLabelFix(@NotNull GrTypeDefinition targetClass, @NotNull GrNamedArgument namedArgument) {
myFix = new CreateFieldFix(targetClass);
myNamedArgumentPointer = createSmartPointer(namedArgument);
}
@Nullable
private String getFieldName() {
GrNamedArgument namedArgument = myNamedArgumentPointer.getElement();
if (namedArgument == null) return null;
final GrArgumentLabel label = namedArgument.getLabel();
assert label != null;
return label.getName();
}
private static TypeConstraint[] calculateTypeConstrains(@NotNull GrNamedArgument namedArgument) {
final GrExpression expression = namedArgument.getExpression();
PsiType type = null;
if (expression != null) {
type = expression.getType();
}
if (type != null) {
return new TypeConstraint[]{SupertypeConstraint.create(type, type)};
}
else {
return TypeConstraint.EMPTY_ARRAY;
}
}
@NotNull
@Override
public String getName() {
return GroovyBundle.message("create.field.from.usage", getFieldName());
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return "Create field";
}
@Override
protected void doFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) throws IncorrectOperationException {
GrNamedArgument namedArgument = myNamedArgumentPointer.getElement();
if (namedArgument == null) return;
String fieldName = getFieldName();
if (fieldName == null) return;
myFix.doFix(project, ArrayUtil.EMPTY_STRING_ARRAY, fieldName, calculateTypeConstrains(namedArgument), namedArgument);
}
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromConstructorLabelFix.java | /*
* 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 org.jetbrains.plugins.groovy.annotator.intentions;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.codeInspection.GroovyFix;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint;
/**
* @author Maxim.Medvedev
*/
public class CreateFieldFromConstructorLabelFix extends GroovyFix {
private final CreateFieldFix myFix;
private final GrNamedArgument myNamedArgument;
public CreateFieldFromConstructorLabelFix(GrTypeDefinition targetClass, GrNamedArgument namedArgument) {
myFix = new CreateFieldFix(targetClass);
myNamedArgument = namedArgument;
}
@Nullable
private String getFieldName() {
final GrArgumentLabel label = myNamedArgument.getLabel();
assert label != null;
return label.getName();
}
private TypeConstraint[] calculateTypeConstrains() {
final GrExpression expression = myNamedArgument.getExpression();
PsiType type = null;
if (expression != null) {
type = expression.getType();
}
if (type != null) {
return new TypeConstraint[]{SupertypeConstraint.create(type, type)};
}
else {
return TypeConstraint.EMPTY_ARRAY;
}
}
@NotNull
@Override
public String getName() {
return GroovyBundle.message("create.field.from.usage", getFieldName());
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return "Create field";
}
@Override
protected void doFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) throws IncorrectOperationException {
myFix.doFix(project, ArrayUtil.EMPTY_STRING_ARRAY, getFieldName(), calculateTypeConstrains(), myNamedArgument);
}
}
| [groovy] fix psi class leak and CreateFieldFromConstructorLabelFix
| plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateFieldFromConstructorLabelFix.java | [groovy] fix psi class leak and CreateFieldFromConstructorLabelFix |
|
Java | apache-2.0 | 4087f32aa25c067be9aa27c902225d5364227d18 | 0 | amidst/toolbox,amidst/toolbox | /*
* 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 eu.amidst.modelExperiments;
import eu.amidst.core.datastream.Attributes;
import eu.amidst.core.datastream.DataInstance;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.variables.Variable;
import eu.amidst.core.variables.Variables;
import eu.amidst.flinklink.core.data.DataFlink;
import eu.amidst.flinklink.core.io.DataFlinkWriter;
import eu.amidst.flinklink.core.utils.BayesianNetworkSampler;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by andresmasegosa on 17/2/16.
*/
public class DAGsGeneration {
public static DAG getIDAMultiLocalGlobalDAG(Attributes attributes, int nlocals) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define a local hidden variable.
List<Variable> localHiddenVars = new ArrayList<>();
for (int i = 0; i < nlocals; i++) {
localHiddenVars.add(variables.newGaussianVariable("LocalHidden_"+i));
}
// Define the global hidden variable.
Variable globalHiddenVar = variables.newGaussianVariable("GlobalHidden");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(globalHiddenVar));
// Link the local hidden as parent of all predictive attributes
for (Variable localHiddenVar : localHiddenVars) {
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(localHiddenVar));
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDAMultiLocalGaussianDAG(Attributes attributes, int nlocals) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define a local hidden variable.
List<Variable> localHiddenVars = new ArrayList<>();
for (int i = 0; i < nlocals; i++) {
localHiddenVars.add(variables.newGaussianVariable("LocalHidden_"+i));
}
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(classVar));
// Link the local hidden as parent of all predictive attributes
for (Variable localHiddenVar : localHiddenVars) {
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(localHiddenVar));
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDAMultinomialMultiLocalGaussianDAG(Attributes attributes, int nstates, int nlocals) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define a local hidden variable.
List<Variable> localHiddenVars = new ArrayList<>();
for (int i = 0; i < nlocals; i++) {
localHiddenVars.add(variables.newGaussianVariable("LocalHidden_"+i));
}
// Define the global hidden variable.
Variable globalHiddenVar = variables.newMultionomialVariable("MultinomialHidden",nstates);
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(globalHiddenVar));
// Link the local hidden as parent of all predictive attributes
for (Variable localHiddenVar : localHiddenVars) {
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(localHiddenVar));
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDALocalGlobalDAG(Attributes attributes) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define a local hidden variable.
Variable localHiddenVar = variables.newGaussianVariable("LocalHidden");
// Define the global hidden variable.
Variable globalHiddenVar = variables.newGaussianVariable("GlobalHidden");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> w.getMainVar() != localHiddenVar)
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> w.getMainVar() != localHiddenVar)
.forEach(w -> w.addParent(globalHiddenVar));
// Link the local hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> w.getMainVar() != localHiddenVar)
.forEach(w -> w.addParent(localHiddenVar));
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDAGlobalMultinomialDAG(Attributes attributes, int states) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define the global hidden variable.
Variable globalHiddenVar = variables.newMultionomialVariable("GlobalHidden",states);
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(globalHiddenVar));
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDAGlobalDAG(Attributes attributes) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define the global hidden variable.
Variable globalHiddenVar = variables.newGaussianVariable("GlobalHidden");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(globalHiddenVar));
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getConnectedNBDAG(int n) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables();
variables.newMultionomialVariable("Default", 2);
for (int i = 0; i < n; i++) {
variables.newGaussianVariable("G_" + i);
}
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.forEach(w -> w.addParent(classVar));
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
dag.getParentSet(variables.getVariableByName("G_" + i)).addParent(variables.getVariableByName("G_" + j));
}
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static void generateData(int nVars, int nsamples, int batchsize) throws Exception {
DAG dag = getConnectedNBDAG(nVars);
BayesianNetwork bn = new BayesianNetwork(dag);
bn.randomInitialization(new Random(0));
System.out.println(bn.toString());
BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn);
sampler.setBatchSize(batchsize);
DataFlink<DataInstance> data = sampler.sampleToDataFlink(nsamples);
DataFlinkWriter.writeDataToARFFFolder(data, "./datasets/dataFlink/data.arff");
}
public static void main(String[] args) throws Exception {
int nVars = 5;
int dataSetSize=4000;
int windowSize = 1000;
generateData(nVars,dataSetSize, windowSize);
}
} | extensions/uai2016/src/main/java/eu/amidst/modelExperiments/DAGsGeneration.java | /*
* 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 eu.amidst.modelExperiments;
import eu.amidst.core.datastream.Attributes;
import eu.amidst.core.datastream.DataInstance;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.variables.Variable;
import eu.amidst.core.variables.Variables;
import eu.amidst.flinklink.core.data.DataFlink;
import eu.amidst.flinklink.core.io.DataFlinkWriter;
import eu.amidst.flinklink.core.utils.BayesianNetworkSampler;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by andresmasegosa on 17/2/16.
*/
public class DAGsGeneration {
public static DAG getIDAMultiLocalGlobalDAG(Attributes attributes, int nlocals) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define a local hidden variable.
List<Variable> localHiddenVars = new ArrayList<>();
for (int i = 0; i < nlocals; i++) {
localHiddenVars.add(variables.newGaussianVariable("LocalHidden_"+i));
}
// Define the global hidden variable.
Variable globalHiddenVar = variables.newGaussianVariable("GlobalHidden");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(globalHiddenVar));
// Link the local hidden as parent of all predictive attributes
for (Variable localHiddenVar : localHiddenVars) {
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(localHiddenVar));
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDAMultiLocalGaussianDAG(Attributes attributes, int nlocals) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define a local hidden variable.
List<Variable> localHiddenVars = new ArrayList<>();
for (int i = 0; i < nlocals; i++) {
localHiddenVars.add(variables.newGaussianVariable("LocalHidden_"+i));
}
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(classVar));
// Link the local hidden as parent of all predictive attributes
for (Variable localHiddenVar : localHiddenVars) {
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(localHiddenVar));
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDAMultinomialMultiLocalGaussianDAG(Attributes attributes, int nstates, int nlocals) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("DEFAULT");
// Define a local hidden variable.
List<Variable> localHiddenVars = new ArrayList<>();
for (int i = 0; i < nlocals; i++) {
localHiddenVars.add(variables.newGaussianVariable("LocalHidden_"+i));
}
// Define the global hidden variable.
Variable globalHiddenVar = variables.newMultionomialVariable("MultinomialHidden",nstates);
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(globalHiddenVar));
// Link the local hidden as parent of all predictive attributes
for (Variable localHiddenVar : localHiddenVars) {
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> !w.getMainVar().getName().startsWith("Local"))
.forEach(w -> w.addParent(localHiddenVar));
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDALocalGlobalDAG(Attributes attributes) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define a local hidden variable.
Variable localHiddenVar = variables.newGaussianVariable("LocalHidden");
// Define the global hidden variable.
Variable globalHiddenVar = variables.newGaussianVariable("GlobalHidden");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> w.getMainVar() != localHiddenVar)
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> w.getMainVar() != localHiddenVar)
.forEach(w -> w.addParent(globalHiddenVar));
// Link the local hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.filter(w -> w.getMainVar() != localHiddenVar)
.forEach(w -> w.addParent(localHiddenVar));
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getIDAGlobalDAG(Attributes attributes) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables(attributes);
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Define the global hidden variable.
Variable globalHiddenVar = variables.newGaussianVariable("GlobalHidden");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(classVar));
// Link the global hidden as parent of all predictive attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.filter(w -> w.getMainVar() != globalHiddenVar)
.forEach(w -> w.addParent(globalHiddenVar));
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static DAG getConnectedNBDAG(int n) {
// Create a Variables object from the attributes of the input data stream.
Variables variables = new Variables();
variables.newMultionomialVariable("Default", 2);
for (int i = 0; i < n; i++) {
variables.newGaussianVariable("G_" + i);
}
// Define the class variable.
Variable classVar = variables.getVariableByName("Default");
// Create an empty DAG object with the defined variables.
DAG dag = new DAG(variables);
// Link the class as parent of all attributes
dag.getParentSets()
.stream()
.filter(w -> w.getMainVar() != classVar)
.forEach(w -> w.addParent(classVar));
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
dag.getParentSet(variables.getVariableByName("G_" + i)).addParent(variables.getVariableByName("G_" + j));
}
}
// Show the new dynamic DAG structure
System.out.println(dag.toString());
return dag;
}
public static void generateData(int nVars, int nsamples, int batchsize) throws Exception {
DAG dag = getConnectedNBDAG(nVars);
BayesianNetwork bn = new BayesianNetwork(dag);
bn.randomInitialization(new Random(0));
System.out.println(bn.toString());
BayesianNetworkSampler sampler = new BayesianNetworkSampler(bn);
sampler.setBatchSize(batchsize);
DataFlink<DataInstance> data = sampler.sampleToDataFlink(nsamples);
DataFlinkWriter.writeDataToARFFFolder(data, "./datasets/dataFlink/data.arff");
}
public static void main(String[] args) throws Exception {
int nVars = 2;
int dataSetSize=4000;
int windowSize = 1000;
generateData(nVars,dataSetSize, windowSize);
}
} | Update
| extensions/uai2016/src/main/java/eu/amidst/modelExperiments/DAGsGeneration.java | Update |
|
Java | apache-2.0 | 5898513616980165d17cb67f346ac56e51aff1ee | 0 | tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki | /*
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.wiki.workflow;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.log4j.Logger;
import org.apache.wiki.api.core.Context;
import org.apache.wiki.api.core.Engine;
import org.apache.wiki.api.core.Session;
import org.apache.wiki.api.exceptions.WikiException;
import org.apache.wiki.auth.AuthorizationManager;
import org.apache.wiki.auth.acl.UnresolvedPrincipal;
import org.apache.wiki.event.WikiEvent;
import org.apache.wiki.event.WikiEventEmitter;
import org.apache.wiki.event.WorkflowEvent;
import org.apache.wiki.util.TextUtil;
import java.io.*;
import java.security.Principal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* <p>
* Monitor class that tracks running Workflows. The WorkflowManager also keeps track of the names of
* users or groups expected to approve particular Workflows.
* </p>
*/
public class DefaultWorkflowManager implements WorkflowManager {
private static final Logger LOG = Logger.getLogger( DefaultWorkflowManager.class );
static final String SERIALIZATION_FILE = "wkflmgr.ser";
/** We use this also a generic serialization id */
private static final long serialVersionUID = 6L;
DecisionQueue m_queue;
Set< Workflow > m_workflows;
final Map< String, Principal > m_approvers;
Queue< Workflow > m_completed;
private Engine m_engine = null;
private int retainCompleted;
/**
* Constructs a new WorkflowManager, with an empty workflow cache.
*/
public DefaultWorkflowManager() {
m_workflows = ConcurrentHashMap.newKeySet();
m_approvers = new ConcurrentHashMap<>();
m_queue = new DecisionQueue();
WikiEventEmitter.attach( this );
}
/**
* {@inheritDoc}
*/
@Override
public Set< Workflow > getWorkflows() {
final Set< Workflow > workflows = ConcurrentHashMap.newKeySet();
workflows.addAll( m_workflows );
return workflows;
}
/**
* {@inheritDoc}
*/
@Override
public List< Workflow > getCompletedWorkflows() {
return new CopyOnWriteArrayList< >( m_completed );
}
/**
* {@inheritDoc}
*
* Any properties that begin with {@link #PROPERTY_APPROVER_PREFIX} will be assumed to be Decisions that require approval. For a given
* property key, everything after the prefix denotes the Decision's message key. The property value indicates the Principal (Role,
* GroupPrincipal, WikiPrincipal) that must approve the Decision. For example, if the property key/value pair is
* {@code jspwiki.approver.workflow.saveWikiPage=Admin}, the Decision's message key is <code>workflow.saveWikiPage</code>. The Principal
* <code>Admin</code> will be resolved via {@link org.apache.wiki.auth.AuthorizationManager#resolvePrincipal(String)}.
*/
@Override
public void initialize( final Engine engine, final Properties props ) {
m_engine = engine;
retainCompleted = TextUtil.getIntegerProperty( engine.getWikiProperties(), "jspwiki.workflow.completed.retain", 2048 );
m_completed = new CircularFifoQueue<>( retainCompleted );
// Identify the workflows requiring approvals
for( final Object o : props.keySet() ) {
final String prop = ( String )o;
if( prop.startsWith( PROPERTY_APPROVER_PREFIX ) ) {
// For the key, everything after the prefix is the workflow name
final String key = prop.substring( PROPERTY_APPROVER_PREFIX.length() );
if( key.length() > 0 ) {
// Only use non-null/non-blank approvers
final String approver = props.getProperty( prop );
if( approver != null && approver.length() > 0 ) {
m_approvers.put( key, new UnresolvedPrincipal( approver ) );
}
}
}
}
unserializeFromDisk( new File( m_engine.getWorkDir(), SERIALIZATION_FILE ) );
}
/**
* Reads the serialized data from the disk back to memory.
*
* @return the date when the data was last written on disk or {@code 0} if there has been problems reading from disk.
*/
@SuppressWarnings( "unchecked" )
synchronized long unserializeFromDisk( final File f ) {
long saved = 0L;
final StopWatch sw = new StopWatch();
sw.start();
try( final ObjectInputStream in = new ObjectInputStream( new BufferedInputStream( new FileInputStream( f ) ) ) ) {
final long ver = in.readLong();
if( ver != serialVersionUID ) {
LOG.warn( "File format has changed; Unable to recover workflows and decision queue from disk." );
} else {
saved = in.readLong();
m_workflows = ( Set< Workflow > )in.readObject();
m_queue = ( DecisionQueue )in.readObject();
m_completed = new CircularFifoQueue<>( retainCompleted );
m_completed.addAll( ( Collection< Workflow > )in.readObject() );
LOG.debug( "Read serialized data successfully in " + sw );
}
} catch( final IOException | ClassNotFoundException e ) {
LOG.warn( "unable to recover from disk workflows and decision queue: " + e.getMessage() );
}
sw.stop();
return saved;
}
/**
* Serializes workflows and decisionqueue to disk. The format is private, don't touch it.
*/
synchronized void serializeToDisk( final File f ) {
try( final ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream( f ) ) ) ) {
final StopWatch sw = new StopWatch();
sw.start();
out.writeLong( serialVersionUID );
out.writeLong( System.currentTimeMillis() ); // Timestamp
out.writeObject( m_workflows );
out.writeObject( m_queue );
out.writeObject( m_completed );
sw.stop();
LOG.debug( "serialization done - took " + sw );
} catch( final IOException ioe ) {
LOG.error( "Unable to serialize!", ioe );
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean requiresApproval( final String messageKey ) {
return m_approvers.containsKey( messageKey );
}
/**
* {@inheritDoc}
*/
@Override
public Principal getApprover( final String messageKey ) throws WikiException {
Principal approver = m_approvers.get( messageKey );
if ( approver == null ) {
throw new WikiException( "Workflow '" + messageKey + "' does not require approval." );
}
// Try to resolve UnresolvedPrincipals
if ( approver instanceof UnresolvedPrincipal ) {
final String name = approver.getName();
approver = m_engine.getManager( AuthorizationManager.class ).resolvePrincipal( name );
// If still unresolved, throw exception; otherwise, freshen our cache
if ( approver instanceof UnresolvedPrincipal ) {
throw new WikiException( "Workflow approver '" + name + "' cannot not be resolved." );
}
m_approvers.put( messageKey, approver );
}
return approver;
}
/**
* Protected helper method that returns the associated Engine
*
* @return the wiki engine
*/
protected Engine getEngine() {
if ( m_engine == null ) {
throw new IllegalStateException( "Engine cannot be null; please initialize WorkflowManager first." );
}
return m_engine;
}
/**
* Returns the DecisionQueue associated with this WorkflowManager
*
* @return the decision queue
*/
@Override
public DecisionQueue getDecisionQueue() {
return m_queue;
}
/**
* {@inheritDoc}
*/
@Override
public List< Workflow > getOwnerWorkflows( final Session session ) {
final List< Workflow > workflows = new ArrayList<>();
if ( session.isAuthenticated() ) {
final Principal[] sessionPrincipals = session.getPrincipals();
for( final Workflow w : m_workflows ) {
final Principal owner = w.getOwner();
for ( final Principal sessionPrincipal : sessionPrincipals ) {
if ( sessionPrincipal.equals( owner ) ) {
workflows.add( w );
break;
}
}
}
}
return workflows;
}
/**
* Listens for {@link WorkflowEvent} objects emitted by Workflows. In particular, this method listens for {@link WorkflowEvent#CREATED},
* {@link WorkflowEvent#ABORTED}, {@link WorkflowEvent#COMPLETED} and {@link WorkflowEvent#DQ_REMOVAL} events. If a workflow is created,
* it is automatically added to the cache. If one is aborted or completed, it is automatically removed. If a removal from decision queue
* is issued, the current step from workflow, which is assumed to be a {@link Decision}, is removed from the {@link DecisionQueue}.
*
* @param event the event passed to this listener
*/
@Override
public void actionPerformed( final WikiEvent event ) {
if( event instanceof WorkflowEvent ) {
if( event.getSrc() instanceof Workflow ) {
final Workflow workflow = event.getSrc();
switch( event.getType() ) {
// Remove from manager
case WorkflowEvent.ABORTED :
case WorkflowEvent.COMPLETED : remove( workflow ); break;
// Add to manager
case WorkflowEvent.CREATED : add( workflow ); break;
default: break;
}
} else if( event.getSrc() instanceof Decision ) {
final Decision decision = event.getSrc();
switch( event.getType() ) {
// Add to DecisionQueue
case WorkflowEvent.DQ_ADDITION : addToDecisionQueue( decision ); break;
// Remove from DecisionQueue
case WorkflowEvent.DQ_REMOVAL : removeFromDecisionQueue( decision, event.getArg( 0, Context.class ) ); break;
default: break;
}
}
serializeToDisk( new File( m_engine.getWorkDir(), SERIALIZATION_FILE ) );
}
}
/**
* Protected helper method that adds a newly created Workflow to the cache, and sets its {@code workflowManager} and
* {@code Id} properties if not set.
*
* @param workflow the workflow to add
*/
protected void add( final Workflow workflow ) {
m_workflows.add( workflow );
}
/**
* Protected helper method that removes a specified Workflow from the cache, and moves it to the workflow history list. This method
* defensively checks to see if the workflow has not yet been removed.
*
* @param workflow the workflow to remove
*/
protected void remove( final Workflow workflow ) {
if( m_workflows.contains( workflow ) ) {
m_workflows.remove( workflow );
m_completed.add( workflow );
}
}
protected void removeFromDecisionQueue( final Decision decision, final Context context ) {
// If current workflow is waiting for input, restart it and remove Decision from DecisionQueue
final int workflowId = decision.getWorkflowId();
final Optional< Workflow > optw = m_workflows.stream().filter( w -> w.getId() == workflowId ).findAny();
if( optw.isPresent() ) {
final Workflow w = optw.get();
if( w.getCurrentState() == Workflow.WAITING && decision.equals( w.getCurrentStep() ) ) {
getDecisionQueue().remove( decision );
// Restart workflow
try {
w.restart( context );
} catch( final WikiException e ) {
LOG.error( "restarting workflow #" + w.getId() + " caused " + e.getMessage(), e );
}
}
}
}
protected void addToDecisionQueue( final Decision decision ) {
getDecisionQueue().add( decision );
}
}
| jspwiki-main/src/main/java/org/apache/wiki/workflow/DefaultWorkflowManager.java | /*
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.wiki.workflow;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.log4j.Logger;
import org.apache.wiki.api.core.Context;
import org.apache.wiki.api.core.Engine;
import org.apache.wiki.api.core.Session;
import org.apache.wiki.api.exceptions.WikiException;
import org.apache.wiki.auth.AuthorizationManager;
import org.apache.wiki.auth.acl.UnresolvedPrincipal;
import org.apache.wiki.event.WikiEvent;
import org.apache.wiki.event.WikiEventEmitter;
import org.apache.wiki.event.WorkflowEvent;
import org.apache.wiki.util.TextUtil;
import java.io.*;
import java.security.Principal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* <p>
* Monitor class that tracks running Workflows. The WorkflowManager also keeps track of the names of
* users or groups expected to approve particular Workflows.
* </p>
*/
public class DefaultWorkflowManager implements WorkflowManager {
private static final Logger LOG = Logger.getLogger( DefaultWorkflowManager.class );
static final String SERIALIZATION_FILE = "wkflmgr.ser";
/** We use this also a generic serialization id */
private static final long serialVersionUID = 6L;
DecisionQueue m_queue = new DecisionQueue();
Set< Workflow > m_workflows;
final Map< String, Principal > m_approvers;
Queue< Workflow > m_completed;
private Engine m_engine = null;
private int retainCompleted;
/**
* Constructs a new WorkflowManager, with an empty workflow cache.
*/
public DefaultWorkflowManager() {
m_workflows = ConcurrentHashMap.newKeySet();
m_approvers = new ConcurrentHashMap<>();
WikiEventEmitter.attach( this );
}
/**
* {@inheritDoc}
*/
@Override
public Set< Workflow > getWorkflows() {
final Set< Workflow > workflows = ConcurrentHashMap.newKeySet();
workflows.addAll( m_workflows );
return workflows;
}
/**
* {@inheritDoc}
*/
@Override
public List< Workflow > getCompletedWorkflows() {
return new CopyOnWriteArrayList< >( m_completed );
}
/**
* {@inheritDoc}
*
* Any properties that begin with {@link #PROPERTY_APPROVER_PREFIX} will be assumed to be Decisions that require approval. For a given
* property key, everything after the prefix denotes the Decision's message key. The property value indicates the Principal (Role,
* GroupPrincipal, WikiPrincipal) that must approve the Decision. For example, if the property key/value pair is
* {@code jspwiki.approver.workflow.saveWikiPage=Admin}, the Decision's message key is <code>workflow.saveWikiPage</code>. The Principal
* <code>Admin</code> will be resolved via {@link org.apache.wiki.auth.AuthorizationManager#resolvePrincipal(String)}.
*/
@Override
public void initialize( final Engine engine, final Properties props ) {
m_engine = engine;
retainCompleted = TextUtil.getIntegerProperty( engine.getWikiProperties(), "jspwiki.workflow.completed.retain", 2048 );
m_completed = new CircularFifoQueue<>( retainCompleted );
// Identify the workflows requiring approvals
for( final Object o : props.keySet() ) {
final String prop = ( String )o;
if( prop.startsWith( PROPERTY_APPROVER_PREFIX ) ) {
// For the key, everything after the prefix is the workflow name
final String key = prop.substring( PROPERTY_APPROVER_PREFIX.length() );
if( key.length() > 0 ) {
// Only use non-null/non-blank approvers
final String approver = props.getProperty( prop );
if( approver != null && approver.length() > 0 ) {
m_approvers.put( key, new UnresolvedPrincipal( approver ) );
}
}
}
}
unserializeFromDisk( new File( m_engine.getWorkDir(), SERIALIZATION_FILE ) );
}
/**
* Reads the serialized data from the disk back to memory.
*
* @return the date when the data was last written on disk or {@code 0} if there has been problems reading from disk.
*/
@SuppressWarnings( "unchecked" )
synchronized long unserializeFromDisk( final File f ) {
long saved = 0L;
final StopWatch sw = new StopWatch();
sw.start();
try( final ObjectInputStream in = new ObjectInputStream( new BufferedInputStream( new FileInputStream( f ) ) ) ) {
final long ver = in.readLong();
if( ver != serialVersionUID ) {
LOG.warn( "File format has changed; Unable to recover workflows and decision queue from disk." );
} else {
saved = in.readLong();
m_workflows = ( Set< Workflow > )in.readObject();
m_queue = ( DecisionQueue )in.readObject();
m_completed = new CircularFifoQueue<>( retainCompleted );
m_completed.addAll( ( Collection< Workflow > )in.readObject() );
LOG.debug( "Read serialized data successfully in " + sw );
}
} catch( final IOException | ClassNotFoundException e ) {
LOG.warn( "unable to recover from disk workflows and decision queue: " + e.getMessage() );
}
sw.stop();
return saved;
}
/**
* Serializes workflows and decisionqueue to disk. The format is private, don't touch it.
*/
synchronized void serializeToDisk( final File f ) {
try( final ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream( f ) ) ) ) {
final StopWatch sw = new StopWatch();
sw.start();
out.writeLong( serialVersionUID );
out.writeLong( System.currentTimeMillis() ); // Timestamp
out.writeObject( m_workflows );
out.writeObject( m_queue );
out.writeObject( m_completed );
sw.stop();
LOG.debug( "serialization done - took " + sw );
} catch( final IOException ioe ) {
LOG.error( "Unable to serialize!", ioe );
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean requiresApproval( final String messageKey ) {
return m_approvers.containsKey( messageKey );
}
/**
* {@inheritDoc}
*/
@Override
public Principal getApprover( final String messageKey ) throws WikiException {
Principal approver = m_approvers.get( messageKey );
if ( approver == null ) {
throw new WikiException( "Workflow '" + messageKey + "' does not require approval." );
}
// Try to resolve UnresolvedPrincipals
if ( approver instanceof UnresolvedPrincipal ) {
final String name = approver.getName();
approver = m_engine.getManager( AuthorizationManager.class ).resolvePrincipal( name );
// If still unresolved, throw exception; otherwise, freshen our cache
if ( approver instanceof UnresolvedPrincipal ) {
throw new WikiException( "Workflow approver '" + name + "' cannot not be resolved." );
}
m_approvers.put( messageKey, approver );
}
return approver;
}
/**
* Protected helper method that returns the associated Engine
*
* @return the wiki engine
*/
protected Engine getEngine() {
if ( m_engine == null ) {
throw new IllegalStateException( "Engine cannot be null; please initialize WorkflowManager first." );
}
return m_engine;
}
/**
* Returns the DecisionQueue associated with this WorkflowManager
*
* @return the decision queue
*/
@Override
public DecisionQueue getDecisionQueue() {
return m_queue;
}
/**
* {@inheritDoc}
*/
@Override
public List< Workflow > getOwnerWorkflows( final Session session ) {
final List< Workflow > workflows = new ArrayList<>();
if ( session.isAuthenticated() ) {
final Principal[] sessionPrincipals = session.getPrincipals();
for( final Workflow w : m_workflows ) {
final Principal owner = w.getOwner();
for ( final Principal sessionPrincipal : sessionPrincipals ) {
if ( sessionPrincipal.equals( owner ) ) {
workflows.add( w );
break;
}
}
}
}
return workflows;
}
/**
* Listens for {@link WorkflowEvent} objects emitted by Workflows. In particular, this method listens for {@link WorkflowEvent#CREATED},
* {@link WorkflowEvent#ABORTED}, {@link WorkflowEvent#COMPLETED} and {@link WorkflowEvent#DQ_REMOVAL} events. If a workflow is created,
* it is automatically added to the cache. If one is aborted or completed, it is automatically removed. If a removal from decision queue
* is issued, the current step from workflow, which is assumed to be a {@link Decision}, is removed from the {@link DecisionQueue}.
*
* @param event the event passed to this listener
*/
@Override
public void actionPerformed( final WikiEvent event ) {
if( event instanceof WorkflowEvent ) {
if( event.getSrc() instanceof Workflow ) {
final Workflow workflow = event.getSrc();
switch( event.getType() ) {
// Remove from manager
case WorkflowEvent.ABORTED :
case WorkflowEvent.COMPLETED : remove( workflow ); break;
// Add to manager
case WorkflowEvent.CREATED : add( workflow ); break;
default: break;
}
} else if( event.getSrc() instanceof Decision ) {
final Decision decision = event.getSrc();
switch( event.getType() ) {
// Add to DecisionQueue
case WorkflowEvent.DQ_ADDITION : addToDecisionQueue( decision ); break;
// Remove from DecisionQueue
case WorkflowEvent.DQ_REMOVAL : removeFromDecisionQueue( decision, event.getArg( 0, Context.class ) ); break;
default: break;
}
}
serializeToDisk( new File( m_engine.getWorkDir(), SERIALIZATION_FILE ) );
}
}
/**
* Protected helper method that adds a newly created Workflow to the cache, and sets its {@code workflowManager} and
* {@code Id} properties if not set.
*
* @param workflow the workflow to add
*/
protected void add( final Workflow workflow ) {
m_workflows.add( workflow );
}
/**
* Protected helper method that removes a specified Workflow from the cache, and moves it to the workflow history list. This method
* defensively checks to see if the workflow has not yet been removed.
*
* @param workflow the workflow to remove
*/
protected void remove( final Workflow workflow ) {
if( m_workflows.contains( workflow ) ) {
m_workflows.remove( workflow );
m_completed.add( workflow );
}
}
protected void removeFromDecisionQueue( final Decision decision, final Context context ) {
// If current workflow is waiting for input, restart it and remove Decision from DecisionQueue
final int workflowId = decision.getWorkflowId();
final Optional< Workflow > optw = m_workflows.stream().filter( w -> w.getId() == workflowId ).findAny();
if( optw.isPresent() ) {
final Workflow w = optw.get();
if( w.getCurrentState() == Workflow.WAITING && decision.equals( w.getCurrentStep() ) ) {
getDecisionQueue().remove( decision );
// Restart workflow
try {
w.restart( context );
} catch( final WikiException e ) {
LOG.error( "restarting workflow #" + w.getId() + " caused " + e.getMessage(), e );
}
}
}
}
protected void addToDecisionQueue( final Decision decision ) {
getDecisionQueue().add( decision );
}
}
| code polish
| jspwiki-main/src/main/java/org/apache/wiki/workflow/DefaultWorkflowManager.java | code polish |
|
Java | apache-2.0 | 28c0513dbbe11ce258ead456ba9bd9a9c5f4f635 | 0 | T-Systems-MMS/perfsig-jenkins,T-Systems-MMS/perfsig-jenkins | /*
* Copyright (c) 2014-2018 T-Systems Multimedia Solutions GmbH
*
* 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 de.tsystems.mms.apm.performancesignature.dynatracesaas;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import de.tsystems.mms.apm.performancesignature.dynatrace.model.*;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.model.DynatraceServerConfiguration;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.model.Specification;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.model.SpecificationTM;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.DynatraceServerConnection;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.AggregationTypeEnum;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.TimeseriesDataPointQueryResult;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.TimeseriesDefinition;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.UnitEnum;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.util.ConversionHelper;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.util.DynatraceUtils;
import de.tsystems.mms.apm.performancesignature.ui.PerfSigBuildAction;
import de.tsystems.mms.apm.performancesignature.ui.util.PerfSigUIUtils;
import hudson.FilePath;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.workflow.steps.MissingContextVariableException;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class DynatraceReportStepExecution extends SynchronousNonBlockingStepExecution<Void> {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(DynatraceReportStepExecution.class.getName());
private static final String DEFAULT_COLOR = "#006bba";
private final transient DynatraceReportStep step;
private FilePath ws;
public DynatraceReportStepExecution(DynatraceReportStep dynatraceReportStep, StepContext context) {
super(context);
this.step = dynatraceReportStep;
}
static void convertUnitOfDataPoints(Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> aggregations) {
for (TimeseriesDataPointQueryResult queryResult : aggregations.values()) {
Map<String, Map<Long, Double>> dataPoints = queryResult.getDataPoints();
if (MapUtils.isEmpty(dataPoints)) continue;
//get the max value from each entity
OptionalDouble maxValue2 = dataPoints.entrySet().stream()
.flatMapToDouble(stringMapEntry -> stringMapEntry.getValue().entrySet().stream()
.filter(longDoubleEntry -> longDoubleEntry.getValue() != null)
.mapToDouble(Map.Entry::getValue)).max();
UnitEnum calculatedUnit = calculateUnitEnum(aggregations.entrySet().iterator().next().getValue(), maxValue2.isPresent() ? maxValue2.getAsDouble() : 0);
Map<String, Map<Long, Double>> convertedDataPoints = new LinkedHashMap<>();
for (Map.Entry<String, Map<Long, Double>> entry : dataPoints.entrySet()) {
String key = entry.getKey();
Map<Long, Double> value = entry.getValue();
Map<Long, Double> convertedValuesPerEntity = new LinkedHashMap<>();
for (Map.Entry<Long, Double> mapEntry : value.entrySet()) {
convertedValuesPerEntity.put(mapEntry.getKey(), ConversionHelper.convertUnit(mapEntry.getValue(), queryResult.getUnit(), calculatedUnit));
}
convertedDataPoints.put(key, convertedValuesPerEntity);
}
queryResult.setUnit(calculatedUnit);
queryResult.getDataPoints().clear();
queryResult.getDataPoints().putAll(convertedDataPoints);
}
}
private static double getMeasurementValue(Map<AggregationTypeEnum, Map<Long, Double>> scalarValues, long key, AggregationTypeEnum aggregation) {
Map<Long, Double> aggregationValues = scalarValues.get(aggregation);
if (MapUtils.isNotEmpty(aggregationValues)) {
return PerfSigUIUtils.roundAsDouble(aggregationValues.get(key));
}
return 0;
}
private static String handleEntityIdString(Map<String, String> entities, String entityId) {
if (StringUtils.isBlank(entityId) || MapUtils.isEmpty(entities)) return null;
String cleanedEntityId = entityId.split(",")[0];
return entities.get(cleanedEntityId);
}
private static Map<AggregationTypeEnum, Map<Long, Double>> getScalarValues(Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> dataPointQueryResultMap) {
Map<AggregationTypeEnum, Map<Long, Double>> hashMap = new LinkedHashMap<>();
dataPointQueryResultMap.forEach((key, value) -> {
Map<String, Map<Long, Double>> dataPoints = value.getDataPoints();
if (dataPoints != null) {
Map<Long, Double> aggregatedValues = dataPoints.values().stream()
.flatMap(test -> test.entrySet().stream())
.filter(longDoubleEntry -> longDoubleEntry.getValue() != null)
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.averagingDouble(Map.Entry::getValue)
)
);
hashMap.put(key, aggregatedValues);
}
});
return hashMap;
}
private static double getScalarValue(TimeseriesDataPointQueryResult dataPointQueryResult) {
if (dataPointQueryResult != null && MapUtils.isNotEmpty(dataPointQueryResult.getDataPoints())) {
OptionalDouble average = dataPointQueryResult.getDataPoints().values().stream()
.flatMap(values -> values.values().stream())
.mapToDouble(a -> a).average();
if (average.isPresent()) return PerfSigUIUtils.roundAsDouble(average.getAsDouble());
}
return 0;
}
private static String translateAggregation(AggregationTypeEnum aggregation) {
switch (aggregation) {
case MIN:
return "Minimum";
case MAX:
return "Maximum";
case AVG:
return "Average";
default:
return StringUtils.capitalize(aggregation.getValue().toLowerCase());
}
}
private static List<Alert> evaluateSpecification(double globalLowerBound, double globalUpperBound, SpecificationTM specTM, Map<AggregationTypeEnum,
TimeseriesDataPointQueryResult> aggregations, Map<String, TimeseriesDefinition> timeseries) {
List<Alert> alerts = new ArrayList<>();
double lowerbound = Optional.ofNullable(specTM.getLowerLimit()).orElse(globalLowerBound);
double upperBound = Optional.ofNullable(specTM.getUpperLimit()).orElse(globalUpperBound);
TimeseriesDataPointQueryResult result = aggregations.get(specTM.getAggregation());
if (specTM.getAggregation() == null || result == null) return alerts;
for (Map.Entry<String, Map<Long, Double>> entry : result.getDataPoints().entrySet()) {
String entity = handleEntityIdString(result.getEntities(), entry.getKey());
for (Map.Entry<Long, Double> e : entry.getValue().entrySet()) {
Long timestamp = e.getKey();
Double value = e.getValue();
if (value != null) {
if (lowerbound < upperBound) {
if (value > lowerbound && value < upperBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.WARNING,
String.format("SpecFile threshold violation: %s lower bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Lower Bound: %.2f %s",
rule, value, result.getUnit(), entity, lowerbound, result.getUnit()),
timestamp, rule));
} else if (value > upperBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.SEVERE,
String.format("SpecFile threshold violation: %s upper bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Upper Bound: %.2f %s",
rule, value, result.getUnit(), entity, upperBound, result.getUnit()),
timestamp, rule));
}
} else {
if (value < lowerbound && value > upperBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.WARNING,
String.format("SpecFile threshold violation: %s lower bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Lower Bound: %.2f %s",
rule, value, result.getUnit(), entity, lowerbound, result.getUnit()),
timestamp, rule));
} else {
if (value < upperBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.SEVERE,
String.format("SpecFile threshold violation: %s upper bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Upper Bound: %.2f %s",
rule, value, result.getUnit(), entity, upperBound, result.getUnit()),
timestamp, rule));
}
}
}
}
}
}
return alerts;
}
private static UnitEnum calculateUnitEnum(TimeseriesDataPointQueryResult baseResult, double maxValue) {
System.out.println(baseResult);
UnitEnum unit = baseResult.getUnit();
if (ConversionHelper.TIME_UNITS.contains(unit)) {
return UnitEnum.MILLISECOND;
} else {
return ConversionHelper.convertByteUnitEnum(maxValue, unit);
}
}
private static Number getAggregationValue(TimeseriesDataPointQueryResult value, String key, Long timestamp) {
if (value == null) return 0;
return value.getDataPoints().get(key).get(timestamp);
}
public DynatraceReportStep getStep() {
return step;
}
@Override
protected Void run() throws Exception {
Run<?, ?> run = getContext().get(Run.class);
TaskListener listener = getContext().get(TaskListener.class);
ws = getContext().get(FilePath.class);
if (run == null || listener == null) {
throw new IllegalStateException("pipeline step was called without run or task listener in context");
}
if (StringUtils.isNotBlank(step.getSpecFile()) && CollectionUtils.isNotEmpty(step.getMetrics())) {
throw new IllegalArgumentException("At most one of file or text must be provided to " + step.getDescriptor().getFunctionName());
}
if (ws == null && StringUtils.isNotBlank(step.getSpecFile())) {
throw new MissingContextVariableException(FilePath.class);
}
DynatraceServerConnection serverConnection = DynatraceUtils.createDynatraceServerConnection(step.getEnvId(), true);
println("getting metric data from Dynatrace Server");
Map<String, TimeseriesDefinition> timeseries = serverConnection.getTimeseries()
.parallelStream().collect(Collectors.toMap(TimeseriesDefinition::getTimeseriesId, item -> item));
final List<DynatraceEnvInvisAction> envInvisActions = run.getActions(DynatraceEnvInvisAction.class);
final List<DashboardReport> dashboardReports = new ArrayList<>();
Specification spec = getSpecifications();
try {
for (DynatraceEnvInvisAction dynatraceAction : envInvisActions) {
Long start = dynatraceAction.getTimeframeStart();
Long end = dynatraceAction.getTimeframeStop();
DashboardReport dashboardReport = new DashboardReport(dynatraceAction.getTestCase());
//set url for Dynatrace dashboard
DynatraceServerConfiguration configuration = serverConnection.getConfiguration();
dashboardReport.setClientUrl(String.format("%s/#dashboard;gtf=c_%d_%d", configuration.getServerUrl(), start, end));
//iterate over specified timeseries ids
spec.getTimeseries().forEach(specTM -> {
TimeseriesDefinition tm = timeseries.get(specTM.getTimeseriesId());
//get data points for every possible aggregation
Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> aggregations = tm.getAggregationTypes().parallelStream()
.collect(Collectors.toMap(
Function.identity(),
aggregation -> serverConnection.getTimeseriesData(specTM.getTimeseriesId(), start, end, aggregation, specTM.getEntityIds(), specTM.getTags()),
(a, b) -> b, LinkedHashMap::new)
);
convertUnitOfDataPoints(aggregations);
TimeseriesDataPointQueryResult baseResult = aggregations.get(AggregationTypeEnum.AVG);
if (baseResult != null && MapUtils.isNotEmpty(baseResult.getDataPoints())) {
//get a scalar value for every possible aggregation
Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> totalValues = tm.getAggregationTypes().parallelStream()
.collect(Collectors.toMap(Function.identity(),
aggregation -> serverConnection.getTotalTimeseriesData(specTM.getTimeseriesId(), start, end, aggregation, specTM.getEntityIds(), specTM.getTags()),
(a, b) -> b, LinkedHashMap::new));
convertUnitOfDataPoints(totalValues);
//evaluate possible incidents
dashboardReport.getIncidents().addAll(evaluateSpecification(spec.getLowerLimit(), spec.getUpperLimit(),
specTM, aggregations, timeseries));
ChartDashlet chartDashlet = new ChartDashlet();
chartDashlet.setName(tm.getDetailedSource() + " - " + tm.getDisplayName());
//create aggregated overall measure
Measure overallMeasure = new Measure("overall");
overallMeasure.setAggregation(translateAggregation(specTM.getAggregation()));
overallMeasure.setColor(DEFAULT_COLOR);
UnitEnum calculatedUnit = calculateUnitEnum(baseResult, getScalarValue(totalValues.get(AggregationTypeEnum.MAX)));
overallMeasure.setUnit(calculatedUnit.getValue());
//calculate aggregated values from totalValues
overallMeasure.setAvg(getScalarValue(totalValues.get(AggregationTypeEnum.AVG)));
overallMeasure.setMin(getScalarValue(totalValues.get(AggregationTypeEnum.MIN)));
overallMeasure.setMax(getScalarValue(totalValues.get(AggregationTypeEnum.MAX)));
overallMeasure.setSum(getScalarValue(totalValues.get(AggregationTypeEnum.SUM)));
overallMeasure.setCount(getScalarValue(totalValues.get(AggregationTypeEnum.COUNT)));
//calculate aggregated values from seriesValues
Map<AggregationTypeEnum, Map<Long, Double>> scalarValues = getScalarValues(aggregations);
scalarValues.entrySet().iterator().next().getValue().keySet().forEach(entry -> {
Measurement m = new Measurement(entry,
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.AVG),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.MIN),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.MAX),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.SUM),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.COUNT)
);
overallMeasure.getMeasurements().add(m);
});
chartDashlet.getMeasures().add(overallMeasure);
//iterate over every entityId
baseResult.getDataPoints().forEach((key, value) -> {
Map<AggregationTypeEnum, Double> totalValuesPerDataPoint = tm.getAggregationTypes().stream()
.collect(Collectors.toMap(Function.identity(),
aggregation -> totalValues.get(aggregation).getDataPoints().get(key).entrySet().iterator().next().getValue(),
(a, b) -> b, LinkedHashMap::new));
Measure measure = new Measure(handleEntityIdString(baseResult.getEntities(), key));
measure.setAggregation(translateAggregation(specTM.getAggregation()));
measure.setUnit(calculatedUnit.getValue());
measure.setColor(DEFAULT_COLOR);
measure.setAvg(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.AVG, 0D));
measure.setMin(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.MIN, 0D));
measure.setMax(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.MAX, 0D));
measure.setSum(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.SUM, 0D));
measure.setCount(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.COUNT, 0D));
value.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.forEach(entry -> {
Measurement m = new Measurement(entry.getKey(),
getAggregationValue(aggregations.get(AggregationTypeEnum.AVG), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.MIN), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.MAX), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.SUM), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.COUNT), key, entry.getKey())
);
measure.getMeasurements().add(m);
});
chartDashlet.getMeasures().add(measure);
});
dashboardReport.addChartDashlet(chartDashlet);
} else {
println(String.format("Timeseries %s has no data points", tm.getTimeseriesId()));
}
});
dashboardReports.add(dashboardReport);
PrintStream stream = Optional.ofNullable(DynatraceUtils.getTaskListener(getContext())).map(TaskListener::getLogger).orElseGet(() -> new PrintStream(System.out));
PerfSigUIUtils.handleIncidents(run, dashboardReport.getIncidents(), PerfSigUIUtils.createLogger(stream), step.getNonFunctionalFailure());
}
} finally {
println("created " + dashboardReports.size() + " DashboardReports");
PerfSigBuildAction action = new PerfSigBuildAction(dashboardReports);
run.addAction(action);
}
return null;
}
private Specification getSpecifications() throws IOException, InterruptedException {
Specification specification = new Specification();
if (ws != null && StringUtils.isNotBlank(step.getSpecFile())) {
FilePath f = ws.child(step.getSpecFile());
if (f.exists() && !f.isDirectory()) {
try (InputStream is = f.read()) {
Type type = new TypeToken<Specification>() {
}.getType();
return new Gson().fromJson(IOUtils.toString(is, StandardCharsets.UTF_8), type);
}
} else if (f.isDirectory()) {
throw new IllegalArgumentException(f.getRemote() + " is a directory ...");
} else if (!f.exists()) {
throw new FileNotFoundException(f.getRemote() + " does not exist ...");
}
return specification;
} else {
specification.setTimeseries(step.getMetrics().stream().map(metric -> new SpecificationTM(metric.getMetricId())).collect(Collectors.toList()));
return specification;
}
}
private void println(String message) {
TaskListener listener = DynatraceUtils.getTaskListener(getContext());
if (listener == null) {
LOGGER.log(Level.FINE, "failed to print message {0} due to null TaskListener", message);
} else {
PerfSigUIUtils.createLogger(listener.getLogger()).log(message);
}
}
}
| dynatracesaas/src/main/java/de/tsystems/mms/apm/performancesignature/dynatracesaas/DynatraceReportStepExecution.java | /*
* Copyright (c) 2014-2018 T-Systems Multimedia Solutions GmbH
*
* 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 de.tsystems.mms.apm.performancesignature.dynatracesaas;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import de.tsystems.mms.apm.performancesignature.dynatrace.model.*;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.model.DynatraceServerConfiguration;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.model.Specification;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.model.SpecificationTM;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.DynatraceServerConnection;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.AggregationTypeEnum;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.TimeseriesDataPointQueryResult;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.TimeseriesDefinition;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.rest.model.UnitEnum;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.util.ConversionHelper;
import de.tsystems.mms.apm.performancesignature.dynatracesaas.util.DynatraceUtils;
import de.tsystems.mms.apm.performancesignature.ui.PerfSigBuildAction;
import de.tsystems.mms.apm.performancesignature.ui.util.PerfSigUIUtils;
import hudson.FilePath;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.workflow.steps.MissingContextVariableException;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class DynatraceReportStepExecution extends SynchronousNonBlockingStepExecution<Void> {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(DynatraceReportStepExecution.class.getName());
private static final String DEFAULT_COLOR = "#006bba";
private final transient DynatraceReportStep step;
private FilePath ws;
public DynatraceReportStepExecution(DynatraceReportStep dynatraceReportStep, StepContext context) {
super(context);
this.step = dynatraceReportStep;
}
static void convertUnitOfDataPoints(Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> aggregations) {
for (TimeseriesDataPointQueryResult queryResult : aggregations.values()) {
Map<String, Map<Long, Double>> dataPoints = queryResult.getDataPoints();
if (MapUtils.isEmpty(dataPoints)) continue;
//get the max value from each entity
OptionalDouble maxValue2 = dataPoints.entrySet().stream()
.flatMapToDouble(stringMapEntry -> stringMapEntry.getValue().entrySet().stream()
.filter(longDoubleEntry -> longDoubleEntry.getValue() != null)
.mapToDouble(Map.Entry::getValue)).max();
UnitEnum calculatedUnit = calculateUnitEnum(aggregations.entrySet().iterator().next().getValue(), maxValue2.isPresent() ? maxValue2.getAsDouble() : 0);
Map<String, Map<Long, Double>> convertedDataPoints = new LinkedHashMap<>();
for (Map.Entry<String, Map<Long, Double>> entry : dataPoints.entrySet()) {
String key = entry.getKey();
Map<Long, Double> value = entry.getValue();
Map<Long, Double> convertedValuesPerEntity = new LinkedHashMap<>();
for (Map.Entry<Long, Double> mapEntry : value.entrySet()) {
convertedValuesPerEntity.put(mapEntry.getKey(), ConversionHelper.convertUnit(mapEntry.getValue(), queryResult.getUnit(), calculatedUnit));
}
convertedDataPoints.put(key, convertedValuesPerEntity);
}
queryResult.setUnit(calculatedUnit);
queryResult.getDataPoints().clear();
queryResult.getDataPoints().putAll(convertedDataPoints);
}
}
private static double getMeasurementValue(Map<AggregationTypeEnum, Map<Long, Double>> scalarValues, long key, AggregationTypeEnum aggregation) {
Map<Long, Double> aggregationValues = scalarValues.get(aggregation);
if (MapUtils.isNotEmpty(aggregationValues)) {
return PerfSigUIUtils.roundAsDouble(aggregationValues.get(key));
}
return 0;
}
private static String handleEntityIdString(Map<String, String> entities, String entityId) {
if (StringUtils.isBlank(entityId) || MapUtils.isEmpty(entities)) return null;
String cleanedEntityId = entityId.split(",")[0];
return entities.get(cleanedEntityId);
}
private static Map<AggregationTypeEnum, Map<Long, Double>> getScalarValues(Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> dataPointQueryResultMap) {
Map<AggregationTypeEnum, Map<Long, Double>> hashMap = new LinkedHashMap<>();
dataPointQueryResultMap.forEach((key, value) -> {
Map<String, Map<Long, Double>> dataPoints = value.getDataPoints();
if (dataPoints != null) {
Map<Long, Double> aggregatedValues = dataPoints.values().stream()
.flatMap(test -> test.entrySet().stream())
.filter(longDoubleEntry -> longDoubleEntry.getValue() != null)
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.averagingDouble(Map.Entry::getValue)
)
);
hashMap.put(key, aggregatedValues);
}
});
return hashMap;
}
private static double getScalarValue(TimeseriesDataPointQueryResult dataPointQueryResult) {
if (dataPointQueryResult != null && MapUtils.isNotEmpty(dataPointQueryResult.getDataPoints())) {
OptionalDouble average = dataPointQueryResult.getDataPoints().values().stream()
.flatMap(values -> values.values().stream())
.mapToDouble(a -> a).average();
if (average.isPresent()) return PerfSigUIUtils.roundAsDouble(average.getAsDouble());
}
return 0;
}
private static String translateAggregation(AggregationTypeEnum aggregation) {
switch (aggregation) {
case MIN:
return "Minimum";
case MAX:
return "Maximum";
case AVG:
return "Average";
default:
return StringUtils.capitalize(aggregation.getValue().toLowerCase());
}
}
private static List<Alert> evaluateSpecification(double globalTolerateBound, double globalFrustrateBound, SpecificationTM specTM, Map<AggregationTypeEnum,
TimeseriesDataPointQueryResult> aggregations, Map<String, TimeseriesDefinition> timeseries) {
List<Alert> alerts = new ArrayList<>();
double tolerateBound = Optional.ofNullable(specTM.getLowerLimit()).orElse(globalTolerateBound);
double frustrateBound = Optional.ofNullable(specTM.getUpperLimit()).orElse(globalFrustrateBound);
TimeseriesDataPointQueryResult result = aggregations.get(specTM.getAggregation());
if (specTM.getAggregation() == null || result == null) return alerts;
for (Map.Entry<String, Map<Long, Double>> entry : result.getDataPoints().entrySet()) {
String entity = handleEntityIdString(result.getEntities(), entry.getKey());
for (Map.Entry<Long, Double> e : entry.getValue().entrySet()) {
Long timestamp = e.getKey();
Double value = e.getValue();
if (value != null) {
if (tolerateBound < frustrateBound) {
if (value > tolerateBound && value < frustrateBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.WARNING,
String.format("SpecFile threshold violation: %s upper tolerate bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Upper Bound: %.2f %s",
rule, value, result.getUnit(), entity, tolerateBound, result.getUnit()),
timestamp, rule));
} else if (value > frustrateBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.SEVERE,
String.format("SpecFile threshold violation: %s upper frustrate bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Upper Bound: %.2f %s",
rule, value, result.getUnit(), entity, frustrateBound, result.getUnit()),
timestamp, rule));
}
} else {
if (value < tolerateBound && value > frustrateBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.WARNING,
String.format("SpecFile threshold violation: %s lower tolerate bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Lower Bound: %.2f %s",
rule, value, result.getUnit(), entity, tolerateBound, result.getUnit()),
timestamp, rule));
} else {
if (value < frustrateBound) {
String rule = timeseries.get(result.getTimeseriesId()).getDetailedSource() + " - " + timeseries.get(result.getTimeseriesId()).getDisplayName();
alerts.add(new Alert(Alert.SeverityEnum.SEVERE,
String.format("SpecFile threshold violation: %s lower frustrate bound exceeded", rule),
String.format("%s: Measured peak value: %.2f %s on Entity: %s, Lower Bound: %.2f %s",
rule, value, result.getUnit(), entity, frustrateBound, result.getUnit()),
timestamp, rule));
}
}
}
}
}
}
return alerts;
}
private static UnitEnum calculateUnitEnum(TimeseriesDataPointQueryResult baseResult, double maxValue) {
System.out.println(baseResult);
UnitEnum unit = baseResult.getUnit();
if (ConversionHelper.TIME_UNITS.contains(unit)) {
return UnitEnum.MILLISECOND;
} else {
return ConversionHelper.convertByteUnitEnum(maxValue, unit);
}
}
private static Number getAggregationValue(TimeseriesDataPointQueryResult value, String key, Long timestamp) {
if (value == null) return 0;
return value.getDataPoints().get(key).get(timestamp);
}
public DynatraceReportStep getStep() {
return step;
}
@Override
protected Void run() throws Exception {
Run<?, ?> run = getContext().get(Run.class);
TaskListener listener = getContext().get(TaskListener.class);
ws = getContext().get(FilePath.class);
if (run == null || listener == null) {
throw new IllegalStateException("pipeline step was called without run or task listener in context");
}
if (StringUtils.isNotBlank(step.getSpecFile()) && CollectionUtils.isNotEmpty(step.getMetrics())) {
throw new IllegalArgumentException("At most one of file or text must be provided to " + step.getDescriptor().getFunctionName());
}
if (ws == null && StringUtils.isNotBlank(step.getSpecFile())) {
throw new MissingContextVariableException(FilePath.class);
}
DynatraceServerConnection serverConnection = DynatraceUtils.createDynatraceServerConnection(step.getEnvId(), true);
println("getting metric data from Dynatrace Server");
Map<String, TimeseriesDefinition> timeseries = serverConnection.getTimeseries()
.parallelStream().collect(Collectors.toMap(TimeseriesDefinition::getTimeseriesId, item -> item));
final List<DynatraceEnvInvisAction> envInvisActions = run.getActions(DynatraceEnvInvisAction.class);
final List<DashboardReport> dashboardReports = new ArrayList<>();
Specification spec = getSpecifications();
try {
for (DynatraceEnvInvisAction dynatraceAction : envInvisActions) {
Long start = dynatraceAction.getTimeframeStart();
Long end = dynatraceAction.getTimeframeStop();
DashboardReport dashboardReport = new DashboardReport(dynatraceAction.getTestCase());
//set url for Dynatrace dashboard
DynatraceServerConfiguration configuration = serverConnection.getConfiguration();
dashboardReport.setClientUrl(String.format("%s/#dashboard;gtf=c_%d_%d", configuration.getServerUrl(), start, end));
//iterate over specified timeseries ids
spec.getTimeseries().forEach(specTM -> {
TimeseriesDefinition tm = timeseries.get(specTM.getTimeseriesId());
//get data points for every possible aggregation
Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> aggregations = tm.getAggregationTypes().parallelStream()
.collect(Collectors.toMap(
Function.identity(),
aggregation -> serverConnection.getTimeseriesData(specTM.getTimeseriesId(), start, end, aggregation, specTM.getEntityIds(), specTM.getTags()),
(a, b) -> b, LinkedHashMap::new)
);
convertUnitOfDataPoints(aggregations);
TimeseriesDataPointQueryResult baseResult = aggregations.get(AggregationTypeEnum.AVG);
if (baseResult != null && MapUtils.isNotEmpty(baseResult.getDataPoints())) {
//get a scalar value for every possible aggregation
Map<AggregationTypeEnum, TimeseriesDataPointQueryResult> totalValues = tm.getAggregationTypes().parallelStream()
.collect(Collectors.toMap(Function.identity(),
aggregation -> serverConnection.getTotalTimeseriesData(specTM.getTimeseriesId(), start, end, aggregation, specTM.getEntityIds(), specTM.getTags()),
(a, b) -> b, LinkedHashMap::new));
convertUnitOfDataPoints(totalValues);
//evaluate possible incidents
dashboardReport.getIncidents().addAll(evaluateSpecification(spec.getLowerLimit(), spec.getUpperLimit(),
specTM, aggregations, timeseries));
ChartDashlet chartDashlet = new ChartDashlet();
chartDashlet.setName(tm.getDetailedSource() + " - " + tm.getDisplayName());
//create aggregated overall measure
Measure overallMeasure = new Measure("overall");
overallMeasure.setAggregation(translateAggregation(specTM.getAggregation()));
overallMeasure.setColor(DEFAULT_COLOR);
UnitEnum calculatedUnit = calculateUnitEnum(baseResult, getScalarValue(totalValues.get(AggregationTypeEnum.MAX)));
overallMeasure.setUnit(calculatedUnit.getValue());
//calculate aggregated values from totalValues
overallMeasure.setAvg(getScalarValue(totalValues.get(AggregationTypeEnum.AVG)));
overallMeasure.setMin(getScalarValue(totalValues.get(AggregationTypeEnum.MIN)));
overallMeasure.setMax(getScalarValue(totalValues.get(AggregationTypeEnum.MAX)));
overallMeasure.setSum(getScalarValue(totalValues.get(AggregationTypeEnum.SUM)));
overallMeasure.setCount(getScalarValue(totalValues.get(AggregationTypeEnum.COUNT)));
//calculate aggregated values from seriesValues
Map<AggregationTypeEnum, Map<Long, Double>> scalarValues = getScalarValues(aggregations);
scalarValues.entrySet().iterator().next().getValue().keySet().forEach(entry -> {
Measurement m = new Measurement(entry,
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.AVG),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.MIN),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.MAX),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.SUM),
getMeasurementValue(scalarValues, entry, AggregationTypeEnum.COUNT)
);
overallMeasure.getMeasurements().add(m);
});
chartDashlet.getMeasures().add(overallMeasure);
//iterate over every entityId
baseResult.getDataPoints().forEach((key, value) -> {
Map<AggregationTypeEnum, Double> totalValuesPerDataPoint = tm.getAggregationTypes().stream()
.collect(Collectors.toMap(Function.identity(),
aggregation -> totalValues.get(aggregation).getDataPoints().get(key).entrySet().iterator().next().getValue(),
(a, b) -> b, LinkedHashMap::new));
Measure measure = new Measure(handleEntityIdString(baseResult.getEntities(), key));
measure.setAggregation(translateAggregation(specTM.getAggregation()));
measure.setUnit(calculatedUnit.getValue());
measure.setColor(DEFAULT_COLOR);
measure.setAvg(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.AVG, 0D));
measure.setMin(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.MIN, 0D));
measure.setMax(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.MAX, 0D));
measure.setSum(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.SUM, 0D));
measure.setCount(totalValuesPerDataPoint.getOrDefault(AggregationTypeEnum.COUNT, 0D));
value.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.forEach(entry -> {
Measurement m = new Measurement(entry.getKey(),
getAggregationValue(aggregations.get(AggregationTypeEnum.AVG), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.MIN), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.MAX), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.SUM), key, entry.getKey()),
getAggregationValue(aggregations.get(AggregationTypeEnum.COUNT), key, entry.getKey())
);
measure.getMeasurements().add(m);
});
chartDashlet.getMeasures().add(measure);
});
dashboardReport.addChartDashlet(chartDashlet);
} else {
println(String.format("Timeseries %s has no data points", tm.getTimeseriesId()));
}
});
dashboardReports.add(dashboardReport);
PrintStream stream = Optional.ofNullable(DynatraceUtils.getTaskListener(getContext())).map(TaskListener::getLogger).orElseGet(() -> new PrintStream(System.out));
PerfSigUIUtils.handleIncidents(run, dashboardReport.getIncidents(), PerfSigUIUtils.createLogger(stream), step.getNonFunctionalFailure());
}
} finally {
println("created " + dashboardReports.size() + " DashboardReports");
PerfSigBuildAction action = new PerfSigBuildAction(dashboardReports);
run.addAction(action);
}
return null;
}
private Specification getSpecifications() throws IOException, InterruptedException {
Specification specification = new Specification();
if (ws != null && StringUtils.isNotBlank(step.getSpecFile())) {
FilePath f = ws.child(step.getSpecFile());
if (f.exists() && !f.isDirectory()) {
try (InputStream is = f.read()) {
Type type = new TypeToken<Specification>() {
}.getType();
return new Gson().fromJson(IOUtils.toString(is, StandardCharsets.UTF_8), type);
}
} else if (f.isDirectory()) {
throw new IllegalArgumentException(f.getRemote() + " is a directory ...");
} else if (!f.exists()) {
throw new FileNotFoundException(f.getRemote() + " does not exist ...");
}
return specification;
} else {
specification.setTimeseries(step.getMetrics().stream().map(metric -> new SpecificationTM(metric.getMetricId())).collect(Collectors.toList()));
return specification;
}
}
private void println(String message) {
TaskListener listener = DynatraceUtils.getTaskListener(getContext());
if (listener == null) {
LOGGER.log(Level.FINE, "failed to print message {0} due to null TaskListener", message);
} else {
PerfSigUIUtils.createLogger(listener.getLogger()).log(message);
}
}
}
| changed wording 2/2
| dynatracesaas/src/main/java/de/tsystems/mms/apm/performancesignature/dynatracesaas/DynatraceReportStepExecution.java | changed wording 2/2 |
|
Java | apache-2.0 | c43aa49eb82b50460d78c76db52179b94200a614 | 0 | gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom | /*
* Copyright 2016 Crown Copyright
*
* 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 stroom.dashboard.client.query;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.View;
import stroom.alert.client.event.AlertEvent;
import stroom.dashboard.client.main.AbstractComponentPresenter;
import stroom.dashboard.client.main.ComponentRegistry.ComponentType;
import stroom.dashboard.client.main.IndexLoader;
import stroom.dashboard.client.main.SearchBus;
import stroom.dashboard.client.main.SearchModel;
import stroom.dashboard.client.main.UsesParams;
import stroom.dashboard.client.table.TimeZones;
import stroom.dashboard.shared.ComponentConfig;
import stroom.dashboard.shared.Dashboard;
import stroom.dashboard.shared.QueryKeyImpl;
import stroom.data.client.event.DataSelectionEvent;
import stroom.data.client.event.DataSelectionEvent.DataSelectionHandler;
import stroom.dispatch.client.AsyncCallbackAdaptor;
import stroom.dispatch.client.ClientDispatchAsync;
import stroom.entity.client.event.DirtyEvent;
import stroom.entity.client.event.DirtyEvent.DirtyHandler;
import stroom.entity.client.event.HasDirtyHandlers;
import stroom.entity.shared.DocRef;
import stroom.explorer.client.presenter.ExplorerDropDownTreePresenter;
import stroom.explorer.shared.ExplorerData;
import stroom.node.client.ClientPropertyCache;
import stroom.node.shared.ClientProperties;
import stroom.pipeline.client.event.ChangeDataEvent;
import stroom.pipeline.client.event.ChangeDataEvent.ChangeDataHandler;
import stroom.pipeline.client.event.CreateProcessorEvent;
import stroom.pipeline.processor.shared.CreateProcessorAction;
import stroom.pipeline.shared.PipelineEntity;
import stroom.query.client.ExpressionTreePresenter;
import stroom.query.client.ExpressionUiHandlers;
import stroom.query.shared.Automate;
import stroom.query.shared.ComponentSettings;
import stroom.query.shared.ExpressionItem;
import stroom.query.shared.ExpressionOperator;
import stroom.query.shared.IndexField;
import stroom.query.shared.IndexFieldsMap;
import stroom.query.shared.Limits;
import stroom.query.shared.QueryData;
import stroom.security.client.ClientSecurityContext;
import stroom.security.shared.DocumentPermissionNames;
import stroom.streamstore.shared.FindStreamCriteria;
import stroom.streamtask.shared.StreamProcessor;
import stroom.streamtask.shared.StreamProcessorFilter;
import stroom.util.shared.EqualsBuilder;
import stroom.util.shared.ModelStringUtil;
import stroom.widget.button.client.GlyphButtonView;
import stroom.widget.button.client.GlyphIcon;
import stroom.widget.button.client.GlyphIcons;
import stroom.widget.button.client.ImageButtonView;
import stroom.widget.contextmenu.client.event.ContextMenuEvent;
import stroom.widget.menu.client.presenter.IconMenuItem;
import stroom.widget.menu.client.presenter.Item;
import stroom.widget.menu.client.presenter.MenuListPresenter;
import stroom.widget.popup.client.event.HidePopupEvent;
import stroom.widget.popup.client.event.ShowPopupEvent;
import stroom.widget.popup.client.presenter.PopupPosition;
import stroom.widget.popup.client.presenter.PopupSize;
import stroom.widget.popup.client.presenter.PopupUiHandlers;
import stroom.widget.popup.client.presenter.PopupView.PopupType;
import stroom.widget.tab.client.presenter.ImageIcon;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class QueryPresenter extends AbstractComponentPresenter<QueryPresenter.QueryView>
implements QueryUiHandlers, HasDirtyHandlers, UsesParams {
public static final ComponentType TYPE = new ComponentType(0, "query", "Query");
private static final long DEFAULT_TIME_LIMIT = 30L;
private static final long DEFAULT_RECORD_LIMIT = 1000000L;
private static final int TEN_SECONDS = 10000;
private final ExpressionTreePresenter expressionPresenter;
private final QueryHistoryPresenter historyPresenter;
private final QueryFavouritesPresenter favouritesPresenter;
private final Provider<ExplorerDropDownTreePresenter> pipelineSelection;
private final ProcessorLimitsPresenter processorLimitsPresenter;
private final Resources resources;
private final MenuListPresenter menuListPresenter;
private final ClientDispatchAsync dispatcher;
private final IndexLoader indexLoader;
private final SearchModel searchModel;
private final ImageButtonView addOperatorButton;
private final GlyphButtonView addTermButton;
private final GlyphButtonView disableItemButton;
private final GlyphButtonView deleteItemButton;
private final ImageButtonView historyButton;
private final ImageButtonView favouriteButton;
private final ImageButtonView warningsButton;
private String params;
private QueryData queryData;
private String currentWarnings;
private ImageButtonView processButton;
private long defaultProcessorTimeLimit = DEFAULT_TIME_LIMIT;
private long defaultProcessorRecordLimit = DEFAULT_RECORD_LIMIT;
private boolean initialised;
private Timer autoRefreshTimer;
@Inject
public QueryPresenter(final EventBus eventBus, final QueryView view, final SearchBus searchBus,
final Provider<QuerySettingsPresenter> settingsPresenterProvider,
final ExpressionTreePresenter expressionPresenter, final QueryHistoryPresenter historyPresenter,
final QueryFavouritesPresenter favouritesPresenter,
final Provider<ExplorerDropDownTreePresenter> pipelineSelection,
final ProcessorLimitsPresenter processorLimitsPresenter, final Resources resources,
final MenuListPresenter menuListPresenter, final ClientDispatchAsync dispatcher,
final ClientSecurityContext securityContext, final ClientPropertyCache clientPropertyCache,
final TimeZones timeZones) {
super(eventBus, view, settingsPresenterProvider);
this.expressionPresenter = expressionPresenter;
this.historyPresenter = historyPresenter;
this.favouritesPresenter = favouritesPresenter;
this.pipelineSelection = pipelineSelection;
this.processorLimitsPresenter = processorLimitsPresenter;
this.menuListPresenter = menuListPresenter;
this.resources = resources;
this.dispatcher = dispatcher;
view.setExpressionView(expressionPresenter.getView());
view.setUiHandlers(this);
expressionPresenter.setUiHandlers(new ExpressionUiHandlers() {
@Override
public void fireDirty() {
setDirty(true);
}
@Override
public void search() {
start();
}
});
addTermButton = view.addButton(GlyphIcons.ADD);
addTermButton.setTitle("Add Term");
addOperatorButton = view.addButton("Add Operator", resources.addOperator(), resources.addOperator(), true);
disableItemButton = view.addButton(GlyphIcons.DISABLE);
deleteItemButton = view.addButton(GlyphIcons.DELETE);
historyButton = view.addButton("History", resources.history(), null, true);
favouriteButton = view.addButton("Favourites", resources.favourite(), null, true);
if (securityContext.hasAppPermission(StreamProcessor.MANAGE_PROCESSORS_PERMISSION)) {
processButton = view.addButton("Process", resources.pipeline(), resources.pipelineDisabled(), true);
}
warningsButton = view.addButton("Show Warnings", resources.warning(), null, true);
warningsButton.setVisible(false);
indexLoader = new IndexLoader(getEventBus(), dispatcher);
searchModel = new SearchModel(searchBus, this, indexLoader, timeZones);
clientPropertyCache.get(new AsyncCallbackAdaptor<ClientProperties>() {
@Override
public void onSuccess(final ClientProperties result) {
defaultProcessorTimeLimit = result.getLong(ClientProperties.PROCESS_TIME_LIMIT, DEFAULT_TIME_LIMIT);
defaultProcessorRecordLimit = result.getLong(ClientProperties.PROCESS_RECORD_LIMIT,
DEFAULT_RECORD_LIMIT);
}
@Override
public void onFailure(final Throwable caught) {
AlertEvent.fireError(QueryPresenter.this, caught.getMessage(), null);
}
});
}
@Override
protected void onBind() {
super.onBind();
registerHandler(expressionPresenter.addDataSelectionHandler(new DataSelectionHandler<ExpressionItem>() {
@Override
public void onSelection(final DataSelectionEvent<ExpressionItem> event) {
setButtonsEnabled();
}
}));
registerHandler(expressionPresenter.addContextMenuHandler(new ContextMenuEvent.Handler() {
@Override
public void onContextMenu(final ContextMenuEvent event) {
final List<Item> menuItems = addExpressionActionsToMenu();
if (menuItems != null && menuItems.size() > 0) {
final PopupPosition popupPosition = new PopupPosition(event.getX(), event.getY());
showMenu(popupPosition, menuItems);
}
}
}));
registerHandler(addOperatorButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
addOperator();
}
}
}));
registerHandler(addTermButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
addTerm();
}
}
}));
registerHandler(disableItemButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
disable();
}
}
}));
registerHandler(deleteItemButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
delete();
}
}
}));
registerHandler(historyButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
historyPresenter.show(QueryPresenter.this, getComponents().getDashboard().getId());
}
}
}));
registerHandler(favouriteButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
final ExpressionOperator root = new ExpressionOperator();
expressionPresenter.write(root);
favouritesPresenter.show(QueryPresenter.this, getComponents().getDashboard().getId(),
getSettings().getDataSource(), root);
}
}
}));
if (processButton != null) {
registerHandler(processButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
choosePipeline();
}
}
}));
}
registerHandler(warningsButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
showWarnings();
}
}
}));
registerHandler(indexLoader.addChangeDataHandler(new ChangeDataHandler<IndexLoader>() {
@Override
public void onChange(final ChangeDataEvent<IndexLoader> event) {
loadedDataSource(indexLoader.getLoadedDataSourceRef(), indexLoader.getIndexFieldsMap());
}
}));
}
public void setErrors(final String errors) {
currentWarnings = errors;
warningsButton.setVisible(currentWarnings != null && currentWarnings.length() > 0);
}
private void setButtonsEnabled() {
final ExpressionItem selectedItem = getSelectedItem();
if (selectedItem == null) {
disableItemButton.setEnabled(false);
disableItemButton.setTitle("");
} else {
disableItemButton.setEnabled(true);
disableItemButton.setTitle(getEnableDisableText());
}
if (selectedItem == null) {
deleteItemButton.setEnabled(false);
deleteItemButton.setTitle("");
} else {
deleteItemButton.setEnabled(true);
deleteItemButton.setTitle("Delete");
}
}
private void loadDataSource(final DocRef dataSourceRef) {
searchModel.getIndexLoader().loadDataSource(dataSourceRef);
}
private void loadedDataSource(final DocRef dataSourceRef, final IndexFieldsMap indexFieldsMap) {
// Create a list of index fields.
final List<IndexField> indexedFields = new ArrayList<>();
if (indexFieldsMap != null) {
for (final IndexField indexField : indexFieldsMap.values()) {
if (indexField.isIndexed()) {
indexedFields.add(indexField);
}
}
}
Collections.sort(indexedFields);
expressionPresenter.setFields(indexedFields);
final EqualsBuilder builder = new EqualsBuilder();
builder.append(queryData.getDataSource(), dataSourceRef);
if (!builder.isEquals()) {
queryData.setDataSource(dataSourceRef);
setDirty(true);
}
// Only allow searching if we have a data source and have loaded fields from it successfully.
getView().setEnabled(dataSourceRef != null && indexedFields.size() > 0);
init();
}
private void addOperator() {
expressionPresenter.addOperator();
}
private void addTerm() {
final DocRef dataSourceRef = queryData.getDataSource();
if (dataSourceRef == null) {
warnNoDataSource();
} else {
expressionPresenter.addTerm();
}
}
private void warnNoDataSource() {
AlertEvent.fireWarn(this, "No data source has been chosen to search", null);
}
private void disable() {
expressionPresenter.disable();
setButtonsEnabled();
}
private void delete() {
expressionPresenter.delete();
}
private void choosePipeline() {
expressionPresenter.clearSelection();
// Write expression.
final ExpressionOperator root = new ExpressionOperator();
expressionPresenter.write(root);
final QueryData queryData = new QueryData();
queryData.setDataSource(this.queryData.getDataSource());
queryData.setExpression(root);
final ExplorerDropDownTreePresenter chooser = pipelineSelection.get();
chooser.setCaption("Choose Pipeline To Process Results With");
chooser.setIncludedTypes(PipelineEntity.ENTITY_TYPE);
chooser.setRequiredPermissions(DocumentPermissionNames.USE);
chooser.addDataSelectionHandler(new DataSelectionHandler<ExplorerData>() {
@Override
public void onSelection(final DataSelectionEvent<ExplorerData> event) {
final DocRef pipeline = chooser.getSelectedEntityReference();
if (pipeline != null) {
setProcessorLimits(queryData, pipeline);
}
}
});
chooser.show();
}
private void setProcessorLimits(final QueryData queryData, final DocRef pipeline) {
processorLimitsPresenter.setTimeLimitMins(defaultProcessorTimeLimit);
processorLimitsPresenter.setRecordLimit(defaultProcessorRecordLimit);
final PopupSize popupSize = new PopupSize(321, 102, false);
ShowPopupEvent.fire(this, processorLimitsPresenter, PopupType.OK_CANCEL_DIALOG, popupSize,
"Process Search Results", new PopupUiHandlers() {
@Override
public void onHideRequest(final boolean autoClose, final boolean ok) {
if (ok) {
final Limits limits = new Limits();
if (processorLimitsPresenter.getRecordLimit() != null) {
limits.setEventCount(processorLimitsPresenter.getRecordLimit());
}
if (processorLimitsPresenter.getTimeLimitMins() != null) {
limits.setDurationMs(processorLimitsPresenter.getTimeLimitMins() * 60 * 1000);
}
queryData.setLimits(limits);
openEditor(queryData, pipeline);
}
HidePopupEvent.fire(QueryPresenter.this, processorLimitsPresenter);
}
@Override
public void onHide(final boolean autoClose, final boolean ok) {
}
});
}
private void openEditor(final QueryData queryData, final DocRef pipeline) {
// Now create the processor filter using the find stream criteria.
final FindStreamCriteria findStreamCriteria = new FindStreamCriteria();
findStreamCriteria.setQueryData(queryData);
dispatcher.execute(new CreateProcessorAction(pipeline, findStreamCriteria, true, 1),
new AsyncCallbackAdaptor<StreamProcessorFilter>() {
@Override
public void onSuccess(final StreamProcessorFilter streamProcessorFilter) {
CreateProcessorEvent.fire(QueryPresenter.this, streamProcessorFilter);
}
});
}
private void showWarnings() {
if (currentWarnings != null && currentWarnings.length() > 0) {
AlertEvent.fireWarn(this, "The following warnings have been created while running this search:",
currentWarnings, null);
}
}
@Override
public void onParamsChanged(final String params) {
this.params = params;
if (initialised) {
stop();
start();
}
}
@Override
public void start() {
run(true);
}
@Override
public void stop() {
if (autoRefreshTimer != null) {
autoRefreshTimer.cancel();
autoRefreshTimer = null;
}
searchModel.destroy();
}
private void run(final boolean incremental) {
final DocRef dataSourceRef = queryData.getDataSource();
if (dataSourceRef == null) {
warnNoDataSource();
} else {
currentWarnings = null;
expressionPresenter.clearSelection();
warningsButton.setVisible(false);
// Write expression.
final ExpressionOperator root = new ExpressionOperator();
expressionPresenter.write(root);
searchModel.search(root, params, incremental);
}
}
@Override
public void read(final ComponentConfig componentData) {
super.read(componentData);
queryData = getSettings();
// Create and register the search model.
final Dashboard dashboard = getComponents().getDashboard();
final QueryKeyImpl initialQueryKey = new QueryKeyImpl(dashboard.getId(), dashboard.getName(),
getComponentData().getId());
searchModel.setInitialQueryKey(initialQueryKey);
// Read data source.
loadDataSource(queryData.getDataSource());
// Read expression.
ExpressionOperator root = queryData.getExpression();
if (root == null) {
root = new ExpressionOperator();
}
setExpression(root);
}
@Override
public void write(final ComponentConfig componentData) {
super.write(componentData);
// Write expression.
ExpressionOperator root = queryData.getExpression();
if (root == null) {
root = new ExpressionOperator();
queryData.setExpression(root);
}
expressionPresenter.write(root);
componentData.setSettings(queryData);
}
@Override
public void onRemove() {
super.onRemove();
searchModel.destroy();
}
@Override
public void link() {
}
private void init() {
if (!initialised) {
initialised = true;
// An auto search can only commence if the UI has fully loaded and the data source has also loaded from the server.
final Automate automate = getAutomate();
if (automate.isOpen()) {
run(true);
}
}
}
@Override
public void changeSettings() {
super.changeSettings();
loadDataSource(queryData.getDataSource());
}
@Override
public HandlerRegistration addDirtyHandler(final DirtyHandler handler) {
return addHandlerToSource(DirtyEvent.getType(), handler);
}
@Override
public ComponentType getType() {
return TYPE;
}
private QueryData getSettings() {
ComponentSettings settings = getComponentData().getSettings();
if (settings == null || !(settings instanceof QueryData)) {
settings = createSettings();
getComponentData().setSettings(settings);
}
return (QueryData) settings;
}
private Automate getAutomate() {
final QueryData queryData = getSettings();
Automate automate = queryData.getAutomate();
if (automate == null) {
automate = new Automate();
queryData.setAutomate(automate);
}
return automate;
}
private ComponentSettings createSettings() {
return new QueryData();
}
public SearchModel getSearchModel() {
return searchModel;
}
public void setExpression(final ExpressionOperator root) {
expressionPresenter.read(root);
}
public void setMode(final SearchModel.Mode mode) {
getView().setMode(mode);
// If this is the end of a query then schedule a refresh.
if (SearchModel.Mode.INACTIVE.equals(mode)) {
scheduleRefresh();
}
}
private void scheduleRefresh() {
// Schedule auto refresh after a query has finished.
if (autoRefreshTimer != null) {
autoRefreshTimer.cancel();
}
autoRefreshTimer = null;
final Automate automate = getAutomate();
if (automate.isRefresh()) {
try {
final String interval = automate.getRefreshInterval();
int millis = ModelStringUtil.parseDurationString(interval).intValue();
// Ensure that the refresh interval is not less than 10 seconds.
millis = Math.max(millis, TEN_SECONDS);
autoRefreshTimer = new Timer() {
@Override
public void run() {
// Make sure search is currently inactive before we attempt to execute a new query.
if (SearchModel.Mode.INACTIVE.equals(searchModel.getMode())) {
QueryPresenter.this.run(false);
}
}
};
autoRefreshTimer.schedule(millis);
} catch (final Exception e) {
// Ignore as we cannot display this error now.
}
}
}
private List<Item> addExpressionActionsToMenu() {
final ExpressionItem selectedItem = getSelectedItem();
final boolean hasSelection = selectedItem != null;
final List<Item> menuItems = new ArrayList<Item>();
menuItems.add(new IconMenuItem(1, GlyphIcons.ADD, GlyphIcons.ADD, "Add Term", null, true, new Command() {
@Override
public void execute() {
addTerm();
}
}));
menuItems.add(new IconMenuItem(2, ImageIcon.create(resources.addOperator()), ImageIcon.create(resources.addOperator()), "Add Operator", null,
true, new Command() {
@Override
public void execute() {
addOperator();
}
}));
menuItems.add(new IconMenuItem(3, GlyphIcons.DISABLE, GlyphIcons.DISABLE, getEnableDisableText(),
null, hasSelection, new Command() {
@Override
public void execute() {
disable();
}
}));
menuItems.add(new IconMenuItem(4, GlyphIcons.DELETE, GlyphIcons.DELETE, "Delete", null,
hasSelection, new Command() {
@Override
public void execute() {
delete();
}
}));
return menuItems;
}
private String getEnableDisableText() {
final ExpressionItem selectedItem = getSelectedItem();
if (selectedItem != null && !selectedItem.isEnabled()) {
return "Enable";
}
return "Disable";
}
private ExpressionItem getSelectedItem() {
if (expressionPresenter.getSelectionModel() != null) {
return expressionPresenter.getSelectionModel().getSelectedObject();
}
return null;
}
private void showMenu(final PopupPosition popupPosition, final List<Item> menuItems) {
menuListPresenter.setData(menuItems);
final PopupUiHandlers popupUiHandlers = new PopupUiHandlers() {
@Override
public void onHideRequest(final boolean autoClose, final boolean ok) {
HidePopupEvent.fire(QueryPresenter.this, menuListPresenter);
}
@Override
public void onHide(final boolean autoClose, final boolean ok) {
}
};
ShowPopupEvent.fire(this, menuListPresenter, PopupType.POPUP, popupPosition, popupUiHandlers);
}
public interface QueryView extends View, HasUiHandlers<QueryUiHandlers> {
ImageButtonView addButton(String title, ImageResource enabledImage, ImageResource disabledImage,
boolean enabled);
GlyphButtonView addButton(GlyphIcon preset);
void setExpressionView(View view);
void setMode(SearchModel.Mode mode);
void setEnabled(boolean enabled);
}
public interface Resources extends ClientBundle {
ImageResource addOperator();
ImageResource search();
ImageResource history();
ImageResource favourite();
ImageResource pipeline();
ImageResource pipelineDisabled();
ImageResource warning();
}
}
| stroom-dashboard/src/main/java/stroom/dashboard/client/query/QueryPresenter.java | /*
* Copyright 2016 Crown Copyright
*
* 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 stroom.dashboard.client.query;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.View;
import stroom.alert.client.event.AlertEvent;
import stroom.dashboard.client.main.AbstractComponentPresenter;
import stroom.dashboard.client.main.ComponentRegistry.ComponentType;
import stroom.dashboard.client.main.IndexLoader;
import stroom.dashboard.client.main.SearchBus;
import stroom.dashboard.client.main.SearchModel;
import stroom.dashboard.client.main.UsesParams;
import stroom.dashboard.client.table.TimeZones;
import stroom.dashboard.shared.ComponentConfig;
import stroom.dashboard.shared.Dashboard;
import stroom.dashboard.shared.QueryKeyImpl;
import stroom.data.client.event.DataSelectionEvent;
import stroom.data.client.event.DataSelectionEvent.DataSelectionHandler;
import stroom.dispatch.client.AsyncCallbackAdaptor;
import stroom.dispatch.client.ClientDispatchAsync;
import stroom.entity.client.event.DirtyEvent;
import stroom.entity.client.event.DirtyEvent.DirtyHandler;
import stroom.entity.client.event.HasDirtyHandlers;
import stroom.entity.shared.DocRef;
import stroom.explorer.client.presenter.ExplorerDropDownTreePresenter;
import stroom.explorer.shared.ExplorerData;
import stroom.node.client.ClientPropertyCache;
import stroom.node.shared.ClientProperties;
import stroom.pipeline.client.event.ChangeDataEvent;
import stroom.pipeline.client.event.ChangeDataEvent.ChangeDataHandler;
import stroom.pipeline.client.event.CreateProcessorEvent;
import stroom.pipeline.processor.shared.CreateProcessorAction;
import stroom.pipeline.shared.PipelineEntity;
import stroom.query.client.ExpressionTreePresenter;
import stroom.query.client.ExpressionUiHandlers;
import stroom.query.shared.Automate;
import stroom.query.shared.ComponentSettings;
import stroom.query.shared.ExpressionItem;
import stroom.query.shared.ExpressionOperator;
import stroom.query.shared.IndexField;
import stroom.query.shared.IndexFieldsMap;
import stroom.query.shared.Limits;
import stroom.query.shared.QueryData;
import stroom.security.client.ClientSecurityContext;
import stroom.security.shared.DocumentPermissionNames;
import stroom.streamstore.shared.FindStreamCriteria;
import stroom.streamtask.shared.StreamProcessor;
import stroom.streamtask.shared.StreamProcessorFilter;
import stroom.util.shared.EqualsBuilder;
import stroom.util.shared.ModelStringUtil;
import stroom.widget.button.client.GlyphButtonView;
import stroom.widget.button.client.GlyphIcon;
import stroom.widget.button.client.GlyphIcons;
import stroom.widget.button.client.ImageButtonView;
import stroom.widget.contextmenu.client.event.ContextMenuEvent;
import stroom.widget.menu.client.presenter.IconMenuItem;
import stroom.widget.menu.client.presenter.Item;
import stroom.widget.menu.client.presenter.MenuListPresenter;
import stroom.widget.popup.client.event.HidePopupEvent;
import stroom.widget.popup.client.event.ShowPopupEvent;
import stroom.widget.popup.client.presenter.PopupPosition;
import stroom.widget.popup.client.presenter.PopupSize;
import stroom.widget.popup.client.presenter.PopupUiHandlers;
import stroom.widget.popup.client.presenter.PopupView.PopupType;
import stroom.widget.tab.client.presenter.ImageIcon;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class QueryPresenter extends AbstractComponentPresenter<QueryPresenter.QueryView>
implements QueryUiHandlers, HasDirtyHandlers, UsesParams {
public static final ComponentType TYPE = new ComponentType(0, "query", "Query");
private static final long DEFAULT_TIME_LIMIT = 30L;
private static final long DEFAULT_RECORD_LIMIT = 1000000L;
private final ExpressionTreePresenter expressionPresenter;
private final QueryHistoryPresenter historyPresenter;
private final QueryFavouritesPresenter favouritesPresenter;
private final Provider<ExplorerDropDownTreePresenter> pipelineSelection;
private final ProcessorLimitsPresenter processorLimitsPresenter;
private final Resources resources;
private final MenuListPresenter menuListPresenter;
private final ClientDispatchAsync dispatcher;
private final IndexLoader indexLoader;
private final SearchModel searchModel;
private final ImageButtonView addOperatorButton;
private final GlyphButtonView addTermButton;
private final GlyphButtonView disableItemButton;
private final GlyphButtonView deleteItemButton;
private final ImageButtonView historyButton;
private final ImageButtonView favouriteButton;
private final ImageButtonView warningsButton;
private String params;
private QueryData queryData;
private String currentWarnings;
private ImageButtonView processButton;
private long defaultProcessorTimeLimit = DEFAULT_TIME_LIMIT;
private long defaultProcessorRecordLimit = DEFAULT_RECORD_LIMIT;
private boolean initialised;
private Timer autoRefreshTimer;
@Inject
public QueryPresenter(final EventBus eventBus, final QueryView view, final SearchBus searchBus,
final Provider<QuerySettingsPresenter> settingsPresenterProvider,
final ExpressionTreePresenter expressionPresenter, final QueryHistoryPresenter historyPresenter,
final QueryFavouritesPresenter favouritesPresenter,
final Provider<ExplorerDropDownTreePresenter> pipelineSelection,
final ProcessorLimitsPresenter processorLimitsPresenter, final Resources resources,
final MenuListPresenter menuListPresenter, final ClientDispatchAsync dispatcher,
final ClientSecurityContext securityContext, final ClientPropertyCache clientPropertyCache,
final TimeZones timeZones) {
super(eventBus, view, settingsPresenterProvider);
this.expressionPresenter = expressionPresenter;
this.historyPresenter = historyPresenter;
this.favouritesPresenter = favouritesPresenter;
this.pipelineSelection = pipelineSelection;
this.processorLimitsPresenter = processorLimitsPresenter;
this.menuListPresenter = menuListPresenter;
this.resources = resources;
this.dispatcher = dispatcher;
view.setExpressionView(expressionPresenter.getView());
view.setUiHandlers(this);
expressionPresenter.setUiHandlers(new ExpressionUiHandlers() {
@Override
public void fireDirty() {
setDirty(true);
}
@Override
public void search() {
start();
}
});
addTermButton = view.addButton(GlyphIcons.ADD);
addTermButton.setTitle("Add Term");
addOperatorButton = view.addButton("Add Operator", resources.addOperator(), resources.addOperator(), true);
disableItemButton = view.addButton(GlyphIcons.DISABLE);
deleteItemButton = view.addButton(GlyphIcons.DELETE);
historyButton = view.addButton("History", resources.history(), null, true);
favouriteButton = view.addButton("Favourites", resources.favourite(), null, true);
if (securityContext.hasAppPermission(StreamProcessor.MANAGE_PROCESSORS_PERMISSION)) {
processButton = view.addButton("Process", resources.pipeline(), resources.pipelineDisabled(), true);
}
warningsButton = view.addButton("Show Warnings", resources.warning(), null, true);
warningsButton.setVisible(false);
indexLoader = new IndexLoader(getEventBus(), dispatcher);
searchModel = new SearchModel(searchBus, this, indexLoader, timeZones);
clientPropertyCache.get(new AsyncCallbackAdaptor<ClientProperties>() {
@Override
public void onSuccess(final ClientProperties result) {
defaultProcessorTimeLimit = result.getLong(ClientProperties.PROCESS_TIME_LIMIT, DEFAULT_TIME_LIMIT);
defaultProcessorRecordLimit = result.getLong(ClientProperties.PROCESS_RECORD_LIMIT,
DEFAULT_RECORD_LIMIT);
}
@Override
public void onFailure(final Throwable caught) {
AlertEvent.fireError(QueryPresenter.this, caught.getMessage(), null);
}
});
}
@Override
protected void onBind() {
super.onBind();
registerHandler(expressionPresenter.addDataSelectionHandler(new DataSelectionHandler<ExpressionItem>() {
@Override
public void onSelection(final DataSelectionEvent<ExpressionItem> event) {
setButtonsEnabled();
}
}));
registerHandler(expressionPresenter.addContextMenuHandler(new ContextMenuEvent.Handler() {
@Override
public void onContextMenu(final ContextMenuEvent event) {
final List<Item> menuItems = addExpressionActionsToMenu();
if (menuItems != null && menuItems.size() > 0) {
final PopupPosition popupPosition = new PopupPosition(event.getX(), event.getY());
showMenu(popupPosition, menuItems);
}
}
}));
registerHandler(addOperatorButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
addOperator();
}
}
}));
registerHandler(addTermButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
addTerm();
}
}
}));
registerHandler(disableItemButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
disable();
}
}
}));
registerHandler(deleteItemButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
delete();
}
}
}));
registerHandler(historyButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
historyPresenter.show(QueryPresenter.this, getComponents().getDashboard().getId());
}
}
}));
registerHandler(favouriteButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
final ExpressionOperator root = new ExpressionOperator();
expressionPresenter.write(root);
favouritesPresenter.show(QueryPresenter.this, getComponents().getDashboard().getId(),
getSettings().getDataSource(), root);
}
}
}));
if (processButton != null) {
registerHandler(processButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
choosePipeline();
}
}
}));
}
registerHandler(warningsButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
if ((event.getNativeButton() & NativeEvent.BUTTON_LEFT) != 0) {
showWarnings();
}
}
}));
registerHandler(indexLoader.addChangeDataHandler(new ChangeDataHandler<IndexLoader>() {
@Override
public void onChange(final ChangeDataEvent<IndexLoader> event) {
loadedDataSource(indexLoader.getLoadedDataSourceRef(), indexLoader.getIndexFieldsMap());
}
}));
}
public void setErrors(final String errors) {
currentWarnings = errors;
warningsButton.setVisible(currentWarnings != null && currentWarnings.length() > 0);
}
private void setButtonsEnabled() {
final ExpressionItem selectedItem = getSelectedItem();
if (selectedItem == null) {
disableItemButton.setEnabled(false);
disableItemButton.setTitle("");
} else {
disableItemButton.setEnabled(true);
disableItemButton.setTitle(getEnableDisableText());
}
if (selectedItem == null) {
deleteItemButton.setEnabled(false);
deleteItemButton.setTitle("");
} else {
deleteItemButton.setEnabled(true);
deleteItemButton.setTitle("Delete");
}
}
private void loadDataSource(final DocRef dataSourceRef) {
searchModel.getIndexLoader().loadDataSource(dataSourceRef);
}
private void loadedDataSource(final DocRef dataSourceRef, final IndexFieldsMap indexFieldsMap) {
// Create a list of index fields.
final List<IndexField> indexedFields = new ArrayList<>();
if (indexFieldsMap != null) {
for (final IndexField indexField : indexFieldsMap.values()) {
if (indexField.isIndexed()) {
indexedFields.add(indexField);
}
}
}
Collections.sort(indexedFields);
expressionPresenter.setFields(indexedFields);
final EqualsBuilder builder = new EqualsBuilder();
builder.append(queryData.getDataSource(), dataSourceRef);
if (!builder.isEquals()) {
queryData.setDataSource(dataSourceRef);
setDirty(true);
}
// Only allow searching if we have a data source and have loaded fields from it successfully.
getView().setEnabled(dataSourceRef != null && indexedFields.size() > 0);
init();
}
private void addOperator() {
expressionPresenter.addOperator();
}
private void addTerm() {
final DocRef dataSourceRef = queryData.getDataSource();
if (dataSourceRef == null) {
warnNoDataSource();
} else {
expressionPresenter.addTerm();
}
}
private void warnNoDataSource() {
AlertEvent.fireWarn(this, "No data source has been chosen to search", null);
}
private void disable() {
expressionPresenter.disable();
setButtonsEnabled();
}
private void delete() {
expressionPresenter.delete();
}
private void choosePipeline() {
expressionPresenter.clearSelection();
// Write expression.
final ExpressionOperator root = new ExpressionOperator();
expressionPresenter.write(root);
final QueryData queryData = new QueryData();
queryData.setDataSource(this.queryData.getDataSource());
queryData.setExpression(root);
final ExplorerDropDownTreePresenter chooser = pipelineSelection.get();
chooser.setCaption("Choose Pipeline To Process Results With");
chooser.setIncludedTypes(PipelineEntity.ENTITY_TYPE);
chooser.setRequiredPermissions(DocumentPermissionNames.USE);
chooser.addDataSelectionHandler(new DataSelectionHandler<ExplorerData>() {
@Override
public void onSelection(final DataSelectionEvent<ExplorerData> event) {
final DocRef pipeline = chooser.getSelectedEntityReference();
if (pipeline != null) {
setProcessorLimits(queryData, pipeline);
}
}
});
chooser.show();
}
private void setProcessorLimits(final QueryData queryData, final DocRef pipeline) {
processorLimitsPresenter.setTimeLimitMins(defaultProcessorTimeLimit);
processorLimitsPresenter.setRecordLimit(defaultProcessorRecordLimit);
final PopupSize popupSize = new PopupSize(321, 102, false);
ShowPopupEvent.fire(this, processorLimitsPresenter, PopupType.OK_CANCEL_DIALOG, popupSize,
"Process Search Results", new PopupUiHandlers() {
@Override
public void onHideRequest(final boolean autoClose, final boolean ok) {
if (ok) {
final Limits limits = new Limits();
if (processorLimitsPresenter.getRecordLimit() != null) {
limits.setEventCount(processorLimitsPresenter.getRecordLimit());
}
if (processorLimitsPresenter.getTimeLimitMins() != null) {
limits.setDurationMs(processorLimitsPresenter.getTimeLimitMins() * 60 * 1000);
}
queryData.setLimits(limits);
openEditor(queryData, pipeline);
}
HidePopupEvent.fire(QueryPresenter.this, processorLimitsPresenter);
}
@Override
public void onHide(final boolean autoClose, final boolean ok) {
}
});
}
private void openEditor(final QueryData queryData, final DocRef pipeline) {
// Now create the processor filter using the find stream criteria.
final FindStreamCriteria findStreamCriteria = new FindStreamCriteria();
findStreamCriteria.setQueryData(queryData);
dispatcher.execute(new CreateProcessorAction(pipeline, findStreamCriteria, true, 1),
new AsyncCallbackAdaptor<StreamProcessorFilter>() {
@Override
public void onSuccess(final StreamProcessorFilter streamProcessorFilter) {
CreateProcessorEvent.fire(QueryPresenter.this, streamProcessorFilter);
}
});
}
private void showWarnings() {
if (currentWarnings != null && currentWarnings.length() > 0) {
AlertEvent.fireWarn(this, "The following warnings have been created while running this search:",
currentWarnings, null);
}
}
@Override
public void onParamsChanged(final String params) {
this.params = params;
if (initialised) {
stop();
start();
}
}
@Override
public void start() {
run(true);
}
@Override
public void stop() {
if (autoRefreshTimer != null) {
autoRefreshTimer.cancel();
autoRefreshTimer = null;
}
searchModel.destroy();
}
private void run(final boolean incremental) {
final DocRef dataSourceRef = queryData.getDataSource();
if (dataSourceRef == null) {
warnNoDataSource();
} else {
currentWarnings = null;
expressionPresenter.clearSelection();
warningsButton.setVisible(false);
// Write expression.
final ExpressionOperator root = new ExpressionOperator();
expressionPresenter.write(root);
searchModel.search(root, params, incremental);
}
}
@Override
public void read(final ComponentConfig componentData) {
super.read(componentData);
queryData = getSettings();
// Create and register the search model.
final Dashboard dashboard = getComponents().getDashboard();
final QueryKeyImpl initialQueryKey = new QueryKeyImpl(dashboard.getId(), dashboard.getName(),
getComponentData().getId());
searchModel.setInitialQueryKey(initialQueryKey);
// Read data source.
loadDataSource(queryData.getDataSource());
// Read expression.
ExpressionOperator root = queryData.getExpression();
if (root == null) {
root = new ExpressionOperator();
}
setExpression(root);
}
@Override
public void write(final ComponentConfig componentData) {
super.write(componentData);
// Write expression.
ExpressionOperator root = queryData.getExpression();
if (root == null) {
root = new ExpressionOperator();
queryData.setExpression(root);
}
expressionPresenter.write(root);
componentData.setSettings(queryData);
}
@Override
public void onRemove() {
super.onRemove();
searchModel.destroy();
}
@Override
public void link() {
}
private void init() {
if (!initialised) {
initialised = true;
// An auto search can only commence if the UI has fully loaded and the data source has also loaded from the server.
final Automate automate = getAutomate();
if (automate.isOpen()) {
run(true);
}
}
}
@Override
public void changeSettings() {
super.changeSettings();
loadDataSource(queryData.getDataSource());
}
@Override
public HandlerRegistration addDirtyHandler(final DirtyHandler handler) {
return addHandlerToSource(DirtyEvent.getType(), handler);
}
@Override
public ComponentType getType() {
return TYPE;
}
private QueryData getSettings() {
ComponentSettings settings = getComponentData().getSettings();
if (settings == null || !(settings instanceof QueryData)) {
settings = createSettings();
getComponentData().setSettings(settings);
}
return (QueryData) settings;
}
private Automate getAutomate() {
final QueryData queryData = getSettings();
Automate automate = queryData.getAutomate();
if (automate == null) {
automate = new Automate();
queryData.setAutomate(automate);
}
return automate;
}
private ComponentSettings createSettings() {
return new QueryData();
}
public SearchModel getSearchModel() {
return searchModel;
}
public void setExpression(final ExpressionOperator root) {
expressionPresenter.read(root);
}
public void setMode(final SearchModel.Mode mode) {
getView().setMode(mode);
// If this is the end of a query then schedule a refresh.
if (SearchModel.Mode.INACTIVE.equals(mode)) {
scheduleRefresh();
}
}
private void scheduleRefresh() {
// Schedule auto refresh after a query has finished.
if (autoRefreshTimer != null) {
autoRefreshTimer.cancel();
}
autoRefreshTimer = null;
final Automate automate = getAutomate();
if (automate.isRefresh()) {
try {
final String interval = automate.getRefreshInterval();
final int millis = ModelStringUtil.parseDurationString(interval).intValue();
autoRefreshTimer = new Timer() {
@Override
public void run() {
// Make sure search is currently inactive before we attempt to execute a new query.
if (SearchModel.Mode.INACTIVE.equals(searchModel.getMode())) {
QueryPresenter.this.run(false);
}
}
};
autoRefreshTimer.schedule(millis);
} catch (final Exception e) {
// Ignore as we cannot display this error now.
}
}
}
private List<Item> addExpressionActionsToMenu() {
final ExpressionItem selectedItem = getSelectedItem();
final boolean hasSelection = selectedItem != null;
final List<Item> menuItems = new ArrayList<Item>();
menuItems.add(new IconMenuItem(1, GlyphIcons.ADD, GlyphIcons.ADD, "Add Term", null, true, new Command() {
@Override
public void execute() {
addTerm();
}
}));
menuItems.add(new IconMenuItem(2, ImageIcon.create(resources.addOperator()), ImageIcon.create(resources.addOperator()), "Add Operator", null,
true, new Command() {
@Override
public void execute() {
addOperator();
}
}));
menuItems.add(new IconMenuItem(3, GlyphIcons.DISABLE, GlyphIcons.DISABLE, getEnableDisableText(),
null, hasSelection, new Command() {
@Override
public void execute() {
disable();
}
}));
menuItems.add(new IconMenuItem(4, GlyphIcons.DELETE, GlyphIcons.DELETE, "Delete", null,
hasSelection, new Command() {
@Override
public void execute() {
delete();
}
}));
return menuItems;
}
private String getEnableDisableText() {
final ExpressionItem selectedItem = getSelectedItem();
if (selectedItem != null && !selectedItem.isEnabled()) {
return "Enable";
}
return "Disable";
}
private ExpressionItem getSelectedItem() {
if (expressionPresenter.getSelectionModel() != null) {
return expressionPresenter.getSelectionModel().getSelectedObject();
}
return null;
}
private void showMenu(final PopupPosition popupPosition, final List<Item> menuItems) {
menuListPresenter.setData(menuItems);
final PopupUiHandlers popupUiHandlers = new PopupUiHandlers() {
@Override
public void onHideRequest(final boolean autoClose, final boolean ok) {
HidePopupEvent.fire(QueryPresenter.this, menuListPresenter);
}
@Override
public void onHide(final boolean autoClose, final boolean ok) {
}
};
ShowPopupEvent.fire(this, menuListPresenter, PopupType.POPUP, popupPosition, popupUiHandlers);
}
public interface QueryView extends View, HasUiHandlers<QueryUiHandlers> {
ImageButtonView addButton(String title, ImageResource enabledImage, ImageResource disabledImage,
boolean enabled);
GlyphButtonView addButton(GlyphIcon preset);
void setExpressionView(View view);
void setMode(SearchModel.Mode mode);
void setEnabled(boolean enabled);
}
public interface Resources extends ClientBundle {
ImageResource addOperator();
ImageResource search();
ImageResource history();
ImageResource favourite();
ImageResource pipeline();
ImageResource pipelineDisabled();
ImageResource warning();
}
}
| Re-query refresh interval can no longer be less than 10 seconds.
| stroom-dashboard/src/main/java/stroom/dashboard/client/query/QueryPresenter.java | Re-query refresh interval can no longer be less than 10 seconds. |
|
Java | apache-2.0 | e2bc22f53b7549b99c9e14066ebdeb5ae50c1a2b | 0 | renatocf/MAC0242-PROJECT,renatocf/MAC0242-PROJECT,renatocf/MAC0242-PROJECT | /**********************************************************************/
/* Copyright 2013 KRV */
/* */
/* 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 main;
// Default Libraries
import java.io.*;
import java.util.Vector;
import java.util.Arrays;
import java.util.Random;
// Libraries
import ui.MENU;
import arena.*;
import players.*;
import exception.*;
import stackable.*;
import parameters.*;
import robot.Command;
// Configs interfaces
import ui.Interfaces;
import random.Weather;
// External Libraries (.jar)
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
/**
* <b>Main class</b><br>
* Controls all the user interactions,
* the start and end of the program.
*/
public class Main
{
final private static String USAGE =
"USAGE: java -jar dist/MAC0242.jar <prog1> <prog2> <prog3> [-v|-d]";
// Options
static private int port = 3742;
static private boolean help = false;
static private boolean usage = false;
static private boolean multi = false;
static private Interfaces UI = Interfaces.GRAPHICAL;
static private MENU MENU = new ui.graphical.Menu();
/**
* <b>Main method</b><br>
* Gets options from command line, interacts
* with user and starts the game.
*/
public static void main(String[] argv)
throws InvalidOperationException
{
String[] args = getopt(argv); // Get options
System.out.println("");
// Help and Usage
if(help) { help(); return; }
if(args.length > Game.ROBOTS_NUM_INITIAL)
{ System.err.println(USAGE); return; }
if(multi)
{
System.out.println("Multiplayer mode: not creating maps...");
return;
}
while(menu(args));
System.exit(0);
}
/**
* Call menu and deal whith its options.
* @param args File names from stdin
* @return Boolean to indicate if the game
* may or not continue
*/
private static boolean menu(String[] args)
throws InvalidOperationException
{
if(Debugger.debugging()) newGame(args);
else switch(MENU.exhibit())
{
case NEW_GAME: newGame(args); break;
case EXIT: return false;
}
return true;
}
/**
* Create a new game.
* @param args File names from stdin
*/
private static void newGame(String[] args)
throws InvalidOperationException
{
// Generate map
Player[] p = World.genesis(2, 1, Game.WEATHER, UI, Game.RAND);
// Menu
// TODO: automate inserction of programs
String ROOT = "/data/behaviors/";
if(args.length > 1 && !multi)
{
p[0].insertArmy("Caprica Six" , ROOT + "Protector.asm");
p[0].insertArmy("Number Seventeen", ROOT + "Protector.asm");
p[0].insertArmy("Megatron" , ROOT + "Carrier.asm" );
}
String[] names = { "Boomer", "Number Eighteen", "Optimus Prime" };
for(int i = 0; i < args.length && i < Game.ROBOTS_NUM_INITIAL; i++)
p[1].insertArmy(names[i], args[i]);
// Game main loop
if(Debugger.debugging())
{
for(int ts = 0; ts < 1000 && World.timeStep(); ts++);
System.exit(0);
}
// Run ad infinitum if not debugging
while(World.timeStep());
}
/**
* Encapsulates the use of the library
* GetOpt to get the options for the program.
* @param argv Argument vector (with options)
* @return Argument vector without options (args)
*/
private static String[] getopt(String[] argv)
{
String arg;
LongOpt[] longopts =
{
// Help and Debug
new LongOpt("help" , LongOpt.NO_ARGUMENT, null, 'h'),
new LongOpt("debug" , LongOpt.NO_ARGUMENT, null, 'd'),
new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v'),
// Weather options
new LongOpt("artical" , LongOpt.NO_ARGUMENT, null, 1),
new LongOpt("desertic" , LongOpt.NO_ARGUMENT, null, 2),
new LongOpt("tropical" , LongOpt.NO_ARGUMENT, null, 3),
new LongOpt("continental" , LongOpt.NO_ARGUMENT, null, 4),
// Interfaces
new LongOpt("textual", LongOpt.NO_ARGUMENT, null, 't'),
// Size
new LongOpt("small", LongOpt.NO_ARGUMENT, null, 's'),
new LongOpt("large", LongOpt.NO_ARGUMENT, null, 'l'),
// Seed
new LongOpt("seed", LongOpt.REQUIRED_ARGUMENT, null, 5),
// Server-Client structure
new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 'p'),
new LongOpt("multi", LongOpt.NO_ARGUMENT, null, 6 ),
new LongOpt("single", LongOpt.NO_ARGUMENT, null, 7 ),
};
//
Getopt g = new Getopt("MAC0242-Project",argv,"hdvtslp:",longopts);
int c;
while ((c = g.getopt()) != -1)
{
switch(c)
{
case 'h': // --help
help = true;
break;
//
case 'v': // --verbose
Debugger.init();
break;
//
case 'd': // --debug
Debugger.init();
UI = Interfaces.NONE;
break;
//
case 1: Game.WEATHER = Weather.ARTICAL; break;
case 2: Game.WEATHER = Weather.DESERTIC; break;
case 3: Game.WEATHER = Weather.TROPICAL; break;
case 4: Game.WEATHER = Weather.CONTINENTAL; break;
//
case 5: // --seed
arg = g.getOptarg();
Game.RAND = new Random(Integer.valueOf(arg));
break;
//
case 'p': // --port
arg = g.getOptarg();
port = Integer.valueOf(arg);
break;
//
case 6: multi = true; break; // --multi
case 7: multi = false; break; // --single
//
case 't': // --textual
UI = Interfaces.TEXTUAL;
MENU = new ui.textual.Menu();
break;
//
case 's': Game.MAP_SIZE = 16; break; // --small
case 'l': Game.MAP_SIZE = 50; break; // --large
//
case '?': // getopt() will print the error
break;
//
default:
System.out.println("getopt() returned " + c);
}
}
// Return array without the options
return Arrays.copyOfRange(argv, g.getOptind(), argv.length);
}
/**
* Execute man page to show the help
*/
private static void help()
{
// Generate and run process
try {
Process p = Runtime.getRuntime().exec(
new String[] {
"sh", "-c", "man ./doc/robots.6 < /dev/tty > /dev/tty"
}
);
try{ p.waitFor(); }
catch(InterruptedException e) {
System.err.println("Execution interrupted!");
}
}
catch(IOException e)
{
System.err.print("[MAIN] Impossible to print man output ");
}
}
}
| src/main/Main.java | /**********************************************************************/
/* Copyright 2013 KRV */
/* */
/* 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 main;
// Default Libraries
import java.io.*;
import java.util.Vector;
import java.util.Arrays;
import java.util.Random;
// Libraries
import arena.*;
import players.*;
import exception.*;
import stackable.*;
import parameters.*;
import robot.Command;
import ui.MENU;
import ui.MENU.Opts;
// Configs interfaces
import ui.Interfaces;
import random.Weather;
// External Libraries (.jar)
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
/**
* <b>Main class</b><br>
* Controls all the user interactions,
* the start and end of the program.
*/
public class Main
{
final private static String USAGE =
"USAGE: java -jar dist/MAC0242.jar <prog1> <prog2> <prog3> [-v|-d]";
// Options
static private int port = 3742;
static private boolean help = false;
static private boolean usage = false;
static private boolean multi = false;
static private Interfaces UI = Interfaces.GRAPHICAL;
static private MENU MENU = new ui.graphical.Menu();
/**
* <b>Main method</b><br>
* Gets options from command line, interacts
* with user and starts the game.
*/
public static void main(String[] argv)
throws InvalidOperationException
{
String[] args = getopt(argv); // Get options
System.out.println("");
// Help and Usage
if(help) { help(); return; }
if(args.length > Game.ROBOTS_NUM_INITIAL)
{ System.err.println(USAGE); return; }
if(multi)
{
System.out.println("Multiplayer mode: not creating maps...");
return;
}
while(menu(args));
System.exit(0);
}
/**
* Call menu and deal whith its options.
* @param args File names from stdin
* @return Boolean to indicate if the game
* may or not continue
*/
private static boolean menu(String[] args)
throws InvalidOperationException
{
if(Debugger.debugging()) newGame(args);
else switch(MENU.exhibit())
{
case NEW_GAME: newGame(args); break;
case EXIT: return false;
}
return true;
}
/**
* Create a new game.
* @param args File names from stdin
*/
private static void newGame(String[] args)
throws InvalidOperationException
{
// Generate map
Player[] p = World.genesis(2, 1, Game.WEATHER, UI, Game.RAND);
// Menu
// TODO: automate inserction of programs
String ROOT = "/data/behaviors/";
if(args.length > 1 && !multi)
{
p[0].insertArmy("Caprica Six" , ROOT + "Protector.asm");
p[0].insertArmy("Number Seventeen", ROOT + "Protector.asm");
p[0].insertArmy("Megatron" , ROOT + "Carrier.asm" );
}
String[] names = { "Boomer", "Number Eighteen", "Optimus Prime" };
for(int i = 0; i < args.length && i < Game.ROBOTS_NUM_INITIAL; i++)
p[1].insertArmy(names[i], args[i]);
// Game main loop
if(Debugger.debugging())
{
for(int ts = 0; ts < 1000 && World.timeStep(); ts++);
System.exit(0);
}
// Run ad infinitum if not debugging
while(World.timeStep());
}
/**
* Encapsulates the use of the library
* GetOpt to get the options for the program.
* @param argv Argument vector (with options)
* @return Argument vector without options (args)
*/
private static String[] getopt(String[] argv)
{
String arg;
LongOpt[] longopts =
{
// Help and Debug
new LongOpt("help" , LongOpt.NO_ARGUMENT, null, 'h'),
new LongOpt("debug" , LongOpt.NO_ARGUMENT, null, 'd'),
new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v'),
// Weather options
new LongOpt("artical" , LongOpt.NO_ARGUMENT, null, 1),
new LongOpt("desertic" , LongOpt.NO_ARGUMENT, null, 2),
new LongOpt("tropical" , LongOpt.NO_ARGUMENT, null, 3),
new LongOpt("continental" , LongOpt.NO_ARGUMENT, null, 4),
// Interfaces
new LongOpt("textual", LongOpt.NO_ARGUMENT, null, 't'),
// Size
new LongOpt("small", LongOpt.NO_ARGUMENT, null, 's'),
new LongOpt("large", LongOpt.NO_ARGUMENT, null, 'l'),
// Seed
new LongOpt("seed", LongOpt.REQUIRED_ARGUMENT, null, 5),
// Server-Client structure
new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 'p'),
new LongOpt("multi", LongOpt.NO_ARGUMENT, null, 6 ),
new LongOpt("single", LongOpt.NO_ARGUMENT, null, 7 ),
};
//
Getopt g = new Getopt("MAC0242-Project",argv,"hdvtslp:",longopts);
int c;
while ((c = g.getopt()) != -1)
{
switch(c)
{
case 'h': // --help
help = true;
break;
//
case 'v': // --verbose
Debugger.init();
break;
//
case 'd': // --debug
Debugger.init();
UI = Interfaces.NONE;
break;
//
case 1: Game.WEATHER = Weather.ARTICAL; break;
case 2: Game.WEATHER = Weather.DESERTIC; break;
case 3: Game.WEATHER = Weather.TROPICAL; break;
case 4: Game.WEATHER = Weather.CONTINENTAL; break;
//
case 5: // --seed
arg = g.getOptarg();
Game.RAND = new Random(Integer.valueOf(arg));
break;
//
case 'p': // --port
arg = g.getOptarg();
port = Integer.valueOf(arg);
break;
//
case 6: multi = true; break; // --multi
case 7: multi = false; break; // --single
//
case 't': // --textual
UI = Interfaces.TEXTUAL;
MENU = new ui.textual.Menu();
break;
//
case 's': Game.MAP_SIZE = 16; break; // --small
case 'l': Game.MAP_SIZE = 50; break; // --large
//
case '?': // getopt() will print the error
break;
//
default:
System.out.println("getopt() returned " + c);
}
}
// Return array without the options
return Arrays.copyOfRange(argv, g.getOptind(), argv.length);
}
/**
* Execute man page to show the help
*/
private static void help()
{
// Generate and run process
try {
Process p = Runtime.getRuntime().exec(
new String[] {
"sh", "-c", "man ./doc/robots.6 < /dev/tty > /dev/tty"
}
);
try{ p.waitFor(); }
catch(InterruptedException e) {
System.err.println("Execution interrupted!");
}
}
catch(IOException e)
{
System.err.print("[MAIN] Impossible to print man output ");
}
}
}
| Fixing imports
| src/main/Main.java | Fixing imports |
|
Java | apache-2.0 | a85952e8b36460e04555de9adf13894e8cef5129 | 0 | chamindias/carbon-apimgt,uvindra/carbon-apimgt,ChamNDeSilva/carbon-apimgt,hevayo/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Rajith90/carbon-apimgt,malinthaprasan/carbon-apimgt,nuwand/carbon-apimgt,Arshardh/carbon-apimgt,jaadds/carbon-apimgt,ChamNDeSilva/carbon-apimgt,Arshardh/carbon-apimgt,rswijesena/carbon-apimgt,Minoli/carbon-apimgt,tharikaGitHub/carbon-apimgt,isharac/carbon-apimgt,tharindu1st/carbon-apimgt,fazlan-nazeem/carbon-apimgt,uvindra/carbon-apimgt,nuwand/carbon-apimgt,harsha89/carbon-apimgt,nuwand/carbon-apimgt,malinthaprasan/carbon-apimgt,sambaheerathan/carbon-apimgt,tharindu1st/carbon-apimgt,wso2/carbon-apimgt,abimarank/carbon-apimgt,fazlan-nazeem/carbon-apimgt,uvindra/carbon-apimgt,dewmini/carbon-apimgt,ruks/carbon-apimgt,fazlan-nazeem/carbon-apimgt,prasa7/carbon-apimgt,praminda/carbon-apimgt,sambaheerathan/carbon-apimgt,Rajith90/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,hevayo/carbon-apimgt,nuwand/carbon-apimgt,ruks/carbon-apimgt,lalaji/carbon-apimgt,ruks/carbon-apimgt,wso2/carbon-apimgt,abimarank/carbon-apimgt,hevayo/carbon-apimgt,tharikaGitHub/carbon-apimgt,Arshardh/carbon-apimgt,chamindias/carbon-apimgt,Minoli/carbon-apimgt,bhathiya/carbon-apimgt,tharikaGitHub/carbon-apimgt,lakmali/carbon-apimgt,harsha89/carbon-apimgt,abimarank/carbon-apimgt,dewmini/carbon-apimgt,Rajith90/carbon-apimgt,chamilaadhi/carbon-apimgt,pubudu538/carbon-apimgt,malinthaprasan/carbon-apimgt,isharac/carbon-apimgt,bhathiya/carbon-apimgt,lalaji/carbon-apimgt,thusithak/carbon-apimgt,harsha89/carbon-apimgt,chamilaadhi/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,harsha89/carbon-apimgt,lalaji/carbon-apimgt,lakmali/carbon-apimgt,chamindias/carbon-apimgt,ChamNDeSilva/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,wso2/carbon-apimgt,tharindu1st/carbon-apimgt,prasa7/carbon-apimgt,chamindias/carbon-apimgt,thusithak/carbon-apimgt,thusithak/carbon-apimgt,pubudu538/carbon-apimgt,pubudu538/carbon-apimgt,uvindra/carbon-apimgt,dewmini/carbon-apimgt,prasa7/carbon-apimgt,fazlan-nazeem/carbon-apimgt,pubudu538/carbon-apimgt,Rajith90/carbon-apimgt,Arshardh/carbon-apimgt,lakmali/carbon-apimgt,rswijesena/carbon-apimgt,hevayo/carbon-apimgt,bhathiya/carbon-apimgt,sineth-neranjana/carbon-apimgt,praminda/carbon-apimgt,Minoli/carbon-apimgt,malinthaprasan/carbon-apimgt,praminda/carbon-apimgt,jaadds/carbon-apimgt,bhathiya/carbon-apimgt,ruks/carbon-apimgt,tharindu1st/carbon-apimgt,isharac/carbon-apimgt,sambaheerathan/carbon-apimgt,wso2/carbon-apimgt,chamilaadhi/carbon-apimgt,sineth-neranjana/carbon-apimgt,isharac/carbon-apimgt,rswijesena/carbon-apimgt,sineth-neranjana/carbon-apimgt,jaadds/carbon-apimgt,prasa7/carbon-apimgt,jaadds/carbon-apimgt,tharikaGitHub/carbon-apimgt,chamilaadhi/carbon-apimgt,sineth-neranjana/carbon-apimgt | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.gateway.handlers;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.apache.axiom.util.UIDGenerator;
import org.apache.http.HttpHeaders;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityConstants;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityUtils;
import org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleConstants;
import org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher;
import org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataPublisher;
import org.wso2.carbon.apimgt.usage.publisher.DataPublisherUtil;
import org.wso2.carbon.apimgt.usage.publisher.dto.RequestPublisherDTO;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.net.InetSocketAddress;
/**
* This is a handler which is actually embedded to the netty pipeline which does operations such as
* authentication and throttling for the websocket handshake and subsequent websocket frames.
*/
public class WebsocketInboundHandler extends ChannelInboundHandlerAdapter {
private static String tenantDomain;
private static int port;
private static volatile ThrottleDataPublisher throttleDataPublisher = null;
private static APIMgtUsageDataPublisher usageDataPublisher;
private static Logger log = LoggerFactory.getLogger(WebsocketInboundHandler.class);
private boolean isDefaultVersion;
private String uri;
private String version;
private APIKeyValidationInfoDTO infoDTO = new APIKeyValidationInfoDTO();
private io.netty.handler.codec.http.HttpHeaders headers;
public WebsocketInboundHandler() {
if (throttleDataPublisher == null) {
// The publisher initializes in the first request only
synchronized (this) {
throttleDataPublisher = new ThrottleDataPublisher();
}
}
if (usageDataPublisher == null) {
usageDataPublisher = new APIMgtUsageDataBridgeDataPublisher();
usageDataPublisher.init();
}
}
/**
* extract the version from the request uri
*
* @param url
* @return version String
*/
private String getversionFromUrl(final String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
private String getContextFromUrl(String url) {
int lastIndex = url.lastIndexOf('/');
return url.substring(0, lastIndex);
}
@SuppressWarnings("unchecked")
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//check if the request is a handshake
if (msg instanceof FullHttpRequest) {
FullHttpRequest req = (FullHttpRequest) msg;
uri = req.getUri();
port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
tenantDomain = MultitenantUtils.getTenantDomainFromUrl(req.getUri());
if (tenantDomain.equals(req.getUri())) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
} else {
req.setUri(req.getUri().replaceFirst("/", "-"));
msg = req;
}
if (validateOAuthHeader(req)) {
headers = req.headers();
req.setUri(uri);
ctx.fireChannelRead(msg);
} else {
ctx.writeAndFlush(new TextWebSocketFrame(
APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
} else if (msg instanceof WebSocketFrame) {
boolean isThrottledOut = doThrottle(ctx, (WebSocketFrame) msg);
String clientIp = ctx.channel().remoteAddress().toString();
if (isThrottledOut) {
ctx.fireChannelRead(msg);
} else {
ctx.writeAndFlush(new TextWebSocketFrame("Websocket frame throttled out"));
}
// publish analytics events if analytics is enabled
if (APIUtil.isAnalyticsEnabled()) {
publishRequestEvent(infoDTO, clientIp, isThrottledOut);
}
}
}
/**
* Authenticate request
*
* @param req Full Http Request
* @return true if the access token is valid
* @throws APIManagementException
*/
private boolean validateOAuthHeader(FullHttpRequest req)
throws APIManagementException, APISecurityException {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(tenantDomain, true);
version = getversionFromUrl(uri);
APIKeyValidationInfoDTO info;
if (!req.headers().contains(HttpHeaders.AUTHORIZATION)) {
log.error("No Authorization Header Present");
return false;
}
String[] auth = req.headers().get(HttpHeaders.AUTHORIZATION).split(" ");
if (APIConstants.CONSUMER_KEY_SEGMENT.equals(auth[0])) {
String cacheKey;
String apikey = auth[1];
if (WebsocketUtil.isRemoveOAuthHeadersFromOutMessage()) {
req.headers().remove(HttpHeaders.AUTHORIZATION);
}
//If the key have already been validated
if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
cacheKey = WebsocketUtil.getAccessTokenCacheKey(apikey, uri);
info = WebsocketUtil.validateCache(apikey, cacheKey);
if (info != null) {
infoDTO = info;
return info.isAuthorized();
}
}
String keyValidatorClientType = APISecurityUtils.getKeyValidatorClientType();
if (APIConstants.API_KEY_VALIDATOR_WS_CLIENT.equals(keyValidatorClientType)) {
info = new WebsocketWSClient().getAPIKeyData(uri, version, apikey);
} else if (APIConstants.API_KEY_VALIDATOR_THRIFT_CLIENT
.equals(keyValidatorClientType)) {
info = new WebsocketThriftClient().getAPIKeyData(uri, version, apikey);
} else {
return false;
}
if (info == null || !info.isAuthorized()) {
return false;
}
if (info.getApiName() != null && info.getApiName().contains("*")) {
isDefaultVersion = true;
String[] str = info.getApiName().split("\\*");
version = str[1];
uri += "/" + str[1];
info.setApiName(str[0]);
}
if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(info.getType())) {
uri = "/_PRODUCTION_" + uri;
}
if (APIConstants.API_KEY_TYPE_SANDBOX.equals(info.getType())) {
uri = "/_SANDBOX_" + uri;
}
if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
cacheKey = WebsocketUtil.getAccessTokenCacheKey(apikey, uri);
WebsocketUtil.putCache(info, apikey, cacheKey);
}
infoDTO = info;
return true;
} else {
return false;
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Checks if the request is throttled
*
* @param ctx ChannelHandlerContext
* @return false if throttled
* @throws APIManagementException
*/
public boolean doThrottle(ChannelHandlerContext ctx, WebSocketFrame msg)
throws APIManagementException {
String applicationLevelTier = infoDTO.getApplicationTier();
String apiLevelTier = infoDTO.getApiTier();
String subscriptionLevelTier = infoDTO.getTier();
String resourceLevelTier = apiLevelTier;
String authorizedUser;
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
.equalsIgnoreCase(infoDTO.getSubscriberTenantDomain())) {
authorizedUser = infoDTO.getSubscriber() + "@" + infoDTO.getSubscriberTenantDomain();
} else {
authorizedUser = infoDTO.getSubscriber();
}
String apiName = infoDTO.getApiName();
String apiContext = uri;
String apiVersion = version;
String appTenant = infoDTO.getSubscriberTenantDomain();
String apiTenant = tenantDomain;
String appId = infoDTO.getApplicationId();
String applicationLevelThrottleKey = appId + ":" + authorizedUser;
String apiLevelThrottleKey = apiContext + ":" + apiVersion;
String resourceLevelThrottleKey = apiLevelThrottleKey;
String subscriptionLevelThrottleKey = appId + ":" + apiContext + ":" + apiVersion;
String messageId = UIDGenerator.generateURNString();
String remoteIP = ctx.channel().remoteAddress().toString();
remoteIP = remoteIP.substring(1, remoteIP.indexOf(":"));
JSONObject jsonObMap = new JSONObject();
if (remoteIP != null && remoteIP.length() > 0) {
jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(remoteIP));
}
jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, msg.content().capacity());
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(tenantDomain, true);
boolean isThrottled = WebsocketUtil
.isThrottled(resourceLevelThrottleKey, subscriptionLevelThrottleKey,
applicationLevelThrottleKey);
if (isThrottled) {
return false;
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
Object[] objects =
new Object[] { messageId, applicationLevelThrottleKey, applicationLevelTier,
apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey,
subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier,
authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId,
apiName, jsonObMap.toString() };
org.wso2.carbon.databridge.commons.Event event =
new org.wso2.carbon.databridge.commons.Event(
"org.wso2.throttle.request.stream:1.0.0", System.currentTimeMillis(), null,
null, objects);
throttleDataPublisher.getDataPublisher().tryPublish(event);
return true;
}
/**
* Publish reuqest event to analytics server
*
* @param infoDTO API and Application data
* @param clientIp client's IP Address
* @param isThrottledOut request is throttled out or not
*/
private void publishRequestEvent(APIKeyValidationInfoDTO infoDTO, String clientIp, boolean isThrottledOut) {
long requestTime = System.currentTimeMillis();
String useragent = headers.get(APIConstants.USER_AGENT);
useragent = useragent != null ? useragent : "-"; // '-' is used for empty values for easiness in DAS side
try {
Application app = ApiMgtDAO.getInstance().getApplicationById(Integer.parseInt(infoDTO.getApplicationId()));
String appOwner = app.getSubscriber().getName();
RequestPublisherDTO requestPublisherDTO = new RequestPublisherDTO();
requestPublisherDTO.setApi(infoDTO.getApiName());
requestPublisherDTO.setApiPublisher(infoDTO.getApiPublisher());
requestPublisherDTO.setApiVersion(infoDTO.getApiName() + ':' + version);
requestPublisherDTO.setApplicationId(infoDTO.getApplicationId());
requestPublisherDTO.setApplicationName(infoDTO.getApplicationName());
requestPublisherDTO.setApplicationOwner(appOwner);
requestPublisherDTO.setClientIp(clientIp);
requestPublisherDTO.setConsumerKey(infoDTO.getConsumerKey());
requestPublisherDTO.setContext(getContextFromUrl(uri));
requestPublisherDTO.setContinuedOnThrottleOut(isThrottledOut);
requestPublisherDTO.setHostName(DataPublisherUtil.getHostAddress());
requestPublisherDTO.setMethod("-");
requestPublisherDTO.setRequestTime(requestTime);
requestPublisherDTO.setResourcePath("-");
requestPublisherDTO.setResourceTemplate("-");
requestPublisherDTO.setUserAgent(useragent);
requestPublisherDTO.setUsername(infoDTO.getEndUserName());
requestPublisherDTO.setTenantDomain(tenantDomain);
requestPublisherDTO.setTier(infoDTO.getTier());
requestPublisherDTO.setVersion(version);
usageDataPublisher.publishEvent(requestPublisherDTO);
} catch (Exception e) {
log.error("Cannot publish event. " + e.getMessage(), e); // flow should not break if event publishing failed
}
}
}
| components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/WebsocketInboundHandler.java | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.gateway.handlers;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.apache.axiom.util.UIDGenerator;
import org.apache.http.HttpHeaders;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityConstants;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityUtils;
import org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleConstants;
import org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher;
import org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataPublisher;
import org.wso2.carbon.apimgt.usage.publisher.DataPublisherUtil;
import org.wso2.carbon.apimgt.usage.publisher.dto.RequestPublisherDTO;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.net.InetSocketAddress;
/**
* This is a handler which is actually embedded to the netty pipeline which does operations such as
* authentication and throttling for the websocket handshake and subsequent websocket frames.
*/
public class WebsocketInboundHandler extends ChannelInboundHandlerAdapter {
private static String tenantDomain;
private static int port;
private static volatile ThrottleDataPublisher throttleDataPublisher = null;
private static APIMgtUsageDataPublisher usageDataPublisher;
private static Logger log = LoggerFactory.getLogger(WebsocketInboundHandler.class);
private boolean isDefaultVersion;
private String uri;
private String version;
private APIKeyValidationInfoDTO infoDTO = new APIKeyValidationInfoDTO();
private io.netty.handler.codec.http.HttpHeaders headers;
public WebsocketInboundHandler() {
if (throttleDataPublisher == null) {
// The publisher initializes in the first request only
synchronized (this) {
throttleDataPublisher = new ThrottleDataPublisher();
}
}
if (usageDataPublisher == null) {
usageDataPublisher = new APIMgtUsageDataBridgeDataPublisher();
usageDataPublisher.init();
}
}
/**
* extract the version from the request uri
*
* @param url
* @return version String
*/
private String getversionFromUrl(final String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
private String getContextFromUrl(String url) {
int lastIndex = url.lastIndexOf('/');
return url.substring(0, lastIndex);
}
@SuppressWarnings("unchecked")
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//check if the request is a handshake
if (msg instanceof FullHttpRequest) {
FullHttpRequest req = (FullHttpRequest) msg;
uri = req.getUri();
port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
tenantDomain = MultitenantUtils.getTenantDomainFromUrl(req.getUri());
if (tenantDomain.equals(req.getUri())) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
} else {
req.setUri(req.getUri().replaceFirst("/", "-"));
msg = req;
}
if (validateOAuthHeader(req)) {
headers = req.headers();
req.setUri(uri);
ctx.fireChannelRead(msg);
} else {
ctx.writeAndFlush(new TextWebSocketFrame(
APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
} else if (msg instanceof WebSocketFrame) {
boolean isThrottledOut = doThrottle(ctx, (WebSocketFrame) msg);
if (isThrottledOut) {
ctx.fireChannelRead(msg);
} else {
ctx.writeAndFlush(new TextWebSocketFrame("Websocket frame throttled out"));
}
publishRequestEvent(infoDTO, ctx.channel().remoteAddress().toString(), isThrottledOut);
}
}
/**
* Authenticate request
*
* @param req Full Http Request
* @return true if the access token is valid
* @throws APIManagementException
*/
private boolean validateOAuthHeader(FullHttpRequest req)
throws APIManagementException, APISecurityException {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(tenantDomain, true);
version = getversionFromUrl(uri);
APIKeyValidationInfoDTO info;
if (!req.headers().contains(HttpHeaders.AUTHORIZATION)) {
log.error("No Authorization Header Present");
return false;
}
String[] auth = req.headers().get(HttpHeaders.AUTHORIZATION).split(" ");
if (APIConstants.CONSUMER_KEY_SEGMENT.equals(auth[0])) {
String cacheKey;
String apikey = auth[1];
if (WebsocketUtil.isRemoveOAuthHeadersFromOutMessage()) {
req.headers().remove(HttpHeaders.AUTHORIZATION);
}
//If the key have already been validated
if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
cacheKey = WebsocketUtil.getAccessTokenCacheKey(apikey, uri);
info = WebsocketUtil.validateCache(apikey, cacheKey);
if (info != null) {
infoDTO = info;
return info.isAuthorized();
}
}
String keyValidatorClientType = APISecurityUtils.getKeyValidatorClientType();
if (APIConstants.API_KEY_VALIDATOR_WS_CLIENT.equals(keyValidatorClientType)) {
info = new WebsocketWSClient().getAPIKeyData(uri, version, apikey);
} else if (APIConstants.API_KEY_VALIDATOR_THRIFT_CLIENT
.equals(keyValidatorClientType)) {
info = new WebsocketThriftClient().getAPIKeyData(uri, version, apikey);
} else {
return false;
}
if (info == null || !info.isAuthorized()) {
return false;
}
if (info.getApiName() != null && info.getApiName().contains("*")) {
isDefaultVersion = true;
String[] str = info.getApiName().split("\\*");
version = str[1];
uri += "/" + str[1];
info.setApiName(str[0]);
}
if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(info.getType())) {
uri = "/_PRODUCTION_" + uri;
}
if (APIConstants.API_KEY_TYPE_SANDBOX.equals(info.getType())) {
uri = "/_SANDBOX_" + uri;
}
if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
cacheKey = WebsocketUtil.getAccessTokenCacheKey(apikey, uri);
WebsocketUtil.putCache(info, apikey, cacheKey);
}
infoDTO = info;
return true;
} else {
return false;
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Checks if the request is throttled
*
* @param ctx ChannelHandlerContext
* @return false if throttled
* @throws APIManagementException
*/
public boolean doThrottle(ChannelHandlerContext ctx, WebSocketFrame msg)
throws APIManagementException {
String applicationLevelTier = infoDTO.getApplicationTier();
String apiLevelTier = infoDTO.getApiTier();
String subscriptionLevelTier = infoDTO.getTier();
String resourceLevelTier = apiLevelTier;
String authorizedUser;
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
.equalsIgnoreCase(infoDTO.getSubscriberTenantDomain())) {
authorizedUser = infoDTO.getSubscriber() + "@" + infoDTO.getSubscriberTenantDomain();
} else {
authorizedUser = infoDTO.getSubscriber();
}
String apiName = infoDTO.getApiName();
String apiContext = uri;
String apiVersion = version;
String appTenant = infoDTO.getSubscriberTenantDomain();
String apiTenant = tenantDomain;
String appId = infoDTO.getApplicationId();
String applicationLevelThrottleKey = appId + ":" + authorizedUser;
String apiLevelThrottleKey = apiContext + ":" + apiVersion;
String resourceLevelThrottleKey = apiLevelThrottleKey;
String subscriptionLevelThrottleKey = appId + ":" + apiContext + ":" + apiVersion;
String messageId = UIDGenerator.generateURNString();
String remoteIP = ctx.channel().remoteAddress().toString();
remoteIP = remoteIP.substring(1, remoteIP.indexOf(":"));
JSONObject jsonObMap = new JSONObject();
if (remoteIP != null && remoteIP.length() > 0) {
jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(remoteIP));
}
jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, msg.content().capacity());
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(tenantDomain, true);
boolean isThrottled = WebsocketUtil
.isThrottled(resourceLevelThrottleKey, subscriptionLevelThrottleKey,
applicationLevelThrottleKey);
if (isThrottled) {
return false;
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
Object[] objects =
new Object[] { messageId, applicationLevelThrottleKey, applicationLevelTier,
apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey,
subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier,
authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId,
apiName, jsonObMap.toString() };
org.wso2.carbon.databridge.commons.Event event =
new org.wso2.carbon.databridge.commons.Event(
"org.wso2.throttle.request.stream:1.0.0", System.currentTimeMillis(), null,
null, objects);
throttleDataPublisher.getDataPublisher().tryPublish(event);
return true;
}
/**
* Publish reuqest event to analytics server
*
* @param infoDTO API and Application data
* @param clientIp client's IP Address
* @param isThrottledOut request is throttled out or not
*/
private void publishRequestEvent(APIKeyValidationInfoDTO infoDTO, String clientIp, boolean isThrottledOut) {
long requestTime = System.currentTimeMillis();
String useragent = headers.get(APIConstants.USER_AGENT);
useragent = useragent != null ? useragent : "-"; // '-' is used for empty values for easiness in DAS side
try {
Application app = ApiMgtDAO.getInstance().getApplicationById(Integer.parseInt(infoDTO.getApplicationId()));
String appOwner = app.getSubscriber().getName();
RequestPublisherDTO requestPublisherDTO = new RequestPublisherDTO();
requestPublisherDTO.setApi(infoDTO.getApiName());
requestPublisherDTO.setApiPublisher(infoDTO.getApiPublisher());
requestPublisherDTO.setApiVersion(infoDTO.getApiName() + ':' + version);
requestPublisherDTO.setApplicationId(infoDTO.getApplicationId());
requestPublisherDTO.setApplicationName(infoDTO.getApplicationName());
requestPublisherDTO.setApplicationOwner(appOwner);
requestPublisherDTO.setClientIp(clientIp);
requestPublisherDTO.setConsumerKey(infoDTO.getConsumerKey());
requestPublisherDTO.setContext(getContextFromUrl(uri));
requestPublisherDTO.setContinuedOnThrottleOut(isThrottledOut);
requestPublisherDTO.setHostName(DataPublisherUtil.getHostAddress());
requestPublisherDTO.setMethod("-");
requestPublisherDTO.setRequestTime(requestTime);
requestPublisherDTO.setResourcePath("-");
requestPublisherDTO.setResourceTemplate("-");
requestPublisherDTO.setUserAgent(useragent);
requestPublisherDTO.setUsername(infoDTO.getEndUserName());
requestPublisherDTO.setTenantDomain(tenantDomain);
requestPublisherDTO.setTier(infoDTO.getTier());
requestPublisherDTO.setVersion(version);
usageDataPublisher.publishEvent(requestPublisherDTO);
} catch (Exception e) {
log.error("Cannot publish event. " + e.getMessage(), e); // flow should not break if event publishing failed
}
}
}
| ws: analytics: Check if analytics is enabled before publishing events
This check was mistakenly not added and it caused errors when
analytics is not enabled.
| components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/WebsocketInboundHandler.java | ws: analytics: Check if analytics is enabled before publishing events |
|
Java | apache-2.0 | c812506afc2c4a1696fc9d16cf7692230320e92e | 0 | qiujuer/Genius-Android,qiujuer/Genius-Android,qiujuer/Genius-Android,qiujuer/Genius-Android | /*
* Copyright (C) 2015 Qiujuer <[email protected]>
* WebSite http://www.qiujuer.net
* Created 10/15/2015
* Changed 12/06/2015
* Author Qiujuer
*
* 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.qiujuer.genius.ui.drawable;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
/**
* A drawable to draw loading
*/
public class LoadingCircleDrawable extends LoadingDrawable {
private static final int ANGLE_ADD = 5;
private static final int MIN_ANGLE_SWEEP = 3;
private static final int MAX_ANGLE_SWEEP = 255;
private RectF mOval = new RectF();
private float mStartAngle = 0;
private float mSweepAngle = 0;
private int mAngleIncrement = -3;
public LoadingCircleDrawable() {
super();
}
public LoadingCircleDrawable(int minSize) {
super(minSize);
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
if (bounds.left == 0 && bounds.top == 0 && bounds.right == 0 && bounds.bottom == 0) {
return;
}
final int centerX = bounds.centerX();
final int centerY = bounds.centerY();
final int radius = Math.min(bounds.height(), bounds.width()) >> 1;
final int maxStrokeRadius = ((int) Math.max(getForegroundLineSize(), getBackgroundLineSize()) >> 1) + 1;
final int areRadius = radius - maxStrokeRadius;
mOval.set(centerX - areRadius, centerY - areRadius, centerX + areRadius, centerY + areRadius);
}
@Override
protected void onProgressChange(float progress) {
mStartAngle = 0;
mSweepAngle = 360 * progress;
}
@Override
protected void refresh(long startTime, long curTime, long timeLong) {
final float angle = ANGLE_ADD;
mStartAngle += angle;
if (mStartAngle > 360) {
mStartAngle -= 360;
}
if (mSweepAngle > MAX_ANGLE_SWEEP) {
mAngleIncrement = -mAngleIncrement;
} else if (mSweepAngle < MIN_ANGLE_SWEEP) {
mSweepAngle = MIN_ANGLE_SWEEP;
return;
} else if (mSweepAngle == MIN_ANGLE_SWEEP) {
mAngleIncrement = -mAngleIncrement;
getNextForegroundColor();
}
mSweepAngle += mAngleIncrement;
}
@Override
protected void drawBackground(Canvas canvas, Paint backgroundPaint) {
canvas.drawArc(mOval, 0, 360, false, backgroundPaint);
}
@Override
protected void drawForeground(Canvas canvas, Paint foregroundPaint) {
canvas.drawArc(mOval, mStartAngle, -mSweepAngle, false, foregroundPaint);
}
} | caprice/ui/src/main/java/net/qiujuer/genius/ui/drawable/LoadingCircleDrawable.java | /*
* Copyright (C) 2015 Qiujuer <[email protected]>
* WebSite http://www.qiujuer.net
* Created 10/15/2015
* Changed 12/06/2015
* Author Qiujuer
*
* 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.qiujuer.genius.ui.drawable;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
/**
* A drawable to draw loading
*/
public class LoadingCircleDrawable extends LoadingDrawable {
private static final int ANGLE_ADD = 5;
private static final int MIN_ANGLE_SWEEP = 3;
private static final int MAX_ANGLE_SWEEP = 255;
private RectF mOval = new RectF();
private float mStartAngle = 0;
private float mSweepAngle = MIN_ANGLE_SWEEP;
private int mAngleIncrement = 3;
public LoadingCircleDrawable() {
super();
}
public LoadingCircleDrawable(int minSize) {
super(minSize);
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
if (bounds.left == 0 && bounds.top == 0 && bounds.right == 0 && bounds.bottom == 0) {
return;
}
final int centerX = bounds.centerX();
final int centerY = bounds.centerY();
final int radius = Math.min(bounds.height(), bounds.width()) >> 1;
final int maxStrokeRadius = ((int) Math.max(getForegroundLineSize(), getBackgroundLineSize()) >> 1) + 1;
final int areRadius = radius - maxStrokeRadius;
mOval.set(centerX - areRadius, centerY - areRadius, centerX + areRadius, centerY + areRadius);
}
@Override
protected void onProgressChange(float progress) {
mStartAngle = 0;
mSweepAngle = 360 * progress;
}
@Override
protected void refresh(long startTime, long curTime, long timeLong) {
final float angle = ANGLE_ADD;
mStartAngle += angle;
if (mStartAngle > 360) {
mStartAngle -= 360;
}
if (mSweepAngle > MAX_ANGLE_SWEEP) {
mAngleIncrement = -mAngleIncrement;
} else if (mSweepAngle < MIN_ANGLE_SWEEP) {
mSweepAngle = MIN_ANGLE_SWEEP;
return;
} else if (mSweepAngle == MIN_ANGLE_SWEEP) {
mAngleIncrement = -mAngleIncrement;
getNextForegroundColor();
}
mSweepAngle += mAngleIncrement;
}
@Override
protected void drawBackground(Canvas canvas, Paint backgroundPaint) {
canvas.drawArc(mOval, 0, 360, false, backgroundPaint);
}
@Override
protected void drawForeground(Canvas canvas, Paint foregroundPaint) {
canvas.drawArc(mOval, mStartAngle, -mSweepAngle, false, foregroundPaint);
}
} | fixed the #79 twinkle on start
| caprice/ui/src/main/java/net/qiujuer/genius/ui/drawable/LoadingCircleDrawable.java | fixed the #79 twinkle on start |
|
Java | apache-2.0 | cb2d28e59cc6454fe8f0f3ffadadec437377bbbd | 0 | thesamet/gerrit,quyixia/gerrit,renchaorevee/gerrit,jackminicloud/test,GerritCodeReview/gerrit,quyixia/gerrit,GerritCodeReview/gerrit,supriyantomaftuh/gerrit,TonyChai24/test,Distrotech/gerrit,netroby/gerrit,pkdevbox/gerrit,MerritCR/merrit,pkdevbox/gerrit,hdost/gerrit,hdost/gerrit,joshuawilson/merrit,joshuawilson/merrit,WANdisco/gerrit,MerritCR/merrit,pkdevbox/gerrit,renchaorevee/gerrit,hdost/gerrit,jackminicloud/test,jackminicloud/test,joshuawilson/merrit,WANdisco/gerrit,joshuawilson/merrit,qtproject/qtqa-gerrit,Distrotech/gerrit,thesamet/gerrit,netroby/gerrit,jackminicloud/test,pkdevbox/gerrit,Distrotech/gerrit,Seinlin/gerrit,renchaorevee/gerrit,Distrotech/gerrit,WANdisco/gerrit,Distrotech/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,supriyantomaftuh/gerrit,Distrotech/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,hdost/gerrit,quyixia/gerrit,quyixia/gerrit,thesamet/gerrit,Seinlin/gerrit,renchaorevee/gerrit,quyixia/gerrit,pkdevbox/gerrit,GerritCodeReview/gerrit,pkdevbox/gerrit,jackminicloud/test,netroby/gerrit,TonyChai24/test,TonyChai24/test,hdost/gerrit,supriyantomaftuh/gerrit,gerrit-review/gerrit,netroby/gerrit,supriyantomaftuh/gerrit,gerrit-review/gerrit,MerritCR/merrit,thesamet/gerrit,supriyantomaftuh/gerrit,quyixia/gerrit,GerritCodeReview/gerrit,Seinlin/gerrit,GerritCodeReview/gerrit,thesamet/gerrit,netroby/gerrit,MerritCR/merrit,WANdisco/gerrit,Seinlin/gerrit,MerritCR/merrit,joshuawilson/merrit,qtproject/qtqa-gerrit,jackminicloud/test,hdost/gerrit,renchaorevee/gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit,quyixia/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,gerrit-review/gerrit,TonyChai24/test,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,renchaorevee/gerrit,MerritCR/merrit,pkdevbox/gerrit,gerrit-review/gerrit,Seinlin/gerrit,supriyantomaftuh/gerrit,WANdisco/gerrit,renchaorevee/gerrit,netroby/gerrit,netroby/gerrit,Distrotech/gerrit,GerritCodeReview/gerrit,TonyChai24/test,WANdisco/gerrit,TonyChai24/test,TonyChai24/test,GerritCodeReview/gerrit,thesamet/gerrit,supriyantomaftuh/gerrit,Seinlin/gerrit,MerritCR/merrit,gerrit-review/gerrit,thesamet/gerrit,MerritCR/merrit,joshuawilson/merrit,Seinlin/gerrit,jackminicloud/test,hdost/gerrit | // Copyright (C) 2014 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.gerrit.server.index;
import static com.google.gerrit.server.query.change.ChangeData.asChanges;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.gerrit.extensions.events.GitReferenceUpdatedListener;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.git.QueueProvider.QueueType;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gerrit.server.util.ManualRequestContext;
import com.google.gerrit.server.util.OneOffRequestContext;
import com.google.gerrit.server.util.RequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
public class ReindexAfterUpdate implements GitReferenceUpdatedListener {
private static final Logger log = LoggerFactory
.getLogger(ReindexAfterUpdate.class);
private final OneOffRequestContext requestContext;
private final Provider<InternalChangeQuery> queryProvider;
private final ChangeIndexer.Factory indexerFactory;
private final IndexCollection indexes;
private final ListeningExecutorService executor;
@Inject
ReindexAfterUpdate(
OneOffRequestContext requestContext,
Provider<InternalChangeQuery> queryProvider,
ChangeIndexer.Factory indexerFactory,
IndexCollection indexes,
@IndexExecutor(QueueType.BATCH) ListeningExecutorService executor) {
this.requestContext = requestContext;
this.queryProvider = queryProvider;
this.indexerFactory = indexerFactory;
this.indexes = indexes;
this.executor = executor;
}
@Override
public void onGitReferenceUpdated(final Event event) {
Futures.transform(
executor.submit(new GetChanges(event)),
new AsyncFunction<List<Change>, List<Void>>() {
@Override
public ListenableFuture<List<Void>> apply(List<Change> changes) {
List<ListenableFuture<Void>> result =
Lists.newArrayListWithCapacity(changes.size());
for (Change c : changes) {
result.add(executor.submit(new Index(event, c.getId())));
}
return Futures.allAsList(result);
}
});
}
private abstract class Task<V> implements Callable<V> {
protected Event event;
protected Task(Event event) {
this.event = event;
}
@Override
public final V call() throws Exception {
try (ManualRequestContext ctx = requestContext.open()) {
return impl(ctx);
} catch (Exception e) {
log.error("Failed to reindex changes after " + event, e);
throw e;
}
}
protected abstract V impl(RequestContext ctx) throws Exception;
}
private class GetChanges extends Task<List<Change>> {
private GetChanges(Event event) {
super(event);
}
@Override
protected List<Change> impl(RequestContext ctx) throws OrmException {
String ref = event.getRefName();
Project.NameKey project = new Project.NameKey(event.getProjectName());
if (ref.equals(RefNames.REFS_CONFIG)) {
return asChanges(queryProvider.get().byProjectOpen(project));
} else {
return asChanges(queryProvider.get().byBranchOpen(
new Branch.NameKey(project, ref)));
}
}
@Override
public String toString() {
return "Get changes to reindex caused by " + event.getRefName()
+ " update of project " + event.getProjectName();
}
}
private class Index extends Task<Void> {
private final Change.Id id;
Index(Event event, Change.Id id) {
super(event);
this.id = id;
}
@Override
protected Void impl(RequestContext ctx) throws OrmException, IOException {
// Reload change, as some time may have passed since GetChanges.
ReviewDb db = ctx.getReviewDbProvider().get();
Change c = db.changes().get(id);
indexerFactory.create(executor, indexes).index(db, c);
return null;
}
@Override
public String toString() {
return "Index change " + id.get() + " of project "
+ event.getProjectName();
}
}
}
| gerrit-server/src/main/java/com/google/gerrit/server/index/ReindexAfterUpdate.java | // Copyright (C) 2014 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.gerrit.server.index;
import static com.google.gerrit.server.query.change.ChangeData.asChanges;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.gerrit.extensions.events.GitReferenceUpdatedListener;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.git.QueueProvider.QueueType;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gerrit.server.util.ManualRequestContext;
import com.google.gerrit.server.util.OneOffRequestContext;
import com.google.gerrit.server.util.RequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
public class ReindexAfterUpdate implements GitReferenceUpdatedListener {
private static final Logger log = LoggerFactory
.getLogger(ReindexAfterUpdate.class);
private final OneOffRequestContext requestContext;
private final Provider<InternalChangeQuery> queryProvider;
private final ChangeIndexer.Factory indexerFactory;
private final IndexCollection indexes;
private final ListeningExecutorService executor;
@Inject
ReindexAfterUpdate(
OneOffRequestContext requestContext,
Provider<InternalChangeQuery> queryProvider,
ChangeIndexer.Factory indexerFactory,
IndexCollection indexes,
@IndexExecutor(QueueType.BATCH) ListeningExecutorService executor) {
this.requestContext = requestContext;
this.queryProvider = queryProvider;
this.indexerFactory = indexerFactory;
this.indexes = indexes;
this.executor = executor;
}
@Override
public void onGitReferenceUpdated(final Event event) {
Futures.transform(
executor.submit(new GetChanges(event)),
new AsyncFunction<List<Change>, List<Void>>() {
@Override
public ListenableFuture<List<Void>> apply(List<Change> changes) {
List<ListenableFuture<Void>> result =
Lists.newArrayListWithCapacity(changes.size());
for (Change c : changes) {
result.add(executor.submit(new Index(event, c.getId())));
}
return Futures.allAsList(result);
}
});
}
private abstract class Task<V> implements Callable<V> {
protected Event event;
protected Task(Event event) {
this.event = event;
}
@Override
public final V call() throws Exception {
try (ManualRequestContext ctx = requestContext.open()) {
return impl(ctx);
} catch (Exception e) {
log.error("Failed to reindex changes after " + event, e);
throw e;
}
}
protected abstract V impl(RequestContext ctx) throws Exception;
}
private class GetChanges extends Task<List<Change>> {
private GetChanges(Event event) {
super(event);
}
@Override
protected List<Change> impl(RequestContext ctx) throws OrmException {
String ref = event.getRefName();
Project.NameKey project = new Project.NameKey(event.getProjectName());
if (ref.equals(RefNames.REFS_CONFIG)) {
return asChanges(queryProvider.get().byProjectOpen(project));
} else {
return asChanges(queryProvider.get().byBranchOpen(
new Branch.NameKey(project, ref)));
}
}
}
private class Index extends Task<Void> {
private final Change.Id id;
Index(Event event, Change.Id id) {
super(event);
this.id = id;
}
@Override
protected Void impl(RequestContext ctx) throws OrmException, IOException {
// Reload change, as some time may have passed since GetChanges.
ReviewDb db = ctx.getReviewDbProvider().get();
Change c = db.changes().get(id);
indexerFactory.create(executor, indexes).index(db, c);
return null;
}
}
}
| Print proper name for reindex after update tasks in show-queue command
Change-Id: I5fceac939cc643772e8c970338376767e49a3e31
| gerrit-server/src/main/java/com/google/gerrit/server/index/ReindexAfterUpdate.java | Print proper name for reindex after update tasks in show-queue command |
|
Java | apache-2.0 | 417db2287965af85c2f30563c2d41b9da3d5326a | 0 | gaionim/k-9,tonytamsf/k-9,mawiegand/k-9,huhu/k-9,konfer/k-9,Eagles2F/k-9,sanderbaas/k-9,k9mail/k-9,jberkel/k-9,indus1/k-9,XiveZ/k-9,439teamwork/k-9,suzp1984/k-9,vt0r/k-9,sonork/k-9,philipwhiuk/k-9,herpiko/k-9,gnebsy/k-9,dhootha/k-9,cketti/k-9,icedman21/k-9,mawiegand/k-9,WenduanMou1/k-9,jca02266/k-9,deepworks/k-9,deepworks/k-9,gaionim/k-9,rtreffer/openpgp-k-9,XiveZ/k-9,github201407/k-9,ndew623/k-9,G00fY2/k-9_material_design,rollbrettler/k-9,imaeses/k-9,Eagles2F/k-9,thuanpq/k-9,KitAway/k-9,gilbertw1/k-9,sebkur/k-9,icedman21/k-9,suzp1984/k-9,cketti/k-9,tsunli/k-9,gnebsy/k-9,moparisthebest/k-9,gilbertw1/k-9,denim2x/k-9,crr0004/k-9,tonytamsf/k-9,dgger/k-9,thuanpq/k-9,sedrubal/k-9,rtreffer/openpgp-k-9,nilsbraden/k-9,thuanpq/k-9,torte71/k-9,roscrazy/k-9,cooperpellaton/k-9,philipwhiuk/q-mail,dhootha/k-9,GuillaumeSmaha/k-9,XiveZ/k-9,herpiko/k-9,philipwhiuk/q-mail,sebkur/k-9,439teamwork/k-9,cketti/k-9,bashrc/k-9,439teamwork/k-9,dhootha/k-9,rishabhbitsg/k-9,bashrc/k-9,msdgwzhy6/k-9,torte71/k-9,suzp1984/k-9,deepworks/k-9,gilbertw1/k-9,jberkel/k-9,tsunli/k-9,dgger/k-9,nilsbraden/k-9,icedman21/k-9,mawiegand/k-9,vatsalsura/k-9,ndew623/k-9,cliniome/pki,vt0r/k-9,github201407/k-9,cooperpellaton/k-9,cliniome/pki,indus1/k-9,nilsbraden/k-9,imaeses/k-9,ndew623/k-9,Valodim/k-9,farmboy0/k-9,jca02266/k-9,crr0004/k-9,moparisthebest/k-9,konfer/k-9,huhu/k-9,sanderbaas/k-9,k9mail/k-9,huhu/k-9,vasyl-khomko/k-9,WenduanMou1/k-9,G00fY2/k-9_material_design,KitAway/k-9,msdgwzhy6/k-9,denim2x/k-9,rollbrettler/k-9,GuillaumeSmaha/k-9,leixinstar/k-9,leixinstar/k-9,KitAway/k-9,konfer/k-9,sanderbaas/k-9,torte71/k-9,cooperpellaton/k-9,vasyl-khomko/k-9,gaionim/k-9,CodingRmy/k-9,dpereira411/k-9,cketti/k-9,moparisthebest/k-9,sonork/k-9,vasyl-khomko/k-9,herpiko/k-9,dpereira411/k-9,tonytamsf/k-9,farmboy0/k-9,leixinstar/k-9,k9mail/k-9,gnebsy/k-9,tsunli/k-9,bashrc/k-9,roscrazy/k-9,dgger/k-9,sebkur/k-9,philipwhiuk/q-mail,Eagles2F/k-9,sonork/k-9,rishabhbitsg/k-9,crr0004/k-9,CodingRmy/k-9,jca02266/k-9,sedrubal/k-9,denim2x/k-9,farmboy0/k-9,GuillaumeSmaha/k-9,msdgwzhy6/k-9,rollbrettler/k-9,vatsalsura/k-9,philipwhiuk/k-9,imaeses/k-9,cliniome/pki,dpereira411/k-9,WenduanMou1/k-9,github201407/k-9 |
package com.fsck.k9;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Account stores all of the settings for a single account defined by the user. It is able to save
* and delete itself given a Preferences to work with. Each account is defined by a UUID.
*/
public class Account implements BaseAccount
{
public static final String EXPUNGE_IMMEDIATELY = "EXPUNGE_IMMEDIATELY";
public static final String EXPUNGE_MANUALLY = "EXPUNGE_MANUALLY";
public static final String EXPUNGE_ON_POLL = "EXPUNGE_ON_POLL";
public static final int DELETE_POLICY_NEVER = 0;
public static final int DELETE_POLICY_7DAYS = 1;
public static final int DELETE_POLICY_ON_DELETE = 2;
public static final int DELETE_POLICY_MARK_AS_READ = 3;
public static final String TYPE_WIFI = "WIFI";
public static final String TYPE_MOBILE = "MOBILE";
public static final String TYPE_OTHER = "OTHER";
private static String[] networkTypes = { TYPE_WIFI, TYPE_MOBILE, TYPE_OTHER };
/**
* <pre>
* 0 - Never (DELETE_POLICY_NEVER)
* 1 - After 7 days (DELETE_POLICY_7DAYS)
* 2 - When I delete from inbox (DELETE_POLICY_ON_DELETE)
* 3 - Mark as read (DELETE_POLICY_MARK_AS_READ)
* </pre>
*/
private int mDeletePolicy;
private String mUuid;
private String mStoreUri;
private String mLocalStoreUri;
private String mTransportUri;
private String mDescription;
private String mAlwaysBcc;
private int mAutomaticCheckIntervalMinutes;
private int mDisplayCount;
private int mChipColor;
private long mLastAutomaticCheckTime;
private boolean mNotifyNewMail;
private boolean mNotifySelfNewMail;
private String mDraftsFolderName;
private String mSentFolderName;
private String mTrashFolderName;
private String mOutboxFolderName;
private String mAutoExpandFolderName;
private FolderMode mFolderDisplayMode;
private FolderMode mFolderSyncMode;
private FolderMode mFolderPushMode;
private FolderMode mFolderTargetMode;
private int mAccountNumber;
private boolean mVibrate;
private boolean mRing;
private String mRingtoneUri;
private boolean mNotifySync;
private HideButtons mHideMessageViewButtons;
private boolean mIsSignatureBeforeQuotedText;
private String mExpungePolicy = EXPUNGE_IMMEDIATELY;
private int mMaxPushFolders;
private Map<String, Boolean> compressionMap = new ConcurrentHashMap<String, Boolean>();
private Searchable searchableFolders;
// Tracks if we have sent a notification for this account for
// current set of fetched messages
private boolean mRingNotified;
private List<Identity> identities;
public enum FolderMode
{
NONE, ALL, FIRST_CLASS, FIRST_AND_SECOND_CLASS, NOT_SECOND_CLASS;
}
public enum HideButtons
{
NEVER, ALWAYS, KEYBOARD_AVAILABLE;
}
public enum Searchable
{
ALL, DISPLAYABLE, NONE
}
protected Account(Context context)
{
// TODO Change local store path to something readable / recognizable
mUuid = UUID.randomUUID().toString();
mLocalStoreUri = "local://localhost/" + context.getDatabasePath(mUuid + ".db");
mAutomaticCheckIntervalMinutes = -1;
mDisplayCount = -1;
mAccountNumber = -1;
mNotifyNewMail = true;
mNotifySync = true;
mVibrate = false;
mRing = true;
mNotifySelfNewMail = true;
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
mFolderSyncMode = FolderMode.FIRST_CLASS;
mFolderPushMode = FolderMode.FIRST_CLASS;
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
mHideMessageViewButtons = HideButtons.NEVER;
mRingtoneUri = "content://settings/system/notification_sound";
mIsSignatureBeforeQuotedText = false;
mExpungePolicy = EXPUNGE_IMMEDIATELY;
mAutoExpandFolderName = "INBOX";
mMaxPushFolders = 10;
mChipColor = 0;
searchableFolders = Searchable.ALL;
identities = new ArrayList<Identity>();
Identity identity = new Identity();
identity.setSignatureUse(true);
identity.setSignature(context.getString(R.string.default_signature));
identity.setDescription(context.getString(R.string.default_identity_description));
identities.add(identity);
}
protected Account(Preferences preferences, String uuid)
{
this.mUuid = uuid;
loadAccount(preferences);
}
/**
* Load stored settings for this account.
*/
private synchronized void loadAccount(Preferences preferences)
{
mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".storeUri", null));
mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null);
mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".transportUri", null));
mDescription = preferences.getPreferences().getString(mUuid + ".description", null);
mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc);
mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid
+ ".automaticCheckIntervalMinutes", -1);
mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", -1);
mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid
+ ".lastAutomaticCheckTime", 0);
mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail",
false);
mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail",
true);
mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck",
false);
mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0);
mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName",
"Drafts");
mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName",
"Sent");
mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName",
"Trash");
mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName",
"Outbox");
mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY);
mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10);
for (String type : networkTypes)
{
Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type,
true);
compressionMap.put(type, useCompression);
}
// Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were
// opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code
// should be deleted sometime soon
if (mDraftsFolderName == null || mDraftsFolderName.equals(""))
{
mDraftsFolderName = "Drafts";
}
if (mSentFolderName == null || mSentFolderName.equals(""))
{
mSentFolderName = "Sent";
}
if (mTrashFolderName == null || mTrashFolderName.equals(""))
{
mTrashFolderName = "Trash";
}
if (mOutboxFolderName == null || mOutboxFolderName.equals(""))
{
mOutboxFolderName = "Outbox";
}
// End of 0.103 repair
mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName",
"INBOX");
mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0);
Random random = new Random((long)mAccountNumber+4);
mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor",
(random.nextInt(0x70) ) +
(random.nextInt(0x70) * 0xff ) +
(random.nextInt(0x70) * 0xffff ) +
0xff000000);
mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false);
mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true);
try
{
mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum",
HideButtons.NEVER.name()));
}
catch (Exception e)
{
mHideMessageViewButtons = HideButtons.NEVER;
}
mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone",
"content://settings/system/notification_sound");
try
{
mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderSyncMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderPushMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders",
Searchable.ALL.name()));
}
catch (Exception e)
{
searchableFolders = Searchable.ALL;
}
mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false);
identities = loadIdentities(preferences.getPreferences());
}
protected synchronized void delete(Preferences preferences)
{
String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0, length = uuids.length; i < length; i++)
{
if (!uuids[i].equals(mUuid))
{
if (sb.length() > 0)
{
sb.append(',');
}
sb.append(uuids[i]);
}
}
String accountUuids = sb.toString();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
editor.putString("accountUuids", accountUuids);
editor.remove(mUuid + ".storeUri");
editor.remove(mUuid + ".localStoreUri");
editor.remove(mUuid + ".transportUri");
editor.remove(mUuid + ".description");
editor.remove(mUuid + ".name");
editor.remove(mUuid + ".email");
editor.remove(mUuid + ".alwaysBcc");
editor.remove(mUuid + ".automaticCheckIntervalMinutes");
editor.remove(mUuid + ".lastAutomaticCheckTime");
editor.remove(mUuid + ".notifyNewMail");
editor.remove(mUuid + ".notifySelfNewMail");
editor.remove(mUuid + ".deletePolicy");
editor.remove(mUuid + ".draftsFolderName");
editor.remove(mUuid + ".sentFolderName");
editor.remove(mUuid + ".trashFolderName");
editor.remove(mUuid + ".outboxFolderName");
editor.remove(mUuid + ".autoExpandFolderName");
editor.remove(mUuid + ".accountNumber");
editor.remove(mUuid + ".vibrate");
editor.remove(mUuid + ".ring");
editor.remove(mUuid + ".ringtone");
editor.remove(mUuid + ".lastFullSync");
editor.remove(mUuid + ".folderDisplayMode");
editor.remove(mUuid + ".folderSyncMode");
editor.remove(mUuid + ".folderPushMode");
editor.remove(mUuid + ".folderTargetMode");
editor.remove(mUuid + ".hideButtonsEnum");
editor.remove(mUuid + ".signatureBeforeQuotedText");
editor.remove(mUuid + ".expungePolicy");
editor.remove(mUuid + ".maxPushFolders");
editor.remove(mUuid + ".searchableFolders");
for (String type : networkTypes)
{
editor.remove(mUuid + ".useCompression." + type);
}
deleteIdentities(preferences.getPreferences(), editor);
editor.commit();
}
public synchronized void save(Preferences preferences)
{
SharedPreferences.Editor editor = preferences.getPreferences().edit();
if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid))
{
/*
* When the account is first created we assign it a unique account number. The
* account number will be unique to that account for the lifetime of the account.
* So, we get all the existing account numbers, sort them ascending, loop through
* the list and check if the number is greater than 1 + the previous number. If so
* we use the previous number + 1 as the account number. This refills gaps.
* mAccountNumber starts as -1 on a newly created account. It must be -1 for this
* algorithm to work.
*
* I bet there is a much smarter way to do this. Anyone like to suggest it?
*/
Account[] accounts = preferences.getAccounts();
int[] accountNumbers = new int[accounts.length];
for (int i = 0; i < accounts.length; i++)
{
accountNumbers[i] = accounts[i].getAccountNumber();
}
Arrays.sort(accountNumbers);
for (int accountNumber : accountNumbers)
{
if (accountNumber > mAccountNumber + 1)
{
break;
}
mAccountNumber = accountNumber;
}
mAccountNumber++;
String accountUuids = preferences.getPreferences().getString("accountUuids", "");
accountUuids += (accountUuids.length() != 0 ? "," : "") + mUuid;
editor.putString("accountUuids", accountUuids);
}
editor.putString(mUuid + ".storeUri", Utility.base64Encode(mStoreUri));
editor.putString(mUuid + ".localStoreUri", mLocalStoreUri);
editor.putString(mUuid + ".transportUri", Utility.base64Encode(mTransportUri));
editor.putString(mUuid + ".description", mDescription);
editor.putString(mUuid + ".alwaysBcc", mAlwaysBcc);
editor.putInt(mUuid + ".automaticCheckIntervalMinutes", mAutomaticCheckIntervalMinutes);
editor.putInt(mUuid + ".displayCount", mDisplayCount);
editor.putLong(mUuid + ".lastAutomaticCheckTime", mLastAutomaticCheckTime);
editor.putBoolean(mUuid + ".notifyNewMail", mNotifyNewMail);
editor.putBoolean(mUuid + ".notifySelfNewMail", mNotifySelfNewMail);
editor.putBoolean(mUuid + ".notifyMailCheck", mNotifySync);
editor.putInt(mUuid + ".deletePolicy", mDeletePolicy);
editor.putString(mUuid + ".draftsFolderName", mDraftsFolderName);
editor.putString(mUuid + ".sentFolderName", mSentFolderName);
editor.putString(mUuid + ".trashFolderName", mTrashFolderName);
editor.putString(mUuid + ".outboxFolderName", mOutboxFolderName);
editor.putString(mUuid + ".autoExpandFolderName", mAutoExpandFolderName);
editor.putInt(mUuid + ".accountNumber", mAccountNumber);
editor.putBoolean(mUuid + ".vibrate", mVibrate);
editor.putBoolean(mUuid + ".ring", mRing);
editor.putString(mUuid + ".hideButtonsEnum", mHideMessageViewButtons.name());
editor.putString(mUuid + ".ringtone", mRingtoneUri);
editor.putString(mUuid + ".folderDisplayMode", mFolderDisplayMode.name());
editor.putString(mUuid + ".folderSyncMode", mFolderSyncMode.name());
editor.putString(mUuid + ".folderPushMode", mFolderPushMode.name());
editor.putString(mUuid + ".folderTargetMode", mFolderTargetMode.name());
editor.putBoolean(mUuid + ".signatureBeforeQuotedText", this.mIsSignatureBeforeQuotedText);
editor.putString(mUuid + ".expungePolicy", mExpungePolicy);
editor.putInt(mUuid + ".maxPushFolders", mMaxPushFolders);
editor.putString(mUuid + ".searchableFolders", searchableFolders.name());
editor.putInt(mUuid + ".chipColor", mChipColor);
for (String type : networkTypes)
{
Boolean useCompression = compressionMap.get(type);
if (useCompression != null)
{
editor.putBoolean(mUuid + ".useCompression." + type, useCompression);
}
}
saveIdentities(preferences.getPreferences(), editor);
editor.commit();
}
//TODO: Shouldn't this live in MessagingController?
// Why should everything be in MessagingController? This is an Account-specific operation. --danapple0
public AccountStats getStats(Context context) throws MessagingException
{
long startTime = System.currentTimeMillis();
AccountStats stats = new AccountStats();
int unreadMessageCount = 0;
int flaggedMessageCount = 0;
LocalStore localStore = getLocalStore();
if (K9.measureAccounts())
{
stats.size = localStore.getSize();
}
Account.FolderMode aMode = getFolderDisplayMode();
Preferences prefs = Preferences.getPreferences(context);
long folderLoadStart = System.currentTimeMillis();
List<? extends Folder> folders = localStore.getPersonalNamespaces();
long folderLoadEnd = System.currentTimeMillis();
long folderEvalStart = folderLoadEnd;
for (Folder folder : folders)
{
LocalFolder localFolder = (LocalFolder)folder;
//folder.refresh(prefs);
Folder.FolderClass fMode = localFolder.getDisplayClass(prefs);
if (folder.getName().equals(getTrashFolderName()) == false &&
folder.getName().equals(getDraftsFolderName()) == false &&
folder.getName().equals(getOutboxFolderName()) == false &&
folder.getName().equals(getSentFolderName()) == false &&
folder.getName().equals(getErrorFolderName()) == false)
{
if (aMode == Account.FolderMode.NONE)
{
continue;
}
if (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
{
continue;
}
if (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
{
continue;
}
if (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS)
{
continue;
}
unreadMessageCount += folder.getUnreadMessageCount();
flaggedMessageCount += folder.getFlaggedMessageCount();
}
}
long folderEvalEnd = System.currentTimeMillis();
stats.unreadMessageCount = unreadMessageCount;
stats.flaggedMessageCount = flaggedMessageCount;
long endTime = System.currentTimeMillis();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Account.getStats() on " + getDescription() + " took " + (endTime - startTime) + " ms;"
+ " loading " + folders.size() + " took " + (folderLoadEnd - folderLoadStart) + " ms;"
+ " evaluating took " + (folderEvalEnd - folderEvalStart) + " ms");
return stats;
}
public void setChipColor(int color) {
mChipColor = color;
}
public int getChipColor() {
return mChipColor;
}
public String getUuid()
{
return mUuid;
}
public Uri getContentUri()
{
return Uri.parse("content://accounts/" + getUuid());
}
public synchronized String getStoreUri()
{
return mStoreUri;
}
public synchronized void setStoreUri(String storeUri)
{
this.mStoreUri = storeUri;
}
public synchronized String getTransportUri()
{
return mTransportUri;
}
public synchronized void setTransportUri(String transportUri)
{
this.mTransportUri = transportUri;
}
public synchronized String getDescription()
{
return mDescription;
}
public synchronized void setDescription(String description)
{
this.mDescription = description;
}
public synchronized String getName()
{
return identities.get(0).getName();
}
public synchronized void setName(String name)
{
identities.get(0).setName(name);
}
public synchronized boolean getSignatureUse()
{
return identities.get(0).getSignatureUse();
}
public synchronized void setSignatureUse(boolean signatureUse)
{
identities.get(0).setSignatureUse(signatureUse);
}
public synchronized String getSignature()
{
return identities.get(0).getSignature();
}
public synchronized void setSignature(String signature)
{
identities.get(0).setSignature(signature);
}
public synchronized String getEmail()
{
return identities.get(0).getEmail();
}
public synchronized void setEmail(String email)
{
identities.get(0).setEmail(email);
}
public synchronized String getAlwaysBcc()
{
return mAlwaysBcc;
}
public synchronized void setAlwaysBcc(String alwaysBcc)
{
this.mAlwaysBcc = alwaysBcc;
}
public synchronized boolean isVibrate()
{
return mVibrate;
}
public synchronized void setVibrate(boolean vibrate)
{
mVibrate = vibrate;
}
/* Have we sent a new mail notification on this account */
public boolean isRingNotified()
{
return mRingNotified;
}
public void setRingNotified(boolean ringNotified)
{
mRingNotified = ringNotified;
}
public synchronized String getRingtone()
{
return mRingtoneUri;
}
public synchronized void setRingtone(String ringtoneUri)
{
mRingtoneUri = ringtoneUri;
}
public synchronized String getLocalStoreUri()
{
return mLocalStoreUri;
}
public synchronized void setLocalStoreUri(String localStoreUri)
{
this.mLocalStoreUri = localStoreUri;
}
/**
* Returns -1 for never.
*/
public synchronized int getAutomaticCheckIntervalMinutes()
{
return mAutomaticCheckIntervalMinutes;
}
/**
* @param automaticCheckIntervalMinutes or -1 for never.
*/
public synchronized boolean setAutomaticCheckIntervalMinutes(int automaticCheckIntervalMinutes)
{
int oldInterval = this.mAutomaticCheckIntervalMinutes;
int newInterval = automaticCheckIntervalMinutes;
this.mAutomaticCheckIntervalMinutes = automaticCheckIntervalMinutes;
return (oldInterval != newInterval);
}
public synchronized int getDisplayCount()
{
if (mDisplayCount == -1)
{
this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
}
return mDisplayCount;
}
public synchronized void setDisplayCount(int displayCount)
{
if (displayCount != -1)
{
this.mDisplayCount = displayCount;
}
else
{
this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
}
}
public synchronized long getLastAutomaticCheckTime()
{
return mLastAutomaticCheckTime;
}
public synchronized void setLastAutomaticCheckTime(long lastAutomaticCheckTime)
{
this.mLastAutomaticCheckTime = lastAutomaticCheckTime;
}
public synchronized boolean isNotifyNewMail()
{
return mNotifyNewMail;
}
public synchronized void setNotifyNewMail(boolean notifyNewMail)
{
this.mNotifyNewMail = notifyNewMail;
}
public synchronized int getDeletePolicy()
{
return mDeletePolicy;
}
public synchronized void setDeletePolicy(int deletePolicy)
{
this.mDeletePolicy = deletePolicy;
}
public synchronized String getDraftsFolderName()
{
return mDraftsFolderName;
}
public synchronized void setDraftsFolderName(String draftsFolderName)
{
mDraftsFolderName = draftsFolderName;
}
public synchronized String getSentFolderName()
{
return mSentFolderName;
}
public synchronized String getErrorFolderName()
{
return K9.ERROR_FOLDER_NAME;
}
public synchronized void setSentFolderName(String sentFolderName)
{
mSentFolderName = sentFolderName;
}
public synchronized String getTrashFolderName()
{
return mTrashFolderName;
}
public synchronized void setTrashFolderName(String trashFolderName)
{
mTrashFolderName = trashFolderName;
}
public synchronized String getOutboxFolderName()
{
return mOutboxFolderName;
}
public synchronized void setOutboxFolderName(String outboxFolderName)
{
mOutboxFolderName = outboxFolderName;
}
public synchronized String getAutoExpandFolderName()
{
return mAutoExpandFolderName;
}
public synchronized void setAutoExpandFolderName(String autoExpandFolderName)
{
mAutoExpandFolderName = autoExpandFolderName;
}
public synchronized int getAccountNumber()
{
return mAccountNumber;
}
public synchronized FolderMode getFolderDisplayMode()
{
return mFolderDisplayMode;
}
public synchronized boolean setFolderDisplayMode(FolderMode displayMode)
{
FolderMode oldDisplayMode = mFolderDisplayMode;
mFolderDisplayMode = displayMode;
return oldDisplayMode != displayMode;
}
public synchronized FolderMode getFolderSyncMode()
{
return mFolderSyncMode;
}
public synchronized boolean setFolderSyncMode(FolderMode syncMode)
{
FolderMode oldSyncMode = mFolderSyncMode;
mFolderSyncMode = syncMode;
if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE)
{
return true;
}
if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE)
{
return true;
}
return false;
}
public synchronized FolderMode getFolderPushMode()
{
return mFolderPushMode;
}
public synchronized boolean setFolderPushMode(FolderMode pushMode)
{
FolderMode oldPushMode = mFolderPushMode;
mFolderPushMode = pushMode;
return pushMode != oldPushMode;
}
public synchronized boolean isShowOngoing()
{
return mNotifySync;
}
public synchronized void setShowOngoing(boolean showOngoing)
{
this.mNotifySync = showOngoing;
}
public synchronized HideButtons getHideMessageViewButtons()
{
return mHideMessageViewButtons;
}
public synchronized void setHideMessageViewButtons(HideButtons hideMessageViewButtons)
{
mHideMessageViewButtons = hideMessageViewButtons;
}
public synchronized FolderMode getFolderTargetMode()
{
return mFolderTargetMode;
}
public synchronized void setFolderTargetMode(FolderMode folderTargetMode)
{
mFolderTargetMode = folderTargetMode;
}
public synchronized boolean isSignatureBeforeQuotedText()
{
return mIsSignatureBeforeQuotedText;
}
public synchronized void setSignatureBeforeQuotedText(boolean mIsSignatureBeforeQuotedText)
{
this.mIsSignatureBeforeQuotedText = mIsSignatureBeforeQuotedText;
}
public synchronized boolean isNotifySelfNewMail()
{
return mNotifySelfNewMail;
}
public synchronized void setNotifySelfNewMail(boolean notifySelfNewMail)
{
mNotifySelfNewMail = notifySelfNewMail;
}
public synchronized String getExpungePolicy()
{
return mExpungePolicy;
}
public synchronized void setExpungePolicy(String expungePolicy)
{
mExpungePolicy = expungePolicy;
}
public synchronized int getMaxPushFolders()
{
return mMaxPushFolders;
}
public synchronized boolean setMaxPushFolders(int maxPushFolders)
{
int oldMaxPushFolders = mMaxPushFolders;
mMaxPushFolders = maxPushFolders;
return oldMaxPushFolders != maxPushFolders;
}
public synchronized boolean isRing()
{
return mRing;
}
public synchronized void setRing(boolean ring)
{
mRing = ring;
}
public LocalStore getLocalStore() throws MessagingException
{
return Store.getLocalInstance(this, K9.app);
}
public Store getRemoteStore() throws MessagingException
{
return Store.getRemoteInstance(this);
}
@Override
public synchronized String toString()
{
return mDescription;
}
public void setCompression(String networkType, boolean useCompression)
{
compressionMap.put(networkType, useCompression);
}
public boolean useCompression(String networkType)
{
Boolean useCompression = compressionMap.get(networkType);
if (useCompression == null)
{
return true;
}
else
{
return useCompression;
}
}
public boolean useCompression(int type)
{
String networkType = TYPE_OTHER;
switch (type)
{
case ConnectivityManager.TYPE_MOBILE:
networkType = TYPE_MOBILE;
break;
case ConnectivityManager.TYPE_WIFI:
networkType = TYPE_WIFI;
break;
}
return useCompression(networkType);
}
@Override
public boolean equals(Object o)
{
if (o instanceof Account)
{
return ((Account)o).mUuid.equals(mUuid);
}
return super.equals(o);
}
@Override
public int hashCode()
{
return mUuid.hashCode();
}
private synchronized List<Identity> loadIdentities(SharedPreferences prefs)
{
List<Identity> newIdentities = new ArrayList<Identity>();
int ident = 0;
boolean gotOne = false;
do
{
gotOne = false;
String name = prefs.getString(mUuid + ".name." + ident, null);
String email = prefs.getString(mUuid + ".email." + ident, null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse." + ident, true);
String signature = prefs.getString(mUuid + ".signature." + ident, null);
String description = prefs.getString(mUuid + ".description." + ident, null);
if (email != null)
{
Identity identity = new Identity();
identity.setName(name);
identity.setEmail(email);
identity.setSignatureUse(signatureUse);
identity.setSignature(signature);
identity.setDescription(description);
newIdentities.add(identity);
gotOne = true;
}
ident++;
}
while (gotOne);
if (newIdentities.size() == 0)
{
String name = prefs.getString(mUuid + ".name", null);
String email = prefs.getString(mUuid + ".email", null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse", true);
String signature = prefs.getString(mUuid + ".signature", null);
Identity identity = new Identity();
identity.setName(name);
identity.setEmail(email);
identity.setSignatureUse(signatureUse);
identity.setSignature(signature);
identity.setDescription(email);
newIdentities.add(identity);
}
return newIdentities;
}
private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor)
{
int ident = 0;
boolean gotOne = false;
do
{
gotOne = false;
String email = prefs.getString(mUuid + ".email." + ident, null);
if (email != null)
{
editor.remove(mUuid + ".name." + ident);
editor.remove(mUuid + ".email." + ident);
editor.remove(mUuid + ".signatureUse." + ident);
editor.remove(mUuid + ".signature." + ident);
editor.remove(mUuid + ".description." + ident);
gotOne = true;
}
ident++;
}
while (gotOne);
}
private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor)
{
deleteIdentities(prefs, editor);
int ident = 0;
for (Identity identity : identities)
{
editor.putString(mUuid + ".name." + ident, identity.getName());
editor.putString(mUuid + ".email." + ident, identity.getEmail());
editor.putBoolean(mUuid + ".signatureUse." + ident, identity.getSignatureUse());
editor.putString(mUuid + ".signature." + ident, identity.getSignature());
editor.putString(mUuid + ".description." + ident, identity.getDescription());
ident++;
}
}
public synchronized List<Identity> getIdentities()
{
return identities;
}
public synchronized void setIdentities(List<Identity> newIdentities)
{
identities = new ArrayList<Identity>(newIdentities);
}
public synchronized Identity getIdentity(int i)
{
if (i < identities.size())
{
return identities.get(i);
}
return null;
}
public boolean isAnIdentity(Address[] addrs)
{
if (addrs == null)
{
return false;
}
for (Address addr : addrs)
{
if (findIdentity(addr) != null)
{
return true;
}
}
return false;
}
public boolean isAnIdentity(Address addr)
{
return findIdentity(addr) != null;
}
public synchronized Identity findIdentity(Address addr)
{
for (Identity identity : identities)
{
String email = identity.getEmail();
if (email != null && email.equalsIgnoreCase(addr.getAddress()))
{
return identity;
}
}
return null;
}
public Searchable getSearchableFolders()
{
return searchableFolders;
}
public void setSearchableFolders(Searchable searchableFolders)
{
this.searchableFolders = searchableFolders;
}
}
| src/com/fsck/k9/Account.java |
package com.fsck.k9;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Account stores all of the settings for a single account defined by the user. It is able to save
* and delete itself given a Preferences to work with. Each account is defined by a UUID.
*/
public class Account implements BaseAccount
{
public static final String EXPUNGE_IMMEDIATELY = "EXPUNGE_IMMEDIATELY";
public static final String EXPUNGE_MANUALLY = "EXPUNGE_MANUALLY";
public static final String EXPUNGE_ON_POLL = "EXPUNGE_ON_POLL";
public static final int DELETE_POLICY_NEVER = 0;
public static final int DELETE_POLICY_7DAYS = 1;
public static final int DELETE_POLICY_ON_DELETE = 2;
public static final int DELETE_POLICY_MARK_AS_READ = 3;
public static final String TYPE_WIFI = "WIFI";
public static final String TYPE_MOBILE = "MOBILE";
public static final String TYPE_OTHER = "OTHER";
private static String[] networkTypes = { TYPE_WIFI, TYPE_MOBILE, TYPE_OTHER };
/**
* <pre>
* 0 - Never (DELETE_POLICY_NEVER)
* 1 - After 7 days (DELETE_POLICY_7DAYS)
* 2 - When I delete from inbox (DELETE_POLICY_ON_DELETE)
* 3 - Mark as read (DELETE_POLICY_MARK_AS_READ)
* </pre>
*/
private int mDeletePolicy;
private String mUuid;
private String mStoreUri;
private String mLocalStoreUri;
private String mTransportUri;
private String mDescription;
private String mAlwaysBcc;
private int mAutomaticCheckIntervalMinutes;
private int mDisplayCount;
private int mChipColor;
private long mLastAutomaticCheckTime;
private boolean mNotifyNewMail;
private boolean mNotifySelfNewMail;
private String mDraftsFolderName;
private String mSentFolderName;
private String mTrashFolderName;
private String mOutboxFolderName;
private String mAutoExpandFolderName;
private FolderMode mFolderDisplayMode;
private FolderMode mFolderSyncMode;
private FolderMode mFolderPushMode;
private FolderMode mFolderTargetMode;
private int mAccountNumber;
private boolean mVibrate;
private boolean mRing;
private String mRingtoneUri;
private boolean mNotifySync;
private HideButtons mHideMessageViewButtons;
private boolean mIsSignatureBeforeQuotedText;
private String mExpungePolicy = EXPUNGE_IMMEDIATELY;
private int mMaxPushFolders;
private Map<String, Boolean> compressionMap = new ConcurrentHashMap<String, Boolean>();
private Searchable searchableFolders;
// Tracks if we have sent a notification for this account for
// current set of fetched messages
private boolean mRingNotified;
private List<Identity> identities;
public enum FolderMode
{
NONE, ALL, FIRST_CLASS, FIRST_AND_SECOND_CLASS, NOT_SECOND_CLASS;
}
public enum HideButtons
{
NEVER, ALWAYS, KEYBOARD_AVAILABLE;
}
public enum Searchable
{
ALL, DISPLAYABLE, NONE
}
protected Account(Context context)
{
// TODO Change local store path to something readable / recognizable
mUuid = UUID.randomUUID().toString();
mLocalStoreUri = "local://localhost/" + context.getDatabasePath(mUuid + ".db");
mAutomaticCheckIntervalMinutes = -1;
mDisplayCount = -1;
mAccountNumber = -1;
mNotifyNewMail = true;
mNotifySync = true;
mVibrate = false;
mRing = true;
mNotifySelfNewMail = true;
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
mFolderSyncMode = FolderMode.FIRST_CLASS;
mFolderPushMode = FolderMode.FIRST_CLASS;
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
mHideMessageViewButtons = HideButtons.NEVER;
mRingtoneUri = "content://settings/system/notification_sound";
mIsSignatureBeforeQuotedText = false;
mExpungePolicy = EXPUNGE_IMMEDIATELY;
mAutoExpandFolderName = "INBOX";
mMaxPushFolders = 10;
mChipColor = (new Random()).nextInt();
searchableFolders = Searchable.ALL;
identities = new ArrayList<Identity>();
Identity identity = new Identity();
identity.setSignatureUse(true);
identity.setSignature(context.getString(R.string.default_signature));
identity.setDescription(context.getString(R.string.default_identity_description));
identities.add(identity);
}
protected Account(Preferences preferences, String uuid)
{
this.mUuid = uuid;
loadAccount(preferences);
}
/**
* Load stored settings for this account.
*/
private synchronized void loadAccount(Preferences preferences)
{
mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".storeUri", null));
mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null);
mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".transportUri", null));
mDescription = preferences.getPreferences().getString(mUuid + ".description", null);
mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc);
mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid
+ ".automaticCheckIntervalMinutes", -1);
mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", -1);
mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid
+ ".lastAutomaticCheckTime", 0);
mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail",
false);
mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail",
true);
mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck",
false);
mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0);
mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName",
"Drafts");
mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName",
"Sent");
mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName",
"Trash");
mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName",
"Outbox");
mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY);
mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10);
mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor", (new Random()).nextInt());
for (String type : networkTypes)
{
Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type,
true);
compressionMap.put(type, useCompression);
}
// Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were
// opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code
// should be deleted sometime soon
if (mDraftsFolderName == null || mDraftsFolderName.equals(""))
{
mDraftsFolderName = "Drafts";
}
if (mSentFolderName == null || mSentFolderName.equals(""))
{
mSentFolderName = "Sent";
}
if (mTrashFolderName == null || mTrashFolderName.equals(""))
{
mTrashFolderName = "Trash";
}
if (mOutboxFolderName == null || mOutboxFolderName.equals(""))
{
mOutboxFolderName = "Outbox";
}
// End of 0.103 repair
mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName",
"INBOX");
mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0);
mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false);
mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true);
try
{
mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum",
HideButtons.NEVER.name()));
}
catch (Exception e)
{
mHideMessageViewButtons = HideButtons.NEVER;
}
mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone",
"content://settings/system/notification_sound");
try
{
mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderSyncMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderPushMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders",
Searchable.ALL.name()));
}
catch (Exception e)
{
searchableFolders = Searchable.ALL;
}
mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false);
identities = loadIdentities(preferences.getPreferences());
}
protected synchronized void delete(Preferences preferences)
{
String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0, length = uuids.length; i < length; i++)
{
if (!uuids[i].equals(mUuid))
{
if (sb.length() > 0)
{
sb.append(',');
}
sb.append(uuids[i]);
}
}
String accountUuids = sb.toString();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
editor.putString("accountUuids", accountUuids);
editor.remove(mUuid + ".storeUri");
editor.remove(mUuid + ".localStoreUri");
editor.remove(mUuid + ".transportUri");
editor.remove(mUuid + ".description");
editor.remove(mUuid + ".name");
editor.remove(mUuid + ".email");
editor.remove(mUuid + ".alwaysBcc");
editor.remove(mUuid + ".automaticCheckIntervalMinutes");
editor.remove(mUuid + ".lastAutomaticCheckTime");
editor.remove(mUuid + ".notifyNewMail");
editor.remove(mUuid + ".notifySelfNewMail");
editor.remove(mUuid + ".deletePolicy");
editor.remove(mUuid + ".draftsFolderName");
editor.remove(mUuid + ".sentFolderName");
editor.remove(mUuid + ".trashFolderName");
editor.remove(mUuid + ".outboxFolderName");
editor.remove(mUuid + ".autoExpandFolderName");
editor.remove(mUuid + ".accountNumber");
editor.remove(mUuid + ".vibrate");
editor.remove(mUuid + ".ring");
editor.remove(mUuid + ".ringtone");
editor.remove(mUuid + ".lastFullSync");
editor.remove(mUuid + ".folderDisplayMode");
editor.remove(mUuid + ".folderSyncMode");
editor.remove(mUuid + ".folderPushMode");
editor.remove(mUuid + ".folderTargetMode");
editor.remove(mUuid + ".hideButtonsEnum");
editor.remove(mUuid + ".signatureBeforeQuotedText");
editor.remove(mUuid + ".expungePolicy");
editor.remove(mUuid + ".maxPushFolders");
editor.remove(mUuid + ".searchableFolders");
for (String type : networkTypes)
{
editor.remove(mUuid + ".useCompression." + type);
}
deleteIdentities(preferences.getPreferences(), editor);
editor.commit();
}
public synchronized void save(Preferences preferences)
{
SharedPreferences.Editor editor = preferences.getPreferences().edit();
if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid))
{
/*
* When the account is first created we assign it a unique account number. The
* account number will be unique to that account for the lifetime of the account.
* So, we get all the existing account numbers, sort them ascending, loop through
* the list and check if the number is greater than 1 + the previous number. If so
* we use the previous number + 1 as the account number. This refills gaps.
* mAccountNumber starts as -1 on a newly created account. It must be -1 for this
* algorithm to work.
*
* I bet there is a much smarter way to do this. Anyone like to suggest it?
*/
Account[] accounts = preferences.getAccounts();
int[] accountNumbers = new int[accounts.length];
for (int i = 0; i < accounts.length; i++)
{
accountNumbers[i] = accounts[i].getAccountNumber();
}
Arrays.sort(accountNumbers);
for (int accountNumber : accountNumbers)
{
if (accountNumber > mAccountNumber + 1)
{
break;
}
mAccountNumber = accountNumber;
}
mAccountNumber++;
String accountUuids = preferences.getPreferences().getString("accountUuids", "");
accountUuids += (accountUuids.length() != 0 ? "," : "") + mUuid;
editor.putString("accountUuids", accountUuids);
}
editor.putString(mUuid + ".storeUri", Utility.base64Encode(mStoreUri));
editor.putString(mUuid + ".localStoreUri", mLocalStoreUri);
editor.putString(mUuid + ".transportUri", Utility.base64Encode(mTransportUri));
editor.putString(mUuid + ".description", mDescription);
editor.putString(mUuid + ".alwaysBcc", mAlwaysBcc);
editor.putInt(mUuid + ".automaticCheckIntervalMinutes", mAutomaticCheckIntervalMinutes);
editor.putInt(mUuid + ".displayCount", mDisplayCount);
editor.putLong(mUuid + ".lastAutomaticCheckTime", mLastAutomaticCheckTime);
editor.putBoolean(mUuid + ".notifyNewMail", mNotifyNewMail);
editor.putBoolean(mUuid + ".notifySelfNewMail", mNotifySelfNewMail);
editor.putBoolean(mUuid + ".notifyMailCheck", mNotifySync);
editor.putInt(mUuid + ".deletePolicy", mDeletePolicy);
editor.putString(mUuid + ".draftsFolderName", mDraftsFolderName);
editor.putString(mUuid + ".sentFolderName", mSentFolderName);
editor.putString(mUuid + ".trashFolderName", mTrashFolderName);
editor.putString(mUuid + ".outboxFolderName", mOutboxFolderName);
editor.putString(mUuid + ".autoExpandFolderName", mAutoExpandFolderName);
editor.putInt(mUuid + ".accountNumber", mAccountNumber);
editor.putBoolean(mUuid + ".vibrate", mVibrate);
editor.putBoolean(mUuid + ".ring", mRing);
editor.putString(mUuid + ".hideButtonsEnum", mHideMessageViewButtons.name());
editor.putString(mUuid + ".ringtone", mRingtoneUri);
editor.putString(mUuid + ".folderDisplayMode", mFolderDisplayMode.name());
editor.putString(mUuid + ".folderSyncMode", mFolderSyncMode.name());
editor.putString(mUuid + ".folderPushMode", mFolderPushMode.name());
editor.putString(mUuid + ".folderTargetMode", mFolderTargetMode.name());
editor.putBoolean(mUuid + ".signatureBeforeQuotedText", this.mIsSignatureBeforeQuotedText);
editor.putString(mUuid + ".expungePolicy", mExpungePolicy);
editor.putInt(mUuid + ".maxPushFolders", mMaxPushFolders);
editor.putString(mUuid + ".searchableFolders", searchableFolders.name());
editor.putInt(mUuid + ".chipColor", mChipColor);
for (String type : networkTypes)
{
Boolean useCompression = compressionMap.get(type);
if (useCompression != null)
{
editor.putBoolean(mUuid + ".useCompression." + type, useCompression);
}
}
saveIdentities(preferences.getPreferences(), editor);
editor.commit();
}
//TODO: Shouldn't this live in MessagingController?
// Why should everything be in MessagingController? This is an Account-specific operation. --danapple0
public AccountStats getStats(Context context) throws MessagingException
{
long startTime = System.currentTimeMillis();
AccountStats stats = new AccountStats();
int unreadMessageCount = 0;
int flaggedMessageCount = 0;
LocalStore localStore = getLocalStore();
if (K9.measureAccounts())
{
stats.size = localStore.getSize();
}
Account.FolderMode aMode = getFolderDisplayMode();
Preferences prefs = Preferences.getPreferences(context);
long folderLoadStart = System.currentTimeMillis();
List<? extends Folder> folders = localStore.getPersonalNamespaces();
long folderLoadEnd = System.currentTimeMillis();
long folderEvalStart = folderLoadEnd;
for (Folder folder : folders)
{
LocalFolder localFolder = (LocalFolder)folder;
//folder.refresh(prefs);
Folder.FolderClass fMode = localFolder.getDisplayClass(prefs);
if (folder.getName().equals(getTrashFolderName()) == false &&
folder.getName().equals(getDraftsFolderName()) == false &&
folder.getName().equals(getOutboxFolderName()) == false &&
folder.getName().equals(getSentFolderName()) == false &&
folder.getName().equals(getErrorFolderName()) == false)
{
if (aMode == Account.FolderMode.NONE)
{
continue;
}
if (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
{
continue;
}
if (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
{
continue;
}
if (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS)
{
continue;
}
unreadMessageCount += folder.getUnreadMessageCount();
flaggedMessageCount += folder.getFlaggedMessageCount();
}
}
long folderEvalEnd = System.currentTimeMillis();
stats.unreadMessageCount = unreadMessageCount;
stats.flaggedMessageCount = flaggedMessageCount;
long endTime = System.currentTimeMillis();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Account.getStats() on " + getDescription() + " took " + (endTime - startTime) + " ms;"
+ " loading " + folders.size() + " took " + (folderLoadEnd - folderLoadStart) + " ms;"
+ " evaluating took " + (folderEvalEnd - folderEvalStart) + " ms");
return stats;
}
public void setChipColor(int color) {
mChipColor = color;
}
public int getChipColor() {
return mChipColor;
}
public String getUuid()
{
return mUuid;
}
public Uri getContentUri()
{
return Uri.parse("content://accounts/" + getUuid());
}
public synchronized String getStoreUri()
{
return mStoreUri;
}
public synchronized void setStoreUri(String storeUri)
{
this.mStoreUri = storeUri;
}
public synchronized String getTransportUri()
{
return mTransportUri;
}
public synchronized void setTransportUri(String transportUri)
{
this.mTransportUri = transportUri;
}
public synchronized String getDescription()
{
return mDescription;
}
public synchronized void setDescription(String description)
{
this.mDescription = description;
}
public synchronized String getName()
{
return identities.get(0).getName();
}
public synchronized void setName(String name)
{
identities.get(0).setName(name);
}
public synchronized boolean getSignatureUse()
{
return identities.get(0).getSignatureUse();
}
public synchronized void setSignatureUse(boolean signatureUse)
{
identities.get(0).setSignatureUse(signatureUse);
}
public synchronized String getSignature()
{
return identities.get(0).getSignature();
}
public synchronized void setSignature(String signature)
{
identities.get(0).setSignature(signature);
}
public synchronized String getEmail()
{
return identities.get(0).getEmail();
}
public synchronized void setEmail(String email)
{
identities.get(0).setEmail(email);
}
public synchronized String getAlwaysBcc()
{
return mAlwaysBcc;
}
public synchronized void setAlwaysBcc(String alwaysBcc)
{
this.mAlwaysBcc = alwaysBcc;
}
public synchronized boolean isVibrate()
{
return mVibrate;
}
public synchronized void setVibrate(boolean vibrate)
{
mVibrate = vibrate;
}
/* Have we sent a new mail notification on this account */
public boolean isRingNotified()
{
return mRingNotified;
}
public void setRingNotified(boolean ringNotified)
{
mRingNotified = ringNotified;
}
public synchronized String getRingtone()
{
return mRingtoneUri;
}
public synchronized void setRingtone(String ringtoneUri)
{
mRingtoneUri = ringtoneUri;
}
public synchronized String getLocalStoreUri()
{
return mLocalStoreUri;
}
public synchronized void setLocalStoreUri(String localStoreUri)
{
this.mLocalStoreUri = localStoreUri;
}
/**
* Returns -1 for never.
*/
public synchronized int getAutomaticCheckIntervalMinutes()
{
return mAutomaticCheckIntervalMinutes;
}
/**
* @param automaticCheckIntervalMinutes or -1 for never.
*/
public synchronized boolean setAutomaticCheckIntervalMinutes(int automaticCheckIntervalMinutes)
{
int oldInterval = this.mAutomaticCheckIntervalMinutes;
int newInterval = automaticCheckIntervalMinutes;
this.mAutomaticCheckIntervalMinutes = automaticCheckIntervalMinutes;
return (oldInterval != newInterval);
}
public synchronized int getDisplayCount()
{
if (mDisplayCount == -1)
{
this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
}
return mDisplayCount;
}
public synchronized void setDisplayCount(int displayCount)
{
if (displayCount != -1)
{
this.mDisplayCount = displayCount;
}
else
{
this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
}
}
public synchronized long getLastAutomaticCheckTime()
{
return mLastAutomaticCheckTime;
}
public synchronized void setLastAutomaticCheckTime(long lastAutomaticCheckTime)
{
this.mLastAutomaticCheckTime = lastAutomaticCheckTime;
}
public synchronized boolean isNotifyNewMail()
{
return mNotifyNewMail;
}
public synchronized void setNotifyNewMail(boolean notifyNewMail)
{
this.mNotifyNewMail = notifyNewMail;
}
public synchronized int getDeletePolicy()
{
return mDeletePolicy;
}
public synchronized void setDeletePolicy(int deletePolicy)
{
this.mDeletePolicy = deletePolicy;
}
public synchronized String getDraftsFolderName()
{
return mDraftsFolderName;
}
public synchronized void setDraftsFolderName(String draftsFolderName)
{
mDraftsFolderName = draftsFolderName;
}
public synchronized String getSentFolderName()
{
return mSentFolderName;
}
public synchronized String getErrorFolderName()
{
return K9.ERROR_FOLDER_NAME;
}
public synchronized void setSentFolderName(String sentFolderName)
{
mSentFolderName = sentFolderName;
}
public synchronized String getTrashFolderName()
{
return mTrashFolderName;
}
public synchronized void setTrashFolderName(String trashFolderName)
{
mTrashFolderName = trashFolderName;
}
public synchronized String getOutboxFolderName()
{
return mOutboxFolderName;
}
public synchronized void setOutboxFolderName(String outboxFolderName)
{
mOutboxFolderName = outboxFolderName;
}
public synchronized String getAutoExpandFolderName()
{
return mAutoExpandFolderName;
}
public synchronized void setAutoExpandFolderName(String autoExpandFolderName)
{
mAutoExpandFolderName = autoExpandFolderName;
}
public synchronized int getAccountNumber()
{
return mAccountNumber;
}
public synchronized FolderMode getFolderDisplayMode()
{
return mFolderDisplayMode;
}
public synchronized boolean setFolderDisplayMode(FolderMode displayMode)
{
FolderMode oldDisplayMode = mFolderDisplayMode;
mFolderDisplayMode = displayMode;
return oldDisplayMode != displayMode;
}
public synchronized FolderMode getFolderSyncMode()
{
return mFolderSyncMode;
}
public synchronized boolean setFolderSyncMode(FolderMode syncMode)
{
FolderMode oldSyncMode = mFolderSyncMode;
mFolderSyncMode = syncMode;
if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE)
{
return true;
}
if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE)
{
return true;
}
return false;
}
public synchronized FolderMode getFolderPushMode()
{
return mFolderPushMode;
}
public synchronized boolean setFolderPushMode(FolderMode pushMode)
{
FolderMode oldPushMode = mFolderPushMode;
mFolderPushMode = pushMode;
return pushMode != oldPushMode;
}
public synchronized boolean isShowOngoing()
{
return mNotifySync;
}
public synchronized void setShowOngoing(boolean showOngoing)
{
this.mNotifySync = showOngoing;
}
public synchronized HideButtons getHideMessageViewButtons()
{
return mHideMessageViewButtons;
}
public synchronized void setHideMessageViewButtons(HideButtons hideMessageViewButtons)
{
mHideMessageViewButtons = hideMessageViewButtons;
}
public synchronized FolderMode getFolderTargetMode()
{
return mFolderTargetMode;
}
public synchronized void setFolderTargetMode(FolderMode folderTargetMode)
{
mFolderTargetMode = folderTargetMode;
}
public synchronized boolean isSignatureBeforeQuotedText()
{
return mIsSignatureBeforeQuotedText;
}
public synchronized void setSignatureBeforeQuotedText(boolean mIsSignatureBeforeQuotedText)
{
this.mIsSignatureBeforeQuotedText = mIsSignatureBeforeQuotedText;
}
public synchronized boolean isNotifySelfNewMail()
{
return mNotifySelfNewMail;
}
public synchronized void setNotifySelfNewMail(boolean notifySelfNewMail)
{
mNotifySelfNewMail = notifySelfNewMail;
}
public synchronized String getExpungePolicy()
{
return mExpungePolicy;
}
public synchronized void setExpungePolicy(String expungePolicy)
{
mExpungePolicy = expungePolicy;
}
public synchronized int getMaxPushFolders()
{
return mMaxPushFolders;
}
public synchronized boolean setMaxPushFolders(int maxPushFolders)
{
int oldMaxPushFolders = mMaxPushFolders;
mMaxPushFolders = maxPushFolders;
return oldMaxPushFolders != maxPushFolders;
}
public synchronized boolean isRing()
{
return mRing;
}
public synchronized void setRing(boolean ring)
{
mRing = ring;
}
public LocalStore getLocalStore() throws MessagingException
{
return Store.getLocalInstance(this, K9.app);
}
public Store getRemoteStore() throws MessagingException
{
return Store.getRemoteInstance(this);
}
@Override
public synchronized String toString()
{
return mDescription;
}
public void setCompression(String networkType, boolean useCompression)
{
compressionMap.put(networkType, useCompression);
}
public boolean useCompression(String networkType)
{
Boolean useCompression = compressionMap.get(networkType);
if (useCompression == null)
{
return true;
}
else
{
return useCompression;
}
}
public boolean useCompression(int type)
{
String networkType = TYPE_OTHER;
switch (type)
{
case ConnectivityManager.TYPE_MOBILE:
networkType = TYPE_MOBILE;
break;
case ConnectivityManager.TYPE_WIFI:
networkType = TYPE_WIFI;
break;
}
return useCompression(networkType);
}
@Override
public boolean equals(Object o)
{
if (o instanceof Account)
{
return ((Account)o).mUuid.equals(mUuid);
}
return super.equals(o);
}
@Override
public int hashCode()
{
return mUuid.hashCode();
}
private synchronized List<Identity> loadIdentities(SharedPreferences prefs)
{
List<Identity> newIdentities = new ArrayList<Identity>();
int ident = 0;
boolean gotOne = false;
do
{
gotOne = false;
String name = prefs.getString(mUuid + ".name." + ident, null);
String email = prefs.getString(mUuid + ".email." + ident, null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse." + ident, true);
String signature = prefs.getString(mUuid + ".signature." + ident, null);
String description = prefs.getString(mUuid + ".description." + ident, null);
if (email != null)
{
Identity identity = new Identity();
identity.setName(name);
identity.setEmail(email);
identity.setSignatureUse(signatureUse);
identity.setSignature(signature);
identity.setDescription(description);
newIdentities.add(identity);
gotOne = true;
}
ident++;
}
while (gotOne);
if (newIdentities.size() == 0)
{
String name = prefs.getString(mUuid + ".name", null);
String email = prefs.getString(mUuid + ".email", null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse", true);
String signature = prefs.getString(mUuid + ".signature", null);
Identity identity = new Identity();
identity.setName(name);
identity.setEmail(email);
identity.setSignatureUse(signatureUse);
identity.setSignature(signature);
identity.setDescription(email);
newIdentities.add(identity);
}
return newIdentities;
}
private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor)
{
int ident = 0;
boolean gotOne = false;
do
{
gotOne = false;
String email = prefs.getString(mUuid + ".email." + ident, null);
if (email != null)
{
editor.remove(mUuid + ".name." + ident);
editor.remove(mUuid + ".email." + ident);
editor.remove(mUuid + ".signatureUse." + ident);
editor.remove(mUuid + ".signature." + ident);
editor.remove(mUuid + ".description." + ident);
gotOne = true;
}
ident++;
}
while (gotOne);
}
private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor)
{
deleteIdentities(prefs, editor);
int ident = 0;
for (Identity identity : identities)
{
editor.putString(mUuid + ".name." + ident, identity.getName());
editor.putString(mUuid + ".email." + ident, identity.getEmail());
editor.putBoolean(mUuid + ".signatureUse." + ident, identity.getSignatureUse());
editor.putString(mUuid + ".signature." + ident, identity.getSignature());
editor.putString(mUuid + ".description." + ident, identity.getDescription());
ident++;
}
}
public synchronized List<Identity> getIdentities()
{
return identities;
}
public synchronized void setIdentities(List<Identity> newIdentities)
{
identities = new ArrayList<Identity>(newIdentities);
}
public synchronized Identity getIdentity(int i)
{
if (i < identities.size())
{
return identities.get(i);
}
return null;
}
public boolean isAnIdentity(Address[] addrs)
{
if (addrs == null)
{
return false;
}
for (Address addr : addrs)
{
if (findIdentity(addr) != null)
{
return true;
}
}
return false;
}
public boolean isAnIdentity(Address addr)
{
return findIdentity(addr) != null;
}
public synchronized Identity findIdentity(Address addr)
{
for (Identity identity : identities)
{
String email = identity.getEmail();
if (email != null && email.equalsIgnoreCase(addr.getAddress()))
{
return identity;
}
}
return null;
}
public Searchable getSearchableFolders()
{
return searchableFolders;
}
public void setSearchableFolders(Searchable searchableFolders)
{
this.searchableFolders = searchableFolders;
}
}
| Consistent random colors for accounts without color chips
| src/com/fsck/k9/Account.java | Consistent random colors for accounts without color chips |
|
Java | apache-2.0 | 7add45cf78c93b6e407e2289c2769eb0130d463b | 0 | apereo/cas,apereo/cas,apereo/cas,apereo/cas,apereo/cas,apereo/cas,apereo/cas | package org.apereo.cas.support.oauth.validator.authorization;
import org.apereo.cas.AbstractOAuth20Tests;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.OAuth20ResponseTypes;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.pac4j.core.context.JEEContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is {@link OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidatorTests}.
*
* @author Julien Huon
* @since 6.4.0
*/
@Tag("OAuth")
public class OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidatorTests extends AbstractOAuth20Tests {
@Autowired
@Qualifier("oauthProofKeyCodeExchangeResponseTypeAuthorizationRequestValidator")
private OAuth20AuthorizationRequestValidator validator;
@Test
public void verifySupports() throws Exception {
val service = getRegisteredService("client", "secret");
servicesManager.save(service);
val request = new MockHttpServletRequest();
val response = new MockHttpServletResponse();
val context = new JEEContext(request, response);
assertFalse(validator.supports(context));
request.setParameter(OAuth20Constants.CLIENT_ID, "client");
request.setParameter(OAuth20Constants.REDIRECT_URI, service.getServiceId());
request.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.getType());
request.setParameter(OAuth20Constants.CODE_VERIFIER, "abcd");
assertFalse(validator.supports(context));
request.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.CODE.getType());
assertTrue(validator.supports(context));
}
}
| support/cas-server-support-oauth/src/test/java/org/apereo/cas/support/oauth/validator/authorization/OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidatorTests.java | package org.apereo.cas.support.oauth.validator.authorization;
import org.apereo.cas.authentication.principal.WebApplicationServiceFactory;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.RegisteredServiceAccessStrategyAuditableEnforcer;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.OAuth20ResponseTypes;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.support.oauth.web.DefaultOAuth20RequestParameterResolver;
import org.apereo.cas.token.JwtBuilder;
import org.apereo.cas.util.CollectionUtils;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.pac4j.core.context.JEEContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Collection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* This is {@link OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidatorTests}.
*
* @author Julien Huon
* @since 6.4.0
*/
@Tag("OAuth")
public class OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidatorTests {
@Test
public void verifySupports() throws Exception {
val serviceManager = mock(ServicesManager.class);
val service = new OAuthRegisteredService();
service.setName("OAuth");
service.setClientId("client");
service.setClientSecret("secret");
service.setServiceId("https://callback.example.org");
when(serviceManager.getAllServices()).thenReturn((Collection) CollectionUtils.toCollection(service));
when(serviceManager.getAllServicesOfType(any())).thenReturn((Collection) CollectionUtils.toCollection(service));
val v = new OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidator(
serviceManager, new WebApplicationServiceFactory(),
new RegisteredServiceAccessStrategyAuditableEnforcer(new CasConfigurationProperties()),
new DefaultOAuth20RequestParameterResolver(mock(JwtBuilder.class)));
val request = new MockHttpServletRequest();
val response = new MockHttpServletResponse();
val context = new JEEContext(request, response);
assertFalse(v.supports(context));
request.setParameter(OAuth20Constants.CLIENT_ID, "client");
request.setParameter(OAuth20Constants.REDIRECT_URI, service.getServiceId());
request.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.getType());
request.setParameter(OAuth20Constants.CODE_VERIFIER, "abcd");
assertFalse(v.supports(context));
request.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.CODE.getType());
assertTrue(v.supports(context));
}
}
| fix tests
| support/cas-server-support-oauth/src/test/java/org/apereo/cas/support/oauth/validator/authorization/OAuth20ProofKeyCodeExchangeResponseTypeAuthorizationRequestValidatorTests.java | fix tests |
|
Java | apache-2.0 | f7ab1bc01f37101cb069a29733176f469ccaf439 | 0 | muzuro/jsprit,sinhautkarsh2014/winter_jsprit,HeinrichFilter/jsprit,balage1551/jsprit,michalmac/jsprit,graphhopper/jsprit | package jsprit.core.algorithm;
import jsprit.core.algorithm.io.AlgorithmConfig;
import jsprit.core.algorithm.io.AlgorithmConfigXmlReader;
import jsprit.core.algorithm.io.VehicleRoutingAlgorithms;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.algorithm.state.UpdateActivityTimes;
import jsprit.core.algorithm.state.UpdateEndLocationIfRouteIsOpen;
import jsprit.core.algorithm.state.UpdateVariableCosts;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.constraint.ConstraintManager;
import jsprit.core.problem.solution.SolutionCostCalculator;
/**
* Builder that builds a {@link VehicleRoutingAlgorithm}.
*
* @author schroeder
*
*/
public class VehicleRoutingAlgorithmBuilder {
private String algorithmConfigFile;
private AlgorithmConfig algorithmConfig;
private final VehicleRoutingProblem vrp;
private SolutionCostCalculator solutionCostCalculator;
private StateManager stateManager;
private boolean addCoreConstraints = false;
private boolean addDefaultCostCalculators = false;
private ConstraintManager constraintManager;
private int nuOfThreads=0;
/**
* Constructs the builder with the problem and an algorithmConfigFile. Latter is to configure and specify the ruin-and-recreate meta-heuristic.
*
* @param problem
* @param algorithmConfig
*/
public VehicleRoutingAlgorithmBuilder(VehicleRoutingProblem problem, String algorithmConfig) {
this.vrp=problem;
this.algorithmConfigFile=algorithmConfig;
this.algorithmConfig=null;
}
/**
* Constructs the builder with the problem and an algorithmConfig. Latter is to configure and specify the ruin-and-recreate meta-heuristic.
*
* @param problem
* @param algorithmConfig
*/
public VehicleRoutingAlgorithmBuilder(VehicleRoutingProblem problem, AlgorithmConfig algorithmConfig) {
this.vrp=problem;
this.algorithmConfigFile=null;
this.algorithmConfig=algorithmConfig;
}
/**
* Sets custom objective function.
*
* <p>If objective function is not set, a default function is applied (which basically minimizes
* fixed and variable transportation costs ({@link VariablePlusFixedSolutionCostCalculatorFactory}).
*
* @param objectiveFunction
* @see VariablePlusFixedSolutionCostCalculatorFactory
*/
public void setObjectiveFunction(SolutionCostCalculator objectiveFunction) {
this.solutionCostCalculator = objectiveFunction;
}
/**
* Sets stateManager to memorize states.
*
* @param stateManager
* @see StateManager
*/
public void setStateManager(StateManager stateManager) {
this.stateManager=stateManager;
}
/**
* Adds core constraints.
*
* <p>Thus, it adds vehicle-capacity and time-window constraints and their
* required stateUpdater.
*
*/
public void addCoreConstraints() {
addCoreConstraints=true;
}
/**
* Adds default cost calculators used by the insertion heuristic,
* to calculate activity insertion costs.
* By default, marginal transportation costs are calculated. Thus when inserting
* act_k between act_i and act_j, marginal (additional) transportation costs
* are basically c(act_i,act_k)+c(act_k,act_j)-c(act_i,act_j).
*
* <p>Do not use this method, if you plan to control the insertion heuristic
* entirely via hard- and soft-constraints.
*/
public void addDefaultCostCalculators() {
addDefaultCostCalculators=true;
}
/**
* Sets state- and constraintManager.
*
* @param stateManager
* @param constraintManager
* @see StateManager
* @see ConstraintManager
*/
public void setStateAndConstraintManager(StateManager stateManager, ConstraintManager constraintManager) {
this.stateManager=stateManager;
this.constraintManager=constraintManager;
}
/**
* Sets nuOfThreads.
*
* @param nuOfThreads
*/
public void setNuOfThreads(int nuOfThreads){
this.nuOfThreads=nuOfThreads;
}
/**
* Builds and returns the algorithm.
*
* <p>If algorithmConfigFile is set, it reads the configuration.
*
* @return
*/
public VehicleRoutingAlgorithm build() {
if(stateManager == null) stateManager = new StateManager(vrp.getTransportCosts());
if(constraintManager == null) constraintManager = new ConstraintManager(vrp,stateManager,vrp.getConstraints());
//add core updater
stateManager.addStateUpdater(new UpdateEndLocationIfRouteIsOpen());
// stateManager.addStateUpdater(new OpenRouteStateVerifier());
stateManager.addStateUpdater(new UpdateActivityTimes(vrp.getTransportCosts()));
stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager));
if(addCoreConstraints){
constraintManager.addLoadConstraint();
constraintManager.addTimeWindowConstraint();
stateManager.updateLoadStates();
stateManager.updateTimeWindowStates();
}
if(algorithmConfig==null){
algorithmConfig = new AlgorithmConfig();
AlgorithmConfigXmlReader xmlReader = new AlgorithmConfigXmlReader(algorithmConfig);
xmlReader.read(algorithmConfigFile);
}
return VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, algorithmConfig, nuOfThreads, solutionCostCalculator, stateManager, constraintManager, addDefaultCostCalculators);
}
}
| jsprit-core/src/main/java/jsprit/core/algorithm/VehicleRoutingAlgorithmBuilder.java | package jsprit.core.algorithm;
import jsprit.core.algorithm.io.VehicleRoutingAlgorithms;
import jsprit.core.algorithm.state.StateManager;
import jsprit.core.algorithm.state.UpdateActivityTimes;
import jsprit.core.algorithm.state.UpdateEndLocationIfRouteIsOpen;
import jsprit.core.algorithm.state.UpdateVariableCosts;
import jsprit.core.problem.VehicleRoutingProblem;
import jsprit.core.problem.constraint.ConstraintManager;
import jsprit.core.problem.solution.SolutionCostCalculator;
/**
* Builder that builds a {@link VehicleRoutingAlgorithm}.
*
* @author schroeder
*
*/
public class VehicleRoutingAlgorithmBuilder {
private final String algorithmConfig;
private final VehicleRoutingProblem vrp;
private SolutionCostCalculator solutionCostCalculator;
private StateManager stateManager;
private boolean addCoreConstraints = false;
private boolean addDefaultCostCalculators = false;
private ConstraintManager constraintManager;
private int nuOfThreads=0;
/**
* Constructs the builder.
*
* @param problem
* @param algorithmConfig
*/
public VehicleRoutingAlgorithmBuilder(VehicleRoutingProblem problem, String algorithmConfig) {
this.vrp=problem;
this.algorithmConfig=algorithmConfig;
}
/**
* Sets custom objective function.
*
* <p>If objective function is not set, a default function is applied (which basically minimizes
* fixed and variable transportation costs ({@link VariablePlusFixedSolutionCostCalculatorFactory}).
*
* @param objectiveFunction
* @see VariablePlusFixedSolutionCostCalculatorFactory
*/
public void setObjectiveFunction(SolutionCostCalculator objectiveFunction) {
this.solutionCostCalculator = objectiveFunction;
}
/**
* Sets stateManager to memorize states.
*
* @param stateManager
* @see StateManager
*/
public void setStateManager(StateManager stateManager) {
this.stateManager=stateManager;
}
/**
* Adds core constraints.
*
* <p>Thus, it adds vehicle-capacity and time-window constraints and their
* required stateUpdater.
*
*/
public void addCoreConstraints() {
addCoreConstraints=true;
}
/**
* Adds default cost calculators used by the insertion heuristic,
* to calculate activity insertion costs.
* By default, marginal transportation costs are calculated. Thus when inserting
* act_k between act_i and act_j, marginal (additional) transportation costs
* are basically c(act_i,act_k)+c(act_k,act_j)-c(act_i,act_j).
*
* <p>Do not use this method, if you plan to control the insertion heuristic
* entirely via hard- and soft-constraints.
*/
public void addDefaultCostCalculators() {
addDefaultCostCalculators=true;
}
/**
* Sets state- and constraintManager.
*
* @param stateManager
* @param constraintManager
* @see StateManager
* @see ConstraintManager
*/
public void setStateAndConstraintManager(StateManager stateManager, ConstraintManager constraintManager) {
this.stateManager=stateManager;
this.constraintManager=constraintManager;
}
/**
* Sets nuOfThreads.
*
* @param nuOfThreads
*/
public void setNuOfThreads(int nuOfThreads){
this.nuOfThreads=nuOfThreads;
}
/**
* Builds and returns the algorithm.
*
* @return
*/
public VehicleRoutingAlgorithm build() {
if(stateManager == null) stateManager = new StateManager(vrp.getTransportCosts());
if(constraintManager == null) constraintManager = new ConstraintManager(vrp,stateManager,vrp.getConstraints());
//add core updater
stateManager.addStateUpdater(new UpdateEndLocationIfRouteIsOpen());
// stateManager.addStateUpdater(new OpenRouteStateVerifier());
stateManager.addStateUpdater(new UpdateActivityTimes(vrp.getTransportCosts()));
stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(), stateManager));
if(addCoreConstraints){
constraintManager.addLoadConstraint();
constraintManager.addTimeWindowConstraint();
stateManager.updateLoadStates();
stateManager.updateTimeWindowStates();
}
return VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, algorithmConfig, nuOfThreads, solutionCostCalculator, stateManager, constraintManager, addDefaultCostCalculators);
}
}
| added constructor for AlgortihmConfig | jsprit-core/src/main/java/jsprit/core/algorithm/VehicleRoutingAlgorithmBuilder.java | added constructor for AlgortihmConfig |
|
Java | apache-2.0 | 2590bc2bba62046d97961b2c7c36c7e994560ce0 | 0 | rupertlssmith/lojix,rupertlssmith/lojix,rupertlssmith/lojix | /*
* Copyright The Sett Ltd.
*
* 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.thesett.aima.logic.fol.wam.compiler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import com.thesett.aima.logic.fol.AllTermsVisitor;
import com.thesett.aima.logic.fol.BasePositionalVisitor;
import com.thesett.aima.logic.fol.Clause;
import com.thesett.aima.logic.fol.DelegatingAllTermsVisitor;
import com.thesett.aima.logic.fol.Functor;
import com.thesett.aima.logic.fol.FunctorName;
import com.thesett.aima.logic.fol.LogicCompiler;
import com.thesett.aima.logic.fol.LogicCompilerObserver;
import com.thesett.aima.logic.fol.Sentence;
import com.thesett.aima.logic.fol.Term;
import com.thesett.aima.logic.fol.TermUtils;
import com.thesett.aima.logic.fol.Variable;
import com.thesett.aima.logic.fol.VariableAndFunctorInterner;
import com.thesett.aima.logic.fol.compiler.PositionalContext;
import com.thesett.aima.logic.fol.compiler.PositionalTermTraverser;
import com.thesett.aima.logic.fol.compiler.PositionalTermTraverserImpl;
import com.thesett.aima.logic.fol.compiler.SymbolKeyTraverser;
import com.thesett.aima.logic.fol.compiler.TermWalker;
import com.thesett.aima.logic.fol.wam.builtins.BuiltIn;
import com.thesett.aima.logic.fol.wam.machine.WAMMachine;
import com.thesett.aima.logic.fol.wam.optimizer.Optimizer;
import com.thesett.aima.logic.fol.wam.optimizer.WAMOptimizer;
import com.thesett.aima.logic.fol.wam.printer.WAMCompiledPredicatePrintingVisitor;
import com.thesett.aima.logic.fol.wam.printer.WAMCompiledQueryPrintingVisitor;
import com.thesett.aima.logic.fol.wam.printer.WAMCompiledTermsPrintingVisitor;
import com.thesett.aima.search.QueueBasedSearchMethod;
import com.thesett.aima.search.util.Searches;
import com.thesett.aima.search.util.backtracking.DepthFirstBacktrackingSearch;
import com.thesett.aima.search.util.uninformed.BreadthFirstSearch;
import com.thesett.common.parsing.SourceCodeException;
import com.thesett.common.util.SizeableLinkedList;
import com.thesett.common.util.doublemaps.SymbolKey;
import com.thesett.common.util.doublemaps.SymbolTable;
/**
* WAMCompiled implements a compiler for the logical language, WAM, into a form suitable for passing to an
* {@link WAMMachine}. The WAMMachine accepts sentences in the language that are compiled into a byte code form. The
* byte instructions used in the compiled language are enumerated as constants in the {@link WAMInstruction} class.
*
* <p/>The compilation process is described in "Warren's Abstract Machine, A Tutorial Reconstruction, by Hassan
* Ait-Kaci" and is followed as closely as possible to the WAM compiler given there. The description of the L0
* compilation process is very clear in the text but the WAM compilation is a little ambiguous. It does not fully
* describe the flattening process and presents some conflicting examples of register assignment. (The flattening
* process is essentially the same as for L0, except that each argument of the outermost functor is flattened/compiled
* independently). The register assignment process is harder to fathom, on page 22, the register assignment for p(Z,
* h(Z,W), f(W)) is presented with the following assignment given:
*
* <pre>
* A1 = Z
* A2 = h(A1,X4)
* A3 = f(X4)
* X4 = W
* </pre>
*
* In figure 2.9 a compilation example is given, from which it can be seen that the assignment should be:
*
* <pre>
* A1 = Z (loaded from X4)
* A2 = h(X4,X5)
* A3 = f(X5)
* X4 = Z
* X5 = W
* </pre>
*
* <p/>From figure 2.9 it was concluded that argument registers may only be assigned to functors. Functors can be
* created on the heap and assigned to argument registers directly. Argument registers for variables, should be loaded
* from a separate register assigned to the variable, that comes after the argument registers; so that a variable
* assignment can be copied into multiple arguments, where the same variable is presented multiple times in a predicate
* call. The register assignment process is carried out in two phases to do this, the first pass covers the argument
* registers and the arguments of the outermost functor, only assigning to functors, the second pass continues for
* higher numbered registers, starts again at the beginning of the arguments, and assigns to variables and functors (not
* already assigned) as for the L0 process.
*
* <p/>A brief overview of the compilation process is:
*
* <pre><p/><ul>
* <li>Terms to be compiled are allocated registers, breadth first, enumerating from outermost functors down to
* innermost atoms or variables.</li>
* <li>The outermost functor itself is treated specially, and is not allocated to a register. Its i arguments are
* allocated to registers, and are additionally associated with the first i argument registers. The outermost functor
* is the instigator of a call, in the case of queries, or the recipient of a call, in the case of programs.
* <li>Queries are 'flattened' by traversing each of their arguments in postfix order of their functors, then exploring
* the functors arguments.</li>
* <li>Programs are 'flattened' by traversing each of their arguments breadth first, the same as for the original
* register allocation, then exploring the functors arguments.</li>
* </ul></pre>
*
* <p/>Query terms are compiled into a sequence of instructions, that build up a representation of their argument terms,
* to be unified, on the heap, and assigning registers to refer to those terms on the heap, then calling the matching
* program for the query terms name and arity. Program terms are compiled into a sequence of instructions that, when run
* against the argument registers, attempt to unify all of the arguments with the heap.
*
* <p/>The effect of flattening queries using a post fix ordering, is that the values of inner functors and variables
* are loaded into registers first, before their containing functor is executed, which writes the functor and its
* arguments onto the heap. Programs do not need to be expanded in this way, they simply match functors followed by
* their arguments against the heap, so a breadth first traversal is all that is needed.
*
* <p/>Evaluating a flattened query consists of doing the following as different query tokens are encountered:
*
* <pre><p/><ol>
* <li>For the outermost functor, process all arguments, then make a CALL (functor) to the matching program.
* <li>For a register associated with an inner functor, push an STR onto the heap and copy that cell into the register.
* A put_struc (functor, register) instruction is created for this.</li>
* <li>For a variable in argument position i in the outermost functor, push a REF onto the heap that refers to itself,
* and copy that value into that variables register, as well as argument register i. A put_var (register, register)
* instruction is emitted for this.
* <li>For a register argument of an inner functor, not previously seen, push a REF onto the heap that refers to itself,
* and copy that cell into the register. A set_var (register) instruction is emitted for this.</li>
* <li>For a variables in argument position i in the outermost functor, previously seen, copy its assigned register
* into its argument register. A put_val (register, register) instruction is emitted for this.</li>
* <li>For a register argument previously seen, push a new cell onto the heap and copy into it the register's value.
* A set_val (register) instruction is emitted for this.</li>
* </ol></pre>
*
* <p/>Evaluating a flattened program consists of doing the following as different program tokens are encountered:
*
* <pre><p/><ol>
* <li>For the outermost functor, process all arguments, then execute a PROCEED instruction to indicate success.
* <li>For a register associated with an inner functor, load that register with a reference to the functor. A get_struc
* (functor, register) instruction is created for this.</li>
* <li>For a variable in argument position i in the outermost functor, copy its argument register into its assigned
* register. A get_var (register, register) instruction is emitted for this.
* <li>For a register argument of an inner functor, not previously seen, bind that register to its argument. A
* unify_var (register) instruction is output for this.</li>
* <li>For a variable in argument position i in the outermost functor, unify its assigned register with the
* argument register. A get_val (register, register) instruction is emitted for this.</li>
* <li>For a register argument of an inner functor, previously seen, unify that register against the heap. A
* unify_val (register) instruction is emitted for this.</li>
* </ol></pre>
*
* <pre><p/><table id="crc"><caption>CRC Card</caption>
* <tr><th> Responsibilities <th> Collaborations
* <tr><td> Transform WAM sentences into compiled byte code.
* <td> {@link WAMMachine}, {@link WAMCompiledPredicate}
* </table></pre>
*
* @author Rupert Smith
*/
public class InstructionCompiler extends DefaultBuiltIn
implements LogicCompiler<Clause, WAMCompiledPredicate, WAMCompiledQuery>
{
/** Used for debugging. */
private static final java.util.logging.Logger log =
java.util.logging.Logger.getLogger(InstructionCompiler.class.getName());
/** The symbol table key for allocations. */
public static final String SYMKEY_ALLOCATION = "allocation";
/** The symbol table key for the number of permanent variables remaining. */
protected static final String SYMKEY_PERM_VARS_REMAINING = "perm_vars_remaining";
/** The symbol table key for variable occurrence counts. */
public static final String SYMKEY_VAR_OCCURRENCE_COUNT = "var_occurrence_count";
/** The symbol table key for variable position of occurrence. */
public static final String SYMKEY_VAR_NON_ARG = "var_non_arg";
/** The symbol table key for functor position of occurrence. */
public static final String SYMKEY_FUNCTOR_NON_ARG = "functor_non_arg";
/** The symbol table key for variable introduction type. */
public static final String SYMKEY_VARIABLE_INTRO = "variable_intro";
/** The symbol table key for the last functor in which a variable occurs, if it is purely in argument position. */
public static final String SYMKEY_VAR_LAST_ARG_FUNCTOR = "var_last_arg_functor";
/** The symbol table key for predicate sources. */
protected static final String SYMKEY_PREDICATES = "source_predicates";
/** Holds a list of all predicates encountered in the current scope. */
protected Queue<SymbolKey> predicatesInScope = new LinkedList<SymbolKey>();
/** Holds the compiler output observer. */
private LogicCompilerObserver<WAMCompiledPredicate, WAMCompiledQuery> observer;
/** This is used to keep track of the number of permanent variables. */
protected int numPermanentVars;
/** Keeps count of the current compiler scope, to keep symbols in each scope fresh. */
protected int scope = 0;
/** Holds the current nested compilation scope symbol table. */
private SymbolTable<Integer, String, Object> scopeTable;
/** Holds the instruction optimizer. */
private Optimizer optimizer;
/**
* Creates a new InstructionCompiler.
*
* @param symbolTable The symbol table.
* @param interner The machine to translate functor and variable names.
*/
protected InstructionCompiler(SymbolTable<Integer, String, Object> symbolTable, VariableAndFunctorInterner interner)
{
super(symbolTable, interner);
optimizer = new WAMOptimizer(symbolTable, interner);
}
/** {@inheritDoc} */
public void setCompilerObserver(LogicCompilerObserver<WAMCompiledPredicate, WAMCompiledQuery> observer)
{
this.observer = observer;
}
/** {@inheritDoc} */
public void endScope() throws SourceCodeException
{
// Loop over all predicates in the current scope, found in the symbol table, and consume and compile them.
for (SymbolKey predicateKey = predicatesInScope.poll(); predicateKey != null;
predicateKey = predicatesInScope.poll())
{
List<Clause> clauseList = (List<Clause>) scopeTable.get(predicateKey, SYMKEY_PREDICATES);
// Used to keep track of where within the predicate the current clause is.
int size = clauseList.size();
int current = 0;
boolean multipleClauses = size > 1;
// Used to build up the compiled predicate in.
WAMCompiledPredicate result = null;
for (Iterator<Clause> iterator = clauseList.iterator(); iterator.hasNext(); iterator.remove())
{
Clause clause = iterator.next();
if (result == null)
{
result = new WAMCompiledPredicate(clause.getHead().getName());
}
// Compile the single clause, adding it to the parent compiled predicate.
compileClause(clause, result, current == 0, current >= (size - 1), multipleClauses, current);
current++;
}
// Run the optimizer on the output.
result = optimizer.apply(result);
displayCompiledPredicate(result);
observer.onCompilation(result);
// Move up the low water mark on the predicates table.
symbolTable.setLowMark(predicateKey, SYMKEY_PREDICATES);
}
// Clear up the symbol table, and bump the compilation scope up by one.
symbolTable.clearUpToLowMark(SYMKEY_PREDICATES);
scopeTable = null;
scope++;
}
/**
* {@inheritDoc}
*
* <p/>Compiles a sentence into a binary form, that provides a Java interface into the compiled structure.
*
* <p/>The clausal sentence may be a query, or a program statement. If it is a query, it is compiled immediately. If
* it is a clause, it is retained against the predicate which it forms part of, and compiled on the
* {@link #endScope()} method is invoked.
*/
public void compile(Sentence<Clause> sentence) throws SourceCodeException
{
/*log.fine("public WAMCompiledClause compile(Sentence<Term> sentence = " + sentence + "): called");*/
// Extract the clause to compile from the parsed sentence.
Clause clause = sentence.getT();
initialiseSymbolTable(clause);
// Classify the sentence to compile by the different sentence types in the language.
if (clause.isQuery())
{
compileQuery(clause);
}
else
{
// Initialise a nested symbol table for the current compilation scope, if it has not already been.
if (scopeTable == null)
{
scopeTable = symbolTable.enterScope(scope);
}
// Check in the symbol table, if a compiled predicate with name matching the program clause exists, and if
// not create it.
SymbolKey predicateKey = scopeTable.getSymbolKey(clause.getHead().getName());
List<Clause> clauseList = (List<Clause>) scopeTable.get(predicateKey, SYMKEY_PREDICATES);
if (clauseList == null)
{
clauseList = new LinkedList<Clause>();
scopeTable.put(predicateKey, SYMKEY_PREDICATES, clauseList);
predicatesInScope.offer(predicateKey);
}
// Add the clause to compile to its parent predicate for compilation at the end of the current scope.
clauseList.add(clause);
}
}
/**
* Compiles a program clause, and adds its instructions to a compiled predicate.
*
* @param clause The source clause to compile.
* @param compiledPredicate The predicate to add instructions to.
* @param isFirst <tt>true</tt> iff the clause is the first in the predicate.
* @param isLast <tt>true</tt> iff the clause is the last in the predicate.
* @param multipleClauses <tt>true</tt> iff the predicate contains >1 clause.
* @param clauseNumber The position of the clause within the predicate.
*
* @throws SourceCodeException If there is an error in the source code preventing its compilation.
*/
private void compileClause(Clause clause, WAMCompiledPredicate compiledPredicate, boolean isFirst, boolean isLast,
boolean multipleClauses, int clauseNumber) throws SourceCodeException
{
// Used to build up the compiled clause in.
WAMCompiledClause result = new WAMCompiledClause(compiledPredicate);
// Check if the clause to compile is a fact (no body).
boolean isFact = clause.getBody() == null;
// Check if the clause to compile is a chain rule, (one called body).
boolean isChainRule = (clause.getBody() != null) && (clause.getBody().length == 1);
// Used to keep track of registers as they are seen during compilation. The first time a variable is seen,
// a variable is written onto the heap, subsequent times its value. The first time a functor is seen,
// its structure is written onto the heap, subsequent times it is compared with.
seenRegisters = new TreeSet<Integer>();
// This is used to keep track of the next temporary register available to allocate.
lastAllocatedTempReg = findMaxArgumentsInClause(clause);
// This is used to keep track of the number of permanent variables.
numPermanentVars = 0;
// These are used to generate pre and post instructions for the clause, for example, for the creation and
// clean-up of stack frames.
SizeableLinkedList<WAMInstruction> preFixInstructions = new SizeableLinkedList<WAMInstruction>();
SizeableLinkedList<WAMInstruction> postFixInstructions = new SizeableLinkedList<WAMInstruction>();
// Find all the free non-anonymous variables in the clause.
Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(clause);
Set<Integer> freeVarNames = new TreeSet<Integer>();
for (Variable var : freeVars)
{
freeVarNames.add(var.getName());
}
// Allocate permanent variables for a program clause. Program clauses only use permanent variables when really
// needed to preserve variables across calls.
allocatePermanentProgramRegisters(clause);
// Gather information about the counts and positions of occurrence of variables and constants within the clause.
gatherPositionAndOccurrenceInfo(clause);
// Labels the entry point to each choice point.
FunctorName fn = interner.getFunctorFunctorName(clause.getHead());
WAMLabel entryLabel = new WAMLabel(fn, clauseNumber);
// Label for the entry point to the next choice point, to backtrack to.
WAMLabel retryLabel = new WAMLabel(fn, clauseNumber + 1);
// Create choice point instructions for the clause, depending on its position within the containing predicate.
// The choice point instructions are only created when a predicate is built from multiple clauses, as otherwise
// there are no choices to be made.
if (isFirst && !isLast && multipleClauses)
{
// try me else.
preFixInstructions.add(new WAMInstruction(entryLabel, WAMInstruction.WAMInstructionSet.TryMeElse,
retryLabel));
}
else if (!isFirst && !isLast && multipleClauses)
{
// retry me else.
preFixInstructions.add(new WAMInstruction(entryLabel, WAMInstruction.WAMInstructionSet.RetryMeElse,
retryLabel));
}
else if (isLast && multipleClauses)
{
// trust me.
preFixInstructions.add(new WAMInstruction(entryLabel, WAMInstruction.WAMInstructionSet.TrustMe));
}
// Generate the prefix code for the clause.
// Rules may chain multiple, so require stack frames to preserve registers across calls.
// Facts are always leafs so can use the global continuation point register to return from calls.
// Chain rules only make one call, so also do not need a stack frame.
if (!(isFact || isChainRule))
{
// Allocate a stack frame at the start of the clause.
/*log.fine("ALLOCATE " + numPermanentVars);*/
preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Allocate));
}
result.addInstructions(preFixInstructions);
// Compile the clause head.
Functor expression = clause.getHead();
SizeableLinkedList<WAMInstruction> instructions = compileHead(expression);
result.addInstructions(expression, instructions);
// Compile all of the conjunctive parts of the body of the clause, if there are any.
if (!isFact)
{
Functor[] expressions = clause.getBody();
for (int i = 0; i < expressions.length; i++)
{
expression = expressions[i];
boolean isLastBody = i == (expressions.length - 1);
Integer permVarsRemaining =
(Integer) symbolTable.get(expression.getSymbolKey(), SYMKEY_PERM_VARS_REMAINING);
// Select a non-default built-in implementation to compile the functor with, if it is a built-in.
BuiltIn builtIn;
if (expression instanceof BuiltIn)
{
builtIn = (BuiltIn) expression;
}
else
{
builtIn = this;
}
// The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule.
instructions = builtIn.compileBody(expression, i == 0);
result.addInstructions(expression, instructions);
// Call the body. The number of permanent variables remaining is specified for environment trimming.
instructions = builtIn.compileBodyCall(expression, isLastBody, isChainRule, permVarsRemaining);
result.addInstructions(expression, instructions);
}
}
// Generate the postfix code for the clause. Rules may chain, so require stack frames.
// Facts are always leafs so can use the global continuation point register to return from calls.
if (isFact)
{
/*log.fine("PROCEED");*/
postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Proceed));
}
result.addInstructions(postFixInstructions);
}
/**
* Compiles a clause as a query. The clause should have no head, only a body.
*
* @param clause The clause to compile as a query.
*
* @throws SourceCodeException If there is an error in the source code preventing its compilation.
*/
private void compileQuery(Clause clause) throws SourceCodeException
{
// Used to build up the compiled result in.
WAMCompiledQuery result;
// A mapping from top stack frame slots to interned variable names is built up in this.
// This is used to track the stack positions that variables in a query are assigned to.
Map<Byte, Integer> varNames = new TreeMap<Byte, Integer>();
// Used to keep track of registers as they are seen during compilation. The first time a variable is seen,
// a variable is written onto the heap, subsequent times its value. The first time a functor is seen,
// its structure is written onto the heap, subsequent times it is compared with.
seenRegisters = new TreeSet<Integer>();
// This is used to keep track of the next temporary register available to allocate.
lastAllocatedTempReg = findMaxArgumentsInClause(clause);
// This is used to keep track of the number of permanent variables.
numPermanentVars = 0;
// These are used to generate pre and post instructions for the clause, for example, for the creation and
// clean-up of stack frames.
SizeableLinkedList<WAMInstruction> preFixInstructions = new SizeableLinkedList<WAMInstruction>();
SizeableLinkedList<WAMInstruction> postFixInstructions = new SizeableLinkedList<WAMInstruction>();
// Find all the free non-anonymous variables in the clause.
Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(clause);
Set<Integer> freeVarNames = new TreeSet<Integer>();
for (Variable var : freeVars)
{
freeVarNames.add(var.getName());
}
// Allocate permanent variables for a query. In queries all variables are permanent so that they are preserved
// on the stack upon completion of the query.
allocatePermanentQueryRegisters(clause, varNames);
// Gather information about the counts and positions of occurrence of variables and constants within the clause.
gatherPositionAndOccurrenceInfo(clause);
result = new WAMCompiledQuery(varNames, freeVarNames);
// Generate the prefix code for the clause. Queries require a stack frames to hold their environment.
/*log.fine("ALLOCATE " + numPermanentVars);*/
preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.AllocateN, WAMInstruction.REG_ADDR,
(byte) (numPermanentVars & 0xff)));
result.addInstructions(preFixInstructions);
// Compile all of the conjunctive parts of the body of the clause, if there are any.
Functor[] expressions = clause.getBody();
for (int i = 0; i < expressions.length; i++)
{
Functor expression = expressions[i];
// Select a non-default built-in implementation to compile the functor with, if it is a built-in.
BuiltIn builtIn;
if (expression instanceof BuiltIn)
{
builtIn = (BuiltIn) expression;
}
else
{
builtIn = this;
}
// The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule, which it
// never is for a query.
SizeableLinkedList<WAMInstruction> instructions = builtIn.compileBody(expression, false);
result.addInstructions(expression, instructions);
// Queries are never chain rules, and as all permanent variables are preserved, bodies are never called
// as last calls.
instructions = builtIn.compileBodyCall(expression, false, false, numPermanentVars);
result.addInstructions(expression, instructions);
}
// Generate the postfix code for the clause.
/*log.fine("DEALLOCATE");*/
postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Suspend));
postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Deallocate));
result.addInstructions(postFixInstructions);
// Run the optimizer on the output.
result = optimizer.apply(result);
displayCompiledQuery(result);
observer.onQueryCompilation(result);
}
/**
* Examines all top-level functors within a clause, including any head and body, and determines which functor has
* the highest number of arguments.
*
* @param clause The clause to determine the highest number of arguments within.
*
* @return The highest number of arguments within any top-level functor in the clause.
*/
private int findMaxArgumentsInClause(Clause clause)
{
int result = 0;
Functor head = clause.getHead();
if (head != null)
{
result = head.getArity();
}
Functor[] body = clause.getBody();
if (body != null)
{
for (int i = 0; i < body.length; i++)
{
int arity = body[i].getArity();
result = (arity > result) ? arity : result;
}
}
return result;
}
/**
* Runs a symbol key traverser over the clause to be compiled, to ensure that all of its terms and sub-terms have
* their symbol keys initialised.
*
* @param clause The clause to initialise the symbol keys of.
*/
private void initialiseSymbolTable(Clause clause)
{
// Run the symbol key traverser over the clause, to ensure that all terms have their symbol keys correctly
// set up.
SymbolKeyTraverser symbolKeyTraverser = new SymbolKeyTraverser(interner, symbolTable, null);
symbolKeyTraverser.setContextChangeVisitor(symbolKeyTraverser);
TermWalker symWalker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), symbolKeyTraverser, symbolKeyTraverser);
symWalker.walk(clause);
}
/**
* Compiles the head of a clause into an instruction listing in WAM.
*
* @param expression The clause head to compile.
*
* @return A listing of the instructions for the clause head in the WAM instruction set.
*/
private SizeableLinkedList<WAMInstruction> compileHead(Functor expression)
{
// Used to build up the results in.
SizeableLinkedList<WAMInstruction> instructions = new SizeableLinkedList<WAMInstruction>();
// Allocate argument registers on the body, to all functors as outermost arguments.
// Allocate temporary registers on the body, to all terms not already allocated.
allocateArgumentRegisters(expression);
allocateTemporaryRegisters(expression);
// Program instructions are generated in the same order as the registers are assigned, the postfix
// ordering used for queries is not needed.
QueueBasedSearchMethod<Term, Term> outInSearch = new BreadthFirstSearch<Term, Term>();
outInSearch.reset();
outInSearch.addStartState(expression);
Iterator<Term> treeWalker = Searches.allSolutions(outInSearch);
// Skip the outermost functor.
treeWalker.next();
// Allocate argument registers on the body, to all functors as outermost arguments.
// Allocate temporary registers on the body, to all terms not already allocated.
// Keep track of processing of the arguments to the outermost functor as get_val and get_var instructions
// need to be output for variables encountered in the arguments only.
int numOutermostArgs = expression.getArity();
for (int j = 0; treeWalker.hasNext(); j++)
{
Term nextTerm = treeWalker.next();
/*log.fine("nextTerm = " + nextTerm);*/
// For each functor encountered: get_struc.
if (nextTerm.isFunctor())
{
Functor nextFunctor = (Functor) nextTerm;
int allocation = (Integer) symbolTable.get(nextFunctor.getSymbolKey(), SYMKEY_ALLOCATION);
byte addrMode = (byte) ((allocation & 0xff00) >> 8);
byte address = (byte) (allocation & 0xff);
// Ouput a get_struc instruction, except on the outermost functor.
/*log.fine("GET_STRUC " + interner.getFunctorName(nextFunctor) + "/" + nextFunctor.getArity() +
((addrMode == REG_ADDR) ? ", X" : ", Y") + address);*/
WAMInstruction instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.GetStruc, addrMode, address,
interner.getFunctorFunctorName(nextFunctor), nextFunctor);
instructions.add(instruction);
// For each argument of the functor.
int numArgs = nextFunctor.getArity();
for (int i = 0; i < numArgs; i++)
{
Term nextArg = nextFunctor.getArgument(i);
allocation = (Integer) symbolTable.get(nextArg.getSymbolKey(), SYMKEY_ALLOCATION);
addrMode = (byte) ((allocation & 0xff00) >> 8);
address = (byte) (allocation & 0xff);
/*log.fine("nextArg = " + nextArg);*/
// If it is register not seen before: unify_var.
// If it is register seen before: unify_val.
if (!seenRegisters.contains(allocation))
{
/*log.fine("UNIFY_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/
seenRegisters.add(allocation);
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.UnifyVar, addrMode, address, nextArg);
// Record the way in which this variable was introduced into the clause.
symbolTable.put(nextArg.getSymbolKey(), SYMKEY_VARIABLE_INTRO, VarIntroduction.Unify);
}
else
{
// Check if the variable is 'local' and use a local instruction on the first occurrence.
VarIntroduction introduction =
(VarIntroduction) symbolTable.get(nextArg.getSymbolKey(), SYMKEY_VARIABLE_INTRO);
if (isLocalVariable(introduction, addrMode))
{
log.fine("UNIFY_LOCAL_VAL " + ((addrMode == WAMInstruction.REG_ADDR) ? "X" : "Y") +
address);
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.UnifyLocalVal, addrMode, address,
nextArg);
symbolTable.put(nextArg.getSymbolKey(), SYMKEY_VARIABLE_INTRO, null);
}
else
{
/*log.fine("UNIFY_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.UnifyVal, addrMode, address,
nextArg);
}
}
instructions.add(instruction);
}
}
else if (j < numOutermostArgs)
{
Variable nextVar = (Variable) nextTerm;
int allocation = (Integer) symbolTable.get(nextVar.getSymbolKey(), SYMKEY_ALLOCATION);
byte addrMode = (byte) ((allocation & 0xff00) >> 8);
byte address = (byte) (allocation & 0xff);
WAMInstruction instruction;
// If it is register not seen before: get_var.
// If it is register seen before: get_val.
if (!seenRegisters.contains(allocation))
{
/*log.fine("GET_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/
seenRegisters.add(allocation);
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.GetVar, addrMode, address,
(byte) (j & 0xff));
// Record the way in which this variable was introduced into the clause.
symbolTable.put(nextVar.getSymbolKey(), SYMKEY_VARIABLE_INTRO, VarIntroduction.Get);
}
else
{
/*log.fine("GET_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.GetVal, addrMode, address,
(byte) (j & 0xff));
}
instructions.add(instruction);
}
}
return instructions;
}
/**
* Allocates stack slots where need to the variables in a program clause. The algorithm here is fairly complex.
*
* <p/>A clause head and first body functor are taken together as the first unit, subsequent clause body functors
* are taken as subsequent units. A variable appearing in more than one unit is said to be permanent, and must be
* stored on the stack, rather than a register, otherwise the register that it occupies may be overwritten by calls
* to subsequent units. These variable are called permanent, which really means that they are local variables on the
* call stack.
*
* <p/>In addition to working out which variables are permanent, the variables are also ordered by reverse position
* of last body of occurrence, and assigned to allocation slots in this order. The number of permanent variables
* remaining at each body call is also calculated and recorded against the body functor in the symbol table using
* column {@link #SYMKEY_PERM_VARS_REMAINING}. This allocation ordering of the variables and the count of the number
* remaining are used to implement environment trimming.
*
* @param clause The clause to allocate registers for.
*/
private void allocatePermanentProgramRegisters(Clause clause)
{
// A bag to hold variable occurrence counts in.
Map<Variable, Integer> variableCountBag = new HashMap<Variable, Integer>();
// A mapping from variables to the body number in which they appear last.
Map<Variable, Integer> lastBodyMap = new HashMap<Variable, Integer>();
// Get the occurrence counts of variables in all clauses after the initial head and first body grouping.
// In the same pass, pick out which body variables last occur in.
if ((clause.getBody() != null))
{
for (int i = clause.getBody().length - 1; i >= 1; i--)
{
Set<Variable> groupVariables = TermUtils.findFreeVariables(clause.getBody()[i]);
// Add all their counts to the bag and update their last occurrence positions.
for (Variable variable : groupVariables)
{
Integer count = variableCountBag.get(variable);
variableCountBag.put(variable, (count == null) ? 1 : (count + 1));
if (!lastBodyMap.containsKey(variable))
{
lastBodyMap.put(variable, i);
}
}
}
}
// Get the set of variables in the head and first clause body argument.
Set<Variable> firstGroupVariables = new HashSet<Variable>();
if (clause.getHead() != null)
{
Set<Variable> headVariables = TermUtils.findFreeVariables(clause.getHead());
firstGroupVariables.addAll(headVariables);
}
if ((clause.getBody() != null) && (clause.getBody().length > 0))
{
Set<Variable> firstArgVariables = TermUtils.findFreeVariables(clause.getBody()[0]);
firstGroupVariables.addAll(firstArgVariables);
}
// Add their counts to the bag, and set their last positions of occurrence as required.
for (Variable variable : firstGroupVariables)
{
Integer count = variableCountBag.get(variable);
variableCountBag.put(variable, (count == null) ? 1 : (count + 1));
if (!lastBodyMap.containsKey(variable))
{
lastBodyMap.put(variable, 0);
}
}
// Sort the variables by reverse position of last occurrence.
List<Map.Entry<Variable, Integer>> lastBodyList =
new ArrayList<Map.Entry<Variable, Integer>>(lastBodyMap.entrySet());
Collections.sort(lastBodyList, new Comparator<Map.Entry<Variable, Integer>>()
{
public int compare(Map.Entry<Variable, Integer> o1, Map.Entry<Variable, Integer> o2)
{
return o2.getValue().compareTo(o1.getValue());
}
});
// Holds counts of permanent variable last appearances against the body in which they last occur.
int[] permVarsRemainingCount = new int[(clause.getBody() != null) ? clause.getBody().length : 0];
// Search the count bag for all variable occurrences greater than one, and assign them to stack slots.
// The variables are examined by reverse position of last occurrence, to ensure that later variables
// are assigned to lower permanent allocation slots for environment trimming purposes.
for (Map.Entry<Variable, Integer> entry : lastBodyList)
{
Variable variable = entry.getKey();
Integer count = variableCountBag.get(variable);
int body = entry.getValue();
if ((count != null) && (count > 1))
{
log.fine("Variable " + variable + " is permanent, count = " + count);
int allocation = (numPermanentVars++ & (0xff)) | (WAMInstruction.STACK_ADDR << 8);
symbolTable.put(variable.getSymbolKey(), SYMKEY_ALLOCATION, allocation);
permVarsRemainingCount[body]++;
}
}
// Roll up the permanent variable remaining counts from the counts of last position of occurrence and
// store the count of permanent variables remaining against the body.
int permVarsRemaining = 0;
for (int i = permVarsRemainingCount.length - 1; i >= 0; i--)
{
symbolTable.put(clause.getBody()[i].getSymbolKey(), SYMKEY_PERM_VARS_REMAINING, permVarsRemaining);
permVarsRemaining += permVarsRemainingCount[i];
}
}
/**
* Allocates stack slots to all free variables in a query clause.
*
* <p/>At the end of processing a query its variable bindings are usually printed. For this reason all free
* variables in a query are marked as permanent variables on the call stack, to ensure that they are preserved.
*
* @param clause The clause to allocate registers for.
* @param varNames A map of permanent variables to variable names to record the allocations in.
*/
private void allocatePermanentQueryRegisters(Clause clause, Map<Byte, Integer> varNames)
{
// Allocate local variable slots for all variables in a query.
QueryRegisterAllocatingVisitor allocatingVisitor =
new QueryRegisterAllocatingVisitor(symbolTable, varNames, null);
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
positionalTraverser.setContextChangeVisitor(allocatingVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, allocatingVisitor);
walker.walk(clause);
}
/**
* Gather information about variable counts and positions of occurrence of constants and variable within a clause.
*
* @param clause The clause to check the variable occurrence and position of occurrence within.
*/
private void gatherPositionAndOccurrenceInfo(Clause clause)
{
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
PositionAndOccurrenceVisitor positionAndOccurrenceVisitor =
new PositionAndOccurrenceVisitor(interner, symbolTable, positionalTraverser);
positionalTraverser.setContextChangeVisitor(positionAndOccurrenceVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser,
positionAndOccurrenceVisitor);
walker.walk(clause);
}
/**
* Pretty prints a compiled predicate.
*
* @param predicate The compiled predicate to pretty print.
*/
private void displayCompiledPredicate(WAMCompiledPredicate predicate)
{
// Pretty print the clause.
StringBuffer result = new StringBuffer();
WAMCompiledTermsPrintingVisitor displayVisitor =
new WAMCompiledPredicatePrintingVisitor(interner, symbolTable, result);
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
displayVisitor.setPositionalTraverser(positionalTraverser);
positionalTraverser.setContextChangeVisitor(displayVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, displayVisitor);
walker.walk(predicate);
log.fine(result.toString());
}
/**
* Pretty prints a compiled query.
*
* @param query The compiled query to pretty print.
*/
private void displayCompiledQuery(WAMCompiledQuery query)
{
// Pretty print the clause.
StringBuffer result = new StringBuffer();
WAMCompiledTermsPrintingVisitor displayVisitor =
new WAMCompiledQueryPrintingVisitor(interner, symbolTable, result);
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
displayVisitor.setPositionalTraverser(positionalTraverser);
positionalTraverser.setContextChangeVisitor(displayVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, displayVisitor);
walker.walk(query);
log.fine(result.toString());
}
/**
* QueryRegisterAllocatingVisitor visits named variables in a query, and if they are not already allocated to a
* permanent stack slot, allocates them one. All named variables in queries are stack allocated, so that they are
* preserved on the stack at the end of the query. Anonymous variables in queries are singletons, and not included
* in the query results, so can be temporary.
*/
public class QueryRegisterAllocatingVisitor extends DelegatingAllTermsVisitor
{
/** The symbol table. */
private final SymbolTable<Integer, String, Object> symbolTable;
/** Holds a map of permanent variables to variable names to record the allocations in. */
private final Map<Byte, Integer> varNames;
/**
* Creates a query variable allocator.
*
* @param symbolTable The symbol table.
* @param varNames A map of permanent variables to variable names to record the allocations in.
* @param delegate The term visitor that this delegates to.
*/
public QueryRegisterAllocatingVisitor(SymbolTable<Integer, String, Object> symbolTable,
Map<Byte, Integer> varNames, AllTermsVisitor delegate)
{
super(delegate);
this.symbolTable = symbolTable;
this.varNames = varNames;
}
/**
* {@inheritDoc}
*
* <p/>Allocates unallocated variables to stack slots.
*/
public void visit(Variable variable)
{
if (symbolTable.get(variable.getSymbolKey(), SYMKEY_ALLOCATION) == null)
{
if (variable.isAnonymous())
{
log.fine("Query variable " + variable + " is temporary.");
int allocation = (lastAllocatedTempReg++ & (0xff)) | (WAMInstruction.REG_ADDR << 8);
symbolTable.put(variable.getSymbolKey(), SYMKEY_ALLOCATION, allocation);
varNames.put((byte) allocation, variable.getName());
}
else
{
log.fine("Query variable " + variable + " is permanent.");
int allocation = (numPermanentVars++ & (0xff)) | (WAMInstruction.STACK_ADDR << 8);
symbolTable.put(variable.getSymbolKey(), SYMKEY_ALLOCATION, allocation);
varNames.put((byte) allocation, variable.getName());
}
}
super.visit(variable);
}
}
/**
* PositionAndOccurrenceVisitor visits a clause to gather information about the positions in which components of the
* clause appear.
*
* <p/>For variables, the following information is gathered:
*
* <ol>
* <li>A count of the number of times the variable occurs in the clause (singleton detection).</li>
* <li>A flag indicating that variable only ever appears in non-argument positions.</li>
* <li>The last functor body in the clause in which a variable appears, provided it only does so in argument
* position.</li>
* </ol>
*
* <p/>For constants, the following information is gathered:
*
* <ol>
* <li>A flag indicating the constant only ever appears in non-argument positions.</li>
* </ol>
*/
public class PositionAndOccurrenceVisitor extends BasePositionalVisitor
{
/** Holds the current top-level body functor. <tt>null</tt> when traversing the head. */
private Functor topLevelBodyFunctor;
/** Holds a set of all constants encountered. */
private Map<Integer, List<SymbolKey>> constants = new HashMap<Integer, List<SymbolKey>>();
/** Holds a set of all constants found to be in argument positions. */
private Set<Integer> argumentConstants = new HashSet<Integer>();
/**
* Creates a positional visitor.
*
* @param interner The name interner.
* @param symbolTable The compiler symbol table.
* @param traverser The positional context traverser.
*/
public PositionAndOccurrenceVisitor(VariableAndFunctorInterner interner,
SymbolTable<Integer, String, Object> symbolTable, PositionalTermTraverser traverser)
{
super(interner, symbolTable, traverser);
}
/**
* {@inheritDoc}
*
* <p/>Counts variable occurrences and detects if the variable ever appears in an argument position.
*/
protected void enterVariable(Variable variable)
{
// Initialize the count to one or add one to an existing count.
Integer count = (Integer) symbolTable.get(variable.getSymbolKey(), SYMKEY_VAR_OCCURRENCE_COUNT);
count = (count == null) ? 1 : (count + 1);
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_OCCURRENCE_COUNT, count);
/*log.fine("Variable " + variable + " has count " + count + ".");*/
// Get the nonArgPosition flag, or initialize it to true.
Boolean nonArgPositionOnly = (Boolean) symbolTable.get(variable.getSymbolKey(), SYMKEY_VAR_NON_ARG);
nonArgPositionOnly = (nonArgPositionOnly == null) ? true : nonArgPositionOnly;
// Clear the nonArgPosition flag is the variable occurs in an argument position.
nonArgPositionOnly = inTopLevelFunctor() ? false : nonArgPositionOnly;
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_NON_ARG, nonArgPositionOnly);
/*log.fine("Variable " + variable + " nonArgPosition is " + nonArgPositionOnly + ".");*/
// If in an argument position, record the parent body functor against the variable, as potentially being
// the last one it occurs in, in a purely argument position.
// If not in an argument position, clear any parent functor recorded against the variable, as this current
// last position of occurrence is not purely in argument position.
if (inTopLevelFunctor())
{
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_LAST_ARG_FUNCTOR, topLevelBodyFunctor);
}
else
{
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_LAST_ARG_FUNCTOR, null);
}
}
/**
* {@inheritDoc}
*
* <p/>Checks if a constant ever appears in an argument position.
*
* <p/>Sets the 'inTopLevelFunctor' flag, whenever the traversal is directly within a top-level functors
* arguments. This is set at the end, so that subsequent calls to this will pick up the state of this flag at
* the point immediately below a top-level functor.
*/
protected void enterFunctor(Functor functor)
{
/*log.fine("Functor: " + functor.getName() + " <- " + symbolTable.getSymbolKey(functor.getName()));*/
// Only check position of occurrence for constants.
if (functor.getArity() == 0)
{
// Add the constant to the set of all constants encountered.
List<SymbolKey> constantSymKeys = constants.get(functor.getName());
if (constantSymKeys == null)
{
constantSymKeys = new LinkedList<SymbolKey>();
constants.put(functor.getName(), constantSymKeys);
}
constantSymKeys.add(functor.getSymbolKey());
// If the constant ever appears in argument position, take note of this.
if (inTopLevelFunctor())
{
argumentConstants.add(functor.getName());
}
}
// Keep track of the current top-level body functor.
if (traverser.isTopLevel() && !traverser.isInHead())
{
topLevelBodyFunctor = functor;
}
}
/**
* Upon leaving the clause, sets the nonArgPosition flag on any constants that need it.
*
* @param clause The clause being left.
*/
protected void leaveClause(Clause clause)
{
// Remove the set of constants appearing in argument positions, from the set of all constants, to derive
// the set of constants that appear in non-argument positions only.
constants.keySet().removeAll(argumentConstants);
// Set the nonArgPosition flag on all symbol keys for all constants that only appear in non-arg positions.
for (List<SymbolKey> symbolKeys : constants.values())
{
for (SymbolKey symbolKey : symbolKeys)
{
symbolTable.put(symbolKey, SYMKEY_FUNCTOR_NON_ARG, true);
}
}
}
/**
* Checks if the current position is immediately within a top-level functor.
*
* @return <tt>true</tt> iff the current position is immediately within a top-level functor.
*/
private boolean inTopLevelFunctor()
{
PositionalContext parentContext = traverser.getParentContext();
return (parentContext != null) ? parentContext.isTopLevel() : false;
}
}
}
| lojix/wam/src/main/com/thesett/aima/logic/fol/wam/compiler/InstructionCompiler.java | /*
* Copyright The Sett Ltd.
*
* 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.thesett.aima.logic.fol.wam.compiler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import com.thesett.aima.logic.fol.AllTermsVisitor;
import com.thesett.aima.logic.fol.BasePositionalVisitor;
import com.thesett.aima.logic.fol.Clause;
import com.thesett.aima.logic.fol.DelegatingAllTermsVisitor;
import com.thesett.aima.logic.fol.Functor;
import com.thesett.aima.logic.fol.FunctorName;
import com.thesett.aima.logic.fol.LogicCompiler;
import com.thesett.aima.logic.fol.LogicCompilerObserver;
import com.thesett.aima.logic.fol.Sentence;
import com.thesett.aima.logic.fol.Term;
import com.thesett.aima.logic.fol.TermUtils;
import com.thesett.aima.logic.fol.Variable;
import com.thesett.aima.logic.fol.VariableAndFunctorInterner;
import com.thesett.aima.logic.fol.compiler.PositionalContext;
import com.thesett.aima.logic.fol.compiler.PositionalTermTraverser;
import com.thesett.aima.logic.fol.compiler.PositionalTermTraverserImpl;
import com.thesett.aima.logic.fol.compiler.SymbolKeyTraverser;
import com.thesett.aima.logic.fol.compiler.TermWalker;
import com.thesett.aima.logic.fol.wam.builtins.BuiltIn;
import com.thesett.aima.logic.fol.wam.machine.WAMMachine;
import com.thesett.aima.logic.fol.wam.optimizer.Optimizer;
import com.thesett.aima.logic.fol.wam.optimizer.WAMOptimizer;
import com.thesett.aima.logic.fol.wam.printer.WAMCompiledPredicatePrintingVisitor;
import com.thesett.aima.logic.fol.wam.printer.WAMCompiledQueryPrintingVisitor;
import com.thesett.aima.logic.fol.wam.printer.WAMCompiledTermsPrintingVisitor;
import com.thesett.aima.search.QueueBasedSearchMethod;
import com.thesett.aima.search.util.Searches;
import com.thesett.aima.search.util.backtracking.DepthFirstBacktrackingSearch;
import com.thesett.aima.search.util.uninformed.BreadthFirstSearch;
import com.thesett.common.parsing.SourceCodeException;
import com.thesett.common.util.SizeableLinkedList;
import com.thesett.common.util.doublemaps.SymbolKey;
import com.thesett.common.util.doublemaps.SymbolTable;
/**
* WAMCompiled implements a compiler for the logical language, WAM, into a form suitable for passing to an
* {@link WAMMachine}. The WAMMachine accepts sentences in the language that are compiled into a byte code form. The
* byte instructions used in the compiled language are enumerated as constants in the {@link WAMInstruction} class.
*
* <p/>The compilation process is described in "Warren's Abstract Machine, A Tutorial Reconstruction, by Hassan
* Ait-Kaci" and is followed as closely as possible to the WAM compiler given there. The description of the L0
* compilation process is very clear in the text but the WAM compilation is a little ambiguous. It does not fully
* describe the flattening process and presents some conflicting examples of register assignment. (The flattening
* process is essentially the same as for L0, except that each argument of the outermost functor is flattened/compiled
* independently). The register assignment process is harder to fathom, on page 22, the register assignment for p(Z,
* h(Z,W), f(W)) is presented with the following assignment given:
*
* <pre>
* A1 = Z
* A2 = h(A1,X4)
* A3 = f(X4)
* X4 = W
* </pre>
*
* In figure 2.9 a compilation example is given, from which it can be seen that the assignment should be:
*
* <pre>
* A1 = Z (loaded from X4)
* A2 = h(X4,X5)
* A3 = f(X5)
* X4 = Z
* X5 = W
* </pre>
*
* <p/>From figure 2.9 it was concluded that argument registers may only be assigned to functors. Functors can be
* created on the heap and assigned to argument registers directly. Argument registers for variables, should be loaded
* from a separate register assigned to the variable, that comes after the argument registers; so that a variable
* assignment can be copied into multiple arguments, where the same variable is presented multiple times in a predicate
* call. The register assignment process is carried out in two phases to do this, the first pass covers the argument
* registers and the arguments of the outermost functor, only assigning to functors, the second pass continues for
* higher numbered registers, starts again at the beginning of the arguments, and assigns to variables and functors (not
* already assigned) as for the L0 process.
*
* <p/>A brief overview of the compilation process is:
*
* <pre><p/><ul>
* <li>Terms to be compiled are allocated registers, breadth first, enumerating from outermost functors down to
* innermost atoms or variables.</li>
* <li>The outermost functor itself is treated specially, and is not allocated to a register. Its i arguments are
* allocated to registers, and are additionally associated with the first i argument registers. The outermost functor
* is the instigator of a call, in the case of queries, or the recipient of a call, in the case of programs.
* <li>Queries are 'flattened' by traversing each of their arguments in postfix order of their functors, then exploring
* the functors arguments.</li>
* <li>Programs are 'flattened' by traversing each of their arguments breadth first, the same as for the original
* register allocation, then exploring the functors arguments.</li>
* </ul></pre>
*
* <p/>Query terms are compiled into a sequence of instructions, that build up a representation of their argument terms,
* to be unified, on the heap, and assigning registers to refer to those terms on the heap, then calling the matching
* program for the query terms name and arity. Program terms are compiled into a sequence of instructions that, when run
* against the argument registers, attempt to unify all of the arguments with the heap.
*
* <p/>The effect of flattening queries using a post fix ordering, is that the values of inner functors and variables
* are loaded into registers first, before their containing functor is executed, which writes the functor and its
* arguments onto the heap. Programs do not need to be expanded in this way, they simply match functors followed by
* their arguments against the heap, so a breadth first traversal is all that is needed.
*
* <p/>Evaluating a flattened query consists of doing the following as different query tokens are encountered:
*
* <pre><p/><ol>
* <li>For the outermost functor, process all arguments, then make a CALL (functor) to the matching program.
* <li>For a register associated with an inner functor, push an STR onto the heap and copy that cell into the register.
* A put_struc (functor, register) instruction is created for this.</li>
* <li>For a variable in argument position i in the outermost functor, push a REF onto the heap that refers to itself,
* and copy that value into that variables register, as well as argument register i. A put_var (register, register)
* instruction is emitted for this.
* <li>For a register argument of an inner functor, not previously seen, push a REF onto the heap that refers to itself,
* and copy that cell into the register. A set_var (register) instruction is emitted for this.</li>
* <li>For a variables in argument position i in the outermost functor, previously seen, copy its assigned register
* into its argument register. A put_val (register, register) instruction is emitted for this.</li>
* <li>For a register argument previously seen, push a new cell onto the heap and copy into it the register's value.
* A set_val (register) instruction is emitted for this.</li>
* </ol></pre>
*
* <p/>Evaluating a flattened program consists of doing the following as different program tokens are encountered:
*
* <pre><p/><ol>
* <li>For the outermost functor, process all arguments, then execute a PROCEED instruction to indicate success.
* <li>For a register associated with an inner functor, load that register with a reference to the functor. A get_struc
* (functor, register) instruction is created for this.</li>
* <li>For a variable in argument position i in the outermost functor, copy its argument register into its assigned
* register. A get_var (register, register) instruction is emitted for this.
* <li>For a register argument of an inner functor, not previously seen, bind that register to its argument. A
* unify_var (register) instruction is output for this.</li>
* <li>For a variable in argument position i in the outermost functor, unify its assigned register with the
* argument register. A get_val (register, register) instruction is emitted for this.</li>
* <li>For a register argument of an inner functor, previously seen, unify that register against the heap. A
* unify_val (register) instruction is emitted for this.</li>
* </ol></pre>
*
* <pre><p/><table id="crc"><caption>CRC Card</caption>
* <tr><th> Responsibilities <th> Collaborations
* <tr><td> Transform WAM sentences into compiled byte code.
* <td> {@link WAMMachine}, {@link WAMCompiledPredicate}
* </table></pre>
*
* @author Rupert Smith
*/
public class InstructionCompiler extends DefaultBuiltIn
implements LogicCompiler<Clause, WAMCompiledPredicate, WAMCompiledQuery>
{
/** Used for debugging. */
private static final java.util.logging.Logger log =
java.util.logging.Logger.getLogger(InstructionCompiler.class.getName());
/** The symbol table key for allocations. */
public static final String SYMKEY_ALLOCATION = "allocation";
/** The symbol table key for the number of permanent variables remaining. */
protected static final String SYMKEY_PERM_VARS_REMAINING = "perm_vars_remaining";
/** The symbol table key for variable occurrence counts. */
public static final String SYMKEY_VAR_OCCURRENCE_COUNT = "var_occurrence_count";
/** The symbol table key for variable position of occurrence. */
public static final String SYMKEY_VAR_NON_ARG = "var_non_arg";
/** The symbol table key for functor position of occurrence. */
public static final String SYMKEY_FUNCTOR_NON_ARG = "functor_non_arg";
/** The symbol table key for variable introduction type. */
public static final String SYMKEY_VARIABLE_INTRO = "variable_intro";
/** The symbol table key for the last functor in which a variable occurs, if it is purely in argument position. */
public static final String SYMKEY_VAR_LAST_ARG_FUNCTOR = "var_last_arg_functor";
/** The symbol table key for predicate sources. */
protected static final String SYMKEY_PREDICATES = "source_predicates";
/** Holds a list of all predicates encountered in the current scope. */
protected Queue<SymbolKey> predicatesInScope = new LinkedList<SymbolKey>();
/** Holds the compiler output observer. */
private LogicCompilerObserver<WAMCompiledPredicate, WAMCompiledQuery> observer;
/** This is used to keep track of the number of permanent variables. */
protected int numPermanentVars;
/** Keeps count of the current compiler scope, to keep symbols in each scope fresh. */
protected int scope = 0;
/** Holds the current nested compilation scope symbol table. */
private SymbolTable<Integer, String, Object> scopeTable;
/** Holds the instruction optimizer. */
private Optimizer optimizer;
/**
* Creates a new InstructionCompiler.
*
* @param symbolTable The symbol table.
* @param interner The machine to translate functor and variable names.
*/
protected InstructionCompiler(SymbolTable<Integer, String, Object> symbolTable, VariableAndFunctorInterner interner)
{
super(symbolTable, interner);
optimizer = new WAMOptimizer(symbolTable, interner);
}
/** {@inheritDoc} */
public void setCompilerObserver(LogicCompilerObserver<WAMCompiledPredicate, WAMCompiledQuery> observer)
{
this.observer = observer;
}
/** {@inheritDoc} */
public void endScope() throws SourceCodeException
{
// Loop over all predicates in the current scope, found in the symbol table, and consume and compile them.
for (SymbolKey predicateKey = predicatesInScope.poll(); predicateKey != null;
predicateKey = predicatesInScope.poll())
{
List<Clause> clauseList = (List<Clause>) scopeTable.get(predicateKey, SYMKEY_PREDICATES);
// Used to keep track of where within the predicate the current clause is.
int size = clauseList.size();
int current = 0;
boolean multipleClauses = size > 1;
// Used to build up the compiled predicate in.
WAMCompiledPredicate result = null;
for (Iterator<Clause> iterator = clauseList.iterator(); iterator.hasNext(); iterator.remove())
{
Clause clause = iterator.next();
if (result == null)
{
result = new WAMCompiledPredicate(clause.getHead().getName());
}
// Compile the single clause, adding it to the parent compiled predicate.
compileClause(clause, result, current == 0, current >= (size - 1), multipleClauses, current);
current++;
}
// Run the optimizer on the output.
result = optimizer.apply(result);
displayCompiledPredicate(result);
observer.onCompilation(result);
// Move up the low water mark on the predicates table.
symbolTable.setLowMark(predicateKey, SYMKEY_PREDICATES);
}
// Clear up the symbol table, and bump the compilation scope up by one.
symbolTable.clearUpToLowMark(SYMKEY_PREDICATES);
scopeTable = null;
scope++;
}
/**
* {@inheritDoc}
*
* <p/>Compiles a sentence into a binary form, that provides a Java interface into the compiled structure.
*
* <p/>The clausal sentence may be a query, or a program statement. If it is a query, it is compiled immediately. If
* it is a clause, it is retained against the predicate which it forms part of, and compiled on the
* {@link #endScope()} method is invoked.
*/
public void compile(Sentence<Clause> sentence) throws SourceCodeException
{
/*log.fine("public WAMCompiledClause compile(Sentence<Term> sentence = " + sentence + "): called");*/
// Extract the clause to compile from the parsed sentence.
Clause clause = sentence.getT();
initialiseSymbolTable(clause);
// Classify the sentence to compile by the different sentence types in the language.
if (clause.isQuery())
{
compileQuery(clause);
}
else
{
// Initialise a nested symbol table for the current compilation scope, if it has not already been.
if (scopeTable == null)
{
scopeTable = symbolTable.enterScope(scope);
}
// Check in the symbol table, if a compiled predicate with name matching the program clause exists, and if
// not create it.
SymbolKey predicateKey = scopeTable.getSymbolKey(clause.getHead().getName());
List<Clause> clauseList = (List<Clause>) scopeTable.get(predicateKey, SYMKEY_PREDICATES);
if (clauseList == null)
{
clauseList = new LinkedList<Clause>();
scopeTable.put(predicateKey, SYMKEY_PREDICATES, clauseList);
predicatesInScope.offer(predicateKey);
}
// Add the clause to compile to its parent predicate for compilation at the end of the current scope.
clauseList.add(clause);
}
}
/**
* Compiles a program clause, and adds its instructions to a compiled predicate.
*
* @param clause The source clause to compile.
* @param compiledPredicate The predicate to add instructions to.
* @param isFirst <tt>true</tt> iff the clause is the first in the predicate.
* @param isLast <tt>true</tt> iff the clause is the last in the predicate.
* @param multipleClauses <tt>true</tt> iff the predicate contains >1 clause.
* @param clauseNumber The position of the clause within the predicate.
*
* @throws SourceCodeException If there is an error in the source code preventing its compilation.
*/
private void compileClause(Clause clause, WAMCompiledPredicate compiledPredicate, boolean isFirst, boolean isLast,
boolean multipleClauses, int clauseNumber) throws SourceCodeException
{
// Used to build up the compiled clause in.
WAMCompiledClause result = new WAMCompiledClause(compiledPredicate);
// Check if the clause to compile is a fact (no body).
boolean isFact = clause.getBody() == null;
// Check if the clause to compile is a chain rule, (one called body).
boolean isChainRule = (clause.getBody() != null) && (clause.getBody().length == 1);
// Used to keep track of registers as they are seen during compilation. The first time a variable is seen,
// a variable is written onto the heap, subsequent times its value. The first time a functor is seen,
// its structure is written onto the heap, subsequent times it is compared with.
seenRegisters = new TreeSet<Integer>();
// This is used to keep track of the next temporary register available to allocate.
lastAllocatedTempReg = findMaxArgumentsInClause(clause);
// This is used to keep track of the number of permanent variables.
numPermanentVars = 0;
// These are used to generate pre and post instructions for the clause, for example, for the creation and
// clean-up of stack frames.
SizeableLinkedList<WAMInstruction> preFixInstructions = new SizeableLinkedList<WAMInstruction>();
SizeableLinkedList<WAMInstruction> postFixInstructions = new SizeableLinkedList<WAMInstruction>();
// Find all the free non-anonymous variables in the clause.
Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(clause);
Set<Integer> freeVarNames = new TreeSet<Integer>();
for (Variable var : freeVars)
{
freeVarNames.add(var.getName());
}
// Allocate permanent variables for a program clause. Program clauses only use permanent variables when really
// needed to preserve variables across calls.
allocatePermanentProgramRegisters(clause);
// Gather information about the counts and positions of occurrence of variables and constants within the clause.
gatherPositionAndOccurrenceInfo(clause);
// Labels the entry point to each choice point.
FunctorName fn = interner.getFunctorFunctorName(clause.getHead());
WAMLabel entryLabel = new WAMLabel(fn, clauseNumber);
// Label for the entry point to the next choice point, to backtrack to.
WAMLabel retryLabel = new WAMLabel(fn, clauseNumber + 1);
// Create choice point instructions for the clause, depending on its position within the containing predicate.
// The choice point instructions are only created when a predicate is built from multiple clauses, as otherwise
// there are no choices to be made.
if (isFirst && !isLast && multipleClauses)
{
// try me else.
preFixInstructions.add(new WAMInstruction(entryLabel, WAMInstruction.WAMInstructionSet.TryMeElse,
retryLabel));
}
else if (!isFirst && !isLast && multipleClauses)
{
// retry me else.
preFixInstructions.add(new WAMInstruction(entryLabel, WAMInstruction.WAMInstructionSet.RetryMeElse,
retryLabel));
}
else if (isLast && multipleClauses)
{
// trust me.
preFixInstructions.add(new WAMInstruction(entryLabel, WAMInstruction.WAMInstructionSet.TrustMe));
}
// Generate the prefix code for the clause.
// Rules may chain multiple, so require stack frames to preserve registers across calls.
// Facts are always leafs so can use the global continuation point register to return from calls.
// Chain rules only make one call, so also do not need a stack frame.
if (!(isFact || isChainRule))
{
// Allocate a stack frame at the start of the clause.
/*log.fine("ALLOCATE " + numPermanentVars);*/
preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Allocate));
}
result.addInstructions(preFixInstructions);
// Compile the clause head.
Functor expression = clause.getHead();
SizeableLinkedList<WAMInstruction> instructions = compileHead(expression);
result.addInstructions(expression, instructions);
// Compile all of the conjunctive parts of the body of the clause, if there are any.
if (!isFact)
{
Functor[] expressions = clause.getBody();
for (int i = 0; i < expressions.length; i++)
{
expression = expressions[i];
boolean isLastBody = i == (expressions.length - 1);
Integer permVarsRemaining =
(Integer) symbolTable.get(expression.getSymbolKey(), SYMKEY_PERM_VARS_REMAINING);
// Select a non-default built-in implementation to compile the functor with, if it is a built-in.
BuiltIn builtIn;
if (expression instanceof BuiltIn)
{
builtIn = (BuiltIn) expression;
}
else
{
builtIn = this;
}
// The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule.
instructions = builtIn.compileBody(expression, i == 0);
result.addInstructions(expression, instructions);
// Call the body. The number of permanent variables remaining is specified for environment trimming.
instructions = builtIn.compileBodyCall(expression, isLastBody, isChainRule, permVarsRemaining);
result.addInstructions(expression, instructions);
}
}
// Generate the postfix code for the clause. Rules may chain, so require stack frames.
// Facts are always leafs so can use the global continuation point register to return from calls.
if (isFact)
{
/*log.fine("PROCEED");*/
postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Proceed));
}
result.addInstructions(postFixInstructions);
}
/**
* Compiles a clause as a query. The clause should have no head, only a body.
*
* @param clause The clause to compile as a query.
*
* @throws SourceCodeException If there is an error in the source code preventing its compilation.
*/
private void compileQuery(Clause clause) throws SourceCodeException
{
// Used to build up the compiled result in.
WAMCompiledQuery result;
// A mapping from top stack frame slots to interned variable names is built up in this.
// This is used to track the stack positions that variables in a query are assigned to.
Map<Byte, Integer> varNames = new TreeMap<Byte, Integer>();
// Used to keep track of registers as they are seen during compilation. The first time a variable is seen,
// a variable is written onto the heap, subsequent times its value. The first time a functor is seen,
// its structure is written onto the heap, subsequent times it is compared with.
seenRegisters = new TreeSet<Integer>();
// This is used to keep track of the next temporary register available to allocate.
lastAllocatedTempReg = findMaxArgumentsInClause(clause);
// This is used to keep track of the number of permanent variables.
numPermanentVars = 0;
// These are used to generate pre and post instructions for the clause, for example, for the creation and
// clean-up of stack frames.
SizeableLinkedList<WAMInstruction> preFixInstructions = new SizeableLinkedList<WAMInstruction>();
SizeableLinkedList<WAMInstruction> postFixInstructions = new SizeableLinkedList<WAMInstruction>();
// Find all the free non-anonymous variables in the clause.
Set<Variable> freeVars = TermUtils.findFreeNonAnonymousVariables(clause);
Set<Integer> freeVarNames = new TreeSet<Integer>();
for (Variable var : freeVars)
{
freeVarNames.add(var.getName());
}
// Allocate permanent variables for a query. In queries all variables are permanent so that they are preserved
// on the stack upon completion of the query.
allocatePermanentQueryRegisters(clause, varNames);
// Gather information about the counts and positions of occurrence of variables and constants within the clause.
gatherPositionAndOccurrenceInfo(clause);
result = new WAMCompiledQuery(varNames, freeVarNames);
// Generate the prefix code for the clause. Queries require a stack frames to hold their environment.
/*log.fine("ALLOCATE " + numPermanentVars);*/
preFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.AllocateN, WAMInstruction.REG_ADDR,
(byte) (numPermanentVars & 0xff)));
result.addInstructions(preFixInstructions);
// Compile all of the conjunctive parts of the body of the clause, if there are any.
Functor[] expressions = clause.getBody();
for (int i = 0; i < expressions.length; i++)
{
Functor expression = expressions[i];
// Select a non-default built-in implementation to compile the functor with, if it is a built-in.
BuiltIn builtIn;
if (expression instanceof BuiltIn)
{
builtIn = (BuiltIn) expression;
}
else
{
builtIn = this;
}
// The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule, which it
// never is for a query.
SizeableLinkedList<WAMInstruction> instructions = builtIn.compileBody(expression, false);
result.addInstructions(expression, instructions);
// Queries are never chain rules, and as all permanent variables are preserved, bodies are never called
// as last calls.
instructions = builtIn.compileBodyCall(expression, false, false, numPermanentVars);
result.addInstructions(expression, instructions);
}
// Generate the postfix code for the clause.
/*log.fine("DEALLOCATE");*/
postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Suspend));
postFixInstructions.add(new WAMInstruction(WAMInstruction.WAMInstructionSet.Deallocate));
result.addInstructions(postFixInstructions);
// Run the optimizer on the output.
result = optimizer.apply(result);
displayCompiledQuery(result);
observer.onQueryCompilation(result);
}
/**
* Examines all top-level functors within a clause, including any head and body, and determines which functor has
* the highest number of arguments.
*
* @param clause The clause to determine the highest number of arguments within.
*
* @return The highest number of arguments within any top-level functor in the clause.
*/
private int findMaxArgumentsInClause(Clause clause)
{
int result = 0;
Functor head = clause.getHead();
if (head != null)
{
result = head.getArity();
}
Functor[] body = clause.getBody();
if (body != null)
{
for (int i = 0; i < body.length; i++)
{
int arity = body[i].getArity();
result = (arity > result) ? arity : result;
}
}
return result;
}
/**
* Runs a symbol key traverser over the clause to be compiled, to ensure that all of its terms and sub-terms have
* their symbol keys initialised.
*
* @param clause The clause to initialise the symbol keys of.
*/
private void initialiseSymbolTable(Clause clause)
{
// Run the symbol key traverser over the clause, to ensure that all terms have their symbol keys correctly
// set up.
SymbolKeyTraverser symbolKeyTraverser = new SymbolKeyTraverser(interner, symbolTable, null);
symbolKeyTraverser.setContextChangeVisitor(symbolKeyTraverser);
TermWalker symWalker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), symbolKeyTraverser, symbolKeyTraverser);
symWalker.walk(clause);
}
/**
* Compiles the head of a clause into an instruction listing in WAM.
*
* @param expression The clause head to compile.
*
* @return A listing of the instructions for the clause head in the WAM instruction set.
*/
private SizeableLinkedList<WAMInstruction> compileHead(Functor expression)
{
// Used to build up the results in.
SizeableLinkedList<WAMInstruction> instructions = new SizeableLinkedList<WAMInstruction>();
// Allocate argument registers on the body, to all functors as outermost arguments.
// Allocate temporary registers on the body, to all terms not already allocated.
allocateArgumentRegisters(expression);
allocateTemporaryRegisters(expression);
// Program instructions are generated in the same order as the registers are assigned, the postfix
// ordering used for queries is not needed.
QueueBasedSearchMethod<Term, Term> outInSearch = new BreadthFirstSearch<Term, Term>();
outInSearch.reset();
outInSearch.addStartState(expression);
Iterator<Term> treeWalker = Searches.allSolutions(outInSearch);
// Skip the outermost functor.
treeWalker.next();
// Allocate argument registers on the body, to all functors as outermost arguments.
// Allocate temporary registers on the body, to all terms not already allocated.
// Keep track of processing of the arguments to the outermost functor as get_val and get_var instructions
// need to be output for variables encountered in the arguments only.
int numOutermostArgs = expression.getArity();
for (int j = 0; treeWalker.hasNext(); j++)
{
Term nextTerm = treeWalker.next();
/*log.fine("nextTerm = " + nextTerm);*/
// For each functor encountered: get_struc.
if (nextTerm.isFunctor())
{
Functor nextFunctor = (Functor) nextTerm;
int allocation = (Integer) symbolTable.get(nextFunctor.getSymbolKey(), SYMKEY_ALLOCATION);
byte addrMode = (byte) ((allocation & 0xff00) >> 8);
byte address = (byte) (allocation & 0xff);
// Ouput a get_struc instruction, except on the outermost functor.
/*log.fine("GET_STRUC " + interner.getFunctorName(nextFunctor) + "/" + nextFunctor.getArity() +
((addrMode == REG_ADDR) ? ", X" : ", Y") + address);*/
WAMInstruction instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.GetStruc, addrMode, address,
interner.getFunctorFunctorName(nextFunctor), nextFunctor);
instructions.add(instruction);
// For each argument of the functor.
int numArgs = nextFunctor.getArity();
for (int i = 0; i < numArgs; i++)
{
Term nextArg = nextFunctor.getArgument(i);
allocation = (Integer) symbolTable.get(nextArg.getSymbolKey(), SYMKEY_ALLOCATION);
addrMode = (byte) ((allocation & 0xff00) >> 8);
address = (byte) (allocation & 0xff);
/*log.fine("nextArg = " + nextArg);*/
// If it is register not seen before: unify_var.
// If it is register seen before: unify_val.
if (!seenRegisters.contains(allocation))
{
/*log.fine("UNIFY_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/
seenRegisters.add(allocation);
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.UnifyVar, addrMode, address, nextArg);
// Record the way in which this variable was introduced into the clause.
symbolTable.put(nextArg.getSymbolKey(), SYMKEY_VARIABLE_INTRO, VarIntroduction.Unify);
}
else
{
// Check if the variable is 'local' and use a local instruction on the first occurrence.
VarIntroduction introduction =
(VarIntroduction) symbolTable.get(nextArg.getSymbolKey(), SYMKEY_VARIABLE_INTRO);
if (isLocalVariable(introduction, addrMode))
{
log.fine("UNIFY_LOCAL_VAL " + ((addrMode == WAMInstruction.REG_ADDR) ? "X" : "Y") +
address);
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.UnifyLocalVal, addrMode, address,
nextArg);
symbolTable.put(nextArg.getSymbolKey(), SYMKEY_VARIABLE_INTRO, null);
}
else
{
/*log.fine("UNIFY_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address);*/
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.UnifyVal, addrMode, address,
nextArg);
}
}
instructions.add(instruction);
}
}
else if (j < numOutermostArgs)
{
Variable nextVar = (Variable) nextTerm;
int allocation = (Integer) symbolTable.get(nextVar.getSymbolKey(), SYMKEY_ALLOCATION);
byte addrMode = (byte) ((allocation & 0xff00) >> 8);
byte address = (byte) (allocation & 0xff);
WAMInstruction instruction;
// If it is register not seen before: get_var.
// If it is register seen before: get_val.
if (!seenRegisters.contains(allocation))
{
/*log.fine("GET_VAR " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/
seenRegisters.add(allocation);
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.GetVar, addrMode, address,
(byte) (j & 0xff));
// Record the way in which this variable was introduced into the clause.
symbolTable.put(nextVar.getSymbolKey(), SYMKEY_VARIABLE_INTRO, VarIntroduction.Get);
}
else
{
/*log.fine("GET_VAL " + ((addrMode == REG_ADDR) ? "X" : "Y") + address + ", A" + j);*/
instruction =
new WAMInstruction(WAMInstruction.WAMInstructionSet.GetVal, addrMode, address,
(byte) (j & 0xff));
}
instructions.add(instruction);
}
}
return instructions;
}
/**
* Allocates stack slots where need to the variables in a program clause. The algorithm here is fairly complex.
*
* <p/>A clause head and first body functor are taken together as the first unit, subsequent clause body functors
* are taken as subsequent units. A variable appearing in more than one unit is said to be permanent, and must be
* stored on the stack, rather than a register, otherwise the register that it occupies may be overwritten by calls
* to subsequent units. These variable are called permanent, which really means that they are local variables on the
* call stack.
*
* <p/>In addition to working out which variables are permanent, the variables are also ordered by reverse position
* of last body of occurrence, and assigned to allocation slots in this order. The number of permanent variables
* remaining at each body call is also calculated and recorded against the body functor in the symbol table using
* column {@link #SYMKEY_PERM_VARS_REMAINING}. This allocation ordering of the variables and the count of the number
* remaining are used to implement environment trimming.
*
* @param clause The clause to allocate registers for.
*/
private void allocatePermanentProgramRegisters(Clause clause)
{
// A bag to hold variable occurrence counts in.
Map<Variable, Integer> variableCountBag = new HashMap<Variable, Integer>();
// A mapping from variables to the body number in which they appear last.
Map<Variable, Integer> lastBodyMap = new HashMap<Variable, Integer>();
// Get the occurrence counts of variables in all clauses after the initial head and first body grouping.
// In the same pass, pick out which body variables last occur in.
if ((clause.getBody() != null))
{
for (int i = clause.getBody().length - 1; i >= 1; i--)
{
Set<Variable> groupVariables = TermUtils.findFreeVariables(clause.getBody()[i]);
// Add all their counts to the bag and update their last occurrence positions.
for (Variable variable : groupVariables)
{
Integer count = variableCountBag.get(variable);
variableCountBag.put(variable, (count == null) ? 1 : (count + 1));
if (!lastBodyMap.containsKey(variable))
{
lastBodyMap.put(variable, i);
}
}
}
}
// Get the set of variables in the head and first clause body argument.
Set<Variable> firstGroupVariables = new HashSet<Variable>();
if (clause.getHead() != null)
{
Set<Variable> headVariables = TermUtils.findFreeVariables(clause.getHead());
firstGroupVariables.addAll(headVariables);
}
if ((clause.getBody() != null) && (clause.getBody().length > 0))
{
Set<Variable> firstArgVariables = TermUtils.findFreeVariables(clause.getBody()[0]);
firstGroupVariables.addAll(firstArgVariables);
}
// Add their counts to the bag, and set their last positions of occurrence as required.
for (Variable variable : firstGroupVariables)
{
Integer count = variableCountBag.get(variable);
variableCountBag.put(variable, (count == null) ? 1 : (count + 1));
if (!lastBodyMap.containsKey(variable))
{
lastBodyMap.put(variable, 0);
}
}
// Sort the variables by reverse position of last occurrence.
List<Map.Entry<Variable, Integer>> lastBodyList =
new ArrayList<Map.Entry<Variable, Integer>>(lastBodyMap.entrySet());
Collections.sort(lastBodyList, new Comparator<Map.Entry<Variable, Integer>>()
{
public int compare(Map.Entry<Variable, Integer> o1, Map.Entry<Variable, Integer> o2)
{
return o2.getValue().compareTo(o1.getValue());
}
});
// Holds counts of permanent variable last appearances against the body in which they last occur.
int[] permVarsRemainingCount = new int[(clause.getBody() != null) ? clause.getBody().length : 0];
// Search the count bag for all variable occurrences greater than one, and assign them to stack slots.
// The variables are examined by reverse position of last occurrence, to ensure that later variables
// are assigned to lower permanent allocation slots for environment trimming purposes.
for (Map.Entry<Variable, Integer> entry : lastBodyList)
{
Variable variable = entry.getKey();
Integer count = variableCountBag.get(variable);
int body = entry.getValue();
if ((count != null) && (count > 1))
{
log.fine("Variable " + variable + " is permanent, count = " + count);
int allocation = (numPermanentVars++ & (0xff)) | (WAMInstruction.STACK_ADDR << 8);
symbolTable.put(variable.getSymbolKey(), SYMKEY_ALLOCATION, allocation);
permVarsRemainingCount[body]++;
}
}
// Roll up the permanent variable remaining counts from the counts of last position of occurrence and
// store the count of permanent variables remaining against the body.
int permVarsRemaining = 0;
for (int i = permVarsRemainingCount.length - 1; i >= 0; i--)
{
symbolTable.put(clause.getBody()[i].getSymbolKey(), SYMKEY_PERM_VARS_REMAINING, permVarsRemaining);
permVarsRemaining += permVarsRemainingCount[i];
}
}
/**
* Allocates stack slots to all free variables in a query clause.
*
* <p/>At the end of processing a query its variable bindings are usually printed. For this reason all free
* variables in a query are marked as permanent variables on the call stack, to ensure that they are preserved.
*
* @param clause The clause to allocate registers for.
* @param varNames A map of permanent variables to variable names to record the allocations in.
*/
private void allocatePermanentQueryRegisters(Clause clause, Map<Byte, Integer> varNames)
{
// Allocate local variable slots for all variables in a query.
QueryRegisterAllocatingVisitor allocatingVisitor =
new QueryRegisterAllocatingVisitor(symbolTable, varNames, null);
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
positionalTraverser.setContextChangeVisitor(allocatingVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, allocatingVisitor);
walker.walk(clause);
}
/**
* Gather information about variable counts and positions of occurrence of constants and variable within a clause.
*
* @param clause The clause to check the variable occurrence and position of occurrence within.
*/
private void gatherPositionAndOccurrenceInfo(Clause clause)
{
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
PositionAndOccurrenceVisitor positionAndOccurrenceVisitor =
new PositionAndOccurrenceVisitor(interner, symbolTable, positionalTraverser);
positionalTraverser.setContextChangeVisitor(positionAndOccurrenceVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser,
positionAndOccurrenceVisitor);
walker.walk(clause);
}
/**
* Pretty prints a compiled predicate.
*
* @param predicate The compiled predicate to pretty print.
*/
private void displayCompiledPredicate(WAMCompiledPredicate predicate)
{
// Pretty print the clause.
StringBuffer result = new StringBuffer();
WAMCompiledTermsPrintingVisitor displayVisitor =
new WAMCompiledPredicatePrintingVisitor(interner, symbolTable, result);
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
displayVisitor.setPositionalTraverser(positionalTraverser);
positionalTraverser.setContextChangeVisitor(displayVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, displayVisitor);
walker.walk(predicate);
log.fine(result.toString());
}
/**
* Pretty prints a compiled query.
*
* @param query The compiled query to pretty print.
*/
private void displayCompiledQuery(WAMCompiledQuery query)
{
// Pretty print the clause.
StringBuffer result = new StringBuffer();
WAMCompiledTermsPrintingVisitor displayVisitor =
new WAMCompiledQueryPrintingVisitor(interner, symbolTable, result);
PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
displayVisitor.setPositionalTraverser(positionalTraverser);
positionalTraverser.setContextChangeVisitor(displayVisitor);
TermWalker walker =
new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, displayVisitor);
walker.walk(query);
log.fine(result.toString());
}
/**
* QueryRegisterAllocatingVisitor visits named variables in a query, and if they are not already allocated to a
* permanent stack slot, allocates them one. All named variables in queries are stack allocated, so that they are
* preserved on the stack at the end of the query. Anonymous variables in queries are singletons, and not included
* in the query results, so can be temporary.
*/
public class QueryRegisterAllocatingVisitor extends DelegatingAllTermsVisitor
{
/** The symbol table. */
private final SymbolTable<Integer, String, Object> symbolTable;
/** Holds a map of permanent variables to variable names to record the allocations in. */
private final Map<Byte, Integer> varNames;
/**
* Creates a query variable allocator.
*
* @param symbolTable The symbol table.
* @param varNames A map of permanent variables to variable names to record the allocations in.
* @param delegate The term visitor that this delegates to.
*/
public QueryRegisterAllocatingVisitor(SymbolTable<Integer, String, Object> symbolTable,
Map<Byte, Integer> varNames, AllTermsVisitor delegate)
{
super(delegate);
this.symbolTable = symbolTable;
this.varNames = varNames;
}
/**
* {@inheritDoc}
*
* <p/>Allocates unallocated variables to stack slots.
*/
public void visit(Variable variable)
{
if (symbolTable.get(variable.getSymbolKey(), SYMKEY_ALLOCATION) == null)
{
if (variable.isAnonymous())
{
log.fine("Query variable " + variable + " is temporary.");
int allocation = (lastAllocatedTempReg++ & (0xff)) | (WAMInstruction.REG_ADDR << 8);
symbolTable.put(variable.getSymbolKey(), SYMKEY_ALLOCATION, allocation);
varNames.put((byte) allocation, variable.getName());
}
else
{
log.fine("Query variable " + variable + " is permanent.");
int allocation = (numPermanentVars++ & (0xff)) | (WAMInstruction.STACK_ADDR << 8);
symbolTable.put(variable.getSymbolKey(), SYMKEY_ALLOCATION, allocation);
varNames.put((byte) allocation, variable.getName());
}
}
super.visit(variable);
}
}
/**
* PositionAndOccurrenceVisitor visits a clause to gather information about the positions in which components of the
* clause appear.
*
* <p/>For variables, the following information is gathered:
*
* <ol>
* <li>A count of the number of times the variable occurs in the clause (singleton detection).</li>
* <li>A flag indicating that variable only ever appears in non-argument positions.</li>
* <li>The last functor body in the clause in which a variable appears, provided it only does so in argument
* position.</li>
* </ol>
*
* <p/>For constants, the following information is gathered:
*
* <ol>
* <li>A flag indicating the constant only ever appears in non-argument positions.</li>
* </ol>
*/
public class PositionAndOccurrenceVisitor extends BasePositionalVisitor
{
/** Holds the current top-level body functor. <tt>null</tt> when traversing the head. */
private Functor topLevelBodyFunctor;
/** Holds a set of all constants encountered. */
private Map<Integer, List<SymbolKey>> constants = new HashMap<Integer, List<SymbolKey>>();
/** Holds a set of all constants found to be in argument positions. */
private Set<Integer> argumentConstants = new HashSet<Integer>();
/**
* Creates a positional visitor.
*
* @param interner The name interner.
* @param symbolTable The compiler symbol table.
* @param traverser The positional context traverser.
*/
public PositionAndOccurrenceVisitor(VariableAndFunctorInterner interner,
SymbolTable<Integer, String, Object> symbolTable, PositionalTermTraverser traverser)
{
super(interner, symbolTable, traverser);
}
/**
* {@inheritDoc}
*
* <p/>Counts variable occurrences and detects if the variable ever appears in an argument position.
*/
protected void enterVariable(Variable variable)
{
// Initialize the count to one or add one to an existing count.
Integer count = (Integer) symbolTable.get(variable.getSymbolKey(), SYMKEY_VAR_OCCURRENCE_COUNT);
count = (count == null) ? 1 : (count + 1);
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_OCCURRENCE_COUNT, count);
/*log.fine("Variable " + variable + " has count " + count + ".");*/
// Get the nonArgPosition flag, or initialize it to true.
Boolean nonArgPositionOnly = (Boolean) symbolTable.get(variable.getSymbolKey(), SYMKEY_VAR_NON_ARG);
nonArgPositionOnly = (nonArgPositionOnly == null) ? true : nonArgPositionOnly;
// Clear the nonArgPosition flag is the variable occurs in an argument position.
nonArgPositionOnly = inTopLevelFunctor() ? false : nonArgPositionOnly;
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_NON_ARG, nonArgPositionOnly);
/*log.fine("Variable " + variable + " nonArgPosition is " + nonArgPositionOnly + ".");*/
// If in an argument position, record the parent body functor against the variable, as potentially being
// the last one it occurs in, in a purely argument position.
// If not in an argument position, clear any parent functor recorded against the variable, as this current
// last position of occurrence is not purely in argument position.
if (inTopLevelFunctor())
{
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_LAST_ARG_FUNCTOR, topLevelBodyFunctor);
}
else
{
symbolTable.put(variable.getSymbolKey(), SYMKEY_VAR_LAST_ARG_FUNCTOR, null);
}
}
/**
* {@inheritDoc}
*
* <p/>Checks if a constant ever appears in an argument position.
*
* <p/>Sets the 'inTopLevelFunctor' flag, whenever the traversal is directly within a top-level functors
* arguments. This is set at the end, so that subsequent calls to this will pick up the state of this flag at
* the point immediately below a top-level functor.
*/
protected void enterFunctor(Functor functor)
{
/*log.fine("Functor: " + functor.getName() + " <- " + symbolTable.getSymbolKey(functor.getName()));*/
// Only check position of occurrence for constants.
if (functor.getArity() == 0)
{
// Add the constant to the set of all constants encountered.
List<SymbolKey> constantSymKeys = constants.get(functor.getName());
if (constantSymKeys == null)
{
constantSymKeys = new LinkedList<SymbolKey>();
constants.put(functor.getName(), constantSymKeys);
}
constantSymKeys.add(functor.getSymbolKey());
// If the constant ever appears in argument position, take note of this.
if (inTopLevelFunctor())
{
argumentConstants.add(functor.getName());
}
}
// Keep track of the current top-level body functor.
if (traverser.isTopLevel() && !traverser.isInHead())
{
topLevelBodyFunctor = functor;
}
}
protected void leaveClause(Clause clause)
{
//System.out.println("=== Leaving Clause ===");
//System.out.println("Contants: " + constants.keySet());
//System.out.println(" Arg Pos: " + argumentConstants);
// Remove the set of constants appearing in argument positions, from the set of all constants, to derive
// the set of constants that appear in non-argument positions only.
constants.keySet().removeAll(argumentConstants);
//System.out.println(" Non Arg: " + constants.keySet());
// Set the nonArgPosition flag on all symbol keys for all constants that only appear in non-arg positions.
for (List<SymbolKey> symbolKeys : constants.values())
{
//System.out.println(" Symbols: " + symbolKeys);
for (SymbolKey symbolKey : symbolKeys)
{
symbolTable.put(symbolKey, SYMKEY_FUNCTOR_NON_ARG, true);
}
}
/*// Get the nonArgPosition flag, or initialize it to true.
Boolean nonArgPositionOnly = (Boolean) symbolTable.get(functor.getName(), SYMKEY_FUNCTOR_NON_ARG);
nonArgPositionOnly = (nonArgPositionOnly == null) ? true : nonArgPositionOnly;
// Clear the nonArgPosition flag is the variable occurs in an argument position.
nonArgPositionOnly = inTopLevelFunctor() ? false : nonArgPositionOnly;
symbolTable.put(functor.getName(), SYMKEY_FUNCTOR_NON_ARG, nonArgPositionOnly);*/
/*log.fine("Constant " + functor + " nonArgPosition is " + nonArgPositionOnly + ".");*/
}
/**
* Checks if the current position is immediately within a top-level functor.
*
* @return <tt>true</tt> iff the current position is immediately within a top-level functor.
*/
private boolean inTopLevelFunctor()
{
PositionalContext parentContext = traverser.getParentContext();
return (parentContext != null) ? parentContext.isTopLevel() : false;
}
}
}
| Removed commented out code and javadoced the non-arg position flag.
| lojix/wam/src/main/com/thesett/aima/logic/fol/wam/compiler/InstructionCompiler.java | Removed commented out code and javadoced the non-arg position flag. |
|
Java | apache-2.0 | e5c188667c22a99950b13e99f18da46d9a3896d4 | 0 | forvvard09/job4j_CoursesJunior | package ru.spoddubnyak;
import org.junit.Test;
import ru.spoddubnyak.model.User;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* Tests class User.
*
* @author Sergei Poddubnyak ([email protected])
* @version 1.0
* @since 25.08.2017
*/
public class UserTest {
/**
* property name - name user.
*/
private final String name = "testName";
/**
* property children - number children.
*/
private final int children = 9;
/**
* property birthday - birthday user.
*/
private final Calendar birthday = new GregorianCalendar(1990, 12, 21);
/**
* Test method create object User and get expected field.
*/
@Test
public void whenCreateConstructorObjectGetExpectedFieldObject() {
User user = new User(name, children, birthday);
assertThat(user.getName(), is(name));
assertThat(user.getChildren(), is(children));
assertThat(user.getBirthday(), is(birthday));
}
/**
* Test do not override methods equals() and hashCode().
*/
@Test
public void whenAddMappElementsNotEqualsAndFashCodeGetExpectedResult() {
User userOne = new User(name, children, birthday);
User userTwo = new User(name, children, birthday);
assertThat(userOne.equals(userTwo), is(false));
assertThat(userOne.hashCode() == userTwo.hashCode(), is(false));
Map<User, Object> map = new HashMap<>();
map.put(userOne, "One");
map.put(userTwo, "One");
System.out.println(map);
}
}
| Standart/CollectionsPro/Map/src/test/java/ru/spoddubnyak/UserTest.java | package ru.spoddubnyak;
import org.junit.Test;
import ru.spoddubnyak.model.User;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* Tests class User.
*
* @author Sergei Poddubnyak ([email protected])
* @version 1.0
* @since 25.08.2017
*/
public class UserTest {
/**
* Test method create object User and get expected field.
*/
@Test
public void whenCreateConstructorObjectGetExpectedFieldObject() {
final String name = "testName";
final int children = 9;
final Calendar birthday = new GregorianCalendar(1990, 12, 21);
User user = new User(name, children, birthday);
assertThat(user.getName(), is(name));
assertThat(user.getChildren(), is(children));
assertThat(user.getBirthday(), is(birthday));
}
}
| 2. Не перекрывать equals hashCode [#1005]
| Standart/CollectionsPro/Map/src/test/java/ru/spoddubnyak/UserTest.java | 2. Не перекрывать equals hashCode [#1005] |
|
Java | apache-2.0 | c5ec4eff64289f770b76fa613af913ff2def7076 | 0 | theblackwidower/KanaQuiz | package com.noprestige.kanaquiz.reference;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import com.noprestige.kanaquiz.R;
import com.noprestige.kanaquiz.questions.Question;
import static android.util.TypedValue.COMPLEX_UNIT_SP;
public class ReferenceCell extends View
{
private String subject;
private String description;
private String[] multiLineDescription;
private TextPaint subjectPaint = new TextPaint();
private TextPaint descriptionPaint = new TextPaint();
private float subjectXPoint;
private float subjectYPoint;
private float descriptionXPoint;
private float descriptionYPoint;
private float subjectWidth;
private float descriptionWidth;
private float subjectHeight;
private float descriptionHeight;
private static TypedArray defaultAttributes;
public ReferenceCell(Context context)
{
super(context);
init(null, 0);
}
public ReferenceCell(Context context, AttributeSet attrs)
{
super(context, attrs);
init(attrs, 0);
}
public ReferenceCell(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle)
{
Context context = getContext();
if (defaultAttributes == null)
defaultAttributes = context.getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorTertiary});
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ReferenceCell, defStyle, 0);
setSubject(a.getString(R.styleable.ReferenceCell_subject));
setDescription(a.getString(R.styleable.ReferenceCell_description));
setSubjectSize(a.getDimension(R.styleable.ReferenceCell_subjectSize,
TypedValue.applyDimension(COMPLEX_UNIT_SP, 64, context.getResources().getDisplayMetrics())));
setDescriptionSize(a.getDimension(R.styleable.ReferenceCell_descriptionSize,
TypedValue.applyDimension(COMPLEX_UNIT_SP, 16, context.getResources().getDisplayMetrics())));
setColour(a.getColor(R.styleable.ReferenceCell_colour, defaultAttributes.getColor(0, 0)));
a.recycle();
setOnLongClickListener(view -> copyItem());
subjectPaint.setAntiAlias(true);
descriptionPaint.setAntiAlias(true);
}
private boolean copyItem()
{
//TODO: Allow the ability to select and copy multiple items at once.
String data = subject + " - " + description;
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("Kana Reference", data));
String message = "'" + data + "' " + getContext().getResources().getString(R.string.clipboard_message);
Snackbar.make(this, message, Snackbar.LENGTH_LONG).show();
return true;
}
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight)
{
super.onSizeChanged(width, height, oldWidth, oldHeight);
int contentWidth = width - getPaddingLeft() - getPaddingRight();
int contentHeight = height - getPaddingTop() - getPaddingBottom();
float fullHeight = subjectHeight + descriptionHeight;
subjectXPoint = getPaddingLeft() + ((contentWidth - subjectWidth) / 2);
subjectYPoint = getPaddingTop() + (((contentHeight - fullHeight) / 2) - subjectPaint.getFontMetrics().ascent);
descriptionXPoint = getPaddingLeft() + ((contentWidth - descriptionWidth) / 2);
descriptionYPoint =
getPaddingTop() + (((contentHeight + fullHeight) / 2) - descriptionPaint.getFontMetrics().descent);
}
//ref: http://stackoverflow.com/questions/13273838/onmeasure-wrap-content-how-do-i-know-the-size-to-wrap
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int desiredWidth = Math.round(Math.max(subjectWidth, descriptionWidth)) + getPaddingLeft() + getPaddingRight();
int desiredHeight = Math.round(subjectHeight + descriptionHeight) + getPaddingTop() + getPaddingBottom();
int width = calculateSize(widthMeasureSpec, desiredWidth);
int height = calculateSize(heightMeasureSpec, desiredHeight);
setMeasuredDimension(width, height);
}
private static int calculateSize(int measureSpec, int desired)
{
switch (MeasureSpec.getMode(measureSpec))
{
case MeasureSpec.EXACTLY:
return MeasureSpec.getSize(measureSpec);
case MeasureSpec.AT_MOST:
return Math.min(desired, MeasureSpec.getSize(measureSpec));
case MeasureSpec.UNSPECIFIED:
default:
return desired;
}
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawText(subject, subjectXPoint, subjectYPoint, subjectPaint);
if (multiLineDescription != null)
{
float descriptionLineHeight = descriptionHeight / multiLineDescription.length;
int contentWidth = getWidth() - getPaddingLeft() - getPaddingRight();
for (int i = 0; i < multiLineDescription.length; i++)
{
canvas.drawText(multiLineDescription[i],
getPaddingLeft() + ((contentWidth - descriptionPaint.measureText(multiLineDescription[i])) / 2),
descriptionYPoint - ((multiLineDescription.length - i - 1) * descriptionLineHeight),
descriptionPaint);
}
}
else
canvas.drawText(description, descriptionXPoint, descriptionYPoint, descriptionPaint);
}
public String getSubject()
{
return subject;
}
public float getSubjectSize()
{
return subjectPaint.getTextSize();
}
public String getDescription()
{
return description;
}
public float getDescriptionSize()
{
return descriptionPaint.getTextSize();
}
public int getColour()
{
return subjectPaint.getColor();
//return descriptionPaint.getColor();
}
public void setSubject(String subject)
{
this.subject = (subject == null) ? "" : subject;
subjectWidth = subjectPaint.measureText(this.subject);
}
public void setSubjectSize(float subjectSize)
{
subjectPaint.setTextSize(subjectSize);
subjectHeight = subjectPaint.getFontMetrics().descent - subjectPaint.getFontMetrics().ascent;
subjectWidth = subjectPaint.measureText(subject);
}
public void setDescription(String description)
{
this.description = (description == null) ? "" : description;
measureDescription();
}
public void setDescriptionSize(float descriptionSize)
{
descriptionPaint.setTextSize(descriptionSize);
measureDescription();
}
private void measureDescription()
{
descriptionHeight = descriptionPaint.getFontMetrics().descent - descriptionPaint.getFontMetrics().ascent;
if (description.contains("/"))
{
multiLineDescription = description.split("/");
descriptionWidth = 0;
for (String part : multiLineDescription)
{
float partWidth = descriptionPaint.measureText(part);
if (partWidth > descriptionWidth)
descriptionWidth = partWidth;
}
descriptionHeight *= multiLineDescription.length;
}
else
{
multiLineDescription = null;
descriptionWidth = descriptionPaint.measureText(description);
}
}
public void setColour(int colour)
{
subjectPaint.setColor(colour);
descriptionPaint.setColor(colour);
}
public static TableRow buildSpecialRow(Context context, Question[] questions)
{
if (questions == null)
return null;
else
{
TableRow row = new TableRow(context);
switch (questions.length)
{
case 1:
row.addView(new View(context));
row.addView(new View(context));
row.addView(questions[0].generateReference(context));
break;
case 2:
row.addView(questions[0].generateReference(context));
row.addView(new View(context));
row.addView(new View(context));
row.addView(new View(context));
row.addView(questions[1].generateReference(context));
break;
case 3:
row.addView(questions[0].generateReference(context));
row.addView(new View(context));
row.addView(questions[1].generateReference(context));
row.addView(new View(context));
row.addView(questions[2].generateReference(context));
break;
case 4:
row.addView(questions[0].generateReference(context));
row.addView(questions[1].generateReference(context));
row.addView(new View(context));
row.addView(questions[2].generateReference(context));
row.addView(questions[3].generateReference(context));
break;
default:
for (Question question : questions)
row.addView(question.generateReference(context));
}
return row;
}
}
public static TableRow buildRow(Context context, Question[] questions)
{
if (questions == null)
return null;
else
{
TableRow row = new TableRow(context);
for (Question question : questions)
row.addView(question.generateReference(context));
return row;
}
}
static TextView buildHeader(Context context, int title)
{
TextView header = new TextView(context);
header.setText(title);
header.setLayoutParams(
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
header.setTextSize(COMPLEX_UNIT_SP, 14);
header.setPadding(0,
Math.round(TypedValue.applyDimension(COMPLEX_UNIT_SP, 28, context.getResources().getDisplayMetrics())),
0,
Math.round(TypedValue.applyDimension(COMPLEX_UNIT_SP, 14, context.getResources().getDisplayMetrics())));
header.setTypeface(header.getTypeface(), Typeface.BOLD);
header.setAllCaps(true);
return header;
}
}
| app/src/main/java/com/noprestige/kanaquiz/reference/ReferenceCell.java | package com.noprestige.kanaquiz.reference;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import com.noprestige.kanaquiz.R;
import com.noprestige.kanaquiz.questions.Question;
import static android.util.TypedValue.COMPLEX_UNIT_SP;
public class ReferenceCell extends View
{
private String subject;
private String description;
private TextPaint subjectPaint = new TextPaint();
private TextPaint descriptionPaint = new TextPaint();
private float subjectXPoint;
private float subjectYPoint;
private float descriptionXPoint;
private float descriptionYPoint;
private float subjectWidth;
private float descriptionWidth;
private float subjectHeight;
private float descriptionHeight;
private static TypedArray defaultAttributes;
public ReferenceCell(Context context)
{
super(context);
init(null, 0);
}
public ReferenceCell(Context context, AttributeSet attrs)
{
super(context, attrs);
init(attrs, 0);
}
public ReferenceCell(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle)
{
Context context = getContext();
if (defaultAttributes == null)
defaultAttributes = context.getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorTertiary});
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ReferenceCell, defStyle, 0);
setSubject(a.getString(R.styleable.ReferenceCell_subject));
setDescription(a.getString(R.styleable.ReferenceCell_description));
setSubjectSize(a.getDimension(R.styleable.ReferenceCell_subjectSize,
TypedValue.applyDimension(COMPLEX_UNIT_SP, 64, context.getResources().getDisplayMetrics())));
setDescriptionSize(a.getDimension(R.styleable.ReferenceCell_descriptionSize,
TypedValue.applyDimension(COMPLEX_UNIT_SP, 16, context.getResources().getDisplayMetrics())));
setColour(a.getColor(R.styleable.ReferenceCell_colour, defaultAttributes.getColor(0, 0)));
a.recycle();
setOnLongClickListener(view -> copyItem());
subjectPaint.setAntiAlias(true);
descriptionPaint.setAntiAlias(true);
}
private boolean copyItem()
{
//TODO: Allow the ability to select and copy multiple items at once.
String data = subject + " - " + description;
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("Kana Reference", data));
String message = "'" + data + "' " + getContext().getResources().getString(R.string.clipboard_message);
Snackbar.make(this, message, Snackbar.LENGTH_LONG).show();
return true;
}
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight)
{
super.onSizeChanged(width, height, oldWidth, oldHeight);
int contentWidth = width - getPaddingLeft() - getPaddingRight();
int contentHeight = height - getPaddingTop() - getPaddingBottom();
float fullHeight = subjectHeight + descriptionHeight;
subjectXPoint = getPaddingLeft() + ((contentWidth - subjectWidth) / 2);
subjectYPoint = getPaddingTop() + (((contentHeight - fullHeight) / 2) - subjectPaint.getFontMetrics().ascent);
descriptionXPoint = getPaddingLeft() + ((contentWidth - descriptionWidth) / 2);
descriptionYPoint =
getPaddingTop() + (((contentHeight + fullHeight) / 2) - descriptionPaint.getFontMetrics().descent);
}
//ref: http://stackoverflow.com/questions/13273838/onmeasure-wrap-content-how-do-i-know-the-size-to-wrap
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int desiredWidth = Math.round(Math.max(subjectWidth, descriptionWidth)) + getPaddingLeft() + getPaddingRight();
int desiredHeight = Math.round(subjectHeight + descriptionHeight) + getPaddingTop() + getPaddingBottom();
int width = calculateSize(widthMeasureSpec, desiredWidth);
int height = calculateSize(heightMeasureSpec, desiredHeight);
setMeasuredDimension(width, height);
}
private static int calculateSize(int measureSpec, int desired)
{
switch (MeasureSpec.getMode(measureSpec))
{
case MeasureSpec.EXACTLY:
return MeasureSpec.getSize(measureSpec);
case MeasureSpec.AT_MOST:
return Math.min(desired, MeasureSpec.getSize(measureSpec));
case MeasureSpec.UNSPECIFIED:
default:
return desired;
}
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawText(subject, subjectXPoint, subjectYPoint, subjectPaint);
if (description.contains("/"))
{
String[] parts = description.split("/");
float descriptionLineHeight = descriptionHeight / parts.length;
int contentWidth = getWidth() - getPaddingLeft() - getPaddingRight();
for (int i = 0; i < parts.length; i++)
{
canvas.drawText(parts[i],
getPaddingLeft() + ((contentWidth - descriptionPaint.measureText(parts[i])) / 2),
descriptionYPoint - ((parts.length - i - 1) * descriptionLineHeight), descriptionPaint);
}
}
else
canvas.drawText(description, descriptionXPoint, descriptionYPoint, descriptionPaint);
}
public String getSubject()
{
return subject;
}
public float getSubjectSize()
{
return subjectPaint.getTextSize();
}
public String getDescription()
{
return description;
}
public float getDescriptionSize()
{
return descriptionPaint.getTextSize();
}
public int getColour()
{
return subjectPaint.getColor();
//return descriptionPaint.getColor();
}
public void setSubject(String subject)
{
this.subject = (subject == null) ? "" : subject;
subjectWidth = subjectPaint.measureText(this.subject);
}
public void setSubjectSize(float subjectSize)
{
subjectPaint.setTextSize(subjectSize);
subjectHeight = subjectPaint.getFontMetrics().descent - subjectPaint.getFontMetrics().ascent;
subjectWidth = subjectPaint.measureText(subject);
}
public void setDescription(String description)
{
this.description = (description == null) ? "" : description;
measureDescription();
}
public void setDescriptionSize(float descriptionSize)
{
descriptionPaint.setTextSize(descriptionSize);
measureDescription();
}
private void measureDescription()
{
descriptionHeight = descriptionPaint.getFontMetrics().descent - descriptionPaint.getFontMetrics().ascent;
if (description.contains("/"))
{
String[] parts = description.split("/");
descriptionHeight *= parts.length;
descriptionWidth = 0;
for (String part : parts)
{
float partWidth = descriptionPaint.measureText(part);
if (partWidth > descriptionWidth)
descriptionWidth = partWidth;
}
}
else
descriptionWidth = descriptionPaint.measureText(description);
}
public void setColour(int colour)
{
subjectPaint.setColor(colour);
descriptionPaint.setColor(colour);
}
public static TableRow buildSpecialRow(Context context, Question[] questions)
{
if (questions == null)
return null;
else
{
TableRow row = new TableRow(context);
switch (questions.length)
{
case 1:
row.addView(new View(context));
row.addView(new View(context));
row.addView(questions[0].generateReference(context));
break;
case 2:
row.addView(questions[0].generateReference(context));
row.addView(new View(context));
row.addView(new View(context));
row.addView(new View(context));
row.addView(questions[1].generateReference(context));
break;
case 3:
row.addView(questions[0].generateReference(context));
row.addView(new View(context));
row.addView(questions[1].generateReference(context));
row.addView(new View(context));
row.addView(questions[2].generateReference(context));
break;
case 4:
row.addView(questions[0].generateReference(context));
row.addView(questions[1].generateReference(context));
row.addView(new View(context));
row.addView(questions[2].generateReference(context));
row.addView(questions[3].generateReference(context));
break;
default:
for (Question question : questions)
row.addView(question.generateReference(context));
}
return row;
}
}
public static TableRow buildRow(Context context, Question[] questions)
{
if (questions == null)
return null;
else
{
TableRow row = new TableRow(context);
for (Question question : questions)
row.addView(question.generateReference(context));
return row;
}
}
static TextView buildHeader(Context context, int title)
{
TextView header = new TextView(context);
header.setText(title);
header.setLayoutParams(
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
header.setTextSize(COMPLEX_UNIT_SP, 14);
header.setPadding(0,
Math.round(TypedValue.applyDimension(COMPLEX_UNIT_SP, 28, context.getResources().getDisplayMetrics())),
0,
Math.round(TypedValue.applyDimension(COMPLEX_UNIT_SP, 14, context.getResources().getDisplayMetrics())));
header.setTypeface(header.getTypeface(), Typeface.BOLD);
header.setAllCaps(true);
return header;
}
}
| Caching multi-line descriptions
Decided to alter the code for multi-line descriptions in the reference cells (09ec2480f84a704464746ff607cf801cb9bbab05), so that it records where the line breaks are, and doesn't have to reparse it. Should be more efficient.
| app/src/main/java/com/noprestige/kanaquiz/reference/ReferenceCell.java | Caching multi-line descriptions |
|
Java | apache-2.0 | 16604b2e65383832b998cddfb3da2ba861b9dff3 | 0 | ddanny/achartengine,kaytdek/achartengine,ylfonline/achartengine,ddanny/achartengine,kaytdek/achartengine,ylfonline/achartengine | /**
* Copyright (C) 2009, 2010 SC 4ViewSoft SRL
*
* 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.achartengine.chartdemo.demo.chart;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.BubbleChart;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.model.XYValueSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
/**
* Average temperature demo chart.
*/
public class CombinedTemperatureChart extends AbstractDemoChart {
/**
* Returns the chart name.
*
* @return the chart name
*/
public String getName() {
return "Combined temperature";
}
/**
* Returns the chart description.
*
* @return the chart description
*/
public String getDesc() {
return "The average temperature in 2 Greek islands, water temperature and sun shine hours (combined chart)";
}
/**
* Executes the chart demo.
*
* @param context the context
* @return the built intent
*/
public Intent execute(Context context) {
String[] titles = new String[] { "Crete Air Temperature", "Skiathos Air Temperature" };
List<double[]> x = new ArrayList<double[]>();
for (int i = 0; i < titles.length; i++) {
x.add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
}
List<double[]> values = new ArrayList<double[]>();
values.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2,
13.9 });
values.add(new double[] { 9, 10, 11, 15, 19, 23, 26, 25, 22, 18, 13, 10 });
int[] colors = new int[] { Color.GREEN, Color.rgb(200, 150, 0) };
PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND };
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
renderer.setPointSize(5.5f);
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
XYSeriesRenderer r = (XYSeriesRenderer) renderer.getSeriesRendererAt(i);
r.setLineWidth(5);
r.setFillPoints(true);
}
setChartSettings(renderer, "Weather data", "Month", "Temperature", 0.5, 12.5, 0, 40,
Color.LTGRAY, Color.LTGRAY);
renderer.setXLabels(12);
renderer.setYLabels(10);
renderer.setShowGrid(true);
renderer.setXLabelsAlign(Align.RIGHT);
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setZoomButtonsVisible(true);
renderer.setPanLimits(new double[] { -10, 20, -10, 40 });
renderer.setZoomLimits(new double[] { -10, 20, -10, 40 });
XYValueSeries sunSeries = new XYValueSeries("Sunshine hours");
sunSeries.add(1, 35, 4.3);
sunSeries.add(2, 35, 4.9);
sunSeries.add(3, 35, 5.9);
sunSeries.add(4, 35, 8.8);
sunSeries.add(5, 35, 10.8);
sunSeries.add(6, 35, 11.9);
sunSeries.add(7, 35, 13.6);
sunSeries.add(8, 35, 12.8);
sunSeries.add(9, 35, 11.4);
sunSeries.add(10, 35, 9.5);
sunSeries.add(11, 35, 7.5);
sunSeries.add(12, 35, 5.5);
XYSeriesRenderer lightRenderer = new XYSeriesRenderer();
lightRenderer.setColor(Color.YELLOW);
XYSeries waterSeries = new XYSeries("Water Temperature");
waterSeries.add(1, 16);
waterSeries.add(2, 15);
waterSeries.add(3, 16);
waterSeries.add(4, 17);
waterSeries.add(5, 20);
waterSeries.add(6, 23);
waterSeries.add(7, 25);
waterSeries.add(8, 25.5);
waterSeries.add(9, 26.5);
waterSeries.add(10, 24);
waterSeries.add(11, 22);
waterSeries.add(12, 18);
renderer.setBarSpacing(0.5);
XYSeriesRenderer waterRenderer = new XYSeriesRenderer();
waterRenderer.setColor(Color.argb(250, 0, 210, 250));
XYMultipleSeriesDataset dataset = buildDataset(titles, x, values);
dataset.addSeries(0, sunSeries);
dataset.addSeries(0, waterSeries);
renderer.addSeriesRenderer(0, lightRenderer);
renderer.addSeriesRenderer(0, waterRenderer);
String[] types = new String[] { BarChart.TYPE, BubbleChart.TYPE, LineChart.TYPE,
LineChart.TYPE };
Intent intent = ChartFactory.getCombinedXYChartIntent(context, dataset, renderer, types,
"Weather parameters");
return intent;
}
}
| achartengine/demo/org/achartengine/chartdemo/demo/chart/CombinedTemperatureChart.java | /**
* Copyright (C) 2009, 2010 SC 4ViewSoft SRL
*
* 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.achartengine.chartdemo.demo.chart;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.BubbleChart;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.model.XYValueSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
/**
* Average temperature demo chart.
*/
public class CombinedTemperatureChart extends AbstractDemoChart {
/**
* Returns the chart name.
*
* @return the chart name
*/
public String getName() {
return "Combined temperature";
}
/**
* Returns the chart description.
*
* @return the chart description
*/
public String getDesc() {
return "The average temperature in 4 Greek islands, water temperature and sun shine hours (combined chart)";
}
/**
* Executes the chart demo.
*
* @param context the context
* @return the built intent
*/
public Intent execute(Context context) {
String[] titles = new String[] { "Crete", "Corfu", "Thassos", "Skiathos" };
List<double[]> x = new ArrayList<double[]>();
for (int i = 0; i < titles.length; i++) {
x.add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
}
List<double[]> values = new ArrayList<double[]>();
values.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2,
13.9 });
values.add(new double[] { 10, 10, 12, 15, 20, 24, 26, 26, 23, 18, 14, 11 });
values.add(new double[] { 5, 5.3, 8, 12, 17, 22, 24.2, 24, 19, 15, 9, 6 });
values.add(new double[] { 9, 10, 11, 15, 19, 23, 26, 25, 22, 18, 13, 10 });
int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.CYAN, Color.rgb(200, 150, 0) };
PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND,
PointStyle.TRIANGLE, PointStyle.SQUARE };
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
}
setChartSettings(renderer, "Average temperature", "Month", "Temperature", 0.5, 12.5, 0, 32,
Color.LTGRAY, Color.LTGRAY);
renderer.setXLabels(12);
renderer.setYLabels(10);
renderer.setShowGrid(true);
renderer.setXLabelsAlign(Align.RIGHT);
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setZoomButtonsVisible(true);
renderer.setPanLimits(new double[] { -10, 20, -10, 40 });
renderer.setZoomLimits(new double[] { -10, 20, -10, 40 });
XYValueSeries sunSeries = new XYValueSeries("Sunshine hours");
sunSeries.add(1, 5, 4.3);
sunSeries.add(2, 5, 4.9);
sunSeries.add(3, 5, 5.9);
sunSeries.add(4, 5, 8.8);
sunSeries.add(5, 5, 10.8);
sunSeries.add(6, 5, 11.9);
sunSeries.add(7, 5, 13.6);
sunSeries.add(8, 5, 12.8);
sunSeries.add(9, 5, 11.4);
sunSeries.add(10, 5, 9.5);
sunSeries.add(11, 5, 7.5);
sunSeries.add(12, 5, 5.5);
XYSeriesRenderer lightRenderer = new XYSeriesRenderer();
lightRenderer.setColor(Color.YELLOW);
XYSeries waterSeries = new XYSeries("Water Temperature");
waterSeries.add(1, 16);
waterSeries.add(2, 15);
waterSeries.add(3, 16);
waterSeries.add(4, 17);
waterSeries.add(5, 20);
waterSeries.add(6, 23);
waterSeries.add(7, 25);
waterSeries.add(8, 25.5);
waterSeries.add(9, 26.5);
waterSeries.add(10, 24);
waterSeries.add(11, 22);
waterSeries.add(12, 18);
renderer.setBarSpacing(0.5);
XYSeriesRenderer waterRenderer = new XYSeriesRenderer();
waterRenderer.setColor(Color.argb(200, 0, 200, 200));
XYMultipleSeriesDataset dataset = buildDataset(titles, x, values);
dataset.addSeries(0, sunSeries);
dataset.addSeries(0, waterSeries);
renderer.addSeriesRenderer(0, lightRenderer);
renderer.addSeriesRenderer(0, waterRenderer);
String[] types = new String[] { BarChart.TYPE, BubbleChart.TYPE, LineChart.TYPE,
LineChart.TYPE, LineChart.TYPE, LineChart.TYPE };
Intent intent = ChartFactory.getCombinedXYChartIntent(context, dataset, renderer, types,
"Weather parameters");
return intent;
}
}
| Improved the combined XY chart example. | achartengine/demo/org/achartengine/chartdemo/demo/chart/CombinedTemperatureChart.java | Improved the combined XY chart example. |
|
Java | apache-2.0 | 8221823fe9bd281130896d43159a8771b959c62d | 0 | hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,sequenceiq/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak | package com.sequenceiq.cloudbreak.core.flow.service;
import static com.sequenceiq.cloudbreak.domain.BillingStatus.BILLING_STARTED;
import static com.sequenceiq.cloudbreak.domain.BillingStatus.BILLING_STOPPED;
import static com.sequenceiq.cloudbreak.domain.Status.AVAILABLE;
import static com.sequenceiq.cloudbreak.domain.Status.CREATE_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.CREATE_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.DELETE_COMPLETED;
import static com.sequenceiq.cloudbreak.domain.Status.DELETE_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.DELETE_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.START_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.START_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.STOPPED;
import static com.sequenceiq.cloudbreak.domain.Status.STOP_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.STOP_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.STOP_REQUESTED;
import static com.sequenceiq.cloudbreak.domain.Status.UPDATE_IN_PROGRESS;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.sequenceiq.cloudbreak.controller.json.HostGroupAdjustmentJson;
import com.sequenceiq.cloudbreak.core.CloudbreakException;
import com.sequenceiq.cloudbreak.core.bootstrap.service.ClusterBootstrapper;
import com.sequenceiq.cloudbreak.core.flow.context.ClusterScalingContext;
import com.sequenceiq.cloudbreak.core.flow.context.DefaultFlowContext;
import com.sequenceiq.cloudbreak.core.flow.context.FlowContext;
import com.sequenceiq.cloudbreak.core.flow.context.ProvisioningContext;
import com.sequenceiq.cloudbreak.core.flow.context.StackInstanceUpdateContext;
import com.sequenceiq.cloudbreak.core.flow.context.StackScalingContext;
import com.sequenceiq.cloudbreak.core.flow.context.StackStatusUpdateContext;
import com.sequenceiq.cloudbreak.core.flow.context.UpdateAllowedSubnetsContext;
import com.sequenceiq.cloudbreak.domain.BillingStatus;
import com.sequenceiq.cloudbreak.domain.CloudPlatform;
import com.sequenceiq.cloudbreak.domain.Cluster;
import com.sequenceiq.cloudbreak.domain.HostGroup;
import com.sequenceiq.cloudbreak.domain.HostMetadata;
import com.sequenceiq.cloudbreak.domain.InstanceGroupType;
import com.sequenceiq.cloudbreak.domain.OnFailureAction;
import com.sequenceiq.cloudbreak.domain.Resource;
import com.sequenceiq.cloudbreak.domain.SecurityGroup;
import com.sequenceiq.cloudbreak.domain.SecurityRule;
import com.sequenceiq.cloudbreak.domain.Stack;
import com.sequenceiq.cloudbreak.domain.Status;
import com.sequenceiq.cloudbreak.logger.MDCBuilder;
import com.sequenceiq.cloudbreak.repository.StackUpdater;
import com.sequenceiq.cloudbreak.service.TlsSecurityService;
import com.sequenceiq.cloudbreak.repository.SecurityRuleRepository;
import com.sequenceiq.cloudbreak.service.cluster.ClusterService;
import com.sequenceiq.cloudbreak.service.cluster.flow.EmailSenderService;
import com.sequenceiq.cloudbreak.service.events.CloudbreakEventService;
import com.sequenceiq.cloudbreak.service.hostgroup.HostGroupService;
import com.sequenceiq.cloudbreak.service.securitygroup.SecurityGroupService;
import com.sequenceiq.cloudbreak.service.stack.StackService;
import com.sequenceiq.cloudbreak.service.stack.connector.CloudPlatformConnector;
import com.sequenceiq.cloudbreak.service.stack.connector.UserDataBuilder;
import com.sequenceiq.cloudbreak.service.stack.event.ProvisionComplete;
import com.sequenceiq.cloudbreak.service.stack.flow.ConsulMetadataSetup;
import com.sequenceiq.cloudbreak.service.stack.flow.MetadataSetupService;
import com.sequenceiq.cloudbreak.service.stack.flow.ProvisioningService;
import com.sequenceiq.cloudbreak.service.stack.flow.StackScalingService;
import com.sequenceiq.cloudbreak.service.stack.flow.StackSyncService;
import com.sequenceiq.cloudbreak.service.stack.flow.TerminationService;
import com.sequenceiq.cloudbreak.service.stack.flow.TlsSetupService;
@Service
public class SimpleStackFacade implements StackFacade {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleStackFacade.class);
private static final String UPDATED_SUBNETS = "updated";
private static final String REMOVED_SUBNETS = "removed";
@Inject
private StackService stackService;
@javax.annotation.Resource
private Map<CloudPlatform, CloudPlatformConnector> cloudPlatformConnectors;
@Inject
private CloudbreakEventService cloudbreakEventService;
@Inject
private TerminationService terminationService;
@Inject
private StackStartService stackStartService;
@Inject
private StackStopService stackStopService;
@Inject
private StackScalingService stackScalingService;
@Inject
private MetadataSetupService metadataSetupService;
@Inject
private UserDataBuilder userDataBuilder;
@Inject
private HostGroupService hostGroupService;
@Inject
private ClusterBootstrapper clusterBootstrapper;
@Inject
private ConsulMetadataSetup consulMetadataSetup;
@Inject
private ProvisioningService provisioningService;
@Inject
private ClusterService clusterService;
@Inject
private StackUpdater stackUpdater;
@Inject
private SecurityRuleRepository securityRuleRepository;
@Inject
private EmailSenderService emailSenderService;
@Inject
private TlsSetupService tlsSetupService;
@Inject
private TlsSecurityService tlsSecurityService;
@Inject
private StackSyncService stackSyncService;
@Inject
private SecurityGroupService securityGroupService;
@Override
public FlowContext bootstrapCluster(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), UPDATE_IN_PROGRESS);
fireEventAndLog(actualContext.getStackId(), context, "Bootstrapping cluster on the infrastructure", UPDATE_IN_PROGRESS);
clusterBootstrapper.bootstrapCluster(actualContext);
} catch (Exception e) {
LOGGER.error("Error occurred while bootstrapping container orchestrator: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext setupConsulMetadata(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), UPDATE_IN_PROGRESS);
fireEventAndLog(actualContext.getStackId(), context, "Setting up metadata", UPDATE_IN_PROGRESS);
consulMetadataSetup.setupConsulMetadata(stack.getId());
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE);
} catch (Exception e) {
LOGGER.error("Exception during the consul metadata setup process.", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext start(FlowContext context) throws CloudbreakException {
StackStatusUpdateContext actualContext = (StackStatusUpdateContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), START_IN_PROGRESS, "Cluster infrastructure is now starting.");
context = stackStartService.start(actualContext);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Cluster infrastructure started successfully.");
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BILLING_STARTED.name(), "Cluster infrastructure started successfully.");
} catch (Exception e) {
LOGGER.error("Exception during the stack start process.", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext stop(FlowContext context) throws CloudbreakException {
StackStatusUpdateContext actualContext = (StackStatusUpdateContext) context;
try {
if (stackStopService.isStopPossible(actualContext)) {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), STOP_IN_PROGRESS, "Cluster infrastructure is now stopping.");
context = stackStopService.stop(actualContext);
stackUpdater.updateStackStatus(stack.getId(), STOPPED, "Cluster infrastructure stopped successfully.");
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BILLING_STOPPED.name(), "Cluster infrastructure stopped successfully.");
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendStopSuccessEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", STOPPED);
}
}
} catch (Exception e) {
LOGGER.error("Exception during the stack stop process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext terminateStack(FlowContext context) throws CloudbreakException {
DefaultFlowContext actualContext = (DefaultFlowContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), DELETE_IN_PROGRESS, "Terminating the cluster and its infrastructure.");
if (stack != null && stack.getCredential() != null) {
terminationService.terminateStack(stack.getId(), actualContext.getCloudPlatform());
}
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BillingStatus.BILLING_STOPPED.name(),
"Billing stopped, the cluster and its infrastructure have been terminated.");
stackUpdater.updateStackStatus(actualContext.getStackId(), DELETE_COMPLETED,
"The cluster and its infrastructure have successfully been terminated.");
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendTerminationSuccessEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", DELETE_COMPLETED);
}
terminationService.finalizeTermination(stack.getId());
clusterService.updateClusterStatusByStackId(stack.getId(), DELETE_COMPLETED);
} catch (Exception e) {
LOGGER.error("Exception during the stack termination process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext addInstances(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
String statusReason = String.format("Add %s new instance(s) to the infrastructure.", actualContext.getScalingAdjustment());
stackUpdater.updateStackStatus(actualContext.getStackId(), UPDATE_IN_PROGRESS, statusReason);
Set<Resource> resources = stackScalingService.addInstances(stack.getId(), actualContext.getInstanceGroup(), actualContext.getScalingAdjustment());
context = new StackScalingContext(stack.getId(), actualContext.getCloudPlatform(), actualContext.getScalingAdjustment(),
actualContext.getInstanceGroup(), resources, actualContext.getScalingType(), null);
} catch (Exception e) {
LOGGER.error("Exception during the upscaling of stack: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext removeInstance(FlowContext context) throws CloudbreakException {
StackInstanceUpdateContext actualContext = (StackInstanceUpdateContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
if (!stack.isDeleteInProgress()) {
stackScalingService.removeInstance(actualContext.getStackId(), actualContext.getInstanceId());
}
} catch (Exception e) {
LOGGER.error("Exception during the removing instance from the stack: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext extendMetadata(FlowContext context) throws CloudbreakException {
StackScalingContext actualCont = (StackScalingContext) context;
Stack stack = stackService.getById(actualCont.getStackId());
Cluster cluster = clusterService.retrieveClusterByStackId(stack.getId());
MDCBuilder.buildMdcContext(stack);
fireEventAndLog(actualCont.getStackId(), context, "Extending metadata with new instances.", UPDATE_IN_PROGRESS);
Set<String> upscaleCandidateAddresses = metadataSetupService.setupNewMetadata(stack.getId(), actualCont.getResources(), actualCont.getInstanceGroup());
HostGroupAdjustmentJson hostGroupAdjustmentJson = new HostGroupAdjustmentJson();
hostGroupAdjustmentJson.setWithStackUpdate(false);
hostGroupAdjustmentJson.setScalingAdjustment(actualCont.getScalingAdjustment());
if (stack.getCluster() != null) {
HostGroup hostGroup = hostGroupService.getByClusterIdAndInstanceGroupName(cluster.getId(), actualCont.getInstanceGroup());
hostGroupAdjustmentJson.setHostGroup(hostGroup.getName());
}
return new StackScalingContext(stack.getId(), actualCont.getCloudPlatform(), actualCont.getScalingAdjustment(), actualCont.getInstanceGroup(),
actualCont.getResources(), actualCont.getScalingType(), upscaleCandidateAddresses);
}
@Override
public FlowContext bootstrapNewNodes(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
fireEventAndLog(actualContext.getStackId(), context, "Bootstrapping new node(s).", UPDATE_IN_PROGRESS);
clusterBootstrapper.bootstrapNewNodes(actualContext);
} catch (Exception e) {
LOGGER.error("Exception during the handling of munchausen setup: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext extendConsulMetadata(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
Cluster cluster = clusterService.retrieveClusterByStackId(stack.getId());
MDCBuilder.buildMdcContext(stack);
consulMetadataSetup.setupNewConsulMetadata(stack.getId(), actualContext.getUpscaleCandidateAddresses());
HostGroupAdjustmentJson hostGroupAdjustmentJson = new HostGroupAdjustmentJson();
hostGroupAdjustmentJson.setWithStackUpdate(false);
hostGroupAdjustmentJson.setScalingAdjustment(actualContext.getScalingAdjustment());
if (cluster != null) {
HostGroup hostGroup = hostGroupService.getByClusterIdAndInstanceGroupName(cluster.getId(), actualContext.getInstanceGroup());
hostGroupAdjustmentJson.setHostGroup(hostGroup.getName());
}
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Stack upscale has been finished successfully.");
context = new ClusterScalingContext(stack.getId(), actualContext.getCloudPlatform(),
hostGroupAdjustmentJson, actualContext.getUpscaleCandidateAddresses(), new ArrayList<HostMetadata>(), actualContext.getScalingType());
} catch (Exception e) {
LOGGER.error("Exception during the extend consul metadata phase: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext downscaleStack(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
String statusMessage = "Removing '%s' instance(s) from the cluster infrastructure.";
stackUpdater.updateStackStatus(stack.getId(), UPDATE_IN_PROGRESS);
cloudbreakEventService
.fireCloudbreakEvent(stack.getId(), UPDATE_IN_PROGRESS.name(), String.format(statusMessage, actualContext.getScalingAdjustment()));
stackScalingService.downscaleStack(stack.getId(), actualContext.getInstanceGroup(), actualContext.getScalingAdjustment());
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Downscale of the cluster infrastructure finished successfully.");
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendDownScaleSuccessEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", AVAILABLE);
}
} catch (Exception e) {
LOGGER.error("Exception during the downscaling of stack: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext stopRequested(FlowContext context) throws CloudbreakException {
StackStatusUpdateContext actualContext = (StackStatusUpdateContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), STOP_REQUESTED, "Stopping of cluster infrastructure has been requested.");
} catch (Exception e) {
LOGGER.error("Exception during the stack stop requested process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext provision(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
Date startDate = new Date();
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), CREATE_IN_PROGRESS, "Creating infrastructure");
ProvisionComplete provisionResult = provisioningService.buildStack(actualContext.getCloudPlatform(), stack, actualContext.getSetupProperties());
Date endDate = new Date();
long seconds = (endDate.getTime() - startDate.getTime()) / DateUtils.MILLIS_PER_SECOND;
fireEventAndLog(stack.getId(), context, String.format("The creation of infrastructure took %s seconds.", seconds), AVAILABLE);
context = new ProvisioningContext.Builder()
.setDefaultParams(provisionResult.getStackId(), provisionResult.getCloudPlatform())
.setProvisionSetupProperties(actualContext.getSetupProperties())
.setProvisionedResources(provisionResult.getResources())
.build();
return context;
}
@Override
public FlowContext setupTls(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
tlsSetupService.setupTls(actualContext.getCloudPlatform(), stack, actualContext.getSetupProperties());
return actualContext;
}
@Override
public FlowContext sync(FlowContext context) throws CloudbreakException {
DefaultFlowContext actualContext = (DefaultFlowContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
if (!stack.isDeleteInProgress()) {
stackSyncService.sync(stack.getId());
}
} catch (Exception e) {
LOGGER.error("Exception during the stack sync process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext updateAllowedSubnets(FlowContext context) throws CloudbreakException {
UpdateAllowedSubnetsContext actualContext = (UpdateAllowedSubnetsContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), UPDATE_IN_PROGRESS, "Updating allowed subnets.");
CloudPlatformConnector connector = cloudPlatformConnectors.get(stack.cloudPlatform());
Map<InstanceGroupType, String> userdata = userDataBuilder.buildUserData(stack.cloudPlatform(),
tlsSecurityService.readPublicSshKey(stack.getId()), connector.getSSHUser());
Map<String, Set<SecurityRule>> modifiedSubnets = getModifiedSubnetList(stack, actualContext.getAllowedSecurityRules());
Set<SecurityRule> newSecurityRules = modifiedSubnets.get(UPDATED_SUBNETS);
stack.getSecurityGroup().setSecurityRules(newSecurityRules);
cloudPlatformConnectors.get(stack.cloudPlatform()).updateAllowedSubnets(stack,
userdata.get(InstanceGroupType.GATEWAY), userdata.get(InstanceGroupType.CORE));
securityRuleRepository.delete(modifiedSubnets.get(REMOVED_SUBNETS));
securityRuleRepository.save(newSecurityRules);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Updating of allowed subnets successfully finished.");
} catch (Exception e) {
Stack stack = stackService.getById(actualContext.getStackId());
SecurityGroup securityGroup = stack.getSecurityGroup();
String msg = String.format("Failed to update security group with allowed subnets: %s", securityGroup);
if (stack != null && stack.isStackInDeletionPhase()) {
msg = String.format("Failed to update security group with allowed subnets: %s; stack is already in deletion phase.",
securityGroup);
}
LOGGER.error(msg, e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext handleUpdateAllowedSubnetsFailure(FlowContext context) throws CloudbreakException {
UpdateAllowedSubnetsContext actualContext = (UpdateAllowedSubnetsContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, String.format("Stack update failed. %s", actualContext.getErrorReason()));
} catch (Exception e) {
LOGGER.error("Exception during the handling of update allowed subnet failure: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext handleScalingFailure(FlowContext context) throws CloudbreakException {
try {
Long id = null;
String errorReason = null;
if (context instanceof StackScalingContext) {
StackScalingContext actualContext = (StackScalingContext) context;
id = actualContext.getStackId();
errorReason = actualContext.getErrorReason();
} else if (context instanceof ClusterScalingContext) {
ClusterScalingContext actualContext = (ClusterScalingContext) context;
id = actualContext.getStackId();
errorReason = actualContext.getErrorReason();
}
if (id != null) {
Stack stack = stackService.getById(id);
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Stack update failed. " + errorReason);
}
} catch (Exception e) {
LOGGER.error("Exception during the handling of stack scaling failure: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext handleCreationFailure(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
final Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
try {
fireEventAndLog(actualContext.getStackId(), context, "Creation of infrastructure failed.", UPDATE_IN_PROGRESS);
if (!stack.isStackInDeletionPhase()) {
final CloudPlatform cloudPlatform = actualContext.getCloudPlatform();
if (!stack.getOnFailureActionAction().equals(OnFailureAction.ROLLBACK)) {
LOGGER.debug("Nothing to do. OnFailureAction {}", stack.getOnFailureActionAction());
} else {
stackUpdater.updateStackStatus(stack.getId(), UPDATE_IN_PROGRESS);
cloudPlatformConnectors.get(cloudPlatform).rollback(stack, stack.getResources());
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BILLING_STOPPED.name(), "Stack creation failed.");
}
stackUpdater.updateStackStatus(stack.getId(), CREATE_FAILED, actualContext.getErrorReason());
}
context = new ProvisioningContext.Builder().setDefaultParams(stack.getId(), stack.cloudPlatform()).build();
} catch (Exception ex) {
LOGGER.error("Stack rollback failed on stack id : {}. Exception:", stack.getId(), ex);
stackUpdater.updateStackStatus(stack.getId(), CREATE_FAILED, String.format("Rollback failed: %s", ex.getMessage()));
throw new CloudbreakException(String.format("Stack rollback failed on {} stack: ", stack.getId(), ex));
}
return context;
}
@Override
public FlowContext handleTerminationFailure(FlowContext context) throws CloudbreakException {
DefaultFlowContext actualContext = (DefaultFlowContext) context;
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), DELETE_FAILED, "Termination failed: " + actualContext.getErrorReason());
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendTerminationFailureEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", DELETE_FAILED);
}
return context;
}
@Override
public FlowContext handleStatusUpdateFailure(FlowContext flowContext) throws CloudbreakException {
StackStatusUpdateContext context = (StackStatusUpdateContext) flowContext;
Stack stack = stackService.getById(context.getStackId());
MDCBuilder.buildMdcContext(stack);
if (context.isStart()) {
stackUpdater.updateStackStatus(context.getStackId(), START_FAILED, "Start failed: " + context.getErrorReason());
if (stack.getCluster() != null) {
clusterService.updateClusterStatusByStackId(context.getStackId(), STOPPED);
if (stack.getCluster().getEmailNeeded()) {
emailSenderService.sendStartFailureEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(context.getStackId(), context, "Notification email has been sent about state of the cluster.", START_FAILED);
}
}
} else {
stackUpdater.updateStackStatus(context.getStackId(), STOP_FAILED, "Stop failed: " + context.getErrorReason());
if (stack.getCluster() != null) {
clusterService.updateClusterStatusByStackId(context.getStackId(), STOPPED);
if (stack.getCluster().getEmailNeeded()) {
emailSenderService.sendStopFailureEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(context.getStackId(), context, "Notification email has been sent about state of the cluster.", STOP_FAILED);
}
}
}
return context;
}
private Map<String, Set<SecurityRule>> getModifiedSubnetList(Stack stack, List<SecurityRule> securityRuleList) {
Map<String, Set<SecurityRule>> result = new HashMap<>();
Set<SecurityRule> removed = new HashSet<>();
Set<SecurityRule> updated = new HashSet<>();
Long securityGroupId = stack.getSecurityGroup().getId();
Set<SecurityRule> securityRules = securityGroupService.get(securityGroupId).getSecurityRules();
for (SecurityRule securityRule : securityRules) {
if (!securityRule.isModifiable()) {
updated.add(securityRule);
removeFromNewSubnetList(securityRule, securityRuleList);
} else {
removed.add(securityRule);
}
}
for (SecurityRule securityRule : securityRuleList) {
updated.add(securityRule);
}
result.put(UPDATED_SUBNETS, updated);
result.put(REMOVED_SUBNETS, removed);
return result;
}
private void removeFromNewSubnetList(SecurityRule securityRule, List<SecurityRule> securityRuleList) {
Iterator<SecurityRule> iterator = securityRuleList.iterator();
String cidr = securityRule.getCidr();
while (iterator.hasNext()) {
SecurityRule next = iterator.next();
if (next.getCidr().equals(cidr)) {
iterator.remove();
}
}
}
private void fireEventAndLog(Long stackId, FlowContext context, String eventMessage, Status eventType) {
LOGGER.debug("{} [STACK_FLOW_STEP]. Context: {}", eventMessage, context);
cloudbreakEventService.fireCloudbreakEvent(stackId, eventType.name(), eventMessage);
}
}
| core/src/main/java/com/sequenceiq/cloudbreak/core/flow/service/SimpleStackFacade.java | package com.sequenceiq.cloudbreak.core.flow.service;
import static com.sequenceiq.cloudbreak.domain.BillingStatus.BILLING_STARTED;
import static com.sequenceiq.cloudbreak.domain.BillingStatus.BILLING_STOPPED;
import static com.sequenceiq.cloudbreak.domain.Status.AVAILABLE;
import static com.sequenceiq.cloudbreak.domain.Status.CREATE_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.CREATE_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.DELETE_COMPLETED;
import static com.sequenceiq.cloudbreak.domain.Status.DELETE_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.DELETE_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.START_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.START_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.STOPPED;
import static com.sequenceiq.cloudbreak.domain.Status.STOP_FAILED;
import static com.sequenceiq.cloudbreak.domain.Status.STOP_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.domain.Status.STOP_REQUESTED;
import static com.sequenceiq.cloudbreak.domain.Status.UPDATE_IN_PROGRESS;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.sequenceiq.cloudbreak.controller.json.HostGroupAdjustmentJson;
import com.sequenceiq.cloudbreak.core.CloudbreakException;
import com.sequenceiq.cloudbreak.core.bootstrap.service.ClusterBootstrapper;
import com.sequenceiq.cloudbreak.core.flow.context.ClusterScalingContext;
import com.sequenceiq.cloudbreak.core.flow.context.DefaultFlowContext;
import com.sequenceiq.cloudbreak.core.flow.context.FlowContext;
import com.sequenceiq.cloudbreak.core.flow.context.ProvisioningContext;
import com.sequenceiq.cloudbreak.core.flow.context.StackInstanceUpdateContext;
import com.sequenceiq.cloudbreak.core.flow.context.StackScalingContext;
import com.sequenceiq.cloudbreak.core.flow.context.StackStatusUpdateContext;
import com.sequenceiq.cloudbreak.core.flow.context.UpdateAllowedSubnetsContext;
import com.sequenceiq.cloudbreak.domain.BillingStatus;
import com.sequenceiq.cloudbreak.domain.CloudPlatform;
import com.sequenceiq.cloudbreak.domain.Cluster;
import com.sequenceiq.cloudbreak.domain.HostGroup;
import com.sequenceiq.cloudbreak.domain.HostMetadata;
import com.sequenceiq.cloudbreak.domain.InstanceGroupType;
import com.sequenceiq.cloudbreak.domain.OnFailureAction;
import com.sequenceiq.cloudbreak.domain.Resource;
import com.sequenceiq.cloudbreak.domain.SecurityGroup;
import com.sequenceiq.cloudbreak.domain.SecurityRule;
import com.sequenceiq.cloudbreak.domain.Stack;
import com.sequenceiq.cloudbreak.domain.Status;
import com.sequenceiq.cloudbreak.logger.MDCBuilder;
import com.sequenceiq.cloudbreak.repository.StackUpdater;
import com.sequenceiq.cloudbreak.service.TlsSecurityService;
import com.sequenceiq.cloudbreak.repository.SecurityRuleRepository;
import com.sequenceiq.cloudbreak.service.cluster.ClusterService;
import com.sequenceiq.cloudbreak.service.cluster.flow.EmailSenderService;
import com.sequenceiq.cloudbreak.service.events.CloudbreakEventService;
import com.sequenceiq.cloudbreak.service.hostgroup.HostGroupService;
import com.sequenceiq.cloudbreak.service.securitygroup.SecurityGroupService;
import com.sequenceiq.cloudbreak.service.stack.StackService;
import com.sequenceiq.cloudbreak.service.stack.connector.CloudPlatformConnector;
import com.sequenceiq.cloudbreak.service.stack.connector.UserDataBuilder;
import com.sequenceiq.cloudbreak.service.stack.event.ProvisionComplete;
import com.sequenceiq.cloudbreak.service.stack.flow.ConsulMetadataSetup;
import com.sequenceiq.cloudbreak.service.stack.flow.MetadataSetupService;
import com.sequenceiq.cloudbreak.service.stack.flow.ProvisioningService;
import com.sequenceiq.cloudbreak.service.stack.flow.StackScalingService;
import com.sequenceiq.cloudbreak.service.stack.flow.StackSyncService;
import com.sequenceiq.cloudbreak.service.stack.flow.TerminationService;
import com.sequenceiq.cloudbreak.service.stack.flow.TlsSetupService;
@Service
public class SimpleStackFacade implements StackFacade {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleStackFacade.class);
private static final String UPDATED_SUBNETS = "updated";
private static final String REMOVED_SUBNETS = "removed";
@Inject
private StackService stackService;
@javax.annotation.Resource
private Map<CloudPlatform, CloudPlatformConnector> cloudPlatformConnectors;
@Inject
private CloudbreakEventService cloudbreakEventService;
@Inject
private TerminationService terminationService;
@Inject
private StackStartService stackStartService;
@Inject
private StackStopService stackStopService;
@Inject
private StackScalingService stackScalingService;
@Inject
private MetadataSetupService metadataSetupService;
@Inject
private UserDataBuilder userDataBuilder;
@Inject
private HostGroupService hostGroupService;
@Inject
private ClusterBootstrapper clusterBootstrapper;
@Inject
private ConsulMetadataSetup consulMetadataSetup;
@Inject
private ProvisioningService provisioningService;
@Inject
private ClusterService clusterService;
@Inject
private StackUpdater stackUpdater;
@Inject
private SecurityRuleRepository securityRuleRepository;
@Inject
private EmailSenderService emailSenderService;
@Inject
private TlsSetupService tlsSetupService;
@Inject
private TlsSecurityService tlsSecurityService;
@Inject
private StackSyncService stackSyncService;
@Inject
private SecurityGroupService securityGroupService;
@Override
public FlowContext bootstrapCluster(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), UPDATE_IN_PROGRESS);
fireEventAndLog(actualContext.getStackId(), context, "Bootstrapping cluster on the infrastructure", UPDATE_IN_PROGRESS);
clusterBootstrapper.bootstrapCluster(actualContext);
} catch (Exception e) {
LOGGER.error("Error occurred while bootstrapping container orchestrator: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext setupConsulMetadata(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), UPDATE_IN_PROGRESS);
fireEventAndLog(actualContext.getStackId(), context, "Setting up metadata", UPDATE_IN_PROGRESS);
consulMetadataSetup.setupConsulMetadata(stack.getId());
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE);
} catch (Exception e) {
LOGGER.error("Exception during the consul metadata setup process.", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext start(FlowContext context) throws CloudbreakException {
StackStatusUpdateContext actualContext = (StackStatusUpdateContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), START_IN_PROGRESS, "Cluster infrastructure is now starting.");
context = stackStartService.start(actualContext);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Cluster infrastructure started successfully.");
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BILLING_STARTED.name(), "Cluster infrastructure started successfully.");
} catch (Exception e) {
LOGGER.error("Exception during the stack start process.", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext stop(FlowContext context) throws CloudbreakException {
StackStatusUpdateContext actualContext = (StackStatusUpdateContext) context;
try {
if (stackStopService.isStopPossible(actualContext)) {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), STOP_IN_PROGRESS, "Cluster infrastructure is now stopping.");
context = stackStopService.stop(actualContext);
stackUpdater.updateStackStatus(stack.getId(), STOPPED, "Cluster infrastructure stopped successfully.");
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BILLING_STOPPED.name(), "Cluster infrastructure stopped successfully.");
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendStopSuccessEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", STOPPED);
}
}
} catch (Exception e) {
LOGGER.error("Exception during the stack stop process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext terminateStack(FlowContext context) throws CloudbreakException {
DefaultFlowContext actualContext = (DefaultFlowContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(actualContext.getStackId(), DELETE_IN_PROGRESS, "Terminating the cluster and its infrastructure.");
if (stack != null && stack.getCredential() != null) {
terminationService.terminateStack(stack.getId(), actualContext.getCloudPlatform());
}
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BillingStatus.BILLING_STOPPED.name(),
"Billing stopped, the cluster and its infrastructure have been terminated.");
stackUpdater.updateStackStatus(actualContext.getStackId(), DELETE_COMPLETED,
"The cluster and its infrastructure have successfully been terminated.");
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendTerminationSuccessEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", DELETE_COMPLETED);
}
terminationService.finalizeTermination(stack.getId());
clusterService.updateClusterStatusByStackId(stack.getId(), DELETE_COMPLETED);
} catch (Exception e) {
LOGGER.error("Exception during the stack termination process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext addInstances(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
String statusReason = String.format("Add %s new instance(s) to the infrastructure.", actualContext.getScalingAdjustment());
stackUpdater.updateStackStatus(actualContext.getStackId(), UPDATE_IN_PROGRESS, statusReason);
Set<Resource> resources = stackScalingService.addInstances(stack.getId(), actualContext.getInstanceGroup(), actualContext.getScalingAdjustment());
context = new StackScalingContext(stack.getId(), actualContext.getCloudPlatform(), actualContext.getScalingAdjustment(),
actualContext.getInstanceGroup(), resources, actualContext.getScalingType(), null);
} catch (Exception e) {
LOGGER.error("Exception during the upscaling of stack: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext removeInstance(FlowContext context) throws CloudbreakException {
StackInstanceUpdateContext actualContext = (StackInstanceUpdateContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
if (!stack.isDeleteInProgress()) {
stackScalingService.removeInstance(actualContext.getStackId(), actualContext.getInstanceId());
}
} catch (Exception e) {
LOGGER.error("Exception during the removing instance from the stack: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext extendMetadata(FlowContext context) throws CloudbreakException {
StackScalingContext actualCont = (StackScalingContext) context;
Stack stack = stackService.getById(actualCont.getStackId());
Cluster cluster = clusterService.retrieveClusterByStackId(stack.getId());
MDCBuilder.buildMdcContext(stack);
fireEventAndLog(actualCont.getStackId(), context, "Extending metadata with new instances.", UPDATE_IN_PROGRESS);
Set<String> upscaleCandidateAddresses = metadataSetupService.setupNewMetadata(stack.getId(), actualCont.getResources(), actualCont.getInstanceGroup());
HostGroupAdjustmentJson hostGroupAdjustmentJson = new HostGroupAdjustmentJson();
hostGroupAdjustmentJson.setWithStackUpdate(false);
hostGroupAdjustmentJson.setScalingAdjustment(actualCont.getScalingAdjustment());
if (stack.getCluster() != null) {
HostGroup hostGroup = hostGroupService.getByClusterIdAndInstanceGroupName(cluster.getId(), actualCont.getInstanceGroup());
hostGroupAdjustmentJson.setHostGroup(hostGroup.getName());
}
return new StackScalingContext(stack.getId(), actualCont.getCloudPlatform(), actualCont.getScalingAdjustment(), actualCont.getInstanceGroup(),
actualCont.getResources(), actualCont.getScalingType(), upscaleCandidateAddresses);
}
@Override
public FlowContext bootstrapNewNodes(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
fireEventAndLog(actualContext.getStackId(), context, "Bootstrapping new node(s).", UPDATE_IN_PROGRESS);
clusterBootstrapper.bootstrapNewNodes(actualContext);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Bootstrapping has been finished successfully.");
} catch (Exception e) {
LOGGER.error("Exception during the handling of munchausen setup: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext extendConsulMetadata(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
Cluster cluster = clusterService.retrieveClusterByStackId(stack.getId());
MDCBuilder.buildMdcContext(stack);
consulMetadataSetup.setupNewConsulMetadata(stack.getId(), actualContext.getUpscaleCandidateAddresses());
HostGroupAdjustmentJson hostGroupAdjustmentJson = new HostGroupAdjustmentJson();
hostGroupAdjustmentJson.setWithStackUpdate(false);
hostGroupAdjustmentJson.setScalingAdjustment(actualContext.getScalingAdjustment());
if (cluster != null) {
HostGroup hostGroup = hostGroupService.getByClusterIdAndInstanceGroupName(cluster.getId(), actualContext.getInstanceGroup());
hostGroupAdjustmentJson.setHostGroup(hostGroup.getName());
}
context = new ClusterScalingContext(stack.getId(), actualContext.getCloudPlatform(),
hostGroupAdjustmentJson, actualContext.getUpscaleCandidateAddresses(), new ArrayList<HostMetadata>(), actualContext.getScalingType());
} catch (Exception e) {
LOGGER.error("Exception during the extend consul metadata phase: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext downscaleStack(FlowContext context) throws CloudbreakException {
StackScalingContext actualContext = (StackScalingContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
String statusMessage = "Removing '%s' instance(s) from the cluster infrastructure.";
stackUpdater.updateStackStatus(stack.getId(), UPDATE_IN_PROGRESS);
cloudbreakEventService
.fireCloudbreakEvent(stack.getId(), UPDATE_IN_PROGRESS.name(), String.format(statusMessage, actualContext.getScalingAdjustment()));
stackScalingService.downscaleStack(stack.getId(), actualContext.getInstanceGroup(), actualContext.getScalingAdjustment());
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Downscale of the cluster infrastructure finished successfully.");
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendDownScaleSuccessEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", AVAILABLE);
}
} catch (Exception e) {
LOGGER.error("Exception during the downscaling of stack: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext stopRequested(FlowContext context) throws CloudbreakException {
StackStatusUpdateContext actualContext = (StackStatusUpdateContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), STOP_REQUESTED, "Stopping of cluster infrastructure has been requested.");
} catch (Exception e) {
LOGGER.error("Exception during the stack stop requested process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext provision(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
Date startDate = new Date();
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), CREATE_IN_PROGRESS, "Creating infrastructure");
ProvisionComplete provisionResult = provisioningService.buildStack(actualContext.getCloudPlatform(), stack, actualContext.getSetupProperties());
Date endDate = new Date();
long seconds = (endDate.getTime() - startDate.getTime()) / DateUtils.MILLIS_PER_SECOND;
fireEventAndLog(stack.getId(), context, String.format("The creation of infrastructure took %s seconds.", seconds), AVAILABLE);
context = new ProvisioningContext.Builder()
.setDefaultParams(provisionResult.getStackId(), provisionResult.getCloudPlatform())
.setProvisionSetupProperties(actualContext.getSetupProperties())
.setProvisionedResources(provisionResult.getResources())
.build();
return context;
}
@Override
public FlowContext setupTls(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
tlsSetupService.setupTls(actualContext.getCloudPlatform(), stack, actualContext.getSetupProperties());
return actualContext;
}
@Override
public FlowContext sync(FlowContext context) throws CloudbreakException {
DefaultFlowContext actualContext = (DefaultFlowContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
if (!stack.isDeleteInProgress()) {
stackSyncService.sync(stack.getId());
}
} catch (Exception e) {
LOGGER.error("Exception during the stack sync process: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext updateAllowedSubnets(FlowContext context) throws CloudbreakException {
UpdateAllowedSubnetsContext actualContext = (UpdateAllowedSubnetsContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), UPDATE_IN_PROGRESS, "Updating allowed subnets.");
CloudPlatformConnector connector = cloudPlatformConnectors.get(stack.cloudPlatform());
Map<InstanceGroupType, String> userdata = userDataBuilder.buildUserData(stack.cloudPlatform(),
tlsSecurityService.readPublicSshKey(stack.getId()), connector.getSSHUser());
Map<String, Set<SecurityRule>> modifiedSubnets = getModifiedSubnetList(stack, actualContext.getAllowedSecurityRules());
Set<SecurityRule> newSecurityRules = modifiedSubnets.get(UPDATED_SUBNETS);
stack.getSecurityGroup().setSecurityRules(newSecurityRules);
cloudPlatformConnectors.get(stack.cloudPlatform()).updateAllowedSubnets(stack,
userdata.get(InstanceGroupType.GATEWAY), userdata.get(InstanceGroupType.CORE));
securityRuleRepository.delete(modifiedSubnets.get(REMOVED_SUBNETS));
securityRuleRepository.save(newSecurityRules);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Updating of allowed subnets successfully finished.");
} catch (Exception e) {
Stack stack = stackService.getById(actualContext.getStackId());
SecurityGroup securityGroup = stack.getSecurityGroup();
String msg = String.format("Failed to update security group with allowed subnets: %s", securityGroup);
if (stack != null && stack.isStackInDeletionPhase()) {
msg = String.format("Failed to update security group with allowed subnets: %s; stack is already in deletion phase.",
securityGroup);
}
LOGGER.error(msg, e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext handleUpdateAllowedSubnetsFailure(FlowContext context) throws CloudbreakException {
UpdateAllowedSubnetsContext actualContext = (UpdateAllowedSubnetsContext) context;
try {
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, String.format("Stack update failed. %s", actualContext.getErrorReason()));
} catch (Exception e) {
LOGGER.error("Exception during the handling of update allowed subnet failure: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext handleScalingFailure(FlowContext context) throws CloudbreakException {
try {
Long id = null;
String errorReason = null;
if (context instanceof StackScalingContext) {
StackScalingContext actualContext = (StackScalingContext) context;
id = actualContext.getStackId();
errorReason = actualContext.getErrorReason();
} else if (context instanceof ClusterScalingContext) {
ClusterScalingContext actualContext = (ClusterScalingContext) context;
id = actualContext.getStackId();
errorReason = actualContext.getErrorReason();
}
if (id != null) {
Stack stack = stackService.getById(id);
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), AVAILABLE, "Stack update failed. " + errorReason);
}
} catch (Exception e) {
LOGGER.error("Exception during the handling of stack scaling failure: {}", e.getMessage());
throw new CloudbreakException(e);
}
return context;
}
@Override
public FlowContext handleCreationFailure(FlowContext context) throws CloudbreakException {
ProvisioningContext actualContext = (ProvisioningContext) context;
final Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
try {
fireEventAndLog(actualContext.getStackId(), context, "Creation of infrastructure failed.", UPDATE_IN_PROGRESS);
if (!stack.isStackInDeletionPhase()) {
final CloudPlatform cloudPlatform = actualContext.getCloudPlatform();
if (!stack.getOnFailureActionAction().equals(OnFailureAction.ROLLBACK)) {
LOGGER.debug("Nothing to do. OnFailureAction {}", stack.getOnFailureActionAction());
} else {
stackUpdater.updateStackStatus(stack.getId(), UPDATE_IN_PROGRESS);
cloudPlatformConnectors.get(cloudPlatform).rollback(stack, stack.getResources());
cloudbreakEventService.fireCloudbreakEvent(stack.getId(), BILLING_STOPPED.name(), "Stack creation failed.");
}
stackUpdater.updateStackStatus(stack.getId(), CREATE_FAILED, actualContext.getErrorReason());
}
context = new ProvisioningContext.Builder().setDefaultParams(stack.getId(), stack.cloudPlatform()).build();
} catch (Exception ex) {
LOGGER.error("Stack rollback failed on stack id : {}. Exception:", stack.getId(), ex);
stackUpdater.updateStackStatus(stack.getId(), CREATE_FAILED, String.format("Rollback failed: %s", ex.getMessage()));
throw new CloudbreakException(String.format("Stack rollback failed on {} stack: ", stack.getId(), ex));
}
return context;
}
@Override
public FlowContext handleTerminationFailure(FlowContext context) throws CloudbreakException {
DefaultFlowContext actualContext = (DefaultFlowContext) context;
Stack stack = stackService.getById(actualContext.getStackId());
MDCBuilder.buildMdcContext(stack);
stackUpdater.updateStackStatus(stack.getId(), DELETE_FAILED, "Termination failed: " + actualContext.getErrorReason());
if (stack.getCluster() != null && stack.getCluster().getEmailNeeded()) {
emailSenderService.sendTerminationFailureEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(actualContext.getStackId(), context, "Notification email has been sent about state of the cluster.", DELETE_FAILED);
}
return context;
}
@Override
public FlowContext handleStatusUpdateFailure(FlowContext flowContext) throws CloudbreakException {
StackStatusUpdateContext context = (StackStatusUpdateContext) flowContext;
Stack stack = stackService.getById(context.getStackId());
MDCBuilder.buildMdcContext(stack);
if (context.isStart()) {
stackUpdater.updateStackStatus(context.getStackId(), START_FAILED, "Start failed: " + context.getErrorReason());
if (stack.getCluster() != null) {
clusterService.updateClusterStatusByStackId(context.getStackId(), STOPPED);
if (stack.getCluster().getEmailNeeded()) {
emailSenderService.sendStartFailureEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(context.getStackId(), context, "Notification email has been sent about state of the cluster.", START_FAILED);
}
}
} else {
stackUpdater.updateStackStatus(context.getStackId(), STOP_FAILED, "Stop failed: " + context.getErrorReason());
if (stack.getCluster() != null) {
clusterService.updateClusterStatusByStackId(context.getStackId(), STOPPED);
if (stack.getCluster().getEmailNeeded()) {
emailSenderService.sendStopFailureEmail(stack.getCluster().getOwner(), stack.getAmbariIp());
fireEventAndLog(context.getStackId(), context, "Notification email has been sent about state of the cluster.", STOP_FAILED);
}
}
}
return context;
}
private Map<String, Set<SecurityRule>> getModifiedSubnetList(Stack stack, List<SecurityRule> securityRuleList) {
Map<String, Set<SecurityRule>> result = new HashMap<>();
Set<SecurityRule> removed = new HashSet<>();
Set<SecurityRule> updated = new HashSet<>();
Long securityGroupId = stack.getSecurityGroup().getId();
Set<SecurityRule> securityRules = securityGroupService.get(securityGroupId).getSecurityRules();
for (SecurityRule securityRule : securityRules) {
if (!securityRule.isModifiable()) {
updated.add(securityRule);
removeFromNewSubnetList(securityRule, securityRuleList);
} else {
removed.add(securityRule);
}
}
for (SecurityRule securityRule : securityRuleList) {
updated.add(securityRule);
}
result.put(UPDATED_SUBNETS, updated);
result.put(REMOVED_SUBNETS, removed);
return result;
}
private void removeFromNewSubnetList(SecurityRule securityRule, List<SecurityRule> securityRuleList) {
Iterator<SecurityRule> iterator = securityRuleList.iterator();
String cidr = securityRule.getCidr();
while (iterator.hasNext()) {
SecurityRule next = iterator.next();
if (next.getCidr().equals(cidr)) {
iterator.remove();
}
}
}
private void fireEventAndLog(Long stackId, FlowContext context, String eventMessage, Status eventType) {
LOGGER.debug("{} [STACK_FLOW_STEP]. Context: {}", eventMessage, context);
cloudbreakEventService.fireCloudbreakEvent(stackId, eventType.name(), eventMessage);
}
}
| CLOUD-938: moving stack status update to AVAILABLE from bootstrapNewNodes to extendConsulMetadata
| core/src/main/java/com/sequenceiq/cloudbreak/core/flow/service/SimpleStackFacade.java | CLOUD-938: moving stack status update to AVAILABLE from bootstrapNewNodes to extendConsulMetadata |
|
Java | apache-2.0 | 5f1fe3ac4c29e94dee7d0de9ef3b7607dd749b76 | 0 | serge-rider/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver | /*
* Copyright (C) 2010-2014 Serge Rieder
* [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jkiss.dbeaver.ext.erd.editor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.draw2d.*;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.*;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.gef.editparts.ScalableFreeformRootEditPart;
import org.eclipse.gef.editparts.ZoomManager;
import org.eclipse.gef.palette.*;
import org.eclipse.gef.requests.CreationFactory;
import org.eclipse.gef.ui.actions.*;
import org.eclipse.gef.ui.palette.FlyoutPaletteComposite.FlyoutPreferences;
import org.eclipse.gef.ui.palette.PaletteViewerProvider;
import org.eclipse.gef.ui.parts.GraphicalEditorWithFlyoutPalette;
import org.eclipse.gef.ui.parts.GraphicalViewerKeyHandler;
import org.eclipse.gef.ui.properties.UndoablePropertySheetEntry;
import org.eclipse.jface.action.*;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.*;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.model.WorkbenchAdapter;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.jkiss.dbeaver.ext.erd.Activator;
import org.jkiss.dbeaver.ext.erd.ERDConstants;
import org.jkiss.dbeaver.ext.erd.action.DiagramLayoutAction;
import org.jkiss.dbeaver.ext.erd.action.DiagramRefreshAction;
import org.jkiss.dbeaver.ext.erd.action.DiagramToggleGridAction;
import org.jkiss.dbeaver.ext.erd.action.ERDEditorPropertyTester;
import org.jkiss.dbeaver.ext.erd.directedit.StatusLineValidationMessageHandler;
import org.jkiss.dbeaver.ext.erd.dnd.DataEditDropTargetListener;
import org.jkiss.dbeaver.ext.erd.dnd.NodeDropTargetListener;
import org.jkiss.dbeaver.ext.erd.model.ERDNote;
import org.jkiss.dbeaver.ext.erd.model.EntityDiagram;
import org.jkiss.dbeaver.ext.erd.part.DiagramPart;
import org.jkiss.dbeaver.ext.ui.IRefreshablePart;
import org.jkiss.dbeaver.ext.ui.ISearchContextProvider;
import org.jkiss.dbeaver.ext.ui.ISearchExecutor;
import org.jkiss.dbeaver.model.DBPDataSourceUser;
import org.jkiss.dbeaver.model.DBPNamedObject;
import org.jkiss.dbeaver.runtime.RuntimeUtils;
import org.jkiss.dbeaver.runtime.load.jobs.LoadingJob;
import org.jkiss.dbeaver.ui.ActionUtils;
import org.jkiss.dbeaver.ui.DBIcon;
import org.jkiss.dbeaver.ui.ImageUtils;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.ProgressPageControl;
import org.jkiss.dbeaver.ui.controls.itemlist.ObjectSearcher;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.utils.CommonUtils;
import java.io.FileOutputStream;
import java.util.*;
/**
* Editor implementation based on the the example editor skeleton that is built in <i>Building
* an editor </i> in chapter <i>Introduction to GEF </i>
*/
public abstract class ERDEditorPart extends GraphicalEditorWithFlyoutPalette
implements DBPDataSourceUser, ISearchContextProvider, IRefreshablePart
{
static final Log log = LogFactory.getLog(ERDEditorPart.class);
protected ProgressControl progressControl;
/**
* the undoable <code>IPropertySheetPage</code>
*/
private PropertySheetPage undoablePropertySheetPage;
/**
* the graphical viewer
*/
private ScalableFreeformRootEditPart rootPart;
/**
* the list of action ids that are to EditPart actions
*/
private List<String> editPartActionIDs = new ArrayList<String>();
/**
* the overview outline page
*/
private ERDOutlinePage outlinePage;
/**
* the <code>EditDomain</code>
*/
private DefaultEditDomain editDomain;
/**
* the dirty state
*/
private boolean isDirty;
private boolean isLoaded;
protected LoadingJob<EntityDiagram> diagramLoadingJob;
private IPropertyChangeListener configPropertyListener;
private PaletteRoot paletteRoot;
/**
* No-arg constructor
*/
protected ERDEditorPart()
{
}
/**
* Initializes the editor.
*/
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException
{
editDomain = new DefaultEditDomain(this);
setEditDomain(editDomain);
super.init(site, input);
// add selection change listener
//getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this);
configPropertyListener = new ConfigPropertyListener();
Activator.getDefault().getPreferenceStore().addPropertyChangeListener(configPropertyListener);
}
@Override
public void createPartControl(Composite parent)
{
progressControl = new ProgressControl(parent, SWT.NONE);
super.createPartControl(progressControl.createContentContainer());
progressControl.createProgressPanel();
}
/**
* The <code>CommandStackListener</code> that listens for
* <code>CommandStack </code> changes.
*/
@Override
public void commandStackChanged(EventObject event)
{
// Reevaluate properties
ActionUtils.evaluatePropertyState(ERDEditorPropertyTester.NAMESPACE + "." + ERDEditorPropertyTester.PROP_CAN_UNDO);
ActionUtils.evaluatePropertyState(ERDEditorPropertyTester.NAMESPACE + "." + ERDEditorPropertyTester.PROP_CAN_REDO);
// Update actions
setDirty(getCommandStack().isDirty());
super.commandStackChanged(event);
}
@Override
public void dispose()
{
Activator.getDefault().getPreferenceStore().removePropertyChangeListener(configPropertyListener);
if (diagramLoadingJob != null) {
diagramLoadingJob.cancel();
diagramLoadingJob = null;
}
// remove selection listener
//getSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
// dispose the ActionRegistry (will dispose all actions)
getActionRegistry().dispose();
// important: always call super implementation of dispose
super.dispose();
}
/**
* Adaptable implementation for Editor
*/
@Override
public Object getAdapter(Class adapter)
{
// we need to handle common GEF elements we created
if (adapter == GraphicalViewer.class || adapter == EditPartViewer.class) {
return getGraphicalViewer();
} else if (adapter == CommandStack.class) {
return getCommandStack();
} else if (adapter == EditDomain.class) {
return getEditDomain();
} else if (adapter == ActionRegistry.class) {
return getActionRegistry();
} else if (adapter == IPropertySheetPage.class) {
return getPropertySheetPage();
} else if (adapter == IContentOutlinePage.class) {
return getOverviewOutlinePage();
} else if (adapter == ZoomManager.class) {
return getGraphicalViewer().getProperty(ZoomManager.class.toString());
} else if (IWorkbenchAdapter.class.equals(adapter)) {
return new WorkbenchAdapter() {
@Override
public String getLabel(Object o)
{
return "ERD Editor";
}
};
}
// the super implementation handles the rest
return super.getAdapter(adapter);
}
@Override
public void doSave(IProgressMonitor monitor)
{
}
/**
* Save as not allowed
*/
@Override
public void doSaveAs()
{
saveDiagramAsImage();
}
/**
* Save as not allowed
*/
@Override
public boolean isSaveAsAllowed()
{
return true;
}
/**
* Indicates if the editor has unsaved changes.
*
* @see org.eclipse.ui.part.EditorPart#isDirty
*/
@Override
public boolean isDirty()
{
return !isReadOnly() && isDirty;
}
public abstract boolean isReadOnly();
/**
* Returns the <code>CommandStack</code> of this editor's
* <code>EditDomain</code>.
*
* @return the <code>CommandStack</code>
*/
@Override
public CommandStack getCommandStack()
{
return getEditDomain().getCommandStack();
}
/**
* Returns the schema model associated with the editor
*
* @return an instance of <code>Schema</code>
*/
public EntityDiagram getDiagram()
{
return getDiagramPart().getDiagram();
}
public DiagramPart getDiagramPart()
{
return rootPart == null ? null : (DiagramPart) rootPart.getContents();
}
/**
* @see org.eclipse.ui.part.EditorPart#setInput(org.eclipse.ui.IEditorInput)
*/
@Override
protected void setInput(IEditorInput input)
{
super.setInput(input);
}
/**
* Creates a PaletteViewerProvider that will be used to create palettes for
* the view and the flyout.
*
* @return the palette provider
*/
@Override
protected PaletteViewerProvider createPaletteViewerProvider()
{
return new ERDPaletteViewerProvider(editDomain);
}
public GraphicalViewer getViewer()
{
return super.getGraphicalViewer();
}
/**
* Creates a new <code>GraphicalViewer</code>, configures, registers and
* initializes it.
*
* @param parent the parent composite
*/
@Override
protected void createGraphicalViewer(Composite parent)
{
GraphicalViewer viewer = createViewer(parent);
// hook the viewer into the EditDomain
setGraphicalViewer(viewer);
configureGraphicalViewer();
hookGraphicalViewer();
initializeGraphicalViewer();
// Set initial (empty) contents
viewer.setContents(new EntityDiagram(null, "empty"));
// Set context menu
ContextMenuProvider provider = new ERDEditorContextMenuProvider(this);
viewer.setContextMenu(provider);
getSite().registerContextMenu(ERDEditorPart.class.getName() + ".EditorContext", provider, viewer);
}
private GraphicalViewer createViewer(Composite parent)
{
StatusLineValidationMessageHandler validationMessageHandler = new StatusLineValidationMessageHandler(getEditorSite());
GraphicalViewer viewer = new ERDGraphicalViewer(this, validationMessageHandler);
viewer.createControl(parent);
// configure the viewer
viewer.getControl().setBackground(ColorConstants.white);
rootPart = new ScalableFreeformRootEditPart();
viewer.setRootEditPart(rootPart);
viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer));
viewer.addDropTargetListener(new DataEditDropTargetListener(viewer));
viewer.addDropTargetListener(new NodeDropTargetListener(viewer));
// initialize the viewer with input
viewer.setEditPartFactory(new ERDEditPartFactory());
return viewer;
}
@Override
protected void configureGraphicalViewer()
{
super.configureGraphicalViewer();
GraphicalViewer graphicalViewer = getGraphicalViewer();
/*
MenuManager manager = new MenuManager(getClass().getName(), getClass().getName());
manager.setRemoveAllWhenShown(true);
getEditorSite().registerContextMenu(getClass().getName() + ".EditorContext", manager, graphicalViewer, true); //$NON-NLS-1$
*/
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_ENABLED, store.getBoolean(ERDConstants.PREF_GRID_ENABLED));
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_VISIBLE, store.getBoolean(ERDConstants.PREF_GRID_ENABLED));
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_SPACING, new Dimension(
store.getInt(ERDConstants.PREF_GRID_WIDTH),
store.getInt(ERDConstants.PREF_GRID_HEIGHT)));
// initialize actions
createActions();
// Setup zoom manager
ZoomManager zoomManager = rootPart.getZoomManager();
List<String> zoomLevels = new ArrayList<String>(3);
zoomLevels.add(ZoomManager.FIT_ALL);
zoomLevels.add(ZoomManager.FIT_WIDTH);
zoomLevels.add(ZoomManager.FIT_HEIGHT);
zoomManager.setZoomLevelContributions(zoomLevels);
zoomManager.setZoomLevels(
new double[]{.1, .25, .5, .75, 1.0, 1.5, 2.0, 2.5, 3, 4}
);
IAction zoomIn = new ZoomInAction(zoomManager);
IAction zoomOut = new ZoomOutAction(zoomManager);
addAction(zoomIn);
addAction(zoomOut);
graphicalViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event)
{
String status;
IStructuredSelection selection = (IStructuredSelection)event.getSelection();
if (selection.isEmpty()) {
status = "";
} else if (selection.size() == 1) {
status = CommonUtils.toString(selection.getFirstElement());
} else {
status = String.valueOf(selection.size()) + " objects";
}
progressControl.setInfo(status);
updateActions(editPartActionIDs);
}
});
}
/**
* Sets the dirty state of this editor.
* <p/>
* <p/>
* An event will be fired immediately if the new state is different than the
* current one.
*
* @param dirty the new dirty state to set
*/
protected void setDirty(boolean dirty)
{
if (isDirty != dirty) {
isDirty = dirty;
firePropertyChange(IEditorPart.PROP_DIRTY);
}
}
/**
* Adds an action to this editor's <code>ActionRegistry</code>. (This is
* a helper method.)
*
* @param action the action to add.
*/
protected void addAction(IAction action)
{
getActionRegistry().registerAction(action);
UIUtils.registerKeyBinding(getSite(), action);
}
/**
* Updates the specified actions.
*
* @param actionIds the list of ids of actions to update
*/
@Override
protected void updateActions(List actionIds)
{
for (Iterator<?> ids = actionIds.iterator(); ids.hasNext();) {
IAction action = getActionRegistry().getAction(ids.next());
if (null != action && action instanceof UpdateAction) {
((UpdateAction) action).update();
}
}
}
/**
* Returns the overview for the outline view.
*
* @return the overview
*/
protected ERDOutlinePage getOverviewOutlinePage()
{
if (null == outlinePage && null != getGraphicalViewer()) {
RootEditPart rootEditPart = getGraphicalViewer().getRootEditPart();
if (rootEditPart instanceof ScalableFreeformRootEditPart) {
outlinePage = new ERDOutlinePage((ScalableFreeformRootEditPart) rootEditPart);
}
}
return outlinePage;
}
/**
* Returns the undoable <code>PropertySheetPage</code> for this editor.
*
* @return the undoable <code>PropertySheetPage</code>
*/
protected PropertySheetPage getPropertySheetPage()
{
if (null == undoablePropertySheetPage) {
undoablePropertySheetPage = new PropertySheetPage();
undoablePropertySheetPage.setRootEntry(new UndoablePropertySheetEntry(getCommandStack()));
}
return undoablePropertySheetPage;
}
/**
* @return the preferences for the Palette Flyout
*/
@Override
protected FlyoutPreferences getPalettePreferences()
{
return new ERDPalettePreferences();
}
/**
* @return the PaletteRoot to be used with the PaletteViewer
*/
@Override
protected PaletteRoot getPaletteRoot()
{
if (paletteRoot == null) {
paletteRoot = createPaletteRoot();
}
return paletteRoot;
}
public PaletteRoot createPaletteRoot()
{
// create root
PaletteRoot paletteRoot = new PaletteRoot();
paletteRoot.setLabel("Entity Diagram");
{
// a group of default control tools
PaletteDrawer controls = new PaletteDrawer("Tools", DBIcon.CONFIGURATION.getImageDescriptor());
paletteRoot.add(controls);
// the selection tool
ToolEntry selectionTool = new SelectionToolEntry();
controls.add(selectionTool);
// use selection tool as default entry
paletteRoot.setDefaultEntry(selectionTool);
// the marquee selection tool
controls.add(new MarqueeToolEntry());
if (!isReadOnly()) {
// separator
PaletteSeparator separator = new PaletteSeparator("tools");
separator.setUserModificationPermission(PaletteEntry.PERMISSION_NO_MODIFICATION);
controls.add(separator);
final ImageDescriptor connectImage = Activator.getImageDescriptor("icons/connect.png");
controls.add(new ConnectionCreationToolEntry("Connection", "Create Connection", null, connectImage, connectImage));
final ImageDescriptor noteImage = Activator.getImageDescriptor("icons/note.png");
controls.add(new CreationToolEntry(
"Note",
"Create Note",
new CreationFactory() {
@Override
public Object getNewObject()
{
return new ERDNote("Note");
}
@Override
public Object getObjectType()
{
return RequestConstants.REQ_CREATE;
}
},
noteImage,
noteImage));
}
}
/*
PaletteDrawer drawer = new PaletteDrawer("New Component",
Activator.getImageDescriptor("icons/connection.gif"));
List<CombinedTemplateCreationEntry> entries = new ArrayList<CombinedTemplateCreationEntry>();
CombinedTemplateCreationEntry tableEntry = new CombinedTemplateCreationEntry("New Table", "Create a new table",
ERDEntity.class, new DataElementFactory(ERDEntity.class),
Activator.getImageDescriptor("icons/table.gif"),
Activator.getImageDescriptor("icons/table.gif"));
CombinedTemplateCreationEntry columnEntry = new CombinedTemplateCreationEntry("New Column", "Add a new column",
ERDEntityAttribute.class, new DataElementFactory(ERDEntityAttribute.class),
Activator.getImageDescriptor("icons/column.gif"),
Activator.getImageDescriptor("icons/column.gif"));
entries.add(tableEntry);
entries.add(columnEntry);
drawer.addAll(entries);
paletteRoot.add(drawer);
*/
return paletteRoot;
}
public boolean isLoaded()
{
return isLoaded;
}
public void refreshDiagram()
{
if (isLoaded) {
loadDiagram();
}
}
@Override
public void refreshPart(Object source, boolean force)
{
refreshDiagram();
}
public void saveDiagramAsImage()
{
final Shell shell = getSite().getShell();
FileDialog saveDialog = new FileDialog(shell, SWT.SAVE);
saveDialog.setFilterExtensions(new String[]{"*.png", "*.gif", "*.jpg", "*.bmp"});
saveDialog.setFilterNames(new String[]{
"PNG format (*.png)",
"GIF format (*.gif)",
"JPEG format (*.jpg)",
"Bitmap format (*.bmp)"});
String filePath = ContentUtils.openFileDialog(saveDialog);
if (filePath == null || filePath.trim().length() == 0) {
return;
}
int imageType = SWT.IMAGE_BMP;
if (filePath.toLowerCase().endsWith(".jpg")) {
imageType = SWT.IMAGE_JPEG;
} else if (filePath.toLowerCase().endsWith(".png")) {
imageType = SWT.IMAGE_PNG;
} else if (filePath.toLowerCase().endsWith(".gif")) {
imageType = SWT.IMAGE_GIF;
}
IFigure figure = rootPart.getLayer(ScalableFreeformRootEditPart.PRINTABLE_LAYERS);
Rectangle contentBounds = figure instanceof FreeformLayeredPane ? ((FreeformLayeredPane) figure).getFreeformExtent() : figure.getBounds();
try {
FileOutputStream fos = new FileOutputStream(filePath);
try {
Rectangle r = figure.getBounds();
GC gc = null;
Graphics g = null;
try {
Image image = new Image(null, contentBounds.x * 2 + contentBounds.width, contentBounds.y * 2 + contentBounds.height);
try {
gc = new GC(image);
gc.setClipping(contentBounds.x, contentBounds.y, contentBounds.width, contentBounds.height);
g = new SWTGraphics(gc);
g.translate(r.x * -1, r.y * -1);
figure.paint(g);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[1];
if (imageType != SWT.IMAGE_JPEG) {
// Convert to 8bit color
imageLoader.data[0] = ImageUtils.makeWebImageData(image);
} else {
// Use maximum colors for JPEG
imageLoader.data[0] = image.getImageData();
}
imageLoader.save(fos, imageType);
} finally {
UIUtils.dispose(image);
}
} finally {
if (g != null) {
g.dispose();
}
UIUtils.dispose(gc);
}
fos.flush();
} finally {
ContentUtils.close(fos);
}
RuntimeUtils.launchProgram(filePath);
//UIUtils.showMessageBox(shell, "Save ERD", "Diagram has been exported to " + filePath, SWT.ICON_INFORMATION);
} catch (Exception e) {
UIUtils.showErrorDialog(getSite().getShell(), "Save ERD as image", null, e);
}
}
public MenuManager createAttributeVisibilityMenu()
{
MenuManager avMenu = new MenuManager("Show Attributes");
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.ALL));
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.KEYS));
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.PRIMARY));
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.NONE));
return avMenu;
}
public void printDiagram()
{
GraphicalViewer viewer = getGraphicalViewer();
PrintDialog dialog = new PrintDialog(viewer.getControl().getShell(), SWT.NULL);
PrinterData data = dialog.open();
if (data != null) {
IFigure rootFigure = rootPart.getLayer(ScalableFreeformRootEditPart.PRINTABLE_LAYERS);
//EntityDiagramFigure diagramFigure = findFigure(rootFigure, EntityDiagramFigure.class);
if (rootFigure != null) {
PrintFigureOperation printOp = new PrintFigureOperation(new Printer(data), rootFigure);
// Set print preferences
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
printOp.setPrintMode(store.getInt(ERDConstants.PREF_PRINT_PAGE_MODE));
printOp.setPrintMargin(new Insets(
store.getInt(ERDConstants.PREF_PRINT_MARGIN_TOP),
store.getInt(ERDConstants.PREF_PRINT_MARGIN_LEFT),
store.getInt(ERDConstants.PREF_PRINT_MARGIN_BOTTOM),
store.getInt(ERDConstants.PREF_PRINT_MARGIN_RIGHT)
));
// Run print
printOp.run("Print ER diagram");
}
}
//new PrintAction(this).run();
}
@Override
public boolean isSearchPossible()
{
return true;
}
@Override
public boolean isSearchEnabled()
{
return progressControl != null && progressControl.isSearchEnabled();
}
@Override
public boolean performSearch(SearchType searchType)
{
return progressControl != null && progressControl.performSearch(searchType);
}
protected abstract void loadDiagram();
private class ChangeAttributeVisibilityAction extends Action {
private final ERDAttributeVisibility visibility;
private ChangeAttributeVisibilityAction(ERDAttributeVisibility visibility)
{
super(visibility.getTitle(), IAction.AS_RADIO_BUTTON);
this.visibility = visibility;
}
@Override
public boolean isChecked()
{
return visibility == getDiagram().getAttributeVisibility();
}
@Override
public void run()
{
getDiagram().setAttributeVisibility(visibility);
refreshDiagram();
//this.setChecked(true);
}
}
private class ConfigPropertyListener implements IPropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent event)
{
GraphicalViewer graphicalViewer = getGraphicalViewer();
if (graphicalViewer == null) {
return;
}
if (ERDConstants.PREF_GRID_ENABLED.equals(event.getProperty())) {
Boolean enabled = (Boolean)event.getNewValue();
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_ENABLED, enabled);
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_VISIBLE, enabled);
} else if (ERDConstants.PREF_GRID_WIDTH.equals(event.getProperty()) || ERDConstants.PREF_GRID_HEIGHT.equals(event.getProperty())) {
final IPreferenceStore store = Activator.getDefault().getPreferenceStore();
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_SPACING, new Dimension(
store.getInt(ERDConstants.PREF_GRID_WIDTH),
store.getInt(ERDConstants.PREF_GRID_HEIGHT)));
}
}
}
protected class ProgressControl extends ProgressPageControl {
private Searcher searcher;
private ZoomComboContributionItem zoomCombo;
private ProgressControl(Composite parent, int style)
{
super(parent, style);
searcher = new Searcher();
}
@Override
protected boolean cancelProgress()
{
if (diagramLoadingJob != null) {
diagramLoadingJob.cancel();
return true;
}
return false;
}
public ProgressVisualizer<EntityDiagram> createLoadVisualizer()
{
getGraphicalControl().setBackground(ColorConstants.lightGray);
return new LoadVisualizer();
}
@Override
protected void fillCustomToolbar(ToolBarManager toolBarManager) {
ZoomManager zoomManager = rootPart.getZoomManager();
String[] zoomStrings = new String[]{
ZoomManager.FIT_ALL,
ZoomManager.FIT_HEIGHT,
ZoomManager.FIT_WIDTH
};
// Init zoom combo with dummy part service
// to prevent zoom disable on part change - as it is standalone zoom control, not global one
zoomCombo = new ZoomComboContributionItem(
new IPartService() {
@Override
public void addPartListener(IPartListener listener)
{
}
@Override
public void addPartListener(IPartListener2 listener)
{
}
@Override
public IWorkbenchPart getActivePart()
{
return ERDEditorPart.this;
}
@Override
public IWorkbenchPartReference getActivePartReference()
{
return null;
}
@Override
public void removePartListener(IPartListener listener)
{
}
@Override
public void removePartListener(IPartListener2 listener)
{
}
},
zoomStrings);
toolBarManager.add(zoomCombo);
//toolBarManager.add(new UndoAction(ERDEditorPart.this));
//toolBarManager.add(new RedoAction(ERDEditorPart.this));
//toolBarManager.add(new PrintAction(ERDEditorPart.this));
toolBarManager.add(new ZoomInAction(zoomManager));
toolBarManager.add(new ZoomOutAction(zoomManager));
toolBarManager.add(new Separator());
//toolBarManager.add(createAttributeVisibilityMenu());
toolBarManager.add(new DiagramLayoutAction(ERDEditorPart.this));
toolBarManager.add(new DiagramToggleGridAction());
toolBarManager.add(new DiagramRefreshAction(ERDEditorPart.this));
toolBarManager.add(new Separator());
{
toolBarManager.add(ActionUtils.makeCommandContribution(
getSite(),
IWorkbenchCommandConstants.FILE_SAVE_AS,
"Save diagram as image",
DBIcon.PICTURE_SAVE.getImageDescriptor()));
toolBarManager.add(ActionUtils.makeCommandContribution(
getSite(),
IWorkbenchCommandConstants.FILE_PRINT,
"Print Diagram",
PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT)));
}
{
Action configAction = new Action("Configuration") {
@Override
public void run()
{
UIUtils.showPreferencesFor(
getSite().getShell(),
ERDEditorPart.this,
ERDPreferencePage.PAGE_ID);
}
};
configAction.setImageDescriptor(DBIcon.CONFIGURATION.getImageDescriptor());
toolBarManager.add(configAction);
}
}
@Override
protected ISearchExecutor getSearchRunner()
{
return searcher;
}
private class LoadVisualizer extends ProgressVisualizer<EntityDiagram> {
@Override
public void visualizeLoading()
{
super.visualizeLoading();
}
@Override
public void completeLoading(EntityDiagram entityDiagram)
{
super.completeLoading(entityDiagram);
Control graphicalControl = getGraphicalControl();
if (graphicalControl == null) {
return;
}
graphicalControl.setBackground(ColorConstants.white);
isLoaded = true;
Control control = getGraphicalViewer().getControl();
if (control == null || control.isDisposed()) {
return;
}
if (entityDiagram != null) {
List<String> errorMessages = entityDiagram.getErrorMessages();
if (!errorMessages.isEmpty()) {
UIUtils.showErrorDialog(
control.getShell(),
"Diagram loading errors",
"Error(s) occurred during diagram loading. If these errors are recoverable then fix errors and then refresh/reopen diagram",
errorMessages);
}
setInfo(entityDiagram.getEntityCount() + " objects");
} else {
setInfo("Empty diagram due to error (see error log)");
}
getCommandStack().flush();
getGraphicalViewer().setContents(entityDiagram);
zoomCombo.setZoomManager(rootPart.getZoomManager());
//toolBarManager.getControl().setEnabled(true);
}
}
}
private class Searcher extends ObjectSearcher<DBPNamedObject> {
@Override
protected void setInfo(String message)
{
progressControl.setInfo(message);
}
@Override
protected Collection<DBPNamedObject> getContent()
{
return getDiagramPart().getChildren();
}
@Override
protected void selectObject(DBPNamedObject object)
{
if (object == null) {
getGraphicalViewer().deselectAll();
} else {
getGraphicalViewer().select((EditPart)object);
}
}
@Override
protected void updateObject(DBPNamedObject object)
{
}
@Override
protected void revealObject(DBPNamedObject object)
{
getGraphicalViewer().reveal((EditPart)object);
}
}
}
| plugins/org.jkiss.dbeaver.erd/src/org/jkiss/dbeaver/ext/erd/editor/ERDEditorPart.java | /*
* Copyright (C) 2010-2014 Serge Rieder
* [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jkiss.dbeaver.ext.erd.editor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.draw2d.*;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.*;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.gef.editparts.ScalableFreeformRootEditPart;
import org.eclipse.gef.editparts.ZoomManager;
import org.eclipse.gef.palette.*;
import org.eclipse.gef.requests.CreationFactory;
import org.eclipse.gef.ui.actions.*;
import org.eclipse.gef.ui.palette.FlyoutPaletteComposite.FlyoutPreferences;
import org.eclipse.gef.ui.palette.PaletteViewerProvider;
import org.eclipse.gef.ui.parts.GraphicalEditorWithFlyoutPalette;
import org.eclipse.gef.ui.parts.GraphicalViewerKeyHandler;
import org.eclipse.gef.ui.properties.UndoablePropertySheetEntry;
import org.eclipse.jface.action.*;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.*;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.model.WorkbenchAdapter;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.jkiss.dbeaver.ext.erd.Activator;
import org.jkiss.dbeaver.ext.erd.ERDConstants;
import org.jkiss.dbeaver.ext.erd.action.DiagramLayoutAction;
import org.jkiss.dbeaver.ext.erd.action.DiagramRefreshAction;
import org.jkiss.dbeaver.ext.erd.action.DiagramToggleGridAction;
import org.jkiss.dbeaver.ext.erd.action.ERDEditorPropertyTester;
import org.jkiss.dbeaver.ext.erd.directedit.StatusLineValidationMessageHandler;
import org.jkiss.dbeaver.ext.erd.dnd.DataEditDropTargetListener;
import org.jkiss.dbeaver.ext.erd.dnd.NodeDropTargetListener;
import org.jkiss.dbeaver.ext.erd.model.ERDNote;
import org.jkiss.dbeaver.ext.erd.model.EntityDiagram;
import org.jkiss.dbeaver.ext.erd.part.DiagramPart;
import org.jkiss.dbeaver.ext.ui.IRefreshablePart;
import org.jkiss.dbeaver.ext.ui.ISearchContextProvider;
import org.jkiss.dbeaver.ext.ui.ISearchExecutor;
import org.jkiss.dbeaver.model.DBPDataSourceUser;
import org.jkiss.dbeaver.model.DBPNamedObject;
import org.jkiss.dbeaver.runtime.RuntimeUtils;
import org.jkiss.dbeaver.runtime.load.jobs.LoadingJob;
import org.jkiss.dbeaver.ui.ActionUtils;
import org.jkiss.dbeaver.ui.DBIcon;
import org.jkiss.dbeaver.ui.ImageUtils;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.ProgressPageControl;
import org.jkiss.dbeaver.ui.controls.itemlist.ObjectSearcher;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.utils.CommonUtils;
import java.io.FileOutputStream;
import java.util.*;
/**
* Editor implementation based on the the example editor skeleton that is built in <i>Building
* an editor </i> in chapter <i>Introduction to GEF </i>
*/
public abstract class ERDEditorPart extends GraphicalEditorWithFlyoutPalette
implements DBPDataSourceUser, ISearchContextProvider, IRefreshablePart
{
static final Log log = LogFactory.getLog(ERDEditorPart.class);
protected ProgressControl progressControl;
/**
* the undoable <code>IPropertySheetPage</code>
*/
private PropertySheetPage undoablePropertySheetPage;
/**
* the graphical viewer
*/
private ScalableFreeformRootEditPart rootPart;
/**
* the list of action ids that are to EditPart actions
*/
private List<String> editPartActionIDs = new ArrayList<String>();
/**
* the overview outline page
*/
private ERDOutlinePage outlinePage;
/**
* the <code>EditDomain</code>
*/
private DefaultEditDomain editDomain;
/**
* the dirty state
*/
private boolean isDirty;
private boolean isLoaded;
protected LoadingJob<EntityDiagram> diagramLoadingJob;
private IPropertyChangeListener configPropertyListener;
private PaletteRoot paletteRoot;
/**
* No-arg constructor
*/
protected ERDEditorPart()
{
}
/**
* Initializes the editor.
*/
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException
{
editDomain = new DefaultEditDomain(this);
setEditDomain(editDomain);
super.init(site, input);
// add selection change listener
//getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this);
configPropertyListener = new ConfigPropertyListener();
Activator.getDefault().getPreferenceStore().addPropertyChangeListener(configPropertyListener);
}
@Override
public void createPartControl(Composite parent)
{
progressControl = new ProgressControl(parent, SWT.NONE);
super.createPartControl(progressControl.createContentContainer());
progressControl.createProgressPanel();
}
/**
* The <code>CommandStackListener</code> that listens for
* <code>CommandStack </code> changes.
*/
@Override
public void commandStackChanged(EventObject event)
{
// Reevaluate properties
ActionUtils.evaluatePropertyState(ERDEditorPropertyTester.NAMESPACE + "." + ERDEditorPropertyTester.PROP_CAN_UNDO);
ActionUtils.evaluatePropertyState(ERDEditorPropertyTester.NAMESPACE + "." + ERDEditorPropertyTester.PROP_CAN_REDO);
// Update actions
setDirty(getCommandStack().isDirty());
super.commandStackChanged(event);
}
@Override
public void dispose()
{
Activator.getDefault().getPreferenceStore().removePropertyChangeListener(configPropertyListener);
if (diagramLoadingJob != null) {
diagramLoadingJob.cancel();
diagramLoadingJob = null;
}
// remove selection listener
//getSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
// dispose the ActionRegistry (will dispose all actions)
getActionRegistry().dispose();
// important: always call super implementation of dispose
super.dispose();
}
/**
* Adaptable implementation for Editor
*/
@Override
public Object getAdapter(Class adapter)
{
// we need to handle common GEF elements we created
if (adapter == GraphicalViewer.class || adapter == EditPartViewer.class) {
return getGraphicalViewer();
} else if (adapter == CommandStack.class) {
return getCommandStack();
} else if (adapter == EditDomain.class) {
return getEditDomain();
} else if (adapter == ActionRegistry.class) {
return getActionRegistry();
} else if (adapter == IPropertySheetPage.class) {
return getPropertySheetPage();
} else if (adapter == IContentOutlinePage.class) {
return getOverviewOutlinePage();
} else if (adapter == ZoomManager.class) {
return getGraphicalViewer().getProperty(ZoomManager.class.toString());
} else if (IWorkbenchAdapter.class.equals(adapter)) {
return new WorkbenchAdapter() {
@Override
public String getLabel(Object o)
{
return "ERD Editor";
}
};
}
// the super implementation handles the rest
return super.getAdapter(adapter);
}
@Override
public void doSave(IProgressMonitor monitor)
{
}
/**
* Save as not allowed
*/
@Override
public void doSaveAs()
{
saveDiagramAsImage();
}
/**
* Save as not allowed
*/
@Override
public boolean isSaveAsAllowed()
{
return true;
}
/**
* Indicates if the editor has unsaved changes.
*
* @see org.eclipse.ui.part.EditorPart#isDirty
*/
@Override
public boolean isDirty()
{
return !isReadOnly() && isDirty;
}
public abstract boolean isReadOnly();
/**
* Returns the <code>CommandStack</code> of this editor's
* <code>EditDomain</code>.
*
* @return the <code>CommandStack</code>
*/
@Override
public CommandStack getCommandStack()
{
return getEditDomain().getCommandStack();
}
/**
* Returns the schema model associated with the editor
*
* @return an instance of <code>Schema</code>
*/
public EntityDiagram getDiagram()
{
return getDiagramPart().getDiagram();
}
public DiagramPart getDiagramPart()
{
return rootPart == null ? null : (DiagramPart) rootPart.getContents();
}
/**
* @see org.eclipse.ui.part.EditorPart#setInput(org.eclipse.ui.IEditorInput)
*/
@Override
protected void setInput(IEditorInput input)
{
super.setInput(input);
}
/**
* Creates a PaletteViewerProvider that will be used to create palettes for
* the view and the flyout.
*
* @return the palette provider
*/
@Override
protected PaletteViewerProvider createPaletteViewerProvider()
{
return new ERDPaletteViewerProvider(editDomain);
}
public GraphicalViewer getViewer()
{
return super.getGraphicalViewer();
}
/**
* Creates a new <code>GraphicalViewer</code>, configures, registers and
* initializes it.
*
* @param parent the parent composite
*/
@Override
protected void createGraphicalViewer(Composite parent)
{
GraphicalViewer viewer = createViewer(parent);
// hook the viewer into the EditDomain
setGraphicalViewer(viewer);
configureGraphicalViewer();
hookGraphicalViewer();
initializeGraphicalViewer();
// Set initial (empty) contents
viewer.setContents(new EntityDiagram(null, "empty"));
// Set context menu
ContextMenuProvider provider = new ERDEditorContextMenuProvider(this);
viewer.setContextMenu(provider);
getSite().registerContextMenu(ERDEditorPart.class.getName() + ".EditorContext", provider, viewer);
}
private GraphicalViewer createViewer(Composite parent)
{
StatusLineValidationMessageHandler validationMessageHandler = new StatusLineValidationMessageHandler(getEditorSite());
GraphicalViewer viewer = new ERDGraphicalViewer(this, validationMessageHandler);
viewer.createControl(parent);
// configure the viewer
viewer.getControl().setBackground(ColorConstants.white);
rootPart = new ScalableFreeformRootEditPart();
viewer.setRootEditPart(rootPart);
viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer));
viewer.addDropTargetListener(new DataEditDropTargetListener(viewer));
viewer.addDropTargetListener(new NodeDropTargetListener(viewer));
// initialize the viewer with input
viewer.setEditPartFactory(new ERDEditPartFactory());
return viewer;
}
@Override
protected void configureGraphicalViewer()
{
super.configureGraphicalViewer();
GraphicalViewer graphicalViewer = getGraphicalViewer();
/*
MenuManager manager = new MenuManager(getClass().getName(), getClass().getName());
manager.setRemoveAllWhenShown(true);
getEditorSite().registerContextMenu(getClass().getName() + ".EditorContext", manager, graphicalViewer, true); //$NON-NLS-1$
*/
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_ENABLED, store.getBoolean(ERDConstants.PREF_GRID_ENABLED));
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_VISIBLE, store.getBoolean(ERDConstants.PREF_GRID_ENABLED));
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_SPACING, new Dimension(
store.getInt(ERDConstants.PREF_GRID_WIDTH),
store.getInt(ERDConstants.PREF_GRID_HEIGHT)));
// initialize actions
createActions();
// Setup zoom manager
ZoomManager zoomManager = rootPart.getZoomManager();
List<String> zoomLevels = new ArrayList<String>(3);
zoomLevels.add(ZoomManager.FIT_ALL);
zoomLevels.add(ZoomManager.FIT_WIDTH);
zoomLevels.add(ZoomManager.FIT_HEIGHT);
zoomManager.setZoomLevelContributions(zoomLevels);
zoomManager.setZoomLevels(
new double[]{.1, .25, .5, .75, 1.0, 1.5, 2.0, 2.5, 3, 4}
);
IAction zoomIn = new ZoomInAction(zoomManager);
IAction zoomOut = new ZoomOutAction(zoomManager);
addAction(zoomIn);
addAction(zoomOut);
graphicalViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event)
{
String status;
IStructuredSelection selection = (IStructuredSelection)event.getSelection();
if (selection.isEmpty()) {
status = "";
} else if (selection.size() == 1) {
status = CommonUtils.toString(selection.getFirstElement());
} else {
status = String.valueOf(selection.size()) + " objects";
}
progressControl.setInfo(status);
updateActions(editPartActionIDs);
}
});
}
/**
* Sets the dirty state of this editor.
* <p/>
* <p/>
* An event will be fired immediately if the new state is different than the
* current one.
*
* @param dirty the new dirty state to set
*/
protected void setDirty(boolean dirty)
{
if (isDirty != dirty) {
isDirty = dirty;
firePropertyChange(IEditorPart.PROP_DIRTY);
}
}
/**
* Adds an action to this editor's <code>ActionRegistry</code>. (This is
* a helper method.)
*
* @param action the action to add.
*/
protected void addAction(IAction action)
{
getActionRegistry().registerAction(action);
UIUtils.registerKeyBinding(getSite(), action);
}
/**
* Updates the specified actions.
*
* @param actionIds the list of ids of actions to update
*/
@Override
protected void updateActions(List actionIds)
{
for (Iterator<?> ids = actionIds.iterator(); ids.hasNext();) {
IAction action = getActionRegistry().getAction(ids.next());
if (null != action && action instanceof UpdateAction) {
((UpdateAction) action).update();
}
}
}
/**
* Returns the overview for the outline view.
*
* @return the overview
*/
protected ERDOutlinePage getOverviewOutlinePage()
{
if (null == outlinePage && null != getGraphicalViewer()) {
RootEditPart rootEditPart = getGraphicalViewer().getRootEditPart();
if (rootEditPart instanceof ScalableFreeformRootEditPart) {
outlinePage = new ERDOutlinePage((ScalableFreeformRootEditPart) rootEditPart);
}
}
return outlinePage;
}
/**
* Returns the undoable <code>PropertySheetPage</code> for this editor.
*
* @return the undoable <code>PropertySheetPage</code>
*/
protected PropertySheetPage getPropertySheetPage()
{
if (null == undoablePropertySheetPage) {
undoablePropertySheetPage = new PropertySheetPage();
undoablePropertySheetPage.setRootEntry(new UndoablePropertySheetEntry(getCommandStack()));
}
return undoablePropertySheetPage;
}
/**
* @return the preferences for the Palette Flyout
*/
@Override
protected FlyoutPreferences getPalettePreferences()
{
return new ERDPalettePreferences();
}
/**
* @return the PaletteRoot to be used with the PaletteViewer
*/
@Override
protected PaletteRoot getPaletteRoot()
{
if (paletteRoot == null) {
paletteRoot = createPaletteRoot();
}
return paletteRoot;
}
public PaletteRoot createPaletteRoot()
{
// create root
PaletteRoot paletteRoot = new PaletteRoot();
paletteRoot.setLabel("Entity Diagram");
{
// a group of default control tools
PaletteDrawer controls = new PaletteDrawer("Tools", DBIcon.CONFIGURATION.getImageDescriptor());
paletteRoot.add(controls);
// the selection tool
ToolEntry selectionTool = new SelectionToolEntry();
controls.add(selectionTool);
// use selection tool as default entry
paletteRoot.setDefaultEntry(selectionTool);
// the marquee selection tool
controls.add(new MarqueeToolEntry());
if (!isReadOnly()) {
// separator
PaletteSeparator separator = new PaletteSeparator("tools");
separator.setUserModificationPermission(PaletteEntry.PERMISSION_NO_MODIFICATION);
controls.add(separator);
final ImageDescriptor connectImage = Activator.getImageDescriptor("icons/connect.png");
controls.add(new ConnectionCreationToolEntry("Connection", "Create Connection", null, connectImage, connectImage));
final ImageDescriptor noteImage = Activator.getImageDescriptor("icons/note.png");
controls.add(new CreationToolEntry(
"Note",
"Create Note",
new CreationFactory() {
@Override
public Object getNewObject()
{
return new ERDNote("Note");
}
@Override
public Object getObjectType()
{
return RequestConstants.REQ_CREATE;
}
},
noteImage,
noteImage));
}
}
/*
PaletteDrawer drawer = new PaletteDrawer("New Component",
Activator.getImageDescriptor("icons/connection.gif"));
List<CombinedTemplateCreationEntry> entries = new ArrayList<CombinedTemplateCreationEntry>();
CombinedTemplateCreationEntry tableEntry = new CombinedTemplateCreationEntry("New Table", "Create a new table",
ERDEntity.class, new DataElementFactory(ERDEntity.class),
Activator.getImageDescriptor("icons/table.gif"),
Activator.getImageDescriptor("icons/table.gif"));
CombinedTemplateCreationEntry columnEntry = new CombinedTemplateCreationEntry("New Column", "Add a new column",
ERDEntityAttribute.class, new DataElementFactory(ERDEntityAttribute.class),
Activator.getImageDescriptor("icons/column.gif"),
Activator.getImageDescriptor("icons/column.gif"));
entries.add(tableEntry);
entries.add(columnEntry);
drawer.addAll(entries);
paletteRoot.add(drawer);
*/
return paletteRoot;
}
public boolean isLoaded()
{
return isLoaded;
}
public void refreshDiagram()
{
if (isLoaded) {
loadDiagram();
}
}
@Override
public void refreshPart(Object source, boolean force)
{
refreshDiagram();
}
public void saveDiagramAsImage()
{
final Shell shell = getSite().getShell();
FileDialog saveDialog = new FileDialog(shell, SWT.SAVE);
saveDialog.setFilterExtensions(new String[]{"*.png", "*.gif", "*.jpg", "*.bmp"});
saveDialog.setFilterNames(new String[]{
"PNG format (*.png)",
"GIF format (*.gif)",
"JPEG format (*.jpg)",
"Bitmap format (*.bmp)"});
String filePath = ContentUtils.openFileDialog(saveDialog);
if (filePath == null || filePath.trim().length() == 0) {
return;
}
int imageType = SWT.IMAGE_BMP;
if (filePath.toLowerCase().endsWith(".jpg")) {
imageType = SWT.IMAGE_JPEG;
} else if (filePath.toLowerCase().endsWith(".png")) {
imageType = SWT.IMAGE_PNG;
} else if (filePath.toLowerCase().endsWith(".gif")) {
imageType = SWT.IMAGE_GIF;
}
IFigure figure = rootPart.getLayer(ScalableFreeformRootEditPart.PRINTABLE_LAYERS);
Rectangle contentBounds = figure instanceof FreeformLayeredPane ? ((FreeformLayeredPane) figure).getFreeformExtent() : figure.getBounds();
try {
FileOutputStream fos = new FileOutputStream(filePath);
try {
Rectangle r = figure.getBounds();
GC gc = null;
Graphics g = null;
try {
Image image = new Image(null, contentBounds.x * 2 + contentBounds.width, contentBounds.y * 2 + contentBounds.height);
try {
gc = new GC(image);
gc.setClipping(contentBounds.x, contentBounds.y, contentBounds.width, contentBounds.height);
g = new SWTGraphics(gc);
g.translate(r.x * -1, r.y * -1);
figure.paint(g);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[1];
if (imageType != SWT.IMAGE_JPEG) {
// Convert to 8bit color
imageLoader.data[0] = ImageUtils.makeWebImageData(image);
} else {
// Use maximum colors for JPEG
imageLoader.data[0] = image.getImageData();
}
imageLoader.save(fos, imageType);
} finally {
UIUtils.dispose(image);
}
} finally {
if (g != null) {
g.dispose();
}
UIUtils.dispose(gc);
}
fos.flush();
} finally {
ContentUtils.close(fos);
}
RuntimeUtils.launchProgram(filePath);
//UIUtils.showMessageBox(shell, "Save ERD", "Diagram has been exported to " + filePath, SWT.ICON_INFORMATION);
} catch (Exception e) {
UIUtils.showErrorDialog(getSite().getShell(), "Save ERD as image", null, e);
}
}
public MenuManager createAttributeVisibilityMenu()
{
MenuManager avMenu = new MenuManager("Show Attributes");
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.ALL));
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.KEYS));
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.PRIMARY));
avMenu.add(new ChangeAttributeVisibilityAction(ERDAttributeVisibility.NONE));
return avMenu;
}
public void printDiagram()
{
GraphicalViewer viewer = getGraphicalViewer();
PrintDialog dialog = new PrintDialog(viewer.getControl().getShell(), SWT.NULL);
PrinterData data = dialog.open();
if (data != null) {
IFigure rootFigure = rootPart.getLayer(ScalableFreeformRootEditPart.PRINTABLE_LAYERS);
//EntityDiagramFigure diagramFigure = findFigure(rootFigure, EntityDiagramFigure.class);
if (rootFigure != null) {
PrintFigureOperation printOp = new PrintFigureOperation(new Printer(data), rootFigure);
// Set print preferences
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
printOp.setPrintMode(store.getInt(ERDConstants.PREF_PRINT_PAGE_MODE));
printOp.setPrintMargin(new Insets(
store.getInt(ERDConstants.PREF_PRINT_MARGIN_TOP),
store.getInt(ERDConstants.PREF_PRINT_MARGIN_LEFT),
store.getInt(ERDConstants.PREF_PRINT_MARGIN_BOTTOM),
store.getInt(ERDConstants.PREF_PRINT_MARGIN_RIGHT)
));
// Run print
printOp.run("Print ER diagram");
}
}
//new PrintAction(this).run();
}
@Override
public boolean isSearchPossible()
{
return true;
}
@Override
public boolean isSearchEnabled()
{
return progressControl != null && progressControl.isSearchEnabled();
}
@Override
public boolean performSearch(SearchType searchType)
{
return progressControl != null && progressControl.performSearch(searchType);
}
protected abstract void loadDiagram();
private class ChangeAttributeVisibilityAction extends Action {
private final ERDAttributeVisibility visibility;
private ChangeAttributeVisibilityAction(ERDAttributeVisibility visibility)
{
super(visibility.getTitle(), IAction.AS_RADIO_BUTTON);
this.visibility = visibility;
}
@Override
public boolean isChecked()
{
return visibility == getDiagram().getAttributeVisibility();
}
@Override
public void run()
{
getDiagram().setAttributeVisibility(visibility);
refreshDiagram();
//this.setChecked(true);
}
}
private class ConfigPropertyListener implements IPropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent event)
{
GraphicalViewer graphicalViewer = getGraphicalViewer();
if (graphicalViewer == null) {
return;
}
if (ERDConstants.PREF_GRID_ENABLED.equals(event.getProperty())) {
Boolean enabled = (Boolean)event.getNewValue();
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_ENABLED, enabled);
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_VISIBLE, enabled);
} else if (ERDConstants.PREF_GRID_WIDTH.equals(event.getProperty()) || ERDConstants.PREF_GRID_HEIGHT.equals(event.getProperty())) {
final IPreferenceStore store = Activator.getDefault().getPreferenceStore();
graphicalViewer.setProperty(SnapToGrid.PROPERTY_GRID_SPACING, new Dimension(
store.getInt(ERDConstants.PREF_GRID_WIDTH),
store.getInt(ERDConstants.PREF_GRID_HEIGHT)));
}
}
}
protected class ProgressControl extends ProgressPageControl {
private Searcher searcher;
private ZoomComboContributionItem zoomCombo;
private ProgressControl(Composite parent, int style)
{
super(parent, style);
searcher = new Searcher();
}
@Override
protected boolean cancelProgress()
{
if (diagramLoadingJob != null) {
diagramLoadingJob.cancel();
return true;
}
return false;
}
public ProgressVisualizer<EntityDiagram> createLoadVisualizer()
{
getGraphicalControl().setBackground(ColorConstants.lightGray);
return new LoadVisualizer();
}
@Override
protected void fillCustomToolbar(ToolBarManager toolBarManager) {
ZoomManager zoomManager = rootPart.getZoomManager();
String[] zoomStrings = new String[]{
ZoomManager.FIT_ALL,
ZoomManager.FIT_HEIGHT,
ZoomManager.FIT_WIDTH
};
// Init zoom combo with dummy part service
// to prevent zoom disable on part change - as it is standalone zoom control, not global one
zoomCombo = new ZoomComboContributionItem(
new IPartService() {
@Override
public void addPartListener(IPartListener listener)
{
}
@Override
public void addPartListener(IPartListener2 listener)
{
}
@Override
public IWorkbenchPart getActivePart()
{
return ERDEditorPart.this;
}
@Override
public IWorkbenchPartReference getActivePartReference()
{
return null;
}
@Override
public void removePartListener(IPartListener listener)
{
}
@Override
public void removePartListener(IPartListener2 listener)
{
}
},
zoomStrings);
toolBarManager.add(zoomCombo);
//toolBarManager.add(new UndoAction(ERDEditorPart.this));
//toolBarManager.add(new RedoAction(ERDEditorPart.this));
//toolBarManager.add(new PrintAction(ERDEditorPart.this));
toolBarManager.add(new ZoomInAction(zoomManager));
toolBarManager.add(new ZoomOutAction(zoomManager));
toolBarManager.add(new Separator());
//toolBarManager.add(createAttributeVisibilityMenu());
toolBarManager.add(new DiagramLayoutAction(ERDEditorPart.this));
toolBarManager.add(new DiagramToggleGridAction());
toolBarManager.add(new DiagramRefreshAction(ERDEditorPart.this));
toolBarManager.add(new Separator());
{
toolBarManager.add(ActionUtils.makeCommandContribution(
getSite(),
IWorkbenchCommandConstants.FILE_SAVE_AS,
"Save diagram as image",
DBIcon.PICTURE_SAVE.getImageDescriptor()));
toolBarManager.add(ActionUtils.makeCommandContribution(
getSite(),
IWorkbenchCommandConstants.FILE_PRINT,
"Print Diagram",
PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT)));
}
{
Action configAction = new Action("Configuration") {
@Override
public void run()
{
UIUtils.showPreferencesFor(
getSite().getShell(),
ERDEditorPart.this,
ERDPreferencePage.PAGE_ID);
}
};
configAction.setImageDescriptor(DBIcon.CONFIGURATION.getImageDescriptor());
toolBarManager.add(configAction);
}
}
@Override
protected ISearchExecutor getSearchRunner()
{
return searcher;
}
private class LoadVisualizer extends ProgressVisualizer<EntityDiagram> {
@Override
public void visualizeLoading()
{
super.visualizeLoading();
}
@Override
public void completeLoading(EntityDiagram entityDiagram)
{
super.completeLoading(entityDiagram);
getGraphicalControl().setBackground(ColorConstants.white);
isLoaded = true;
Control control = getGraphicalViewer().getControl();
if (control == null || control.isDisposed()) {
return;
}
if (entityDiagram != null) {
List<String> errorMessages = entityDiagram.getErrorMessages();
if (!errorMessages.isEmpty()) {
UIUtils.showErrorDialog(
control.getShell(),
"Diagram loading errors",
"Error(s) occurred during diagram loading. If these errors are recoverable then fix errors and then refresh/reopen diagram",
errorMessages);
}
setInfo(entityDiagram.getEntityCount() + " objects");
} else {
setInfo("Empty diagram due to error (see error log)");
}
getCommandStack().flush();
getGraphicalViewer().setContents(entityDiagram);
zoomCombo.setZoomManager(rootPart.getZoomManager());
//toolBarManager.getControl().setEnabled(true);
}
}
}
private class Searcher extends ObjectSearcher<DBPNamedObject> {
@Override
protected void setInfo(String message)
{
progressControl.setInfo(message);
}
@Override
protected Collection<DBPNamedObject> getContent()
{
return getDiagramPart().getChildren();
}
@Override
protected void selectObject(DBPNamedObject object)
{
if (object == null) {
getGraphicalViewer().deselectAll();
} else {
getGraphicalViewer().select((EditPart)object);
}
}
@Override
protected void updateObject(DBPNamedObject object)
{
}
@Override
protected void revealObject(DBPNamedObject object)
{
getGraphicalViewer().reveal((EditPart)object);
}
}
}
| Mongo unique index
Former-commit-id: 51eeed26ac5749acd37375a07d363b0f9c69bf68 | plugins/org.jkiss.dbeaver.erd/src/org/jkiss/dbeaver/ext/erd/editor/ERDEditorPart.java | Mongo unique index |
|
Java | apache-2.0 | a49dfcb0c8274cc787b501850946841fb14b7932 | 0 | nssales/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,jerome79/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.integration.loadsave.portfolio.writer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.integration.loadsave.portfolio.rowparser.RowParser;
import com.opengamma.integration.loadsave.sheet.writer.CsvSheetWriter;
import com.opengamma.integration.loadsave.sheet.writer.SheetWriter;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.master.security.ManageableSecurity;
import com.opengamma.util.ArgumentChecker;
/**
* This class writes positions/securities to a zip file, using the zip file's directory structure to represent the portfolio
* node structure.
*/
public class ZippedPortfolioWriter implements PortfolioWriter {
private static final Logger s_logger = LoggerFactory.getLogger(ZippedPortfolioWriter.class);
private static final String DIRECTORY_SEPARATOR = "/";
private ZipOutputStream _zipFile;
private Map<String, Integer> _versionMap = new HashMap<String, Integer>();
private String[] _currentPath = new String[] {};
private SingleSheetPortfolioWriter _currentWriter;
private Map<String, SingleSheetPortfolioWriter> _writerMap = new HashMap<String, SingleSheetPortfolioWriter>();
private Map<String, ByteArrayOutputStream> _bufferMap = new HashMap<String, ByteArrayOutputStream>();
public ZippedPortfolioWriter(String filename) {
ArgumentChecker.notEmpty(filename, "filename");
// Confirm file doesn't already exist
File file = new File(filename);
if (file.exists()) {
throw new OpenGammaRuntimeException("File " + filename + " already exists");
}
// Create zip file
try {
_zipFile = new ZipOutputStream(new FileOutputStream(filename));
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not create zip archive " + filename + " for writing: " + ex.getMessage());
}
}
@Override
public ManageableSecurity writeSecurity(ManageableSecurity security) {
ArgumentChecker.notNull(security, "security");
identifyOrCreatePortfolioWriter(security);
if (_currentWriter != null) {
security = _currentWriter.writeSecurity(security);
} else {
s_logger.warn("Could not identify a suitable parser for security: " + security.getName());
}
return security;
}
@Override
public ManageablePosition writePosition(ManageablePosition position) {
ArgumentChecker.notNull(position, "position");
if (_currentWriter != null) {
position = _currentWriter.writePosition(position);
} else {
s_logger.warn("Could not identify a suitable parser for position: " + position.getName());
}
return position;
}
@Override
public void setPath(String[] newPath) {
ArgumentChecker.notNull(newPath, "newPath");
// First, write the current set of CSVs to the zip file and clear the map of writers
if (!getPathString(newPath).equals(getPathString(_currentPath))) {
flushCurrentBuffers();
// Change to the new path in the zip file (might need to create)
if (newPath.length > 0) {
String path = StringUtils.arrayToDelimitedString(newPath, DIRECTORY_SEPARATOR) + DIRECTORY_SEPARATOR;
ZipEntry entry = new ZipEntry(path);
try {
_zipFile.putNextEntry(entry);
_zipFile.closeEntry();
} catch (IOException ex) {
// if failed, assume the directory already exists
//throw new OpenGammaRuntimeException("Could not create folder " + entry.getName() + " in zip file: " + ex.getMessage());
}
}
_currentPath = newPath;
}
}
@Override
public String[] getCurrentPath() {
return _currentPath;
}
@Override
public void flush() {
try {
_zipFile.flush();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not flush data into zip archive");
}
}
@Override
public void close() {
flushCurrentBuffers();
flush();
try {
// Write version file
writeMetaData("METADATA.INI");
// Close zip archive
_zipFile.close();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not close zip file");
}
}
private String getPathString(String[] path) {
String pathString = StringUtils.arrayToDelimitedString(path, DIRECTORY_SEPARATOR);
if (pathString.length() > 0) {
pathString += DIRECTORY_SEPARATOR;
}
return pathString;
}
private void flushCurrentBuffers() {
String path = getPathString(_currentPath);
s_logger.info("Flushing CSV buffers for ZIP directory " + path);
for (Map.Entry<String, ByteArrayOutputStream> entry : _bufferMap.entrySet()) {
_writerMap.get(entry.getKey()).flush();
_writerMap.get(entry.getKey()).close();
ZipEntry zipEntry = new ZipEntry(path + entry.getKey() + ".csv");
s_logger.info("Writing " + zipEntry.getName() + " to ZIP archive");
try {
_zipFile.putNextEntry(zipEntry);
entry.getValue().writeTo(_zipFile);
_zipFile.closeEntry();
_zipFile.flush();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not write file entry " + zipEntry.getName() + " to zip archive: " + ex.getMessage());
}
}
_bufferMap = new HashMap<String, ByteArrayOutputStream>();
_writerMap = new HashMap<String, SingleSheetPortfolioWriter>();
}
private PortfolioWriter identifyOrCreatePortfolioWriter(ManageableSecurity security) {
// Identify the correct portfolio writer for this security
String className = security.getClass().toString();
className = className.substring(className.lastIndexOf('.') + 1).replace("Security", "");
_currentWriter = _writerMap.get(className);
RowParser parser;
// create writer/output buffer map entry if not there for this security type
if (_currentWriter == null) {
s_logger.info("Creating a new row parser for " + className + " securities");
parser = RowParser.newRowParser(className);
if (parser == null) {
return null;
}
Map<String, RowParser> parserMap = new HashMap<String, RowParser>();
parserMap.put(className, parser);
ByteArrayOutputStream out = new ByteArrayOutputStream();
SheetWriter sheet = new CsvSheetWriter(out, parser.getColumns());
_currentWriter = new SingleSheetPortfolioWriter(sheet, parserMap);
_writerMap.put(className, _currentWriter);
_bufferMap.put(className, out);
_versionMap.put(className, parser.getSecurityHashCode());
}
return _currentWriter;
}
private void writeMetaData(String filename) {
try {
_zipFile.putNextEntry(new ZipEntry(filename));
_zipFile.write("# Generated by OpenGamma zipped portfolio writer\n\n".getBytes());
_zipFile.write("[securityHashes]\n".getBytes());
for (Entry<String, Integer> entry : _versionMap.entrySet()) {
_zipFile.write((entry.getKey() + " = " + Integer.toHexString(entry.getValue()) + "\n").getBytes());
}
_zipFile.closeEntry();
_zipFile.flush();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not write METADATA.INI to zip archive");
}
}
}
| projects/OG-Integration/src/com/opengamma/integration/loadsave/portfolio/writer/ZippedPortfolioWriter.java | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.integration.loadsave.portfolio.writer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.integration.loadsave.portfolio.rowparser.RowParser;
import com.opengamma.integration.loadsave.sheet.writer.CsvSheetWriter;
import com.opengamma.integration.loadsave.sheet.writer.SheetWriter;
import com.opengamma.master.position.ManageablePosition;
import com.opengamma.master.security.ManageableSecurity;
import com.opengamma.util.ArgumentChecker;
/**
* This class writes positions/securities to a zip file, using the zip file's directory structure to represent the portfolio
* node structure.
*/
public class ZippedPortfolioWriter implements PortfolioWriter {
private static final Logger s_logger = LoggerFactory.getLogger(ZippedPortfolioWriter.class);
private static final String DIRECTORY_SEPARATOR = "/";
private ZipOutputStream _zipFile;
// private ManageablePortfolio _portfolio;
private Map<String, Integer> _versionMap = new HashMap<String, Integer>();
// private ManageablePortfolioNode _currentNode;
private String[] _currentPath = new String[] {};
private SingleSheetPortfolioWriter _currentWriter;
private Map<String, SingleSheetPortfolioWriter> _writerMap = new HashMap<String, SingleSheetPortfolioWriter>();
private Map<String, ByteArrayOutputStream> _bufferMap = new HashMap<String, ByteArrayOutputStream>();
public ZippedPortfolioWriter(String filename) {
ArgumentChecker.notEmpty(filename, "filename");
// Confirm file doesn't already exist
File file = new File(filename);
if (file.exists()) {
throw new OpenGammaRuntimeException("File " + filename + " already exists");
}
// Create zip file
try {
_zipFile = new ZipOutputStream(new FileOutputStream(filename));
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not create zip archive " + filename + " for writing: " + ex.getMessage());
}
// Set up virtual portfolio and root node
// ManageablePortfolioNode root = new ManageablePortfolioNode("Root");
// _portfolio = new ManageablePortfolio("Virtual Portfolio", root);
// _currentNode = _portfolio.getRootNode();
}
@Override
public ManageableSecurity writeSecurity(ManageableSecurity security) {
ArgumentChecker.notNull(security, "security");
identifyOrCreatePortfolioWriter(security);
if (_currentWriter != null) {
security = _currentWriter.writeSecurity(security);
} else {
s_logger.warn("Could not identify a suitable parser for security: " + security.getName());
}
return security;
}
@Override
public ManageablePosition writePosition(ManageablePosition position) {
ArgumentChecker.notNull(position, "position");
if (_currentWriter != null) {
position = _currentWriter.writePosition(position);
} else {
s_logger.warn("Could not identify a suitable parser for position: " + position.getName());
}
return position;
}
// TODO REMOVE
// public ManageablePortfolioNode setCurrentNode(ManageablePortfolioNode node) {
//
// ArgumentChecker.notNull(node, "node");
//
// // First, write the current set of CSVs to the zip file and clear the map of writers
// flushCurrentBuffers();
//
// // Change to the new path in the zip file (might need to create)
// if (_currentPath.length > 0) {
// String path = StringUtils.arrayToDelimitedString(_currentPath, DIRECTORY_SEPARATOR);
// ZipEntry entry = new ZipEntry(path);
// try {
// _zipFile.putNextEntry(entry);
// _zipFile.closeEntry();
// } catch (IOException ex) {
// // if failed, assume the directory already exists
// //throw new OpenGammaRuntimeException("Could not create folder " + entry.getName() + " in zip file: " + ex.getMessage());
// }
// }
//
// _currentNode = node;
// return node;
// }
@Override
public void setPath(String[] newPath) {
ArgumentChecker.notNull(newPath, "newPath");
// First, write the current set of CSVs to the zip file and clear the map of writers
if (!newPath.equals(_currentPath)) {
flushCurrentBuffers();
// Change to the new path in the zip file (might need to create)
if (_currentPath.length > 0) {
String path = StringUtils.arrayToDelimitedString(_currentPath, DIRECTORY_SEPARATOR) + DIRECTORY_SEPARATOR;
ZipEntry entry = new ZipEntry(path);
try {
_zipFile.putNextEntry(entry);
_zipFile.closeEntry();
} catch (IOException ex) {
// if failed, assume the directory already exists
//throw new OpenGammaRuntimeException("Could not create folder " + entry.getName() + " in zip file: " + ex.getMessage());
}
}
_currentPath = newPath;
}
}
@Override
public String[] getCurrentPath() {
return _currentPath;
}
@Override
public void flush() {
try {
_zipFile.flush();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not flush data into zip archive");
}
}
@Override
public void close() {
flushCurrentBuffers();
flush();
try {
// Write version file
writeMetaData("METADATA.INI");
// Close zip archive
_zipFile.close();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not close zip file");
}
}
// private String getPath(ManageablePortfolioNode node) {
// Stack<ManageablePortfolioNode> stack = findNodeStackByNode(_portfolio.getRootNode(), node);
// String path = "";
//
// // The stack should not be empty as the false 'Root' node is always there first: get rid of it immediately
// stack.pop();
//
// while (!stack.isEmpty()) {
// path += stack.pop().getName().replace(DIRECTORY_SEPARATOR + "", "<slash>") + DIRECTORY_SEPARATOR;
// }
//
// return path;
// }
//
// private Stack<ManageablePortfolioNode> findNodeStackByNode(final ManageablePortfolioNode start, final ManageablePortfolioNode treasure) {
//
// // This node IS the treasure
// if (start == treasure) {
// Stack<ManageablePortfolioNode> stack = new Stack<ManageablePortfolioNode>();
// stack.push(start);
// return stack;
// }
//
// // Look for treasure in the child nodes
// for (ManageablePortfolioNode childNode : start.getChildNodes()) {
// Stack<ManageablePortfolioNode> stack = findNodeStackByNode(childNode, treasure);
// if (stack != null) {
// stack.push(start);
// return stack;
// }
// }
//
// // None of the child nodes contain treasure
// return null;
// }
private void flushCurrentBuffers() {
String path = StringUtils.arrayToDelimitedString(_currentPath, DIRECTORY_SEPARATOR);
if (path.length() > 0) {
path += DIRECTORY_SEPARATOR;
}
s_logger.info("Flushing CSV buffers for ZIP directory " + path);
for (Map.Entry<String, ByteArrayOutputStream> entry : _bufferMap.entrySet()) {
_writerMap.get(entry.getKey()).flush();
_writerMap.get(entry.getKey()).close();
ZipEntry zipEntry = new ZipEntry(path + entry.getKey() + ".csv");
s_logger.info("Writing " + zipEntry.getName() + " to ZIP archive");
try {
_zipFile.putNextEntry(zipEntry);
entry.getValue().writeTo(_zipFile);
_zipFile.closeEntry();
_zipFile.flush();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not write file entry " + zipEntry.getName() + " to zip archive: " + ex.getMessage());
}
}
_bufferMap = new HashMap<String, ByteArrayOutputStream>();
_writerMap = new HashMap<String, SingleSheetPortfolioWriter>();
}
private PortfolioWriter identifyOrCreatePortfolioWriter(ManageableSecurity security) {
// Identify the correct portfolio writer for this security
String className = security.getClass().toString();
className = className.substring(className.lastIndexOf('.') + 1).replace("Security", "");
_currentWriter = _writerMap.get(className);
RowParser parser;
// create writer/output buffer map entry if not there for this security type
if (_currentWriter == null) {
s_logger.info("Creating a new row parser for " + className + " securities");
parser = RowParser.newRowParser(className);
if (parser == null) {
return null;
}
Map<String, RowParser> parserMap = new HashMap<String, RowParser>();
parserMap.put(className, parser);
ByteArrayOutputStream out = new ByteArrayOutputStream();
SheetWriter sheet = new CsvSheetWriter(out, parser.getColumns());
_currentWriter = new SingleSheetPortfolioWriter(sheet, parserMap);
_writerMap.put(className, _currentWriter);
_bufferMap.put(className, out);
_versionMap.put(className, parser.getSecurityHashCode());
}
return _currentWriter;
}
private void writeMetaData(String filename) {
try {
_zipFile.putNextEntry(new ZipEntry(filename));
_zipFile.write("# Generated by OpenGamma zipped portfolio writer\n\n".getBytes());
_zipFile.write("[securityHashes]\n".getBytes());
for (Entry<String, Integer> entry : _versionMap.entrySet()) {
_zipFile.write((entry.getKey() + " = " + Integer.toHexString(entry.getValue()) + "\n").getBytes());
}
_zipFile.closeEntry();
_zipFile.flush();
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Could not write METADATA.INI to zip archive");
}
}
}
| Reimplemented hierarchical portfolio saving to zip archive using String[] paths
| projects/OG-Integration/src/com/opengamma/integration/loadsave/portfolio/writer/ZippedPortfolioWriter.java | Reimplemented hierarchical portfolio saving to zip archive using String[] paths |
|
Java | apache-2.0 | 6e56c7fdb403ce418ad310b010cb1e268213c93c | 0 | apache/skywalking,ascrutae/sky-walking,ascrutae/sky-walking,OpenSkywalking/skywalking,apache/skywalking,ascrutae/sky-walking,OpenSkywalking/skywalking,apache/skywalking,hanahmily/sky-walking,ascrutae/sky-walking,apache/skywalking,apache/skywalking,apache/skywalking,apache/skywalking,hanahmily/sky-walking | /*
* 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.skywalking.apm.collector.storage.table.register;
import org.apache.skywalking.apm.collector.core.util.Const;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
/**
* @author peng-yongsheng
*/
public class ServerTypeDefine {
private static ServerTypeDefine INSTANCE = new ServerTypeDefine();
private String[] serverTypeNames;
private ServerType[] serverTypes;
private ServerTypeDefine() {
this.serverTypes = new ServerType[29];
this.serverTypeNames = new String[11];
addServerType(new ServerType(ComponentsDefine.TOMCAT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.HTTPCLIENT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.DUBBO.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.H2.getId(), 1, ComponentsDefine.H2.getName()));
addServerType(new ServerType(ComponentsDefine.MYSQL.getId(), 2, ComponentsDefine.MYSQL.getName()));
addServerType(new ServerType(ComponentsDefine.ORACLE.getId(), 3, ComponentsDefine.ORACLE.getName()));
addServerType(new ServerType(ComponentsDefine.REDIS.getId(), 4, ComponentsDefine.REDIS.getName()));
addServerType(new ServerType(ComponentsDefine.MOTAN.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.MONGODB.getId(), 5, ComponentsDefine.MONGODB.getName()));
addServerType(new ServerType(ComponentsDefine.RESIN.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.FEIGN.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.OKHTTP.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.SPRING_REST_TEMPLATE.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.SPRING_MVC_ANNOTATION.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.STRUTS2.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.NUTZ_MVC_ANNOTATION.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.NUTZ_HTTP.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.JETTY_CLIENT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.JETTY_SERVER.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.MEMCACHED.getId(), 6, ComponentsDefine.MEMCACHED.getName()));
addServerType(new ServerType(ComponentsDefine.SHARDING_JDBC.getId(), 7, ComponentsDefine.SHARDING_JDBC.getName()));
addServerType(new ServerType(ComponentsDefine.POSTGRESQL.getId(), 8, ComponentsDefine.POSTGRESQL.getName()));
addServerType(new ServerType(ComponentsDefine.GRPC.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.ELASTIC_JOB.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.ROCKET_MQ.getId(), 9, ComponentsDefine.ROCKET_MQ.getName()));
addServerType(new ServerType(ComponentsDefine.HTTP_ASYNC_CLIENT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.KAFKA.getId(), 10, ComponentsDefine.KAFKA.getName()));
addServerType(new ServerType(ComponentsDefine.SERVICECOMB.getId(), Const.NONE, ComponentsDefine.SERVICECOMB.getName()));
}
public static ServerTypeDefine getInstance() {
return INSTANCE;
}
private void addServerType(ServerType serverType) {
serverTypeNames[serverType.getId()] = serverType.getName();
serverTypes[serverType.getComponentId()] = serverType;
}
public int getServerTypeId(int componentId) {
return serverTypes[componentId].getId();
}
public String getServerType(int serverTypeId) {
return serverTypeNames[serverTypeId];
}
}
| apm-collector/apm-collector-storage/collector-storage-define/src/main/java/org/apache/skywalking/apm/collector/storage/table/register/ServerTypeDefine.java | /*
* 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.skywalking.apm.collector.storage.table.register;
import org.apache.skywalking.apm.collector.core.util.Const;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
/**
* @author peng-yongsheng
*/
public class ServerTypeDefine {
private static ServerTypeDefine INSTANCE = new ServerTypeDefine();
private String[] serverTypeNames;
private ServerType[] serverTypes;
private ServerTypeDefine() {
this.serverTypes = new ServerType[28];
this.serverTypeNames = new String[11];
addServerType(new ServerType(ComponentsDefine.TOMCAT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.HTTPCLIENT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.DUBBO.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.H2.getId(), 1, ComponentsDefine.H2.getName()));
addServerType(new ServerType(ComponentsDefine.MYSQL.getId(), 2, ComponentsDefine.MYSQL.getName()));
addServerType(new ServerType(ComponentsDefine.ORACLE.getId(), 3, ComponentsDefine.ORACLE.getName()));
addServerType(new ServerType(ComponentsDefine.REDIS.getId(), 4, ComponentsDefine.REDIS.getName()));
addServerType(new ServerType(ComponentsDefine.MOTAN.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.MONGODB.getId(), 5, ComponentsDefine.MONGODB.getName()));
addServerType(new ServerType(ComponentsDefine.RESIN.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.FEIGN.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.OKHTTP.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.SPRING_REST_TEMPLATE.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.SPRING_MVC_ANNOTATION.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.STRUTS2.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.NUTZ_MVC_ANNOTATION.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.NUTZ_HTTP.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.JETTY_CLIENT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.JETTY_SERVER.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.MEMCACHED.getId(), 6, ComponentsDefine.MEMCACHED.getName()));
addServerType(new ServerType(ComponentsDefine.SHARDING_JDBC.getId(), 7, ComponentsDefine.SHARDING_JDBC.getName()));
addServerType(new ServerType(ComponentsDefine.POSTGRESQL.getId(), 8, ComponentsDefine.POSTGRESQL.getName()));
addServerType(new ServerType(ComponentsDefine.GRPC.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.ELASTIC_JOB.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.ROCKET_MQ.getId(), 9, ComponentsDefine.ROCKET_MQ.getName()));
addServerType(new ServerType(ComponentsDefine.HTTP_ASYNC_CLIENT.getId(), Const.NONE, Const.EMPTY_STRING));
addServerType(new ServerType(ComponentsDefine.KAFKA.getId(), 10, ComponentsDefine.KAFKA.getName()));
}
public static ServerTypeDefine getInstance() {
return INSTANCE;
}
private void addServerType(ServerType serverType) {
serverTypeNames[serverType.getId()] = serverType.getName();
serverTypes[serverType.getComponentId()] = serverType;
}
public int getServerTypeId(int componentId) {
return serverTypes[componentId].getId();
}
public String getServerType(int serverTypeId) {
return serverTypeNames[serverTypeId];
}
}
| Update /org/apache/skywalking/apm/collector/storage/table/register/ServerTypeDefine.java
| apm-collector/apm-collector-storage/collector-storage-define/src/main/java/org/apache/skywalking/apm/collector/storage/table/register/ServerTypeDefine.java | Update /org/apache/skywalking/apm/collector/storage/table/register/ServerTypeDefine.java |
|
Java | bsd-3-clause | d07a20daa7603bf6087b75a7f714251caab3a38c | 0 | oranoceallaigh/smppapi,oranoceallaigh/smppapi,oranoceallaigh/smppapi | /*
* Java SMPP API
* Copyright (C) 1998 - 2001 by Oran Kelly
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* A copy of the LGPL can be viewed at http://www.gnu.org/copyleft/lesser.html
* Java SMPP API author: [email protected]
* Java SMPP API Homepage: http://smppapi.sourceforge.net/
*/
package ie.omk.smpp;
import java.io.*;
import java.util.*;
import ie.omk.smpp.util.SMPPDate;
import ie.omk.smpp.message.*;
import ie.omk.debug.Debug;
/** Object used as extra information in an SMPP event.
* Any packets that contain some form of message information will generate a
* MessageDetails object in the 'extra information' field of an SmppEvent.
* @see ie.omk.smpp.SmppEvent
* @see SmppTransmitter#queryMessage
* @see SmppTransmitter#queryMsgDetails
* @author Oran Kelly
* @version 1.0
*/
public class MessageDetails
implements java.io.Serializable
{
/** Message Id assigned by the SMSC to the message */
public String messageId = null;
/** Date and time (SMSC local time) that message reached a final state */
public SMPPDate finalDate = null;
/** Current status of the message */
public int status = 0;
/** Error code associated with this message */
public int error = 0;
/** Service type this message was submitted under */
public String serviceType = null;
/** Source address this message came from */
public SmeAddress sourceAddr = null;
/** Table of all destinations this message was successfully delivered to */
public Vector destinationTable = new Vector();
/** Priority of message. */
public boolean priority = false;
/** Registered delivery. */
public boolean registered = false;
/** Replace if present flag. */
public boolean replaceIfPresent = false;
/** ESM class. */
protected int esmClass = 0;
/** GSM protocol ID. */
protected int protocolID = 0;
/** GSM data coding (see GSM 03.38). */
public int dataCoding = 0;
/** Default message number. */
public int defaultMsg = 0;
/** Date and time this message is scheduled to be delivered on */
public SMPPDate deliveryTime = null;
/** Date and time this message will expire on */
public SMPPDate expiryTime = null;
/** Text of the message */
public byte[] message = null;
/** Create a new Details object with all null (or default) values.
*/
public MessageDetails()
{
}
/** Take any Smpp packet and fill in as many fields as are available.
* Any fields that cannot be read from the packet will default to
* null (ints will equal 0, Strings will equal null)
*/
public MessageDetails(SMPPPacket p)
{
int loop=0;
if(p == null)
return;
getAllFields(p);
}
public SubmitSM getSubmitSM()
throws ie.omk.smpp.SMPPException
{
SubmitSM p = new SubmitSM();
fillAllFields(p);
return (p);
}
public DeliverSM getDeliverSM()
throws ie.omk.smpp.SMPPException
{
DeliverSM p = new DeliverSM();
fillAllFields(p);
return (p);
}
public SubmitMulti getSubmitMulti()
throws ie.omk.smpp.SMPPException
{
SubmitMulti p = new SubmitMulti();
fillAllFields(p);
SmeAddress[] smes = new SmeAddress[destinationTable.size()];
System.arraycopy(destinationTable.toArray(), 0, smes, 0, smes.length);
p.setDestAddresses(smes);
return (p);
}
public QueryMsgDetailsResp getQueryMsgDetailsResp()
throws ie.omk.smpp.SMPPException
{
QueryMsgDetailsResp p = new QueryMsgDetailsResp();
fillAllFields(p);
return (p);
}
public QuerySMResp getQuerySMResp()
throws ie.omk.smpp.SMPPException
{
QuerySMResp p = new QuerySMResp();
fillAllFields(p);
return (p);
}
public ReplaceSM getReplaceSM()
throws ie.omk.smpp.SMPPException
{
ReplaceSM p = new ReplaceSM();
fillAllFields(p);
return (p);
}
public CancelSM getCancelSM()
throws ie.omk.smpp.SMPPException
{
CancelSM p = new CancelSM();
fillAllFields(p);
return (p);
}
public SubmitSMResp getSubmitSMResp()
throws ie.omk.smpp.SMPPException
{
SubmitSMResp p = new SubmitSMResp();
p.setMessageId(messageId);
return (p);
}
public SubmitMultiResp getSubmitMultiResp()
throws ie.omk.smpp.SMPPException
{
SubmitMultiResp p = new SubmitMultiResp();
p.setMessageId(messageId);
return (p);
}
private void getAllFields(SMPPPacket p)
{
this.messageId = p.getMessageId();
this.finalDate = p.getFinalDate();
this.status = p.getMessageStatus();
this.error = p.getErrorCode();
this.serviceType = p.getServiceType();
this.sourceAddr = p.getSource();
this.deliveryTime = p.getDeliveryTime();
this.expiryTime = p.getExpiryTime();
this.message = p.getMessage();
Collection dt = null;
switch (p.getCommandId()) {
case SMPPPacket.ESME_SUB_MULTI:
dt = ((SubmitMulti)p).getDestinationTable();
break;
case SMPPPacket.ESME_QUERY_MSG_DETAILS_RESP:
dt = ((QueryMsgDetailsResp)p).getDestinationTable();
break;
}
if (dt == null) {
this.destinationTable.add(p.getDestination());
} else {
Iterator i = dt.iterator();
while (i.hasNext())
this.destinationTable.add(i.next());
}
this.replaceIfPresent = p.isReplaceIfPresent();
this.priority = p.isPriority();
this.dataCoding = p.getDataCoding();
this.defaultMsg = p.getDefaultMsgId();
this.protocolID = p.getProtocolID();
this.esmClass = p.getEsmClass();
}
private void fillAllFields(SMPPPacket p)
throws ie.omk.smpp.SMPPException
{
p.setMessageId(messageId);
p.setFinalDate(finalDate);
p.setMessageStatus(status);
p.setErrorCode(error);
p.setServiceType(serviceType);
p.setSource(sourceAddr);
p.setDestination((SmeAddress)destinationTable.get(0));
p.setDeliveryTime(deliveryTime);
p.setExpiryTime(expiryTime);
p.setMessage(message);
p.setReplaceIfPresent(replaceIfPresent);
p.setPriority(priority);
p.setDataCoding(dataCoding);
p.setDefaultMsg(defaultMsg);
p.setProtocolID(protocolID);
p.setEsmClass(esmClass);
}
}
| src/ie/omk/smpp/MessageDetails.java | /*
* Java SMPP API
* Copyright (C) 1998 - 2001 by Oran Kelly
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* A copy of the LGPL can be viewed at http://www.gnu.org/copyleft/lesser.html
* Java SMPP API author: [email protected]
* Java SMPP API Homepage: http://smppapi.sourceforge.net/
*/
package ie.omk.smpp;
import java.io.*;
import java.util.*;
import ie.omk.smpp.util.SMPPDate;
import ie.omk.smpp.message.*;
import ie.omk.debug.Debug;
/** Object used as extra information in an SMPP event.
* Any packets that contain some form of message information will generate a
* MessageDetails object in the 'extra information' field of an SmppEvent.
* @see ie.omk.smpp.SmppEvent
* @see SmppTransmitter#queryMessage
* @see SmppTransmitter#queryMsgDetails
* @author Oran Kelly
* @version 1.0
*/
public class MessageDetails
implements java.io.Serializable
{
/** Message Id assigned by the SMSC to the message */
public String messageId = null;
/** Date and time (SMSC local time) that message reached a final state */
public SMPPDate finalDate = null;
/** Current status of the message */
public int status = 0;
/** Error code associated with this message */
public int error = 0;
/** Service type this message was submitted under */
public String serviceType = null;
/** Source address this message came from */
public SmeAddress sourceAddr = null;
/** Table of all destinations this message was successfully delivered to */
public Vector destinationTable = new Vector();
/** Priority of message. */
public boolean priority = false;
/** Registered delivery. */
public boolean registered = false;
/** Replace if present flag. */
public boolean replaceIfPresent = false;
/** ESM class. */
protected int esmClass = 0;
/** GSM protocol ID. */
protected int protocolID = 0;
/** GSM data coding (see GSM 03.38). */
public int dataCoding = 0;
/** Default message number. */
public int defaultMsg = 0;
/** Date and time this message is scheduled to be delivered on */
public SMPPDate deliveryTime = null;
/** Date and time this message will expire on */
public SMPPDate expiryTime = null;
/** Text of the message */
public String message = null;
/** Create a new Details object with all null (or default) values.
*/
public MessageDetails()
{
}
/** Take any Smpp packet and fill in as many fields as are available.
* Any fields that cannot be read from the packet will default to
* null (ints will equal 0, Strings will equal null)
*/
public MessageDetails(SMPPPacket p)
{
int loop=0;
SmeAddress add[] = null;
if(p == null)
return;
if(p instanceof SubmitSM) {
serviceType = ((SubmitSM)p).getServiceType();
sourceAddr = ((SubmitSM)p).getSource();
destinationTable.addElement(((SubmitSM)p).getDestination());
destinationTable.trimToSize();
priority = ((SubmitSM)p).isPriority();
registered = ((SubmitSM)p).isRegistered();
defaultMsg = ((SubmitSM)p).getDefaultMsgId();
protocolID = ((SubmitSM)p).getProtocolID();
dataCoding = ((SubmitSM)p).getDataCoding();
deliveryTime = ((SubmitSM)p).getDeliveryTime();
expiryTime = ((SubmitSM)p).getExpiryTime();
message = ((SubmitSM)p).getMessageText();
} else if(p instanceof DeliverSM) {
serviceType = p.getServiceType();
sourceAddr = p.getSource();
destinationTable.addElement(p.getDestination());
protocolID = p.getProtocolID();
dataCoding = p.getDataCoding();
esmClass = p.getEsmClass();
message = p.getMessageText();
} else if(p instanceof SubmitMulti) {
serviceType = ((SubmitMulti)p).getServiceType();
sourceAddr = ((SubmitMulti)p).getSource();
add = ((SubmitMulti)p).getDestAddresses();
for(loop=0; loop<add.length; loop++)
destinationTable.addElement(add[loop]);
priority = ((SubmitMulti)p).isPriority();
registered = ((SubmitMulti)p).isRegistered();
defaultMsg = ((SubmitMulti)p).getDefaultMsgId();
protocolID = ((SubmitMulti)p).getProtocolID();
dataCoding = ((SubmitMulti)p).getDataCoding();
deliveryTime = ((SubmitMulti)p).getDeliveryTime();
expiryTime = ((SubmitMulti)p).getExpiryTime();
message = ((SubmitMulti)p).getMessageText();
} else if (p instanceof QueryMsgDetailsResp) {
messageId = p.getMessageId();
finalDate = p.getFinalDate();
status = p.getMessageStatus();
error = p.getErrorCode();
serviceType = p.getServiceType();
sourceAddr = p.getSource();
deliveryTime = p.getDeliveryTime();
expiryTime = p.getExpiryTime();
message = p.getMessageText();
priority = p.isPriority();
registered = p.isRegistered();
dataCoding = p.getDataCoding();
protocolID = p.getProtocolID();
} else if (p instanceof QuerySMResp) {
messageId = p.getMessageId();
finalDate = p.getFinalDate();
status = p.getMessageStatus();
error = p.getErrorCode();
} else if(p instanceof ReplaceSM) {
messageId = ((ReplaceSM)p).getMessageId();
sourceAddr = ((ReplaceSM)p).getSource();
deliveryTime = ((ReplaceSM)p).getDeliveryTime();
expiryTime = ((ReplaceSM)p).getExpiryTime();
registered = ((ReplaceSM)p).isRegistered();
defaultMsg = ((ReplaceSM)p).getDefaultMsgId();
message = ((ReplaceSM)p).getMessageText();
} else if(p instanceof CancelSM) {
serviceType = ((CancelSM)p).getServiceType();
messageId = ((CancelSM)p).getMessageId();
sourceAddr = ((CancelSM)p).getSource();
destinationTable.addElement(((CancelSM)p).getDestination());
destinationTable.trimToSize();
} else if(p instanceof SubmitSMResp) {
messageId = ((SubmitSMResp)p).getMessageId();
} else if(p instanceof SubmitMultiResp) {
messageId = ((SubmitMultiResp)p).getMessageId();
}
}
public SubmitSM getSubmitSM()
throws ie.omk.smpp.SMPPException
{
SubmitSM p = new SubmitSM();
fillAllFields(p);
return (p);
}
public DeliverSM getDeliverSM()
throws ie.omk.smpp.SMPPException
{
DeliverSM p = new DeliverSM();
fillAllFields(p);
return (p);
}
public SubmitMulti getSubmitMulti()
throws ie.omk.smpp.SMPPException
{
SubmitMulti p = new SubmitMulti();
fillAllFields(p);
SmeAddress[] smes = new SmeAddress[destinationTable.size()];
System.arraycopy(destinationTable.toArray(), 0, smes, 0, smes.length);
p.setDestAddresses(smes);
return (p);
}
public QueryMsgDetailsResp getQueryMsgDetailsResp()
throws ie.omk.smpp.SMPPException
{
QueryMsgDetailsResp p = new QueryMsgDetailsResp();
fillAllFields(p);
return (p);
}
public QuerySMResp getQuerySMResp()
throws ie.omk.smpp.SMPPException
{
QuerySMResp p = new QuerySMResp();
fillAllFields(p);
return (p);
}
public ReplaceSM getReplaceSM()
throws ie.omk.smpp.SMPPException
{
ReplaceSM p = new ReplaceSM();
fillAllFields(p);
return (p);
}
public CancelSM getCancelSM()
throws ie.omk.smpp.SMPPException
{
CancelSM p = new CancelSM();
fillAllFields(p);
return (p);
}
public SubmitSMResp getSubmitSMResp()
throws ie.omk.smpp.SMPPException
{
SubmitSMResp p = new SubmitSMResp();
p.setMessageId(messageId);
return (p);
}
public SubmitMultiResp getSubmitMultiResp()
throws ie.omk.smpp.SMPPException
{
SubmitMultiResp p = new SubmitMultiResp();
p.setMessageId(messageId);
return (p);
}
private void fillAllFields(SMPPPacket p)
throws ie.omk.smpp.SMPPException
{
p.setMessageId(messageId);
p.setFinalDate(finalDate);
p.setMessageStatus(status);
p.setErrorCode(error);
p.setServiceType(serviceType);
p.setSource(sourceAddr);
p.setDestination((SmeAddress)destinationTable.get(0));
p.setDeliveryTime(deliveryTime);
p.setExpiryTime(expiryTime);
p.setMessageText(message);
p.setReplaceIfPresent(replaceIfPresent);
p.setPriority(priority);
p.setDataCoding(dataCoding);
p.setDefaultMsg(defaultMsg);
p.setProtocolID(protocolID);
p.setEsmClass(esmClass);
}
}
| Was still using getMessageText..should have been retrieving the binary data of
the message.
| src/ie/omk/smpp/MessageDetails.java | Was still using getMessageText..should have been retrieving the binary data of the message. |
|
Java | mit | 61980376ed7e95c3128fc80357ebad12ec387e6a | 0 | EinsamHauer/disthene,EinsamHauer/disthene,EinsamHauer/disthene | package net.iponweb.disthene.service.store;
import com.datastax.driver.core.*;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.google.common.util.concurrent.MoreExecutors;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.listener.Handler;
import net.engio.mbassy.listener.Listener;
import net.engio.mbassy.listener.References;
import net.iponweb.disthene.bean.Metric;
import net.iponweb.disthene.config.StoreConfiguration;
import net.iponweb.disthene.events.DistheneEvent;
import net.iponweb.disthene.events.MetricStoreEvent;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
/**
* @author Andrei Ivanov
*/
@Listener(references = References.Strong)
public class CassandraService {
private static final String QUERY = "UPDATE metric.metric USING TTL ? SET data = data + ? WHERE tenant = ? AND rollup = ? AND period = ? AND path = ? AND time = ?;";
private Logger logger = Logger.getLogger(CassandraService.class);
private Cluster cluster;
private Session session;
private Queue<Metric> metrics = new ConcurrentLinkedQueue<>();
private List<WriterThread> writerThreads = new ArrayList<>();
public CassandraService(StoreConfiguration storeConfiguration, MBassador<DistheneEvent> bus) {
bus.subscribe(this);
SocketOptions socketOptions = new SocketOptions()
.setReceiveBufferSize(1024 * 1024)
.setSendBufferSize(1024 * 1024)
.setTcpNoDelay(false)
.setReadTimeoutMillis(storeConfiguration.getReadTimeout() * 1000)
.setConnectTimeoutMillis(storeConfiguration.getConnectTimeout() * 1000);
PoolingOptions poolingOptions = new PoolingOptions();
poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, storeConfiguration.getMaxConnections());
poolingOptions.setMaxConnectionsPerHost(HostDistance.REMOTE, storeConfiguration.getMaxConnections());
poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.REMOTE, storeConfiguration.getMaxRequests());
poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, storeConfiguration.getMaxRequests());
Cluster.Builder builder = Cluster.builder()
.withSocketOptions(socketOptions)
.withCompression(ProtocolOptions.Compression.LZ4)
.withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
.withPoolingOptions(poolingOptions)
.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.ONE))
.withProtocolVersion(ProtocolVersion.V2)
.withPort(storeConfiguration.getPort());
for (String cp : storeConfiguration.getCluster()) {
builder.addContactPoint(cp);
}
cluster = builder.build();
Metadata metadata = cluster.getMetadata();
logger.debug("Connected to cluster: " + metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
logger.debug(String.format("Datacenter: %s; Host: %s; Rack: %s", host.getDatacenter(), host.getAddress(), host.getRack()));
}
session = cluster.connect();
PreparedStatement statement = session.prepare(QUERY);
// Creating writers
if (storeConfiguration.isBatch()) {
for (int i = 0; i < storeConfiguration.getPool(); i++) {
WriterThread writerThread = new BatchWriterThread(
"distheneCassandraBatchWriter" + i,
bus,
session,
statement,
metrics,
MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()),
storeConfiguration.getBatchSize()
);
writerThreads.add(writerThread);
writerThread.start();
}
} else {
for (int i = 0; i < storeConfiguration.getPool(); i++) {
WriterThread writerThread = new SingleWriterThread(
"distheneCassandraSingleWriter" + i,
bus,
session,
statement,
metrics,
MoreExecutors.listeningDecorator(Executors.newCachedThreadPool())
);
writerThreads.add(writerThread);
writerThread.start();
}
}
}
@Handler(rejectSubtypes = false)
public void handle(MetricStoreEvent metricStoreEvent) {
metrics.offer(metricStoreEvent.getMetric());
}
public void shutdown() {
for (WriterThread writerThread : writerThreads) {
writerThread.shutdown();
}
logger.info("Closing C* session");
logger.info("Waiting for C* queries to be completed");
while (getInFlightQueries(session.getState()) > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
logger.info("Closing C* cluster");
cluster.close();
}
private int getInFlightQueries(Session.State state) {
int result = 0;
Collection<Host> hosts = state.getConnectedHosts();
for(Host host : hosts) {
result += state.getInFlightQueries(host);
}
return result;
}
}
| src/main/java/net/iponweb/disthene/service/store/CassandraService.java | package net.iponweb.disthene.service.store;
import com.datastax.driver.core.*;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.google.common.util.concurrent.MoreExecutors;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.listener.Handler;
import net.engio.mbassy.listener.Listener;
import net.engio.mbassy.listener.References;
import net.iponweb.disthene.bean.Metric;
import net.iponweb.disthene.config.StoreConfiguration;
import net.iponweb.disthene.events.DistheneEvent;
import net.iponweb.disthene.events.MetricStoreEvent;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
/**
* @author Andrei Ivanov
*/
@Listener(references = References.Strong)
public class CassandraService {
private static final String QUERY = "UPDATE metric.metric USING TTL ? SET data = data + ? WHERE tenant = ? AND rollup = ? AND period = ? AND path = ? AND time = ?;";
private Logger logger = Logger.getLogger(CassandraService.class);
private Cluster cluster;
private Session session;
private Queue<Metric> metrics = new ConcurrentLinkedQueue<>();
private List<WriterThread> writerThreads = new ArrayList<>();
public CassandraService(StoreConfiguration storeConfiguration, MBassador<DistheneEvent> bus) {
bus.subscribe(this);
SocketOptions socketOptions = new SocketOptions()
.setReceiveBufferSize(1024 * 1024)
.setSendBufferSize(1024 * 1024)
.setTcpNoDelay(false)
.setReadTimeoutMillis(storeConfiguration.getReadTimeout() * 1000)
.setConnectTimeoutMillis(storeConfiguration.getConnectTimeout() * 1000);
PoolingOptions poolingOptions = new PoolingOptions();
poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, storeConfiguration.getMaxConnections());
poolingOptions.setMaxConnectionsPerHost(HostDistance.REMOTE, storeConfiguration.getMaxConnections());
poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.REMOTE, storeConfiguration.getMaxRequests());
poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, storeConfiguration.getMaxRequests());
Cluster.Builder builder = Cluster.builder()
.withSocketOptions(socketOptions)
.withCompression(ProtocolOptions.Compression.LZ4)
.withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
.withPoolingOptions(poolingOptions)
.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.ONE))
.withProtocolVersion(ProtocolVersion.V2)
.withPort(storeConfiguration.getPort());
for (String cp : storeConfiguration.getCluster()) {
builder.addContactPoint(cp);
}
cluster = builder.build();
Metadata metadata = cluster.getMetadata();
logger.debug("Connected to cluster: " + metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
logger.debug(String.format("Datacenter: %s; Host: %s; Rack: %s", host.getDatacenter(), host.getAddress(), host.getRack()));
}
session = cluster.connect();
PreparedStatement statement = session.prepare(QUERY);
// Creating writers
if (storeConfiguration.isBatch()) {
for (int i = 0; i < storeConfiguration.getPool(); i++) {
WriterThread writerThread = new BatchWriterThread(
"distheneCassandraBatchWriter" + i,
bus,
session,
statement,
metrics,
MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()),
storeConfiguration.getBatchSize()
);
writerThreads.add(writerThread);
writerThread.start();
}
} else {
for (int i = 0; i < storeConfiguration.getPool(); i++) {
WriterThread writerThread = new SingleWriterThread(
"distheneCassandraSingleWriter" + i,
bus,
session,
statement,
metrics,
MoreExecutors.listeningDecorator(Executors.newCachedThreadPool())
);
writerThreads.add(writerThread);
writerThread.start();
}
}
}
@Handler(rejectSubtypes = false)
public void handle(MetricStoreEvent metricStoreEvent) {
metrics.offer(metricStoreEvent.getMetric());
}
public void shutdown() {
for (WriterThread writerThread : writerThreads) {
writerThread.shutdown();
}
logger.info("Closing C* session");
session.close();
logger.info("Sleeping for 10 seconds to allow leftovers to be written");
try {
Thread.sleep(10000);
} catch (InterruptedException ignored) {
}
logger.info("Closing C* cluster");
cluster.close();
}
}
| even more graceful C* client shutdown
| src/main/java/net/iponweb/disthene/service/store/CassandraService.java | even more graceful C* client shutdown |
|
Java | mit | 6a3a8e52d755c9eeda9d30dcde26c71bb2110d38 | 0 | way2muchnoise/refinedstorage,raoulvdberge/refinedstorage,raoulvdberge/refinedstorage,way2muchnoise/refinedstorage | package com.raoulvdberge.refinedstorage.apiimpl.autocrafting.task;
import com.raoulvdberge.refinedstorage.RS;
import com.raoulvdberge.refinedstorage.api.autocrafting.*;
import com.raoulvdberge.refinedstorage.api.autocrafting.craftingmonitor.ICraftingMonitorElement;
import com.raoulvdberge.refinedstorage.api.autocrafting.craftingmonitor.ICraftingMonitorElementList;
import com.raoulvdberge.refinedstorage.api.autocrafting.preview.ICraftingPreviewElement;
import com.raoulvdberge.refinedstorage.api.autocrafting.task.*;
import com.raoulvdberge.refinedstorage.api.network.INetwork;
import com.raoulvdberge.refinedstorage.api.network.node.INetworkNode;
import com.raoulvdberge.refinedstorage.api.storage.disk.IStorageDisk;
import com.raoulvdberge.refinedstorage.api.util.Action;
import com.raoulvdberge.refinedstorage.api.util.IComparer;
import com.raoulvdberge.refinedstorage.api.util.IStackList;
import com.raoulvdberge.refinedstorage.apiimpl.API;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.craftingmonitor.CraftingMonitorElementError;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.craftingmonitor.CraftingMonitorElementFluidRender;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.craftingmonitor.CraftingMonitorElementItemRender;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.preview.CraftingPreviewElementFluidStack;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.preview.CraftingPreviewElementItemStack;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskFactoryFluid;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskFactoryItem;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskFluid;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskItem;
import com.raoulvdberge.refinedstorage.apiimpl.util.OneSixMigrationHelper;
import com.raoulvdberge.refinedstorage.util.StackUtils;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.items.ItemHandlerHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.*;
public class CraftingTask implements ICraftingTask {
private static final String NBT_REQUESTED = "Requested";
private static final String NBT_QUANTITY = "Quantity";
private static final String NBT_PATTERN = "Pattern";
private static final String NBT_TICKS = "Ticks";
private static final String NBT_ID = "Id";
private static final String NBT_EXECUTION_STARTED = "ExecutionStarted";
private static final String NBT_INTERNAL_STORAGE = "InternalStorage";
private static final String NBT_INTERNAL_FLUID_STORAGE = "InternalFluidStorage";
private static final String NBT_TO_EXTRACT_INITIAL = "ToExtractInitial";
private static final String NBT_TO_EXTRACT_INITIAL_FLUIDS = "ToExtractInitialFluids";
private static final String NBT_CRAFTING = "Crafting";
private static final String NBT_PROCESSING = "Processing";
private static final String NBT_MISSING = "Missing";
private static final String NBT_MISSING_FLUIDS = "MissingFluids";
private static final String NBT_PATTERN_STACK = "Stack";
private static final String NBT_PATTERN_CONTAINER_POS = "ContainerPos";
private static final int DEFAULT_EXTRACT_FLAGS = IComparer.COMPARE_NBT | IComparer.COMPARE_DAMAGE;
private static final Logger LOGGER = LogManager.getLogger();
private INetwork network;
private ICraftingRequestInfo requested;
private int quantity;
private ICraftingPattern pattern;
private UUID id = UUID.randomUUID();
private int ticks;
private long calculationStarted = -1;
private long executionStarted = -1;
private Set<ICraftingPattern> patternsUsed = new HashSet<>();
private IStorageDisk<ItemStack> internalStorage;
private IStorageDisk<FluidStack> internalFluidStorage;
private IStackList<ItemStack> toExtractInitial = API.instance().createItemStackList();
private IStackList<FluidStack> toExtractInitialFluids = API.instance().createFluidStackList();
private List<Crafting> crafting = new ArrayList<>();
private List<Processing> processing = new ArrayList<>();
private IStackList<ItemStack> missing = API.instance().createItemStackList();
private IStackList<FluidStack> missingFluids = API.instance().createFluidStackList();
private IStackList<ItemStack> toTake = API.instance().createItemStackList();
private IStackList<FluidStack> toTakeFluids = API.instance().createFluidStackList();
private IStackList<ItemStack> toCraft = API.instance().createItemStackList();
private IStackList<FluidStack> toCraftFluids = API.instance().createFluidStackList();
public CraftingTask(INetwork network, ICraftingRequestInfo requested, int quantity, ICraftingPattern pattern) {
this.network = network;
this.requested = requested;
this.quantity = quantity;
this.pattern = pattern;
this.internalStorage = new StorageDiskItem(network.world(), -1);
this.internalFluidStorage = new StorageDiskFluid(network.world(), -1);
}
public CraftingTask(INetwork network, NBTTagCompound tag) throws CraftingTaskReadException {
OneSixMigrationHelper.removalHook();
if (!tag.hasKey(NBT_INTERNAL_STORAGE)) {
throw new CraftingTaskReadException("Couldn't read crafting task from before RS v1.6.4, skipping...");
}
this.network = network;
this.requested = API.instance().createCraftingRequestInfo(tag.getCompoundTag(NBT_REQUESTED));
this.quantity = tag.getInteger(NBT_QUANTITY);
this.pattern = readPatternFromNbt(tag.getCompoundTag(NBT_PATTERN), network.world());
this.ticks = tag.getInteger(NBT_TICKS);
this.id = tag.getUniqueId(NBT_ID);
this.executionStarted = tag.getLong(NBT_EXECUTION_STARTED);
StorageDiskFactoryItem factoryItem = new StorageDiskFactoryItem();
StorageDiskFactoryFluid factoryFluid = new StorageDiskFactoryFluid();
this.internalStorage = factoryItem.createFromNbt(network.world(), tag.getCompoundTag(NBT_INTERNAL_STORAGE));
this.internalFluidStorage = factoryFluid.createFromNbt(network.world(), tag.getCompoundTag(NBT_INTERNAL_FLUID_STORAGE));
this.toExtractInitial = readItemStackList(tag.getTagList(NBT_TO_EXTRACT_INITIAL, Constants.NBT.TAG_COMPOUND));
this.toExtractInitialFluids = readFluidStackList(tag.getTagList(NBT_TO_EXTRACT_INITIAL_FLUIDS, Constants.NBT.TAG_COMPOUND));
NBTTagList craftingList = tag.getTagList(NBT_CRAFTING, Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < craftingList.tagCount(); ++i) {
crafting.add(new Crafting(network, craftingList.getCompoundTagAt(i)));
}
NBTTagList processingList = tag.getTagList(NBT_PROCESSING, Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < processingList.tagCount(); ++i) {
processing.add(new Processing(network, processingList.getCompoundTagAt(i)));
}
this.missing = readItemStackList(tag.getTagList(NBT_MISSING, Constants.NBT.TAG_COMPOUND));
this.missingFluids = readFluidStackList(tag.getTagList(NBT_MISSING_FLUIDS, Constants.NBT.TAG_COMPOUND));
}
@Override
public NBTTagCompound writeToNbt(NBTTagCompound tag) {
tag.setTag(NBT_REQUESTED, requested.writeToNbt());
tag.setInteger(NBT_QUANTITY, quantity);
tag.setTag(NBT_PATTERN, writePatternToNbt(pattern));
tag.setInteger(NBT_TICKS, ticks);
tag.setUniqueId(NBT_ID, id);
tag.setLong(NBT_EXECUTION_STARTED, executionStarted);
tag.setTag(NBT_INTERNAL_STORAGE, internalStorage.writeToNbt());
tag.setTag(NBT_INTERNAL_FLUID_STORAGE, internalFluidStorage.writeToNbt());
tag.setTag(NBT_TO_EXTRACT_INITIAL, writeItemStackList(toExtractInitial));
tag.setTag(NBT_TO_EXTRACT_INITIAL_FLUIDS, writeFluidStackList(toExtractInitialFluids));
NBTTagList craftingList = new NBTTagList();
for (Crafting crafting : this.crafting) {
craftingList.appendTag(crafting.writeToNbt());
}
tag.setTag(NBT_CRAFTING, craftingList);
NBTTagList processingList = new NBTTagList();
for (Processing processing : this.processing) {
processingList.appendTag(processing.writeToNbt());
}
tag.setTag(NBT_PROCESSING, processingList);
tag.setTag(NBT_MISSING, writeItemStackList(missing));
tag.setTag(NBT_MISSING_FLUIDS, writeFluidStackList(missingFluids));
return tag;
}
static NBTTagList writeItemStackList(IStackList<ItemStack> stacks) {
NBTTagList list = new NBTTagList();
for (ItemStack stack : stacks.getStacks()) {
list.appendTag(StackUtils.serializeStackToNbt(stack));
}
return list;
}
static IStackList<ItemStack> readItemStackList(NBTTagList list) throws CraftingTaskReadException {
IStackList<ItemStack> stacks = API.instance().createItemStackList();
for (int i = 0; i < list.tagCount(); ++i) {
ItemStack stack = StackUtils.deserializeStackFromNbt(list.getCompoundTagAt(i));
if (stack.isEmpty()) {
throw new CraftingTaskReadException("Empty stack!");
}
stacks.add(stack);
}
return stacks;
}
static NBTTagList writeFluidStackList(IStackList<FluidStack> stacks) {
NBTTagList list = new NBTTagList();
for (FluidStack stack : stacks.getStacks()) {
list.appendTag(stack.writeToNBT(new NBTTagCompound()));
}
return list;
}
static IStackList<FluidStack> readFluidStackList(NBTTagList list) throws CraftingTaskReadException {
IStackList<FluidStack> stacks = API.instance().createFluidStackList();
for (int i = 0; i < list.tagCount(); ++i) {
FluidStack stack = FluidStack.loadFluidStackFromNBT(list.getCompoundTagAt(i));
if (stack == null) {
throw new CraftingTaskReadException("Empty stack!");
}
stacks.add(stack);
}
return stacks;
}
@Override
@Nullable
public ICraftingTaskError calculate() {
if (calculationStarted != -1) {
throw new IllegalStateException("Task already calculated!");
}
if (executionStarted != -1) {
throw new IllegalStateException("Task already started!");
}
this.calculationStarted = System.currentTimeMillis();
int qty = this.quantity;
int qtyPerCraft = getQuantityPerCraft();
int crafted = 0;
IStackList<ItemStack> results = API.instance().createItemStackList();
IStackList<FluidStack> fluidResults = API.instance().createFluidStackList();
IStackList<ItemStack> storage = network.getItemStorageCache().getList().copy();
IStackList<FluidStack> fluidStorage = network.getFluidStorageCache().getList().copy();
ICraftingPatternChainList patternChainList = network.getCraftingManager().createPatternChainList();
ICraftingPatternChain patternChain = patternChainList.getChain(pattern);
while (qty > 0) {
ICraftingTaskError result = calculateInternal(storage, fluidStorage, results, fluidResults, patternChainList, patternChain.current(), true);
if (result != null) {
return result;
}
qty -= qtyPerCraft;
crafted += qtyPerCraft;
patternChain.cycle();
}
if (requested.getItem() != null) {
this.toCraft.add(requested.getItem(), crafted);
} else {
this.toCraftFluids.add(requested.getFluid(), crafted);
}
return null;
}
class PossibleInputs {
private List<ItemStack> possibilities;
private int pos;
PossibleInputs(List<ItemStack> possibilities) {
this.possibilities = possibilities;
}
ItemStack get() {
return possibilities.get(pos);
}
// Return false if we're exhausted.
boolean cycle() {
if (pos + 1 >= possibilities.size()) {
pos = 0;
return false;
}
pos++;
return true;
}
void sort(IStackList<ItemStack> mutatedStorage, IStackList<ItemStack> results) {
possibilities.sort((a, b) -> {
ItemStack ar = mutatedStorage.get(a);
ItemStack br = mutatedStorage.get(b);
return (br == null ? 0 : br.getCount()) - (ar == null ? 0 : ar.getCount());
});
possibilities.sort((a, b) -> {
ItemStack ar = results.get(a);
ItemStack br = results.get(b);
return (br == null ? 0 : br.getCount()) - (ar == null ? 0 : ar.getCount());
});
}
}
@Nullable
private ICraftingTaskError calculateInternal(
IStackList<ItemStack> mutatedStorage,
IStackList<FluidStack> mutatedFluidStorage,
IStackList<ItemStack> results,
IStackList<FluidStack> fluidResults,
ICraftingPatternChainList patternChainList,
ICraftingPattern pattern,
boolean root) {
if (System.currentTimeMillis() - calculationStarted > RS.INSTANCE.config.calculationTimeoutMs) {
return new CraftingTaskError(CraftingTaskErrorType.TOO_COMPLEX);
}
if (!patternsUsed.add(pattern)) {
return new CraftingTaskError(CraftingTaskErrorType.RECURSIVE, pattern);
}
IStackList<ItemStack> itemsToExtract = API.instance().createItemStackList();
IStackList<FluidStack> fluidsToExtract = API.instance().createFluidStackList();
NonNullList<ItemStack> took = NonNullList.create();
for (NonNullList<ItemStack> inputs : pattern.getInputs()) {
if (inputs.isEmpty()) {
took.add(ItemStack.EMPTY);
continue;
}
PossibleInputs possibleInputs = new PossibleInputs(new ArrayList<>(inputs));
possibleInputs.sort(mutatedStorage, results);
ItemStack possibleInput = possibleInputs.get();
ItemStack fromSelf = results.get(possibleInput);
ItemStack fromNetwork = mutatedStorage.get(possibleInput);
took.add(possibleInput);
int remaining = possibleInput.getCount();
while (remaining > 0) {
if (fromSelf != null) {
int toTake = Math.min(remaining, fromSelf.getCount());
itemsToExtract.add(possibleInput, toTake);
results.remove(fromSelf, toTake);
remaining -= toTake;
fromSelf = results.get(possibleInput);
} else if (fromNetwork != null) {
int toTake = Math.min(remaining, fromNetwork.getCount());
this.toTake.add(possibleInput, toTake);
itemsToExtract.add(possibleInput, toTake);
mutatedStorage.remove(fromNetwork, toTake);
remaining -= toTake;
fromNetwork = mutatedStorage.get(possibleInput);
toExtractInitial.add(took.get(took.size() - 1));
} else {
ICraftingPattern subPattern = network.getCraftingManager().getPattern(possibleInput);
if (subPattern != null) {
ICraftingPatternChain subPatternChain = patternChainList.getChain(subPattern);
while ((fromSelf == null ? 0 : fromSelf.getCount()) < remaining) {
ICraftingTaskError result = calculateInternal(mutatedStorage, mutatedFluidStorage, results, fluidResults, patternChainList, subPatternChain.current(), false);
if (result != null) {
return result;
}
fromSelf = results.get(possibleInput);
if (fromSelf == null) {
throw new IllegalStateException("Recursive calculation didn't yield anything");
}
fromNetwork = mutatedStorage.get(possibleInput);
subPatternChain.cycle();
}
// fromSelf contains the amount crafted after the loop.
this.toCraft.add(possibleInput, fromSelf.getCount());
} else {
if (!possibleInputs.cycle()) {
// Give up.
possibleInput = possibleInputs.get(); // Revert back to 0.
this.missing.add(possibleInput, remaining);
itemsToExtract.add(possibleInput, remaining);
remaining = 0;
} else {
// Retry with new input...
possibleInput = possibleInputs.get();
fromSelf = results.get(possibleInput);
fromNetwork = mutatedStorage.get(possibleInput);
}
}
}
}
}
for (FluidStack input : pattern.getFluidInputs()) {
FluidStack fromSelf = fluidResults.get(input, IComparer.COMPARE_NBT);
FluidStack fromNetwork = mutatedFluidStorage.get(input, IComparer.COMPARE_NBT);
int remaining = input.amount;
while (remaining > 0) {
if (fromSelf != null) {
int toTake = Math.min(remaining, fromSelf.amount);
fluidsToExtract.add(input, toTake);
fluidResults.remove(input, toTake);
remaining -= toTake;
fromSelf = fluidResults.get(input, IComparer.COMPARE_NBT);
} else if (fromNetwork != null) {
int toTake = Math.min(remaining, fromNetwork.amount);
this.toTakeFluids.add(input, toTake);
fluidsToExtract.add(input, toTake);
mutatedFluidStorage.remove(fromNetwork, toTake);
remaining -= toTake;
fromNetwork = mutatedFluidStorage.get(input, IComparer.COMPARE_NBT);
toExtractInitialFluids.add(input);
} else {
ICraftingPattern subPattern = network.getCraftingManager().getPattern(input);
if (subPattern != null) {
ICraftingPatternChain subPatternChain = patternChainList.getChain(subPattern);
while ((fromSelf == null ? 0 : fromSelf.amount) < remaining) {
ICraftingTaskError result = calculateInternal(mutatedStorage, mutatedFluidStorage, results, fluidResults, patternChainList, subPatternChain.current(), false);
if (result != null) {
return result;
}
fromSelf = fluidResults.get(input, IComparer.COMPARE_NBT);
if (fromSelf == null) {
throw new IllegalStateException("Recursive fluid calculation didn't yield anything");
}
fromNetwork = mutatedFluidStorage.get(input, IComparer.COMPARE_NBT);
subPatternChain.cycle();
}
// fromSelf contains the amount crafted after the loop.
this.toCraftFluids.add(input, fromSelf.amount);
} else {
this.missingFluids.add(input, remaining);
fluidsToExtract.add(input, remaining);
remaining = 0;
}
}
}
}
patternsUsed.remove(pattern);
if (pattern.isProcessing()) {
IStackList<ItemStack> itemsToReceive = API.instance().createItemStackList();
IStackList<FluidStack> fluidsToReceive = API.instance().createFluidStackList();
for (ItemStack output : pattern.getOutputs()) {
results.add(output);
itemsToReceive.add(output);
}
for (FluidStack output : pattern.getFluidOutputs()) {
fluidResults.add(output);
fluidsToReceive.add(output);
}
processing.add(new Processing(pattern, itemsToReceive, fluidsToReceive, new ArrayList<>(itemsToExtract.getStacks()), new ArrayList<>(fluidsToExtract.getStacks()), root));
} else {
if (!fluidsToExtract.isEmpty()) {
throw new IllegalStateException("Cannot extract fluids in normal pattern!");
}
crafting.add(new Crafting(pattern, took, itemsToExtract, root));
results.add(pattern.getOutput(took));
for (ItemStack byproduct : pattern.getByproducts(took)) {
results.add(byproduct);
}
}
return null;
}
private static int getTickInterval(int speedUpgrades) {
switch (speedUpgrades) {
case 0:
return 10;
case 1:
return 8;
case 2:
return 6;
case 3:
return 4;
case 4:
return 2;
default:
return 2;
}
}
private void extractInitial() {
if (!toExtractInitial.isEmpty()) {
List<ItemStack> toRemove = new ArrayList<>();
for (ItemStack toExtract : toExtractInitial.getStacks()) {
ItemStack result = network.extractItem(toExtract, toExtract.getCount(), Action.PERFORM);
if (result != null) {
internalStorage.insert(toExtract, toExtract.getCount(), Action.PERFORM);
toRemove.add(result);
}
}
for (ItemStack stack : toRemove) {
toExtractInitial.remove(stack);
}
if (!toRemove.isEmpty()) {
network.getCraftingManager().onTaskChanged();
}
}
if (!toExtractInitialFluids.isEmpty()) {
List<FluidStack> toRemove = new ArrayList<>();
for (FluidStack toExtract : toExtractInitialFluids.getStacks()) {
FluidStack result = network.extractFluid(toExtract, toExtract.amount, Action.PERFORM);
if (result != null) {
internalFluidStorage.insert(toExtract, toExtract.amount, Action.PERFORM);
toRemove.add(result);
}
}
for (FluidStack stack : toRemove) {
toExtractInitialFluids.remove(stack);
}
if (!toRemove.isEmpty()) {
network.getCraftingManager().onTaskChanged();
}
}
}
private void updateCrafting() {
Iterator<Crafting> it = crafting.iterator();
while (it.hasNext()) {
Crafting c = it.next();
if (ticks % getTickInterval(c.getPattern().getContainer().getSpeedUpgradeCount()) == 0) {
boolean hasAll = true;
for (ItemStack need : c.getToExtract().getStacks()) {
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.SIMULATE);
if (result == null || result.getCount() != need.getCount()) {
hasAll = false;
break;
}
}
if (hasAll) {
for (ItemStack need : c.getToExtract().getStacks()) {
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.PERFORM);
if (result == null || result.getCount() != need.getCount()) {
throw new IllegalStateException("Extractor check lied");
}
}
ItemStack output = c.getPattern().getOutput(c.getTook());
if (!c.isRoot()) {
this.internalStorage.insert(output, output.getCount(), Action.PERFORM);
} else {
ItemStack remainder = this.network.insertItem(output, output.getCount(), Action.PERFORM);
if (remainder != null) {
this.internalStorage.insert(remainder, remainder.getCount(), Action.PERFORM);
}
}
// Byproducts need to always be inserted in the internal storage for later reuse further in the task.
// Regular outputs can be inserted into the network *IF* it's a root since it's *NOT* expected to be used later on.
for (ItemStack byp : c.getPattern().getByproducts(c.getTook())) {
this.internalStorage.insert(byp, byp.getCount(), Action.PERFORM);
}
it.remove();
network.getCraftingManager().onTaskChanged();
return;
}
}
}
}
private void updateProcessing() {
Iterator<Processing> it = processing.iterator();
while (it.hasNext()) {
Processing p = it.next();
if (p.getState() == ProcessingState.PROCESSED) {
it.remove();
network.getCraftingManager().onTaskChanged();
continue;
}
if (p.getState() == ProcessingState.EXTRACTED_ALL) {
continue;
}
if (ticks % getTickInterval(p.getPattern().getContainer().getSpeedUpgradeCount()) == 0) {
ProcessingState originalState = p.getState();
if (p.getPattern().getContainer().isLocked()) {
p.setState(ProcessingState.LOCKED);
} else {
boolean hasAll = true;
for (ItemStack need : p.getItemsToPut()) {
if (p.getPattern().getContainer().getConnectedInventory() == null) {
p.setState(ProcessingState.MACHINE_NONE);
} else {
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.SIMULATE);
if (result == null || result.getCount() != need.getCount()) {
hasAll = false;
break;
} else if (!ItemHandlerHelper.insertItem(p.getPattern().getContainer().getConnectedInventory(), result, true).isEmpty()) {
p.setState(ProcessingState.MACHINE_DOES_NOT_ACCEPT);
break;
} else {
p.setState(ProcessingState.READY);
}
}
}
for (FluidStack need : p.getFluidsToPut()) {
if (p.getPattern().getContainer().getConnectedFluidInventory() == null) {
p.setState(ProcessingState.MACHINE_NONE);
} else {
FluidStack result = this.internalFluidStorage.extract(need, need.amount, IComparer.COMPARE_NBT, Action.SIMULATE);
if (result == null || result.amount != need.amount) {
hasAll = false;
break;
} else if (p.getPattern().getContainer().getConnectedFluidInventory().fill(result, false) != result.amount) {
p.setState(ProcessingState.MACHINE_DOES_NOT_ACCEPT);
break;
} else if (p.getState() == ProcessingState.READY) { // If the items were ok.
p.setState(ProcessingState.READY);
}
}
}
if (p.getState() == ProcessingState.READY && hasAll) {
boolean abort = false;
for (int i = 0; i < p.getItemsToPut().size(); ++i) {
ItemStack need = p.getItemsToPut().get(i);
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.PERFORM);
if (result == null || result.getCount() != need.getCount()) {
throw new IllegalStateException("The internal crafting inventory reported that " + need + " was available but we got " + result);
}
ItemStack remainder = ItemHandlerHelper.insertItem(p.getPattern().getContainer().getConnectedInventory(), result, false);
if (!remainder.isEmpty()) {
LOGGER.warn("In a simulation, " + p.getPattern().getContainer().getConnectedInventory() + " reported that we could insert " + result + " but we got " + remainder + " as a remainder");
this.internalStorage.insert(remainder, remainder.getCount(), Action.PERFORM);
p.getItemsToPut().set(i, remainder);
abort = true;
break;
}
}
if (abort) {
continue;
}
for (int i = 0; i < p.getFluidsToPut().size(); ++i) {
FluidStack need = p.getFluidsToPut().get(i);
FluidStack result = this.internalFluidStorage.extract(need, need.amount, IComparer.COMPARE_NBT, Action.PERFORM);
if (result == null || result.amount != need.amount) {
throw new IllegalStateException("The internal crafting inventory reported that " + need + " was available but we got " + result);
}
int filled = p.getPattern().getContainer().getConnectedFluidInventory().fill(result, true);
if (filled != result.amount) {
LOGGER.warn("In a simulation, " + p.getPattern().getContainer().getConnectedFluidInventory() + " reported that we could fill " + result + " but we only filled " + filled);
this.internalFluidStorage.insert(result, result.amount - filled, Action.PERFORM);
p.getFluidsToPut().set(i, StackUtils.copy(result, result.amount - filled));
abort = true;
break;
}
}
if (abort) {
continue;
}
p.setState(ProcessingState.EXTRACTED_ALL);
p.getPattern().getContainer().onUsedForProcessing();
}
}
if (originalState != p.getState()) {
network.getCraftingManager().onTaskChanged();
}
}
}
}
@Override
public boolean update() {
if (executionStarted == -1) {
executionStarted = System.currentTimeMillis();
}
++ticks;
extractInitial();
if (this.crafting.isEmpty() && this.processing.isEmpty()) {
List<Runnable> toPerform = new ArrayList<>();
for (ItemStack stack : internalStorage.getStacks()) {
ItemStack remainder = network.insertItem(stack, stack.getCount(), Action.PERFORM);
toPerform.add(() -> {
if (remainder == null) {
internalStorage.extract(stack, stack.getCount(), IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
} else {
internalStorage.extract(stack, stack.getCount() - remainder.getCount(), IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
}
});
}
for (FluidStack stack : internalFluidStorage.getStacks()) {
FluidStack remainder = network.insertFluid(stack, stack.amount, Action.PERFORM);
toPerform.add(() -> {
if (remainder == null) {
internalFluidStorage.extract(stack, stack.amount, IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
} else {
internalFluidStorage.extract(stack, stack.amount - remainder.amount, IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
}
});
}
// Prevent CME.
toPerform.forEach(Runnable::run);
return internalStorage.getStacks().isEmpty() && internalFluidStorage.getStacks().isEmpty();
} else {
updateCrafting();
updateProcessing();
return false;
}
}
@Override
public void onCancelled() {
for (ItemStack remainder : internalStorage.getStacks()) {
network.insertItem(remainder, remainder.getCount(), Action.PERFORM);
}
for (FluidStack remainder : internalFluidStorage.getStacks()) {
network.insertFluid(remainder, remainder.amount, Action.PERFORM);
}
}
@Override
public int getQuantity() {
return quantity;
}
@Override
public int getQuantityPerCraft() {
int qty = 0;
if (requested.getItem() != null) {
for (ItemStack output : pattern.getOutputs()) {
if (API.instance().getComparer().isEqualNoQuantity(output, requested.getItem())) {
qty += output.getCount();
if (!pattern.isProcessing()) {
break;
}
}
}
} else {
for (FluidStack output : pattern.getFluidOutputs()) {
if (API.instance().getComparer().isEqual(output, requested.getFluid(), IComparer.COMPARE_NBT)) {
qty += output.amount;
}
}
}
return qty;
}
@Override
public ICraftingRequestInfo getRequested() {
return requested;
}
@Override
public int onTrackedInsert(ItemStack stack, int size) {
for (Processing p : this.processing) {
if (p.getState() != ProcessingState.EXTRACTED_ALL) {
continue;
}
ItemStack content = p.getItemsToReceive().get(stack);
if (content != null) {
int needed = content.getCount();
if (needed > size) {
needed = size;
}
p.getItemsToReceive().remove(stack, needed);
size -= needed;
if (p.getItemsToReceive().isEmpty() && p.getFluidsToReceive().isEmpty()) {
p.setState(ProcessingState.PROCESSED);
}
if (!p.isRoot()) {
internalStorage.insert(stack, needed, Action.PERFORM);
} else {
ItemStack remainder = network.insertItem(stack, needed, Action.PERFORM);
if (remainder != null) {
internalStorage.insert(stack, needed, Action.PERFORM);
}
}
if (size == 0) {
return 0;
}
}
}
return size;
}
@Override
public int onTrackedInsert(FluidStack stack, int size) {
for (Processing p : this.processing) {
if (p.getState() != ProcessingState.EXTRACTED_ALL) {
continue;
}
FluidStack content = p.getFluidsToReceive().get(stack);
if (content != null) {
int needed = content.amount;
if (needed > size) {
needed = size;
}
p.getFluidsToReceive().remove(stack, needed);
size -= needed;
if (p.getItemsToReceive().isEmpty() && p.getFluidsToReceive().isEmpty()) {
p.setState(ProcessingState.PROCESSED);
}
if (!p.isRoot()) {
internalFluidStorage.insert(stack, needed, Action.PERFORM);
} else {
FluidStack remainder = network.insertFluid(stack, needed, Action.PERFORM);
if (remainder != null) {
internalFluidStorage.insert(stack, needed, Action.PERFORM);
}
}
if (size == 0) {
return 0;
}
}
}
return size;
}
static NBTTagCompound writePatternToNbt(ICraftingPattern pattern) {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag(NBT_PATTERN_STACK, pattern.getStack().serializeNBT());
tag.setLong(NBT_PATTERN_CONTAINER_POS, pattern.getContainer().getPosition().toLong());
return tag;
}
static ICraftingPattern readPatternFromNbt(NBTTagCompound tag, World world) throws CraftingTaskReadException {
BlockPos containerPos = BlockPos.fromLong(tag.getLong(NBT_PATTERN_CONTAINER_POS));
INetworkNode node = API.instance().getNetworkNodeManager(world).getNode(containerPos);
if (node instanceof ICraftingPatternContainer) {
ItemStack stack = new ItemStack(tag.getCompoundTag(NBT_PATTERN_STACK));
if (stack.getItem() instanceof ICraftingPatternProvider) {
return ((ICraftingPatternProvider) stack.getItem()).create(world, stack, (ICraftingPatternContainer) node);
} else {
throw new CraftingTaskReadException("Pattern stack is not a crafting pattern provider");
}
} else {
throw new CraftingTaskReadException("Crafting pattern container doesn't exist anymore");
}
}
@Override
public List<ICraftingMonitorElement> getCraftingMonitorElements() {
ICraftingMonitorElementList elements = API.instance().createCraftingMonitorElementList();
for (ItemStack stack : this.internalStorage.getStacks()) {
elements.add(new CraftingMonitorElementItemRender(stack, stack.getCount(), 0, 0, 0, 0));
}
for (ItemStack missing : this.missing.getStacks()) {
elements.add(new CraftingMonitorElementItemRender(missing, 0, missing.getCount(), 0, 0, 0));
}
for (Crafting crafting : this.crafting) {
for (ItemStack receive : crafting.getPattern().getOutputs()) {
elements.add(new CraftingMonitorElementItemRender(receive, 0, 0, 0, 0, receive.getCount()));
}
}
for (Processing processing : this.processing) {
if (processing.getState() == ProcessingState.PROCESSED) {
continue;
}
if (processing.getState() == ProcessingState.EXTRACTED_ALL) {
for (ItemStack put : processing.getItemsToPut()) {
elements.add(new CraftingMonitorElementItemRender(put, 0, 0, put.getCount(), 0, 0));
}
} else if (processing.getState() == ProcessingState.READY || processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT || processing.getState() == ProcessingState.MACHINE_NONE || processing.getState() == ProcessingState.LOCKED) {
for (ItemStack receive : processing.getItemsToReceive().getStacks()) {
ICraftingMonitorElement element = new CraftingMonitorElementItemRender(receive, 0, 0, 0, receive.getCount(), 0);
if (processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_does_not_accept_item");
} else if (processing.getState() == ProcessingState.MACHINE_NONE) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_none");
} else if (processing.getState() == ProcessingState.LOCKED) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.crafter_is_locked");
}
elements.add(element);
}
}
}
elements.commit();
for (FluidStack stack : this.internalFluidStorage.getStacks()) {
elements.add(new CraftingMonitorElementFluidRender(stack, stack.amount, 0, 0, 0, 0));
}
for (FluidStack missing : this.missingFluids.getStacks()) {
elements.add(new CraftingMonitorElementFluidRender(missing, 0, missing.amount, 0, 0, 0));
}
for (Processing processing : this.processing) {
if (processing.getState() == ProcessingState.PROCESSED) {
continue;
}
if (processing.getState() == ProcessingState.EXTRACTED_ALL) {
for (FluidStack put : processing.getFluidsToPut()) {
elements.add(new CraftingMonitorElementFluidRender(put, 0, 0, put.amount, 0, 0));
}
} else if (processing.getState() == ProcessingState.READY || processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT || processing.getState() == ProcessingState.MACHINE_NONE) {
for (FluidStack receive : processing.getFluidsToReceive().getStacks()) {
ICraftingMonitorElement element = new CraftingMonitorElementFluidRender(receive, 0, 0, 0, receive.amount, 0);
if (processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_does_not_accept_fluid");
} else if (processing.getState() == ProcessingState.MACHINE_NONE) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_none");
}
elements.add(element);
}
}
}
elements.commit();
return elements.getElements();
}
@Override
public List<ICraftingPreviewElement> getPreviewStacks() {
Map<Integer, CraftingPreviewElementItemStack> map = new LinkedHashMap<>();
Map<Integer, CraftingPreviewElementFluidStack> mapFluids = new LinkedHashMap<>();
for (ItemStack stack : toCraft.getStacks()) {
int hash = API.instance().getItemStackHashCode(stack);
CraftingPreviewElementItemStack previewStack = map.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementItemStack(stack);
}
previewStack.addToCraft(stack.getCount());
map.put(hash, previewStack);
}
for (FluidStack stack : toCraftFluids.getStacks()) {
int hash = API.instance().getFluidStackHashCode(stack);
CraftingPreviewElementFluidStack previewStack = mapFluids.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementFluidStack(stack);
}
previewStack.addToCraft(stack.amount);
mapFluids.put(hash, previewStack);
}
for (ItemStack stack : missing.getStacks()) {
int hash = API.instance().getItemStackHashCode(stack);
CraftingPreviewElementItemStack previewStack = map.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementItemStack(stack);
}
previewStack.setMissing(true);
previewStack.addToCraft(stack.getCount());
map.put(hash, previewStack);
}
for (FluidStack stack : missingFluids.getStacks()) {
int hash = API.instance().getFluidStackHashCode(stack);
CraftingPreviewElementFluidStack previewStack = mapFluids.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementFluidStack(stack);
}
previewStack.setMissing(true);
previewStack.addToCraft(stack.amount);
mapFluids.put(hash, previewStack);
}
for (ItemStack stack : toTake.getStacks()) {
int hash = API.instance().getItemStackHashCode(stack);
CraftingPreviewElementItemStack previewStack = map.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementItemStack(stack);
}
previewStack.addAvailable(stack.getCount());
map.put(hash, previewStack);
}
for (FluidStack stack : toTakeFluids.getStacks()) {
int hash = API.instance().getFluidStackHashCode(stack);
CraftingPreviewElementFluidStack previewStack = mapFluids.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementFluidStack(stack);
}
previewStack.addAvailable(stack.amount);
mapFluids.put(hash, previewStack);
}
List<ICraftingPreviewElement> elements = new ArrayList<>();
elements.addAll(map.values());
elements.addAll(mapFluids.values());
return elements;
}
@Override
public ICraftingPattern getPattern() {
return pattern;
}
@Override
public long getExecutionStarted() {
return executionStarted;
}
@Override
public IStackList<ItemStack> getMissing() {
return missing;
}
@Override
public UUID getId() {
return id;
}
}
| src/main/java/com/raoulvdberge/refinedstorage/apiimpl/autocrafting/task/CraftingTask.java | package com.raoulvdberge.refinedstorage.apiimpl.autocrafting.task;
import com.raoulvdberge.refinedstorage.RS;
import com.raoulvdberge.refinedstorage.api.autocrafting.*;
import com.raoulvdberge.refinedstorage.api.autocrafting.craftingmonitor.ICraftingMonitorElement;
import com.raoulvdberge.refinedstorage.api.autocrafting.craftingmonitor.ICraftingMonitorElementList;
import com.raoulvdberge.refinedstorage.api.autocrafting.preview.ICraftingPreviewElement;
import com.raoulvdberge.refinedstorage.api.autocrafting.task.*;
import com.raoulvdberge.refinedstorage.api.network.INetwork;
import com.raoulvdberge.refinedstorage.api.network.node.INetworkNode;
import com.raoulvdberge.refinedstorage.api.storage.disk.IStorageDisk;
import com.raoulvdberge.refinedstorage.api.util.Action;
import com.raoulvdberge.refinedstorage.api.util.IComparer;
import com.raoulvdberge.refinedstorage.api.util.IStackList;
import com.raoulvdberge.refinedstorage.apiimpl.API;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.craftingmonitor.CraftingMonitorElementError;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.craftingmonitor.CraftingMonitorElementFluidRender;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.craftingmonitor.CraftingMonitorElementItemRender;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.preview.CraftingPreviewElementFluidStack;
import com.raoulvdberge.refinedstorage.apiimpl.autocrafting.preview.CraftingPreviewElementItemStack;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskFactoryFluid;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskFactoryItem;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskFluid;
import com.raoulvdberge.refinedstorage.apiimpl.storage.disk.StorageDiskItem;
import com.raoulvdberge.refinedstorage.apiimpl.util.OneSixMigrationHelper;
import com.raoulvdberge.refinedstorage.util.StackUtils;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.items.ItemHandlerHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.*;
public class CraftingTask implements ICraftingTask {
private static final String NBT_REQUESTED = "Requested";
private static final String NBT_QUANTITY = "Quantity";
private static final String NBT_PATTERN = "Pattern";
private static final String NBT_TICKS = "Ticks";
private static final String NBT_ID = "Id";
private static final String NBT_EXECUTION_STARTED = "ExecutionStarted";
private static final String NBT_INTERNAL_STORAGE = "InternalStorage";
private static final String NBT_INTERNAL_FLUID_STORAGE = "InternalFluidStorage";
private static final String NBT_TO_EXTRACT_INITIAL = "ToExtractInitial";
private static final String NBT_TO_EXTRACT_INITIAL_FLUIDS = "ToExtractInitialFluids";
private static final String NBT_CRAFTING = "Crafting";
private static final String NBT_PROCESSING = "Processing";
private static final String NBT_MISSING = "Missing";
private static final String NBT_MISSING_FLUIDS = "MissingFluids";
private static final String NBT_PATTERN_STACK = "Stack";
private static final String NBT_PATTERN_CONTAINER_POS = "ContainerPos";
private static final int DEFAULT_EXTRACT_FLAGS = IComparer.COMPARE_NBT | IComparer.COMPARE_DAMAGE;
private static final Logger LOGGER = LogManager.getLogger();
private INetwork network;
private ICraftingRequestInfo requested;
private int quantity;
private ICraftingPattern pattern;
private UUID id = UUID.randomUUID();
private int ticks;
private long calculationStarted = -1;
private long executionStarted = -1;
private Set<ICraftingPattern> patternsUsed = new HashSet<>();
private IStorageDisk<ItemStack> internalStorage;
private IStorageDisk<FluidStack> internalFluidStorage;
private IStackList<ItemStack> toExtractInitial = API.instance().createItemStackList();
private IStackList<FluidStack> toExtractInitialFluids = API.instance().createFluidStackList();
private List<Crafting> crafting = new ArrayList<>();
private List<Processing> processing = new ArrayList<>();
private IStackList<ItemStack> missing = API.instance().createItemStackList();
private IStackList<FluidStack> missingFluids = API.instance().createFluidStackList();
private IStackList<ItemStack> toTake = API.instance().createItemStackList();
private IStackList<FluidStack> toTakeFluids = API.instance().createFluidStackList();
private IStackList<ItemStack> toCraft = API.instance().createItemStackList();
private IStackList<FluidStack> toCraftFluids = API.instance().createFluidStackList();
public CraftingTask(INetwork network, ICraftingRequestInfo requested, int quantity, ICraftingPattern pattern) {
this.network = network;
this.requested = requested;
this.quantity = quantity;
this.pattern = pattern;
this.internalStorage = new StorageDiskItem(network.world(), -1);
this.internalFluidStorage = new StorageDiskFluid(network.world(), -1);
}
public CraftingTask(INetwork network, NBTTagCompound tag) throws CraftingTaskReadException {
OneSixMigrationHelper.removalHook();
if (!tag.hasKey(NBT_INTERNAL_STORAGE)) {
throw new CraftingTaskReadException("Couldn't read crafting task from before RS v1.6.4, skipping...");
}
this.network = network;
this.requested = API.instance().createCraftingRequestInfo(tag.getCompoundTag(NBT_REQUESTED));
this.quantity = tag.getInteger(NBT_QUANTITY);
this.pattern = readPatternFromNbt(tag.getCompoundTag(NBT_PATTERN), network.world());
this.ticks = tag.getInteger(NBT_TICKS);
this.id = tag.getUniqueId(NBT_ID);
this.executionStarted = tag.getLong(NBT_EXECUTION_STARTED);
StorageDiskFactoryItem factoryItem = new StorageDiskFactoryItem();
StorageDiskFactoryFluid factoryFluid = new StorageDiskFactoryFluid();
this.internalStorage = factoryItem.createFromNbt(network.world(), tag.getCompoundTag(NBT_INTERNAL_STORAGE));
this.internalFluidStorage = factoryFluid.createFromNbt(network.world(), tag.getCompoundTag(NBT_INTERNAL_FLUID_STORAGE));
this.toExtractInitial = readItemStackList(tag.getTagList(NBT_TO_EXTRACT_INITIAL, Constants.NBT.TAG_COMPOUND));
this.toExtractInitialFluids = readFluidStackList(tag.getTagList(NBT_TO_EXTRACT_INITIAL_FLUIDS, Constants.NBT.TAG_COMPOUND));
NBTTagList craftingList = tag.getTagList(NBT_CRAFTING, Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < craftingList.tagCount(); ++i) {
crafting.add(new Crafting(network, craftingList.getCompoundTagAt(i)));
}
NBTTagList processingList = tag.getTagList(NBT_PROCESSING, Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < processingList.tagCount(); ++i) {
processing.add(new Processing(network, processingList.getCompoundTagAt(i)));
}
this.missing = readItemStackList(tag.getTagList(NBT_MISSING, Constants.NBT.TAG_COMPOUND));
this.missingFluids = readFluidStackList(tag.getTagList(NBT_MISSING_FLUIDS, Constants.NBT.TAG_COMPOUND));
}
@Override
public NBTTagCompound writeToNbt(NBTTagCompound tag) {
tag.setTag(NBT_REQUESTED, requested.writeToNbt());
tag.setInteger(NBT_QUANTITY, quantity);
tag.setTag(NBT_PATTERN, writePatternToNbt(pattern));
tag.setInteger(NBT_TICKS, ticks);
tag.setUniqueId(NBT_ID, id);
tag.setLong(NBT_EXECUTION_STARTED, executionStarted);
tag.setTag(NBT_INTERNAL_STORAGE, internalStorage.writeToNbt());
tag.setTag(NBT_INTERNAL_FLUID_STORAGE, internalFluidStorage.writeToNbt());
tag.setTag(NBT_TO_EXTRACT_INITIAL, writeItemStackList(toExtractInitial));
tag.setTag(NBT_TO_EXTRACT_INITIAL_FLUIDS, writeFluidStackList(toExtractInitialFluids));
NBTTagList craftingList = new NBTTagList();
for (Crafting crafting : this.crafting) {
craftingList.appendTag(crafting.writeToNbt());
}
tag.setTag(NBT_CRAFTING, craftingList);
NBTTagList processingList = new NBTTagList();
for (Processing processing : this.processing) {
processingList.appendTag(processing.writeToNbt());
}
tag.setTag(NBT_PROCESSING, processingList);
tag.setTag(NBT_MISSING, writeItemStackList(missing));
tag.setTag(NBT_MISSING_FLUIDS, writeFluidStackList(missingFluids));
return tag;
}
static NBTTagList writeItemStackList(IStackList<ItemStack> stacks) {
NBTTagList list = new NBTTagList();
for (ItemStack stack : stacks.getStacks()) {
list.appendTag(StackUtils.serializeStackToNbt(stack));
}
return list;
}
static IStackList<ItemStack> readItemStackList(NBTTagList list) throws CraftingTaskReadException {
IStackList<ItemStack> stacks = API.instance().createItemStackList();
for (int i = 0; i < list.tagCount(); ++i) {
ItemStack stack = StackUtils.deserializeStackFromNbt(list.getCompoundTagAt(i));
if (stack.isEmpty()) {
throw new CraftingTaskReadException("Empty stack!");
}
stacks.add(stack);
}
return stacks;
}
static NBTTagList writeFluidStackList(IStackList<FluidStack> stacks) {
NBTTagList list = new NBTTagList();
for (FluidStack stack : stacks.getStacks()) {
list.appendTag(stack.writeToNBT(new NBTTagCompound()));
}
return list;
}
static IStackList<FluidStack> readFluidStackList(NBTTagList list) throws CraftingTaskReadException {
IStackList<FluidStack> stacks = API.instance().createFluidStackList();
for (int i = 0; i < list.tagCount(); ++i) {
FluidStack stack = FluidStack.loadFluidStackFromNBT(list.getCompoundTagAt(i));
if (stack == null) {
throw new CraftingTaskReadException("Empty stack!");
}
stacks.add(stack);
}
return stacks;
}
@Override
@Nullable
public ICraftingTaskError calculate() {
if (calculationStarted != -1) {
throw new IllegalStateException("Task already calculated!");
}
if (executionStarted != -1) {
throw new IllegalStateException("Task already started!");
}
this.calculationStarted = System.currentTimeMillis();
int qty = this.quantity;
int qtyPerCraft = getQuantityPerCraft();
int crafted = 0;
IStackList<ItemStack> results = API.instance().createItemStackList();
IStackList<FluidStack> fluidResults = API.instance().createFluidStackList();
IStackList<ItemStack> storage = network.getItemStorageCache().getList().copy();
IStackList<FluidStack> fluidStorage = network.getFluidStorageCache().getList().copy();
ICraftingPatternChainList patternChainList = network.getCraftingManager().createPatternChainList();
ICraftingPatternChain patternChain = patternChainList.getChain(pattern);
while (qty > 0) {
ICraftingTaskError result = calculateInternal(storage, fluidStorage, results, fluidResults, patternChainList, patternChain.current(), true);
if (result != null) {
return result;
}
qty -= qtyPerCraft;
crafted += qtyPerCraft;
patternChain.cycle();
}
if (requested.getItem() != null) {
this.toCraft.add(requested.getItem(), crafted);
} else {
this.toCraftFluids.add(requested.getFluid(), crafted);
}
return null;
}
class PossibleInputs {
private List<ItemStack> possibilities;
private int pos;
PossibleInputs(List<ItemStack> possibilities) {
this.possibilities = possibilities;
}
ItemStack get() {
return possibilities.get(pos);
}
// Return false if we're exhausted.
boolean cycle() {
if (pos + 1 >= possibilities.size()) {
pos = 0;
return false;
}
pos++;
return true;
}
void sort(IStackList<ItemStack> mutatedStorage, IStackList<ItemStack> results) {
possibilities.sort((a, b) -> {
ItemStack ar = mutatedStorage.get(a);
ItemStack br = mutatedStorage.get(b);
return (br == null ? 0 : br.getCount()) - (ar == null ? 0 : ar.getCount());
});
possibilities.sort((a, b) -> {
ItemStack ar = results.get(a);
ItemStack br = results.get(b);
return (br == null ? 0 : br.getCount()) - (ar == null ? 0 : ar.getCount());
});
}
}
@Nullable
private ICraftingTaskError calculateInternal(
IStackList<ItemStack> mutatedStorage,
IStackList<FluidStack> mutatedFluidStorage,
IStackList<ItemStack> results,
IStackList<FluidStack> fluidResults,
ICraftingPatternChainList patternChainList,
ICraftingPattern pattern,
boolean root) {
if (System.currentTimeMillis() - calculationStarted > RS.INSTANCE.config.calculationTimeoutMs) {
return new CraftingTaskError(CraftingTaskErrorType.TOO_COMPLEX);
}
if (!patternsUsed.add(pattern)) {
return new CraftingTaskError(CraftingTaskErrorType.RECURSIVE, pattern);
}
IStackList<ItemStack> itemsToExtract = API.instance().createItemStackList();
IStackList<FluidStack> fluidsToExtract = API.instance().createFluidStackList();
NonNullList<ItemStack> took = NonNullList.create();
for (NonNullList<ItemStack> inputs : pattern.getInputs()) {
if (inputs.isEmpty()) {
took.add(ItemStack.EMPTY);
continue;
}
PossibleInputs possibleInputs = new PossibleInputs(inputs);
possibleInputs.sort(mutatedStorage, results);
ItemStack possibleInput = possibleInputs.get();
ItemStack fromSelf = results.get(possibleInput);
ItemStack fromNetwork = mutatedStorage.get(possibleInput);
took.add(possibleInput);
int remaining = possibleInput.getCount();
while (remaining > 0) {
if (fromSelf != null) {
int toTake = Math.min(remaining, fromSelf.getCount());
itemsToExtract.add(possibleInput, toTake);
results.remove(fromSelf, toTake);
remaining -= toTake;
fromSelf = results.get(possibleInput);
} else if (fromNetwork != null) {
int toTake = Math.min(remaining, fromNetwork.getCount());
this.toTake.add(possibleInput, toTake);
itemsToExtract.add(possibleInput, toTake);
mutatedStorage.remove(fromNetwork, toTake);
remaining -= toTake;
fromNetwork = mutatedStorage.get(possibleInput);
toExtractInitial.add(took.get(took.size() - 1));
} else {
ICraftingPattern subPattern = network.getCraftingManager().getPattern(possibleInput);
if (subPattern != null) {
ICraftingPatternChain subPatternChain = patternChainList.getChain(subPattern);
while ((fromSelf == null ? 0 : fromSelf.getCount()) < remaining) {
ICraftingTaskError result = calculateInternal(mutatedStorage, mutatedFluidStorage, results, fluidResults, patternChainList, subPatternChain.current(), false);
if (result != null) {
return result;
}
fromSelf = results.get(possibleInput);
if (fromSelf == null) {
throw new IllegalStateException("Recursive calculation didn't yield anything");
}
fromNetwork = mutatedStorage.get(possibleInput);
subPatternChain.cycle();
}
// fromSelf contains the amount crafted after the loop.
this.toCraft.add(possibleInput, fromSelf.getCount());
} else {
if (!possibleInputs.cycle()) {
// Give up.
possibleInput = possibleInputs.get(); // Revert back to 0.
this.missing.add(possibleInput, remaining);
itemsToExtract.add(possibleInput, remaining);
remaining = 0;
} else {
// Retry with new input...
possibleInput = possibleInputs.get();
fromSelf = results.get(possibleInput);
fromNetwork = mutatedStorage.get(possibleInput);
}
}
}
}
}
for (FluidStack input : pattern.getFluidInputs()) {
FluidStack fromSelf = fluidResults.get(input, IComparer.COMPARE_NBT);
FluidStack fromNetwork = mutatedFluidStorage.get(input, IComparer.COMPARE_NBT);
int remaining = input.amount;
while (remaining > 0) {
if (fromSelf != null) {
int toTake = Math.min(remaining, fromSelf.amount);
fluidsToExtract.add(input, toTake);
fluidResults.remove(input, toTake);
remaining -= toTake;
fromSelf = fluidResults.get(input, IComparer.COMPARE_NBT);
} else if (fromNetwork != null) {
int toTake = Math.min(remaining, fromNetwork.amount);
this.toTakeFluids.add(input, toTake);
fluidsToExtract.add(input, toTake);
mutatedFluidStorage.remove(fromNetwork, toTake);
remaining -= toTake;
fromNetwork = mutatedFluidStorage.get(input, IComparer.COMPARE_NBT);
toExtractInitialFluids.add(input);
} else {
ICraftingPattern subPattern = network.getCraftingManager().getPattern(input);
if (subPattern != null) {
ICraftingPatternChain subPatternChain = patternChainList.getChain(subPattern);
while ((fromSelf == null ? 0 : fromSelf.amount) < remaining) {
ICraftingTaskError result = calculateInternal(mutatedStorage, mutatedFluidStorage, results, fluidResults, patternChainList, subPatternChain.current(), false);
if (result != null) {
return result;
}
fromSelf = fluidResults.get(input, IComparer.COMPARE_NBT);
if (fromSelf == null) {
throw new IllegalStateException("Recursive fluid calculation didn't yield anything");
}
fromNetwork = mutatedFluidStorage.get(input, IComparer.COMPARE_NBT);
subPatternChain.cycle();
}
// fromSelf contains the amount crafted after the loop.
this.toCraftFluids.add(input, fromSelf.amount);
} else {
this.missingFluids.add(input, remaining);
fluidsToExtract.add(input, remaining);
remaining = 0;
}
}
}
}
patternsUsed.remove(pattern);
if (pattern.isProcessing()) {
IStackList<ItemStack> itemsToReceive = API.instance().createItemStackList();
IStackList<FluidStack> fluidsToReceive = API.instance().createFluidStackList();
for (ItemStack output : pattern.getOutputs()) {
results.add(output);
itemsToReceive.add(output);
}
for (FluidStack output : pattern.getFluidOutputs()) {
fluidResults.add(output);
fluidsToReceive.add(output);
}
processing.add(new Processing(pattern, itemsToReceive, fluidsToReceive, new ArrayList<>(itemsToExtract.getStacks()), new ArrayList<>(fluidsToExtract.getStacks()), root));
} else {
if (!fluidsToExtract.isEmpty()) {
throw new IllegalStateException("Cannot extract fluids in normal pattern!");
}
crafting.add(new Crafting(pattern, took, itemsToExtract, root));
results.add(pattern.getOutput(took));
for (ItemStack byproduct : pattern.getByproducts(took)) {
results.add(byproduct);
}
}
return null;
}
private static int getTickInterval(int speedUpgrades) {
switch (speedUpgrades) {
case 0:
return 10;
case 1:
return 8;
case 2:
return 6;
case 3:
return 4;
case 4:
return 2;
default:
return 2;
}
}
private void extractInitial() {
if (!toExtractInitial.isEmpty()) {
List<ItemStack> toRemove = new ArrayList<>();
for (ItemStack toExtract : toExtractInitial.getStacks()) {
ItemStack result = network.extractItem(toExtract, toExtract.getCount(), Action.PERFORM);
if (result != null) {
internalStorage.insert(toExtract, toExtract.getCount(), Action.PERFORM);
toRemove.add(result);
}
}
for (ItemStack stack : toRemove) {
toExtractInitial.remove(stack);
}
if (!toRemove.isEmpty()) {
network.getCraftingManager().onTaskChanged();
}
}
if (!toExtractInitialFluids.isEmpty()) {
List<FluidStack> toRemove = new ArrayList<>();
for (FluidStack toExtract : toExtractInitialFluids.getStacks()) {
FluidStack result = network.extractFluid(toExtract, toExtract.amount, Action.PERFORM);
if (result != null) {
internalFluidStorage.insert(toExtract, toExtract.amount, Action.PERFORM);
toRemove.add(result);
}
}
for (FluidStack stack : toRemove) {
toExtractInitialFluids.remove(stack);
}
if (!toRemove.isEmpty()) {
network.getCraftingManager().onTaskChanged();
}
}
}
private void updateCrafting() {
Iterator<Crafting> it = crafting.iterator();
while (it.hasNext()) {
Crafting c = it.next();
if (ticks % getTickInterval(c.getPattern().getContainer().getSpeedUpgradeCount()) == 0) {
boolean hasAll = true;
for (ItemStack need : c.getToExtract().getStacks()) {
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.SIMULATE);
if (result == null || result.getCount() != need.getCount()) {
hasAll = false;
break;
}
}
if (hasAll) {
for (ItemStack need : c.getToExtract().getStacks()) {
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.PERFORM);
if (result == null || result.getCount() != need.getCount()) {
throw new IllegalStateException("Extractor check lied");
}
}
ItemStack output = c.getPattern().getOutput(c.getTook());
if (!c.isRoot()) {
this.internalStorage.insert(output, output.getCount(), Action.PERFORM);
} else {
ItemStack remainder = this.network.insertItem(output, output.getCount(), Action.PERFORM);
if (remainder != null) {
this.internalStorage.insert(remainder, remainder.getCount(), Action.PERFORM);
}
}
// Byproducts need to always be inserted in the internal storage for later reuse further in the task.
// Regular outputs can be inserted into the network *IF* it's a root since it's *NOT* expected to be used later on.
for (ItemStack byp : c.getPattern().getByproducts(c.getTook())) {
this.internalStorage.insert(byp, byp.getCount(), Action.PERFORM);
}
it.remove();
network.getCraftingManager().onTaskChanged();
return;
}
}
}
}
private void updateProcessing() {
Iterator<Processing> it = processing.iterator();
while (it.hasNext()) {
Processing p = it.next();
if (p.getState() == ProcessingState.PROCESSED) {
it.remove();
network.getCraftingManager().onTaskChanged();
continue;
}
if (p.getState() == ProcessingState.EXTRACTED_ALL) {
continue;
}
if (ticks % getTickInterval(p.getPattern().getContainer().getSpeedUpgradeCount()) == 0) {
ProcessingState originalState = p.getState();
if (p.getPattern().getContainer().isLocked()) {
p.setState(ProcessingState.LOCKED);
} else {
boolean hasAll = true;
for (ItemStack need : p.getItemsToPut()) {
if (p.getPattern().getContainer().getConnectedInventory() == null) {
p.setState(ProcessingState.MACHINE_NONE);
} else {
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.SIMULATE);
if (result == null || result.getCount() != need.getCount()) {
hasAll = false;
break;
} else if (!ItemHandlerHelper.insertItem(p.getPattern().getContainer().getConnectedInventory(), result, true).isEmpty()) {
p.setState(ProcessingState.MACHINE_DOES_NOT_ACCEPT);
break;
} else {
p.setState(ProcessingState.READY);
}
}
}
for (FluidStack need : p.getFluidsToPut()) {
if (p.getPattern().getContainer().getConnectedFluidInventory() == null) {
p.setState(ProcessingState.MACHINE_NONE);
} else {
FluidStack result = this.internalFluidStorage.extract(need, need.amount, IComparer.COMPARE_NBT, Action.SIMULATE);
if (result == null || result.amount != need.amount) {
hasAll = false;
break;
} else if (p.getPattern().getContainer().getConnectedFluidInventory().fill(result, false) != result.amount) {
p.setState(ProcessingState.MACHINE_DOES_NOT_ACCEPT);
break;
} else if (p.getState() == ProcessingState.READY) { // If the items were ok.
p.setState(ProcessingState.READY);
}
}
}
if (p.getState() == ProcessingState.READY && hasAll) {
boolean abort = false;
for (int i = 0; i < p.getItemsToPut().size(); ++i) {
ItemStack need = p.getItemsToPut().get(i);
ItemStack result = this.internalStorage.extract(need, need.getCount(), DEFAULT_EXTRACT_FLAGS, Action.PERFORM);
if (result == null || result.getCount() != need.getCount()) {
throw new IllegalStateException("The internal crafting inventory reported that " + need + " was available but we got " + result);
}
ItemStack remainder = ItemHandlerHelper.insertItem(p.getPattern().getContainer().getConnectedInventory(), result, false);
if (!remainder.isEmpty()) {
LOGGER.warn("In a simulation, " + p.getPattern().getContainer().getConnectedInventory() + " reported that we could insert " + result + " but we got " + remainder + " as a remainder");
this.internalStorage.insert(remainder, remainder.getCount(), Action.PERFORM);
p.getItemsToPut().set(i, remainder);
abort = true;
break;
}
}
if (abort) {
continue;
}
for (int i = 0; i < p.getFluidsToPut().size(); ++i) {
FluidStack need = p.getFluidsToPut().get(i);
FluidStack result = this.internalFluidStorage.extract(need, need.amount, IComparer.COMPARE_NBT, Action.PERFORM);
if (result == null || result.amount != need.amount) {
throw new IllegalStateException("The internal crafting inventory reported that " + need + " was available but we got " + result);
}
int filled = p.getPattern().getContainer().getConnectedFluidInventory().fill(result, true);
if (filled != result.amount) {
LOGGER.warn("In a simulation, " + p.getPattern().getContainer().getConnectedFluidInventory() + " reported that we could fill " + result + " but we only filled " + filled);
this.internalFluidStorage.insert(result, result.amount - filled, Action.PERFORM);
p.getFluidsToPut().set(i, StackUtils.copy(result, result.amount - filled));
abort = true;
break;
}
}
if (abort) {
continue;
}
p.setState(ProcessingState.EXTRACTED_ALL);
p.getPattern().getContainer().onUsedForProcessing();
}
}
if (originalState != p.getState()) {
network.getCraftingManager().onTaskChanged();
}
}
}
}
@Override
public boolean update() {
if (executionStarted == -1) {
executionStarted = System.currentTimeMillis();
}
++ticks;
extractInitial();
if (this.crafting.isEmpty() && this.processing.isEmpty()) {
List<Runnable> toPerform = new ArrayList<>();
for (ItemStack stack : internalStorage.getStacks()) {
ItemStack remainder = network.insertItem(stack, stack.getCount(), Action.PERFORM);
toPerform.add(() -> {
if (remainder == null) {
internalStorage.extract(stack, stack.getCount(), IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
} else {
internalStorage.extract(stack, stack.getCount() - remainder.getCount(), IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
}
});
}
for (FluidStack stack : internalFluidStorage.getStacks()) {
FluidStack remainder = network.insertFluid(stack, stack.amount, Action.PERFORM);
toPerform.add(() -> {
if (remainder == null) {
internalFluidStorage.extract(stack, stack.amount, IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
} else {
internalFluidStorage.extract(stack, stack.amount - remainder.amount, IComparer.COMPARE_DAMAGE | IComparer.COMPARE_NBT, Action.PERFORM);
}
});
}
// Prevent CME.
toPerform.forEach(Runnable::run);
return internalStorage.getStacks().isEmpty() && internalFluidStorage.getStacks().isEmpty();
} else {
updateCrafting();
updateProcessing();
return false;
}
}
@Override
public void onCancelled() {
for (ItemStack remainder : internalStorage.getStacks()) {
network.insertItem(remainder, remainder.getCount(), Action.PERFORM);
}
for (FluidStack remainder : internalFluidStorage.getStacks()) {
network.insertFluid(remainder, remainder.amount, Action.PERFORM);
}
}
@Override
public int getQuantity() {
return quantity;
}
@Override
public int getQuantityPerCraft() {
int qty = 0;
if (requested.getItem() != null) {
for (ItemStack output : pattern.getOutputs()) {
if (API.instance().getComparer().isEqualNoQuantity(output, requested.getItem())) {
qty += output.getCount();
if (!pattern.isProcessing()) {
break;
}
}
}
} else {
for (FluidStack output : pattern.getFluidOutputs()) {
if (API.instance().getComparer().isEqual(output, requested.getFluid(), IComparer.COMPARE_NBT)) {
qty += output.amount;
}
}
}
return qty;
}
@Override
public ICraftingRequestInfo getRequested() {
return requested;
}
@Override
public int onTrackedInsert(ItemStack stack, int size) {
for (Processing p : this.processing) {
if (p.getState() != ProcessingState.EXTRACTED_ALL) {
continue;
}
ItemStack content = p.getItemsToReceive().get(stack);
if (content != null) {
int needed = content.getCount();
if (needed > size) {
needed = size;
}
p.getItemsToReceive().remove(stack, needed);
size -= needed;
if (p.getItemsToReceive().isEmpty() && p.getFluidsToReceive().isEmpty()) {
p.setState(ProcessingState.PROCESSED);
}
if (!p.isRoot()) {
internalStorage.insert(stack, needed, Action.PERFORM);
} else {
ItemStack remainder = network.insertItem(stack, needed, Action.PERFORM);
if (remainder != null) {
internalStorage.insert(stack, needed, Action.PERFORM);
}
}
if (size == 0) {
return 0;
}
}
}
return size;
}
@Override
public int onTrackedInsert(FluidStack stack, int size) {
for (Processing p : this.processing) {
if (p.getState() != ProcessingState.EXTRACTED_ALL) {
continue;
}
FluidStack content = p.getFluidsToReceive().get(stack);
if (content != null) {
int needed = content.amount;
if (needed > size) {
needed = size;
}
p.getFluidsToReceive().remove(stack, needed);
size -= needed;
if (p.getItemsToReceive().isEmpty() && p.getFluidsToReceive().isEmpty()) {
p.setState(ProcessingState.PROCESSED);
}
if (!p.isRoot()) {
internalFluidStorage.insert(stack, needed, Action.PERFORM);
} else {
FluidStack remainder = network.insertFluid(stack, needed, Action.PERFORM);
if (remainder != null) {
internalFluidStorage.insert(stack, needed, Action.PERFORM);
}
}
if (size == 0) {
return 0;
}
}
}
return size;
}
static NBTTagCompound writePatternToNbt(ICraftingPattern pattern) {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag(NBT_PATTERN_STACK, pattern.getStack().serializeNBT());
tag.setLong(NBT_PATTERN_CONTAINER_POS, pattern.getContainer().getPosition().toLong());
return tag;
}
static ICraftingPattern readPatternFromNbt(NBTTagCompound tag, World world) throws CraftingTaskReadException {
BlockPos containerPos = BlockPos.fromLong(tag.getLong(NBT_PATTERN_CONTAINER_POS));
INetworkNode node = API.instance().getNetworkNodeManager(world).getNode(containerPos);
if (node instanceof ICraftingPatternContainer) {
ItemStack stack = new ItemStack(tag.getCompoundTag(NBT_PATTERN_STACK));
if (stack.getItem() instanceof ICraftingPatternProvider) {
return ((ICraftingPatternProvider) stack.getItem()).create(world, stack, (ICraftingPatternContainer) node);
} else {
throw new CraftingTaskReadException("Pattern stack is not a crafting pattern provider");
}
} else {
throw new CraftingTaskReadException("Crafting pattern container doesn't exist anymore");
}
}
@Override
public List<ICraftingMonitorElement> getCraftingMonitorElements() {
ICraftingMonitorElementList elements = API.instance().createCraftingMonitorElementList();
for (ItemStack stack : this.internalStorage.getStacks()) {
elements.add(new CraftingMonitorElementItemRender(stack, stack.getCount(), 0, 0, 0, 0));
}
for (ItemStack missing : this.missing.getStacks()) {
elements.add(new CraftingMonitorElementItemRender(missing, 0, missing.getCount(), 0, 0, 0));
}
for (Crafting crafting : this.crafting) {
for (ItemStack receive : crafting.getPattern().getOutputs()) {
elements.add(new CraftingMonitorElementItemRender(receive, 0, 0, 0, 0, receive.getCount()));
}
}
for (Processing processing : this.processing) {
if (processing.getState() == ProcessingState.PROCESSED) {
continue;
}
if (processing.getState() == ProcessingState.EXTRACTED_ALL) {
for (ItemStack put : processing.getItemsToPut()) {
elements.add(new CraftingMonitorElementItemRender(put, 0, 0, put.getCount(), 0, 0));
}
} else if (processing.getState() == ProcessingState.READY || processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT || processing.getState() == ProcessingState.MACHINE_NONE || processing.getState() == ProcessingState.LOCKED) {
for (ItemStack receive : processing.getItemsToReceive().getStacks()) {
ICraftingMonitorElement element = new CraftingMonitorElementItemRender(receive, 0, 0, 0, receive.getCount(), 0);
if (processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_does_not_accept_item");
} else if (processing.getState() == ProcessingState.MACHINE_NONE) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_none");
} else if (processing.getState() == ProcessingState.LOCKED) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.crafter_is_locked");
}
elements.add(element);
}
}
}
elements.commit();
for (FluidStack stack : this.internalFluidStorage.getStacks()) {
elements.add(new CraftingMonitorElementFluidRender(stack, stack.amount, 0, 0, 0, 0));
}
for (FluidStack missing : this.missingFluids.getStacks()) {
elements.add(new CraftingMonitorElementFluidRender(missing, 0, missing.amount, 0, 0, 0));
}
for (Processing processing : this.processing) {
if (processing.getState() == ProcessingState.PROCESSED) {
continue;
}
if (processing.getState() == ProcessingState.EXTRACTED_ALL) {
for (FluidStack put : processing.getFluidsToPut()) {
elements.add(new CraftingMonitorElementFluidRender(put, 0, 0, put.amount, 0, 0));
}
} else if (processing.getState() == ProcessingState.READY || processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT || processing.getState() == ProcessingState.MACHINE_NONE) {
for (FluidStack receive : processing.getFluidsToReceive().getStacks()) {
ICraftingMonitorElement element = new CraftingMonitorElementFluidRender(receive, 0, 0, 0, receive.amount, 0);
if (processing.getState() == ProcessingState.MACHINE_DOES_NOT_ACCEPT) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_does_not_accept_fluid");
} else if (processing.getState() == ProcessingState.MACHINE_NONE) {
element = new CraftingMonitorElementError(element, "gui.refinedstorage:crafting_monitor.machine_none");
}
elements.add(element);
}
}
}
elements.commit();
return elements.getElements();
}
@Override
public List<ICraftingPreviewElement> getPreviewStacks() {
Map<Integer, CraftingPreviewElementItemStack> map = new LinkedHashMap<>();
Map<Integer, CraftingPreviewElementFluidStack> mapFluids = new LinkedHashMap<>();
for (ItemStack stack : toCraft.getStacks()) {
int hash = API.instance().getItemStackHashCode(stack);
CraftingPreviewElementItemStack previewStack = map.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementItemStack(stack);
}
previewStack.addToCraft(stack.getCount());
map.put(hash, previewStack);
}
for (FluidStack stack : toCraftFluids.getStacks()) {
int hash = API.instance().getFluidStackHashCode(stack);
CraftingPreviewElementFluidStack previewStack = mapFluids.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementFluidStack(stack);
}
previewStack.addToCraft(stack.amount);
mapFluids.put(hash, previewStack);
}
for (ItemStack stack : missing.getStacks()) {
int hash = API.instance().getItemStackHashCode(stack);
CraftingPreviewElementItemStack previewStack = map.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementItemStack(stack);
}
previewStack.setMissing(true);
previewStack.addToCraft(stack.getCount());
map.put(hash, previewStack);
}
for (FluidStack stack : missingFluids.getStacks()) {
int hash = API.instance().getFluidStackHashCode(stack);
CraftingPreviewElementFluidStack previewStack = mapFluids.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementFluidStack(stack);
}
previewStack.setMissing(true);
previewStack.addToCraft(stack.amount);
mapFluids.put(hash, previewStack);
}
for (ItemStack stack : toTake.getStacks()) {
int hash = API.instance().getItemStackHashCode(stack);
CraftingPreviewElementItemStack previewStack = map.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementItemStack(stack);
}
previewStack.addAvailable(stack.getCount());
map.put(hash, previewStack);
}
for (FluidStack stack : toTakeFluids.getStacks()) {
int hash = API.instance().getFluidStackHashCode(stack);
CraftingPreviewElementFluidStack previewStack = mapFluids.get(hash);
if (previewStack == null) {
previewStack = new CraftingPreviewElementFluidStack(stack);
}
previewStack.addAvailable(stack.amount);
mapFluids.put(hash, previewStack);
}
List<ICraftingPreviewElement> elements = new ArrayList<>();
elements.addAll(map.values());
elements.addAll(mapFluids.values());
return elements;
}
@Override
public ICraftingPattern getPattern() {
return pattern;
}
@Override
public long getExecutionStarted() {
return executionStarted;
}
@Override
public IStackList<ItemStack> getMissing() {
return missing;
}
@Override
public UUID getId() {
return id;
}
}
| Minor fix.
| src/main/java/com/raoulvdberge/refinedstorage/apiimpl/autocrafting/task/CraftingTask.java | Minor fix. |
|
Java | mit | 97a8433ac3cfd07fcfe6f943520b993bfed08f76 | 0 | CS2103JAN2017-W14-B2/main,CS2103JAN2017-W14-B2/main | package seedu.taskboss.logic.commands;
/**
* Saves the data at specific filepath. Creates filepath if it does not exist
*/
public class SaveCommand extends Command {
public static final String COMMAND_WORD = "save";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ "Saves the data at specific filepath.\n"
+ "Example: " + COMMAND_WORD
+ " C://user/desktop/taskboss";
public static final String MESSAGE_SUCCESS = "The data has been saved!";
public static final String MESSAGE_INVALID_FILEPATH = "The filepath is invalid.";
private final String filepath;
public SaveCommand(String filepath) {
this.filepath = filepath;
}
@Override
public CommandResult execute() {
assert storage != null;
storage.setFilePath(filepath);
return new CommandResult(MESSAGE_SUCCESS);
}
}
| src/main/java/seedu/taskboss/logic/commands/SaveCommand.java | package seedu.taskboss.logic.commands;
/**
* Saves the data at specific filepath. Creates filepath if it does not exist
*/
public class SaveCommand extends Command {
public static final String COMMAND_WORD = "save";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ "Saves the data at specific filepath.\n"
+ "Example: " + COMMAND_WORD
+ " C://user/desktop/taskboss";
public static final String MESSAGE_SUCCESS = "The data has been saved!";
public static final String MESSAGE_INVALID_FILEPATH = "The filepath is invalid.";
private final String filepath;
public SaveCommand(String filepath) {
this.filepath = filepath;
}
@Override
public CommandResult execute() {
assert storage != null;
storage.setFilePath(filepath);
return new CommandResult(MESSAGE_SUCCESS);
}
}
| Update SaveCommand.java | src/main/java/seedu/taskboss/logic/commands/SaveCommand.java | Update SaveCommand.java |
|
Java | mit | e2c47d6e76ee81a673abc9e698d47e48ed4934c4 | 0 | alessio-santacroce/multiline-string-literals | package com.github.alessiosantacroce.multilinestring;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import java.util.Arrays;
import static com.github.alessiosantacroce.multilinestring.MultilineStringLiteral.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MultilineStringLiteralTest {
@Test
public void defineMultiLineJsonString() throws ParseException {
// given
final JSONParser parser = new JSONParser();
final JSONObject person = new JSONObject();
person.put("name", "John");
person.put("hobbies", Arrays.asList("travel", "make pizza"));
final JSONObject address = new JSONObject();
address.put("streetAddress", "21 2nd Street");
address.put("city", "New York");
person.put("address", address);
// when
// then
assertThat(parser.parse(newString(/*
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(newString(/**
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(S(/*
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(S(/**
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(stripMargin(/*
| {
| "name": "John",
| "hobbies": ["travel", "make pizza"],
| "address": {
| "streetAddress": "21 2nd Street",
| "city": "New York"
| }
| }
*/))).isEqualTo(person);
assertThat(parser.parse(stripMargin(/**
| {
| "name": "John",
| "hobbies": ["travel", "make pizza"],
| "address": {
| "streetAddress": "21 2nd Street",
| "city": "New York"
| }
| }
*/))).isEqualTo(person);
}
@Test
public void defineMultiLineString() throws ParseException {
// given
final String expected = "\n" +
" Wow, we finally have\n" +
" multiline strings in\n" +
" Java! HOOO!";
// when
// then
assertThat(newString(/*
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(newString(/**
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(S(/*
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(S(/**
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(stripMargin(/*
| Wow, we finally have
| multiline strings in
| Java! HOOO!*/)).isEqualTo(expected);
assertThat(stripMargin(/**
| Wow, we finally have
| multiline strings in
| Java! HOOO!*/)).isEqualTo(expected);
}
@Test
public void defineEmptyString() {
// given
// when
// then
assertThat(newString(/**/)).isEqualTo("");
assertThat(newString(/***/)).isEqualTo("");
assertThat(S(/**/)).isEqualTo("");
assertThat(S(/***/)).isEqualTo("");
assertThat(stripMargin(/**/)).isEqualTo("");
assertThat(stripMargin(/***/)).isEqualTo("");
}
@Test
public void defineSingleLineString() {
// given
// when
// then
assertThat(newString(/*111*/)).isEqualTo("111");
assertThat(newString(/**222*/)).isEqualTo("222");
assertThat(S(/*333*/)).isEqualTo("333");
assertThat(S(/**444*/)).isEqualTo("444");
assertThat(stripMargin(/*555*/)).isEqualTo("555");
assertThat(stripMargin(/**666*/)).isEqualTo("666");
}
@Test(expected = MultilineStringLiteralException.class)
public void ifCommentIsMissingRaiseException_S() {
S();
}
@Test(expected = MultilineStringLiteralException.class)
public void ifCommentIsMissingRaiseException_newString() {
newString();
}
@Test(expected = MultilineStringLiteralException.class)
public void ifCommentIsMissingRaiseException_stripMargin() {
stripMargin();
}
@Test
public void defineStringInInnerClass() {
// given
// when
// then
assertThat(new Object() {
@Override
public String toString() {
return S(/* aaa */);
}
}.toString()).isEqualTo(" aaa ");
assertThat(new Object() {
@Override
public String toString() {
return newString(/* bbb */);
}
}.toString()).isEqualTo(" bbb ");
assertThat(new Object() {
@Override
public String toString() {
return stripMargin(/*|ccc */);
}
}.toString()).isEqualTo("ccc ");
}
}
| src/test/java/com/github/alessiosantacroce/multilinestring/MultilineStringLiteralTest.java | package com.github.alessiosantacroce.multilinestring;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import java.util.Arrays;
import static com.github.alessiosantacroce.multilinestring.MultilineStringLiteral.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MultilineStringLiteralTest {
@Test
public void defineMultiLineJsonString() throws ParseException {
// given
final JSONParser parser = new JSONParser();
final JSONObject person = new JSONObject();
person.put("name", "John");
person.put("hobbies", Arrays.asList("travel", "make pizza"));
final JSONObject address = new JSONObject();
address.put("streetAddress", "21 2nd Street");
address.put("city", "New York");
person.put("address", address);
// when
// then
assertThat(parser.parse(newString(/*
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(newString(/**
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(S(/*
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(S(/**
{
"name": "John",
"hobbies": ["travel", "make pizza"],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
*/))).isEqualTo(person);
assertThat(parser.parse(stripMargin(/*
| {
| "name": "John",
| "hobbies": ["travel", "make pizza"],
| "address": {
| "streetAddress": "21 2nd Street",
| "city": "New York"
| }
| }
*/))).isEqualTo(person);
assertThat(parser.parse(stripMargin(/**
| {
| "name": "John",
| "hobbies": ["travel", "make pizza"],
| "address": {
| "streetAddress": "21 2nd Street",
| "city": "New York"
| }
| }
*/))).isEqualTo(person);
}
@Test
public void defineMultiLineString() throws ParseException {
// given
final String expected = "\n" +
" Wow, we finally have\n" +
" multiline strings in\n" +
" Java! HOOO!";
// when
// then
assertThat(newString(/*
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(newString(/**
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(S(/*
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(S(/**
Wow, we finally have
multiline strings in
Java! HOOO!*/)).isEqualTo(expected);
assertThat(stripMargin(/*
| Wow, we finally have
| multiline strings in
| Java! HOOO!*/)).isEqualTo(expected);
assertThat(stripMargin(/**
| Wow, we finally have
| multiline strings in
| Java! HOOO!*/)).isEqualTo(expected);
}
@Test
public void defineEmptyString() {
// given
// when
// then
assertThat(newString(/**/)).isEqualTo("");
assertThat(newString(/***/)).isEqualTo("");
assertThat(S(/**/)).isEqualTo("");
assertThat(S(/***/)).isEqualTo("");
assertThat(stripMargin(/**/)).isEqualTo("");
assertThat(stripMargin(/***/)).isEqualTo("");
}
@Test
public void defineSingleLineString() {
// given
// when
// then
assertThat(newString(/*111*/)).isEqualTo("111");
assertThat(newString(/**222*/)).isEqualTo("222");
assertThat(S(/*333*/)).isEqualTo("333");
assertThat(S(/**444*/)).isEqualTo("444");
assertThat(stripMargin(/*555*/)).isEqualTo("555");
assertThat(stripMargin(/**666*/)).isEqualTo("666");
}
@Test(expected = MultilineStringLiteralException.class)
public void ifCommentIsMissingRaiseException_S() {
S();
}
@Test(expected = MultilineStringLiteralException.class)
public void ifCommentIsMissingRaiseException_newString() {
newString();
}
@Test(expected = MultilineStringLiteralException.class)
public void ifCommentIsMissingRaiseException_stripMargin() {
stripMargin();
}
@Test
public void defineStringInInnerClass() {
// given
// when
// then
assertThat(new Object() {
@Override
public String toString() {
return S(/* aaa */);
}
}.toString()).isEqualTo(" aaa ");
assertThat(new Object() {
@Override
public String toString() {
return newString(/* bbb */);
}
}.toString()).isEqualTo(" bbb ");
assertThat(new Object() {
@Override
public String toString() {
return stripMargin(/*|ccc */);
}
}.toString()).isEqualTo("ccc ");
}
}
| Added stripMargin
| src/test/java/com/github/alessiosantacroce/multilinestring/MultilineStringLiteralTest.java | Added stripMargin |
|
Java | mit | 4a0edce9e610983f83141ac5e998298317f347b0 | 0 | ad-tech-group/openssp,ad-tech-group/openssp | package com.atg.openssp.core.exchange.channel.rtb;
import java.util.concurrent.Callable;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atg.openssp.common.core.broker.AbstractBroker;
import com.atg.openssp.common.demand.ResponseContainer;
import com.atg.openssp.common.demand.Supplier;
import com.atg.openssp.common.exception.BidProcessingException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import openrtb.bidrequest.model.BidRequest;
import openrtb.bidresponse.model.BidResponse;
/**
* This class acts as Broker to a connector used in demand (OpenRTB) context. It represents one Demand side (DSP).
*
* @author André Schmer
*
*/
public final class DemandBroker extends AbstractBroker implements Callable<ResponseContainer> {
private static final Logger log = LoggerFactory.getLogger(DemandBroker.class);
private final Supplier supplier;
private final OpenRtbConnector connector;
private final Header[] headers;
private final Gson gson;
public DemandBroker(final Supplier supplier, final OpenRtbConnector connector) {
this.supplier = supplier;
this.connector = connector;
headers = new Header[2];
headers[0] = new BasicHeader("x-openrtb-version", supplier.getOpenRtbVersion());
headers[1] = new BasicHeader("ContentType", supplier.getContentType());
headers[2] = new BasicHeader("Accept-Encoding", supplier.getAcceptEncoding());
headers[3] = new BasicHeader("Content-Encoding", supplier.getContentEncoding());
gson = new GsonBuilder().setVersion(Double.valueOf(supplier.getOpenRtbVersion())).create();
}
@Override
public ResponseContainer call() throws Exception {
final BidRequest bidrequest = sessionAgent.getBidExchange().getBidRequest(supplier);
if (bidrequest == null) {
return null;
}
try {
final String jsonBidrequest = gson.toJson(bidrequest, BidRequest.class);
log.debug(jsonBidrequest);
final String result = connector.connect(jsonBidrequest, headers);
if (!StringUtils.isEmpty(result)) {
log.debug(result);
final BidResponse bidResponse = gson.fromJson(result, BidResponse.class);
return new ResponseContainer(supplier, bidResponse);
}
} catch (final BidProcessingException e) {
log.error(e.getMessage());
} catch (final Exception e) {
log.error(e.getMessage());
}
return null;
}
public Supplier getSupplier() {
return supplier;
}
}
| open-ssp-parent/core/src/main/java/com/atg/openssp/core/exchange/channel/rtb/DemandBroker.java | package com.atg.openssp.core.exchange.channel.rtb;
import java.util.concurrent.Callable;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.openrtb.validator.OpenRtbInputType;
import org.openrtb.validator.OpenRtbValidator;
import org.openrtb.validator.OpenRtbValidatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atg.openssp.common.core.broker.AbstractBroker;
import com.atg.openssp.common.demand.ResponseContainer;
import com.atg.openssp.common.demand.Supplier;
import com.atg.openssp.common.logadapter.RtbRequestLogProcessor;
import com.atg.openssp.common.logadapter.RtbResponseLogProcessor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import openrtb.bidrequest.model.BidRequest;
import openrtb.bidresponse.model.BidResponse;
/**
* This class acts as Broker to a connector used in demand (OpenRTB) context. It represents one Demand side (DSP).
*
* @author André Schmer
*
*/
public final class DemandBroker extends AbstractBroker implements Callable<ResponseContainer> {
private static final Logger log = LoggerFactory.getLogger(DemandBroker.class);
private final Supplier supplier;
private final OpenRtbConnector connector;
private final Header[] headers;
private final Gson gson;
private static OpenRtbValidator responseValidator;
public DemandBroker(final Supplier supplier, final OpenRtbConnector connector) {
this.supplier = supplier;
this.connector = connector;
headers = new Header[2];
headers[0] = new BasicHeader("x-openrtb-version", supplier.getOpenRtbVersion());
headers[1] = new BasicHeader("ContentType", supplier.getContentType());
headers[2] = new BasicHeader("Accept-Encoding", supplier.getAcceptEncoding());
headers[3] = new BasicHeader("Content-Encoding", supplier.getContentEncoding());
gson = new GsonBuilder().setVersion(Double.valueOf(supplier.getOpenRtbVersion())).create();
responseValidator = OpenRtbValidatorFactory.getValidatorWithFactual(OpenRtbInputType.BID_RESPONSE, supplier.getOpenRtbVersion());
}
@Override
public ResponseContainer call() throws Exception {
try {
final String jsonBidrequest = gson.toJson(sessionAgent.getBidExchange().getBidRequest(supplier).build(), BidRequest.class);
// To decide: BidRequest validation necessary?
// final OpenRtbValidator requestValidator = OpenRtbValidatorFactory.getValidator(OpenRtbInputType.BID_REQUEST, supplier.getOpenRtbVersion());
// if (!requestValidator.isValid(jsonBidrequest)) {
// System.out.println("request is not valid");
// }
log.debug(jsonBidrequest);
RtbRequestLogProcessor.instance.setLogData(jsonBidrequest, "bidrequest", String.valueOf(supplier.getSupplierId()));
final String result = connector.connect(jsonBidrequest, headers);
log.debug("result: " + result);
if (result != null) {
final BidResponse.Builder bidResponse = ResponseParser.parse(result, supplier);
sessionAgent.getBidExchange().setBidResponse(supplier, bidResponse);
return new ResponseContainer(supplier, bidResponse);
}
} catch (final Exception ignore) {
//
}
return null;
}
public Supplier getSupplier() {
return supplier;
}
private static class ResponseParser {
private static Gson gson = new Gson();
private static BidResponse.Builder parse(final String json, final Supplier supplier) {
RtbResponseLogProcessor.instance.setLogData(json, "bidresponse", String.valueOf(supplier.getSupplierId()));
try {
if (responseValidator.isValid(json)) {
final BidResponse response = gson.fromJson(json, BidResponse.class);
return response.getBuilder();
}
} catch (final JsonIOException | JsonSyntaxException e) {
log.error(e.getMessage());
}
return null;
}
}
}
| Using direct object of BidResponse instead of its Builder. Code cleanup.
| open-ssp-parent/core/src/main/java/com/atg/openssp/core/exchange/channel/rtb/DemandBroker.java | Using direct object of BidResponse instead of its Builder. Code cleanup. |
|
Java | mit | a8e992da9505bb6f567fa3367b13eddacd2449b5 | 0 | fclairamb/m2mp,fclairamb/m2mp,fclairamb/m2mp,fclairamb/m2mp | package org.m2mp.db;
import com.datastax.driver.core.*;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.policies.*;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Minimalistic cassandra access wrapper.
*
* @author Florent Clairambault
*/
public class DB {
private static final PoolingOptions poolingOptions = new PoolingOptions() {
{
setCoreConnectionsPerHost(HostDistance.LOCAL, 1);
setCoreConnectionsPerHost(HostDistance.REMOTE, 1);
setMaxConnectionsPerHost(HostDistance.LOCAL, 50);
setMaxConnectionsPerHost(HostDistance.REMOTE, 50);
}
};
private static final SocketOptions socketOptions = new SocketOptions() {
{
setConnectTimeoutMillis(2000);
}
};
private static final LoadingCache<String, PreparedStatement> psCache = CacheBuilder.newBuilder().maximumSize(100).build(new CacheLoader<String, PreparedStatement>() {
@Override
public PreparedStatement load(String query) throws Exception {
return prepareNoCache(query).setConsistencyLevel(level);
}
});
private static Executor executor = Executors.newCachedThreadPool();
private static String keyspaceName;
private static Cluster cluster;
private static Session session;
private static List<String> contactPoints = new ArrayList<String>() {
{
add("localhost");
}
};
private DB() {
}
public enum Mode {
RoundRobin,
LocalOnly
}
private static Mode mode = Mode.LocalOnly;
public static void setMode(Mode m) {
mode = m;
reset();
}
public static Mode getMode() {
return mode;
}
private static ConsistencyLevel level = ConsistencyLevel.ONE;
public static void setConsistencyLevel(ConsistencyLevel level) {
DB.level = level;
reset();
}
public static ConsistencyLevel getConsistencyLevel() {
return DB.level;
}
/**
* Change the default servers.
*
* @param contactPoints
*/
public static void setContactPoints(List<String> contactPoints) {
DB.contactPoints = contactPoints;
reset();
}
private static void reset() {
cluster = null;
session = null;
latencyPolicy = null;
psCache.cleanUp();
}
private static LoadBalancingPolicy latencyPolicy;
public static LoadBalancingPolicy getLatencyPolicy() {
if (latencyPolicy == null) {
if (mode == Mode.LocalOnly) {
ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>() {
{
add(new InetSocketAddress(InetAddress.getLoopbackAddress(), 9042));
}
};
latencyPolicy = new WhiteListPolicy(new RoundRobinPolicy(), list);
} else {
latencyPolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy()).withRetryPeriod(15, TimeUnit.MINUTES).withScale(5, TimeUnit.SECONDS).withExclusionThreshold(1.5).build();
}
}
return latencyPolicy;
}
private static Cluster getCluster() {
if (cluster == null) {
Cluster.Builder c = Cluster.builder();
for (String cp : contactPoints) {
c.addContactPoint(cp);
}
c.withPoolingOptions(poolingOptions)
.withSocketOptions(socketOptions)
.withLoadBalancingPolicy(getLatencyPolicy())
.withReconnectionPolicy(new ExponentialReconnectionPolicy(10000, 900000));
cluster = c.build();
}
return cluster;
}
public static void stop() {
if (cluster != null) {
cluster.close();
cluster = null;
}
psCache.cleanUp();
}
/**
* Change keyspace
*
* @param name Name of the keyspace
* @param create To create it if not already there
* <p/>
* Create option should never be set to free. It is only used for testing.
*/
public static void keyspace(String name, boolean create) {
try {
keyspaceName = name;
reset();
} catch (InvalidQueryException ex) {
if (create) {
cluster.connect().execute("CREATE KEYSPACE " + name + " WITH replication = {'class':'SimpleStrategy', 'replication_factor':3};");
} else {
throw new RuntimeException("Could not load keyspace " + name + " !", ex);
}
}
}
/**
* Change keyspace
*
* @param name Keyspace name
*/
public static void keyspace(String name) {
keyspace(name, false);
}
/**
* Get the internal session object
*
* @return Session object
*/
public static Session session() {
if (session == null) {
if (keyspaceName == null) {
throw new RuntimeException("You need to define a keyspace !");
}
try {
Cluster c = getCluster();
Metadata metadata = c.getMetadata();
Logger.getLogger(DB.class.getName()).log(Level.INFO, String.format("Connecting to cluster '%s' on %s.", metadata.getClusterName(), metadata.getAllHosts()));
session = c.connect(keyspaceName);
Logger.getLogger(DB.class.getName()).log(Level.INFO, String.format("Connected to cluster '%s' on %s.", metadata.getClusterName(), metadata.getAllHosts()));
} catch (Exception ex) {
cluster = null;
throw new RuntimeException("Could not connect to the cluster", ex);
}
}
return session;
}
/**
* Get the keyspace metadata
*
* @return Metadata object
*/
public static KeyspaceMetadata meta() {
return session().getCluster().getMetadata().getKeyspace(keyspaceName);
}
/**
* Prepare a query and put it in cache.
*
* @param query Query to prepare
* @return PreparedStatement
*/
public static PreparedStatement prepare(String query) {
try {
return psCache.get(query);
} catch (ExecutionException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
return session().prepare(query);
}
}
/**
* Prepare a query (whithout putting it in cache)
*
* @param query Query to prepare
* @return PreparedStatement
*/
public static PreparedStatement prepareNoCache(String query) {
return session().prepare(query).setConsistencyLevel(level);
}
/**
* Execute a query
*
* @param query Query to execute
* @return The result
*/
public static ResultSet execute(Statement query) {
//Iterator<Host> hostIterator = latencyPolicy.newQueryPlan("", query);
//System.out.println("Query plan: ");
//while( hostIterator.hasNext() ) {
// System.out.println(" * "+hostIterator.next());
//}
return session().execute(query);
}
/**
* Execute a query
*
* @param query Query to execute
* @return The result
*/
public static ResultSet execute(String query) {
BoundStatement statement = prepare(query).bind();
statement.setConsistencyLevel(level);
return session().execute(statement);
}
/**
* Execute a query asynchronously
*
* @param query Query to execute
* @return The result future
*/
public static ResultSetFuture executeAsync(Statement query) {
return session().executeAsync(query);
}
/**
* Execute a query later. We can't really say when.
*
* @param query Query to execute
*/
public static void executeLater(final Statement query) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
session().executeAsync(query);
} catch (Exception e) {
}
}
});
}
}
| java/org.m2mp.db/src/main/java/org/m2mp/db/DB.java | package org.m2mp.db;
import com.datastax.driver.core.*;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
import com.datastax.driver.core.policies.LatencyAwarePolicy;
import com.datastax.driver.core.policies.RoundRobinPolicy;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Minimalistic cassandra access wrapper.
*
* @author Florent Clairambault
*/
public class DB {
private static final PoolingOptions poolingOptions = new PoolingOptions() {
{
setCoreConnectionsPerHost(HostDistance.LOCAL, 1);
setCoreConnectionsPerHost(HostDistance.REMOTE, 1);
setMaxConnectionsPerHost(HostDistance.LOCAL, 50);
setMaxConnectionsPerHost(HostDistance.REMOTE, 50);
}
};
private static final SocketOptions socketOptions = new SocketOptions() {
{
setConnectTimeoutMillis(2000);
}
};
private static final LoadingCache<String, PreparedStatement> psCache = CacheBuilder.newBuilder().maximumSize(100).build(new CacheLoader<String, PreparedStatement>() {
@Override
public PreparedStatement load(String query) throws Exception {
return prepareNoCache(query).setConsistencyLevel(level);
}
});
private static Executor executor = Executors.newCachedThreadPool();
private static String keyspaceName;
private static Cluster cluster;
private static Session session;
private static List<String> contactPoints = new ArrayList<String>() {
{
add("localhost");
}
};
private DB() {
}
private static ConsistencyLevel level = ConsistencyLevel.ONE;
public static void setConsistencyLevel(ConsistencyLevel level) {
DB.level = level;
reset();
}
public static ConsistencyLevel getConsistencyLevel() {
return DB.level;
}
/**
* Change the default servers.
*
* @param contactPoints
*/
public static void setContactPoints(List<String> contactPoints) {
DB.contactPoints = contactPoints;
reset();
}
private static void reset() {
cluster = null;
session = null;
latencyPolicy = null;
psCache.cleanUp();
}
private static LatencyAwarePolicy latencyPolicy;
public static LatencyAwarePolicy getLatencyPolicy() {
if (latencyPolicy == null) {
latencyPolicy = LatencyAwarePolicy.builder(new RoundRobinPolicy()).withRetryPeriod(15, TimeUnit.MINUTES).withScale(5, TimeUnit.SECONDS).withExclusionThreshold(1.5).build();
}
return latencyPolicy;
}
private static Cluster getCluster() {
if (cluster == null) {
Cluster.Builder c = Cluster.builder();
for (String cp : contactPoints) {
c.addContactPoint(cp);
}
c.withPoolingOptions(poolingOptions)
.withSocketOptions(socketOptions)
.withLoadBalancingPolicy(getLatencyPolicy())
.withReconnectionPolicy(new ExponentialReconnectionPolicy(10000, 900000));
cluster = c.build();
}
return cluster;
}
public static void stop() {
if (cluster != null) {
cluster.close();
cluster = null;
}
psCache.cleanUp();
}
/**
* Change keyspace
*
* @param name Name of the keyspace
* @param create To create it if not already there
* <p/>
* Create option should never be set to free. It is only used for testing.
*/
public static void keyspace(String name, boolean create) {
try {
keyspaceName = name;
reset();
} catch (InvalidQueryException ex) {
if (create) {
cluster.connect().execute("CREATE KEYSPACE " + name + " WITH replication = {'class':'SimpleStrategy', 'replication_factor':3};");
} else {
throw new RuntimeException("Could not load keyspace " + name + " !", ex);
}
}
}
/**
* Change keyspace
*
* @param name Keyspace name
*/
public static void keyspace(String name) {
keyspace(name, false);
}
/**
* Get the internal session object
*
* @return Session object
*/
public static Session session() {
if (session == null) {
if (keyspaceName == null) {
throw new RuntimeException("You need to define a keyspace !");
}
try {
Cluster c = getCluster();
Metadata metadata = c.getMetadata();
Logger.getLogger(DB.class.getName()).log(Level.INFO, String.format("Connecting to cluster '%s' on %s.", metadata.getClusterName(), metadata.getAllHosts()));
session = c.connect(keyspaceName);
Logger.getLogger(DB.class.getName()).log(Level.INFO, String.format("Connected to cluster '%s' on %s.", metadata.getClusterName(), metadata.getAllHosts()));
} catch (Exception ex) {
cluster = null;
throw new RuntimeException("Could not connect to the cluster", ex);
}
}
return session;
}
/**
* Get the keyspace metadata
*
* @return Metadata object
*/
public static KeyspaceMetadata meta() {
return session().getCluster().getMetadata().getKeyspace(keyspaceName);
}
/**
* Prepare a query and put it in cache.
*
* @param query Query to prepare
* @return PreparedStatement
*/
public static PreparedStatement prepare(String query) {
try {
return psCache.get(query);
} catch (ExecutionException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
return session().prepare(query);
}
}
/**
* Prepare a query (whithout putting it in cache)
*
* @param query Query to prepare
* @return PreparedStatement
*/
public static PreparedStatement prepareNoCache(String query) {
return session().prepare(query).setConsistencyLevel(level);
}
/**
* Execute a query
*
* @param query Query to execute
* @return The result
*/
public static ResultSet execute(Statement query) {
//Iterator<Host> hostIterator = latencyPolicy.newQueryPlan("", query);
//System.out.println("Query plan: ");
//while( hostIterator.hasNext() ) {
// System.out.println(" * "+hostIterator.next());
//}
return session().execute(query);
}
/**
* Execute a query
*
* @param query Query to execute
* @return The result
*/
public static ResultSet execute(String query) {
BoundStatement statement = prepare(query).bind();
statement.setConsistencyLevel(level);
return session().execute(statement);
}
/**
* Execute a query asynchronously
*
* @param query Query to execute
* @return The result future
*/
public static ResultSetFuture executeAsync(Statement query) {
return session().executeAsync(query);
}
/**
* Execute a query later. We can't really say when.
*
* @param query Query to execute
*/
public static void executeLater(final Statement query) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
session().executeAsync(query);
} catch (Exception e) {
}
}
});
}
}
| java/db: Adding a local only mode.
When we are in a one consistency mode, it's better to stick with the local host.
| java/org.m2mp.db/src/main/java/org/m2mp/db/DB.java | java/db: Adding a local only mode. |
|
Java | mit | a667848d68cf9f2c406a0736c40700465506ef29 | 0 | mzmine/mzmine3,mzmine/mzmine3 | /*
* Copyright 2006-2008 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine 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 2 of the License, or (at your option) any later
* version.
*
* MZmine 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
* MZmine; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.mzmine.modules.io.rawdataimport.fileformats;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.logging.Logger;
import java.util.zip.Inflater;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import net.sf.mzmine.data.DataPoint;
import net.sf.mzmine.data.PreloadLevel;
import net.sf.mzmine.data.impl.SimpleDataPoint;
import net.sf.mzmine.data.impl.SimpleScan;
import net.sf.mzmine.main.MZmineCore;
import net.sf.mzmine.modules.io.rawdataimport.RawDataFileImpl;
import net.sf.mzmine.taskcontrol.Task;
import org.jfree.xml.util.Base64;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
*/
public class MZXMLReadTask extends DefaultHandler implements Task {
private Logger logger = Logger.getLogger(this.getClass().getName());
private File originalFile;
private RawDataFileImpl newMZmineFile;
private PreloadLevel preloadLevel;
private TaskStatus status;
private int totalScans = -1;
private int parsedScans;
private int peaksCount = 0;
private String errorMessage;
private StringBuilder charBuffer;
private Boolean compressFlag = false;
private int compressedLen;
/*
* This variables are used to set the number of fragments that one single
* scan can have. The initial size of array is set to 10, but it depends of
* fragmentation level.
*/
private int parentTreeValue[] = new int[10];
private int msLevelTree = 0;
/*
* This stack stores the current scan and all his fragments until all the information
* is recover. The logic is FIFO at the moment of write into the MZmineFile
*/
private LinkedList<SimpleScan> parentStack;
/*
* This variable hold the present scan or fragment, it is send to the stack when
* another scan/fragment appears as a parser.startElement
*/
private SimpleScan buildingScan;
public MZXMLReadTask(File fileToOpen, PreloadLevel preloadLevel) {
originalFile = fileToOpen;
status = TaskStatus.WAITING;
this.preloadLevel = preloadLevel;
charBuffer = new StringBuilder(2048);
parentStack = new LinkedList<SimpleScan>();
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getTaskDescription()
*/
public String getTaskDescription() {
return "Opening file " + originalFile;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getFinishedPercentage()
*/
public float getFinishedPercentage() {
return totalScans == 0 ? 0 : (float) parsedScans / totalScans;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getStatus()
*/
public TaskStatus getStatus() {
return status;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getErrorMessage()
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
status = TaskStatus.PROCESSING;
logger.info("Started parsing file " + originalFile);
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
newMZmineFile = new RawDataFileImpl(originalFile.getName(),
"mzxml", preloadLevel);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(originalFile, this);
// Close file
newMZmineFile.finishWriting();
MZmineCore.getCurrentProject().addFile(newMZmineFile);
} catch (Throwable e) {
/* we may already have set the status to CANCELED */
e.printStackTrace();
if (status == TaskStatus.PROCESSING)
status = TaskStatus.ERROR;
errorMessage = e.toString();
return;
}
if (parsedScans == 0) {
status = TaskStatus.ERROR;
errorMessage = "No scans found";
return;
}
logger.info("Finished parsing " + originalFile + ", parsed "
+ parsedScans + " scans");
status = TaskStatus.FINISHED;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#cancel()
*/
public void cancel() {
logger.info("Cancelling opening of MZXML file " + originalFile);
status = TaskStatus.CANCELED;
}
public void startElement(String namespaceURI, String lName, // local name
String qName, // qualified name
Attributes attrs) throws SAXException {
if (status == TaskStatus.CANCELED)
throw new SAXException("Parsing Cancelled");
// <msRun>
if (qName.equals("msRun")) {
String s = attrs.getValue("scanCount");
if (s != null)
totalScans = Integer.parseInt(s);
}
// <scan>
if (qName.equalsIgnoreCase("scan")) {
if (buildingScan != null) {
parentStack.addFirst(buildingScan);
buildingScan = null;
}
/*
* Only num, msLevel & peaksCount values are required according with mzxml standard,
* the others are optional
*/
int scanNumber = Integer.parseInt(attrs.getValue("num"));
int msLevel = Integer.parseInt(attrs.getValue("msLevel"));
peaksCount = Integer.parseInt(attrs.getValue("peaksCount"));
// Parse retention time
float retentionTime = 0;
String retentionTimeStr = attrs.getValue("retentionTime");
if (retentionTimeStr != null){
Date currentDate = new Date();
try {
DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
Duration dur = dataTypeFactory.newDuration(retentionTimeStr);
retentionTime = dur.getTimeInMillis(currentDate) / 1000f;
} catch (DatatypeConfigurationException e) {
throw new SAXException("Could not read retention time: " + e);
}
}else {
status = TaskStatus.ERROR;
errorMessage = "This file does not contain retentionTime for scans";
throw new SAXException("Could not read retention time");
}
int parentScan = -1;
if (msLevelTree > 0) {
if (msLevel > 9) {
status = TaskStatus.ERROR;
errorMessage = "msLevel value bigger than 10";
throw new SAXException("The value of msLevel is bigger than 10");
}
parentScan = parentTreeValue[msLevel - 1];
}
// Setting the level of fragment of scan and parent scan number
msLevelTree++;
parentTreeValue[msLevel] = scanNumber;
buildingScan = new SimpleScan(scanNumber, msLevel, retentionTime,
parentScan, 0f, null, new DataPoint[0], false);
}
// <peak>
if (qName.equalsIgnoreCase("peaks")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
compressFlag = false;
compressedLen = 0;
if ((attrs.getValue("compressionType"))!= null){
compressFlag = true;
compressedLen = Integer.parseInt(attrs.getValue("compressedLen"));
}
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
String precursorCharge = attrs.getValue("precursorCharge");
if (precursorCharge != null)
buildingScan.setPrecursorCharge(Integer
.parseInt(precursorCharge));
}
}
/**
* endElement()
*/
public void endElement(String namespaceURI, String sName, // simple name
String qName // qualified name
) throws SAXException {
// </scan>
if (qName.equalsIgnoreCase("scan")) {
msLevelTree--;
/*
* At this point we verify if the scan and his fragments are closed,
* so we include the present scan/fragment into the stack and start
* to take elements from them (FIFO) for the MZmineFile.
*/
logger.info("Level of msLevelTree " + msLevelTree);
if (msLevelTree == 0) {
parentStack.addFirst(buildingScan);
buildingScan = null;
while (!parentStack.isEmpty()) {
SimpleScan s = parentStack.removeLast();
newMZmineFile.addScan(s);
parsedScans++;
}
/*
* The scan with all his fragments is in the MzmineFile, now we clean
* the stack for the next scan and fragments.
*/
parentStack.clear();
}
/*
* If there are some scan/fragments still open, we update the reference of
* fragments of each element in the stack with the current scan/fragment.
*/
else {
for (SimpleScan s : parentStack) {
if (s.getScanNumber() == buildingScan.getParentScanNumber()) {
int[] b = s.getFragmentScanNumbers();
if (b != null) {
int[] temp = b;
b = new int[temp.length + 1];
System.arraycopy(temp, 0, b, 0, temp.length);
b[temp.length] = buildingScan.getScanNumber();
s.setFragmentScanNumbers(b);
} else {
b = new int[1];
b[0] = s.getScanNumber();
s.setFragmentScanNumbers(b);
}
}
}
}
return;
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
float precursorMz = Float.parseFloat(charBuffer.toString());
buildingScan.setPrecursorMZ(precursorMz);
return;
}
// <peak>
if (qName.equalsIgnoreCase("peaks")) {
//
DataPoint completeDataPoints[] = new DataPoint[peaksCount];
DataPoint tempDataPoints[] = new DataPoint[peaksCount];
byte[] peakBytes = Base64.decode(charBuffer.toString()
.toCharArray());
/*
* This section provides support for decompression ZLIB compression library.
*/
if (compressFlag){
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(peakBytes, 0, compressedLen);
byte[] result = new byte[1024];
byte[] resultTotal = new byte [0];
try {
int resultLength = decompresser.inflate(result);
while (!decompresser.finished()){
byte temp[] = resultTotal;
resultTotal = new byte[resultTotal.length + resultLength];
System.arraycopy(temp, 0, resultTotal, 0, temp.length);
System.arraycopy(result, 0, resultTotal, temp.length, resultLength);
resultLength = decompresser.inflate(result);
}
byte temp[] = resultTotal;
resultTotal = new byte[resultTotal.length + resultLength];
System.arraycopy(temp, 0, resultTotal, 0, temp.length);
System.arraycopy(result, 0, resultTotal, temp.length, resultLength);
decompresser.end();
peakBytes = new byte[resultTotal.length];
peakBytes = resultTotal;
}
catch (Exception eof) {
status = TaskStatus.ERROR;
errorMessage = "Corrupt compressed peak";
throw new SAXException("Parsing Cancelled");
}
}
// make a data input stream
DataInputStream peakStream = new DataInputStream(
new ByteArrayInputStream(peakBytes));
try {
for (int i = 0; i < completeDataPoints.length; i++) {
//Always respect this order pairOrder="m/z-int"
float massOverCharge = peakStream.readFloat();
float intensity = peakStream.readFloat();
// Copy m/z and intensity data
completeDataPoints[i] = new SimpleDataPoint(massOverCharge,
intensity);
}
} catch (IOException eof) {
status = TaskStatus.ERROR;
errorMessage = "Corrupt mzXML file";
throw new SAXException("Parsing Cancelled");
}
/*
* This section verifies DataPoints with intensity="0" and exclude
* them from tempDataPoints array. Only accept some of these points
* because they are part the left/right part of the peak.
*/
int i, j;
for (i = 0, j = 0; i < completeDataPoints.length; i++) {
float intensity = completeDataPoints[i].getIntensity();
float mz = completeDataPoints[i].getMZ();
if (completeDataPoints[i].getIntensity() > 0) {
tempDataPoints[j] = new SimpleDataPoint(mz, intensity);
j++;
continue;
}
if ((i > 0) && (completeDataPoints[i - 1].getIntensity() > 0)) {
tempDataPoints[j] = new SimpleDataPoint(mz, intensity);
j++;
continue;
}
if ((i < completeDataPoints.length - 1)
&& (completeDataPoints[i + 1].getIntensity() > 0)) {
tempDataPoints[j] = new SimpleDataPoint(mz, intensity);
j++;
continue;
}
}
// If we have no peaks with intensity of 0, we assume the scan is
// centroided
if (i == j) {
buildingScan.setCentroided(true);
buildingScan.setDataPoints(tempDataPoints);
} else {
int sizeArray = j;
DataPoint[] dataPoints = new DataPoint[j];
System.arraycopy(tempDataPoints, 0, dataPoints, 0, sizeArray);
/*
* for (int i = 0; i < j; i++){ dataPoints[i]=tempDataPoints[i]; }
*/
buildingScan.setDataPoints(dataPoints);
}
return;
}
}
/**
* characters()
*
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters(char buf[], int offset, int len) throws SAXException {
charBuffer = charBuffer.append(buf, offset, len);
}
}
| src/net/sf/mzmine/modules/io/rawdataimport/fileformats/MZXMLReadTask.java | /*
* Copyright 2006-2008 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine 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 2 of the License, or (at your option) any later
* version.
*
* MZmine 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
* MZmine; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.mzmine.modules.io.rawdataimport.fileformats;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.logging.Logger;
import java.util.zip.Inflater;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import net.sf.mzmine.data.DataPoint;
import net.sf.mzmine.data.PreloadLevel;
import net.sf.mzmine.data.impl.SimpleDataPoint;
import net.sf.mzmine.data.impl.SimpleScan;
import net.sf.mzmine.main.MZmineCore;
import net.sf.mzmine.modules.io.rawdataimport.RawDataFileImpl;
import net.sf.mzmine.taskcontrol.Task;
import org.jfree.xml.util.Base64;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
*/
public class MZXMLReadTask extends DefaultHandler implements Task {
private Logger logger = Logger.getLogger(this.getClass().getName());
private File originalFile;
private RawDataFileImpl newMZmineFile;
private PreloadLevel preloadLevel;
private TaskStatus status;
private int totalScans = -1;
private int parsedScans;
private int peaksCount = 0;
private String errorMessage;
private StringBuilder charBuffer;
private Boolean compressFlag = false;
private int compressedLen;
/*
* This variables are used to set the number of fragments that one single
* scan can have. The initial size of array is set to 10, but it depends of
* fragmentation level.
*/
private int parentTreeValue[] = new int[10];
private int msLevelTree = 0;
/*
* This stack stores the current scan and all his fragments until all the information
* is recover. The logic is FIFO at the moment of write into the MZmineFile
*/
private LinkedList<SimpleScan> parentStack;
/*
* This variable hold the present scan or fragment, it is send to the stack when
* another scan/fragment appears as a parser.startElement
*/
private SimpleScan buildingScan;
public MZXMLReadTask(File fileToOpen, PreloadLevel preloadLevel) {
originalFile = fileToOpen;
status = TaskStatus.WAITING;
this.preloadLevel = preloadLevel;
charBuffer = new StringBuilder(2048);
parentStack = new LinkedList<SimpleScan>();
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getTaskDescription()
*/
public String getTaskDescription() {
return "Opening file " + originalFile;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getFinishedPercentage()
*/
public float getFinishedPercentage() {
return totalScans == 0 ? 0 : (float) parsedScans / totalScans;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getStatus()
*/
public TaskStatus getStatus() {
return status;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#getErrorMessage()
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
status = TaskStatus.PROCESSING;
logger.info("Started parsing file " + originalFile);
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
newMZmineFile = new RawDataFileImpl(originalFile.getName(),
"mzxml", preloadLevel);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(originalFile, this);
// Close file
newMZmineFile.finishWriting();
MZmineCore.getCurrentProject().addFile(newMZmineFile);
} catch (Throwable e) {
/* we may already have set the status to CANCELED */
e.printStackTrace();
if (status == TaskStatus.PROCESSING)
status = TaskStatus.ERROR;
errorMessage = e.toString();
return;
}
if (parsedScans == 0) {
status = TaskStatus.ERROR;
errorMessage = "No scans found";
return;
}
logger.info("Finished parsing " + originalFile + ", parsed "
+ parsedScans + " scans");
status = TaskStatus.FINISHED;
}
/**
* @see net.sf.mzmine.taskcontrol.Task#cancel()
*/
public void cancel() {
logger.info("Cancelling opening of MZXML file " + originalFile);
status = TaskStatus.CANCELED;
}
public void startElement(String namespaceURI, String lName, // local name
String qName, // qualified name
Attributes attrs) throws SAXException {
if (status == TaskStatus.CANCELED)
throw new SAXException("Parsing Cancelled");
// <msRun>
if (qName.equals("msRun")) {
String s = attrs.getValue("scanCount");
if (s != null)
totalScans = Integer.parseInt(s);
}
// <scan>
if (qName.equalsIgnoreCase("scan")) {
if (buildingScan != null) {
parentStack.addFirst(buildingScan);
logger.info("Adiciona a stack scan number: " + buildingScan.getScanNumber());
buildingScan = null;
}
/*
* Only num, msLevel & peaksCount values are required according with mzxml standard,
* the others are optional
*/
int scanNumber = Integer.parseInt(attrs.getValue("num"));
int msLevel = Integer.parseInt(attrs.getValue("msLevel"));
peaksCount = Integer.parseInt(attrs.getValue("peaksCount"));
// Parse retention time
float retentionTime = 0;
String retentionTimeStr = attrs.getValue("retentionTime");
if (retentionTimeStr != null){
Date currentDate = new Date();
try {
DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
Duration dur = dataTypeFactory.newDuration(retentionTimeStr);
retentionTime = dur.getTimeInMillis(currentDate) / 1000f;
} catch (DatatypeConfigurationException e) {
throw new SAXException("Could not read retention time: " + e);
}
}
int parentScan = -1;
if (msLevelTree > 0) {
if (msLevel > 9) {
status = TaskStatus.ERROR;
errorMessage = "msLevel value bigger than 10";
throw new SAXException("The value of msLevel is bigger than 10");
}
parentScan = parentTreeValue[msLevel - 1];
}
// Setting the level of fragment of scan and parent scan number
msLevelTree++;
parentTreeValue[msLevel] = scanNumber;
buildingScan = new SimpleScan(scanNumber, msLevel, retentionTime,
parentScan, 0f, null, new DataPoint[0], false);
}
// <peak>
if (qName.equalsIgnoreCase("peaks")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
compressFlag = false;
compressedLen = 0;
if ((attrs.getValue("compressionType"))!= null){
compressFlag = true;
compressedLen = Integer.parseInt(attrs.getValue("compressedLen"));
}
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
// clean the current char buffer for the new element
charBuffer.setLength(0);
String precursorCharge = attrs.getValue("precursorCharge");
if (precursorCharge != null)
buildingScan.setPrecursorCharge(Integer
.parseInt(precursorCharge));
}
}
/**
* endElement()
*/
public void endElement(String namespaceURI, String sName, // simple name
String qName // qualified name
) throws SAXException {
// </scan>
if (qName.equalsIgnoreCase("scan")) {
msLevelTree--;
/*
* At this point we verify if the scan and his fragments are closed,
* so we include the present scan/fragment into the stack and start
* to take elements from them (FIFO) for the MZmineFile.
*/
logger.info("Level of msLevelTree " + msLevelTree);
if (msLevelTree == 0) {
parentStack.addFirst(buildingScan);
buildingScan = null;
while (!parentStack.isEmpty()) {
newMZmineFile.addScan(parentStack.pollLast());
parsedScans++;
}
/*
* The scan with all his fragments is in the MzmineFile, now we clean
* the stack for the next scan and fragments.
*/
parentStack.clear();
}
/*
* If there are some scan/fragments still open, we update the reference of
* fragments of each element in the stack with the current scan/fragment.
*/
else {
for (SimpleScan s : parentStack) {
if (s.getScanNumber() == buildingScan.getParentScanNumber()) {
int[] b = s.getFragmentScanNumbers();
if (b != null) {
int[] temp = b;
b = new int[temp.length + 1];
System.arraycopy(temp, 0, b, 0, temp.length);
b[temp.length] = buildingScan.getScanNumber();
s.setFragmentScanNumbers(b);
} else {
b = new int[1];
b[0] = s.getScanNumber();
s.setFragmentScanNumbers(b);
}
}
}
}
return;
}
// <precursorMz>
if (qName.equalsIgnoreCase("precursorMz")) {
float precursorMz = Float.parseFloat(charBuffer.toString());
buildingScan.setPrecursorMZ(precursorMz);
return;
}
// <peak>
if (qName.equalsIgnoreCase("peaks")) {
//
DataPoint completeDataPoints[] = new DataPoint[peaksCount];
DataPoint tempDataPoints[] = new DataPoint[peaksCount];
byte[] peakBytes = Base64.decode(charBuffer.toString()
.toCharArray());
/*
* This section provides support for decompression ZLIB compression library.
*/
if (compressFlag){
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(peakBytes, 0, compressedLen);
byte[] result = new byte[1024];
byte[] resultTotal = new byte [0];
try {
int resultLength = decompresser.inflate(result);
while (!decompresser.finished()){
byte temp[] = resultTotal;
resultTotal = new byte[resultTotal.length + resultLength];
System.arraycopy(temp, 0, resultTotal, 0, temp.length);
System.arraycopy(result, 0, resultTotal, temp.length, resultLength);
resultLength = decompresser.inflate(result);
}
byte temp[] = resultTotal;
resultTotal = new byte[resultTotal.length + resultLength];
System.arraycopy(temp, 0, resultTotal, 0, temp.length);
System.arraycopy(result, 0, resultTotal, temp.length, resultLength);
decompresser.end();
peakBytes = new byte[resultTotal.length];
peakBytes = resultTotal;
}
catch (Exception eof) {
status = TaskStatus.ERROR;
errorMessage = "Corrupt compressed peak";
throw new SAXException("Parsing Cancelled");
}
}
// make a data input stream
DataInputStream peakStream = new DataInputStream(
new ByteArrayInputStream(peakBytes));
try {
for (int i = 0; i < completeDataPoints.length; i++) {
//Always respect this order pairOrder="m/z-int"
float massOverCharge = peakStream.readFloat();
float intensity = peakStream.readFloat();
// Copy m/z and intensity data
completeDataPoints[i] = new SimpleDataPoint(massOverCharge,
intensity);
}
} catch (IOException eof) {
status = TaskStatus.ERROR;
errorMessage = "Corrupt mzXML file";
throw new SAXException("Parsing Cancelled");
}
/*
* This section verifies DataPoints with intensity="0" and exclude
* them from tempDataPoints array. Only accept some of these points
* because they are part the left/right part of the peak.
*/
int i, j;
for (i = 0, j = 0; i < completeDataPoints.length; i++) {
float intensity = completeDataPoints[i].getIntensity();
float mz = completeDataPoints[i].getMZ();
if (completeDataPoints[i].getIntensity() > 0) {
tempDataPoints[j] = new SimpleDataPoint(mz, intensity);
j++;
continue;
}
if ((i > 0) && (completeDataPoints[i - 1].getIntensity() > 0)) {
tempDataPoints[j] = new SimpleDataPoint(mz, intensity);
j++;
continue;
}
if ((i < completeDataPoints.length - 1)
&& (completeDataPoints[i + 1].getIntensity() > 0)) {
tempDataPoints[j] = new SimpleDataPoint(mz, intensity);
j++;
continue;
}
}
// If we have no peaks with intensity of 0, we assume the scan is
// centroided
if (i == j) {
buildingScan.setCentroided(true);
buildingScan.setDataPoints(tempDataPoints);
} else {
int sizeArray = j;
DataPoint[] dataPoints = new DataPoint[j];
System.arraycopy(tempDataPoints, 0, dataPoints, 0, sizeArray);
/*
* for (int i = 0; i < j; i++){ dataPoints[i]=tempDataPoints[i]; }
*/
buildingScan.setDataPoints(dataPoints);
}
return;
}
}
/**
* characters()
*
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters(char buf[], int offset, int len) throws SAXException {
charBuffer = charBuffer.append(buf, offset, len);
}
}
| Update MZXMLtask with method removeLast() to manage parentStack. Previous file was using pollLast() (JSE 1.6 only)
| src/net/sf/mzmine/modules/io/rawdataimport/fileformats/MZXMLReadTask.java | Update MZXMLtask with method removeLast() to manage parentStack. Previous file was using pollLast() (JSE 1.6 only) |
|
Java | mit | 5b92f2fea711b0e2615cee561ac88c730d779414 | 0 | GoodTimeStudio/GoodTime-Industrial,GoodTimeStudio/Production-Line,Minecraft-GoodTime/GoodTime-Industrial | package com.mcgoodtime.gti.common.worldgen;
import cpw.mods.fml.common.IWorldGenerator;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenMinable;
import ic2.api.item.IC2Items;
import java.util.Random;
/**
* Another world generator?
*
* @author JAVA10
*/
public class BsaltGen implements IWorldGenerator {
private static final int TICKET = 5;
private static final int MAX_HEIGHT = 27;
private static final int GEN_SIZE = 10;
@Override
public void generate(Random random, int chunkX, int chunkZ, World world,
IChunkProvider chunkGenerator, IChunkProvider chunkProvider) {
if (!world.provider.isHellWorld && !world.provider.hasNoSky)
generateOre(world, random, chunkX, chunkZ);
}
private void generateOre(World world, Random rand, int chunkX, int chunkZ) {
for (int k = 0; k < this.TICKET; k++) {
int x = chunkX * 16 + rand.nextInt(16);
int y = rand.nextInt(this.MAX_HEIGHT);
int z = chunkZ * 16 + rand.nextInt(16);
new WorldGenMinable(IC2Items.getItem("Basalt"), this.GEN_SIZE).generate(world, rand, x, y, z);
}
}
}
| src/main/java/com/mcgoodtime/gti/common/worldgen/BsaltGen.java | package com.mcgoodtime.gti.common.worldgen;
import cpw.mods.fml.common.IWorldGenerator;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenMinable;
import ic2.api.item.IC2Items;
import java.util.Random;
/**
* Another world generator?
*
* @author JAVA10
*/
public class BsaltGen implements IWorldGenerator {
private static final int TICKET = 5;
private static final int MAX_HEIGHT = 27;
private static final int GEN_SIZE = 10;
@Override
public void generate(Random random, int chunkX, int chunkZ, World world,
IChunkProvider chunkGenerator, IChunkProvider chunkProvider) {
if (!world.provider.isHellWorld && !world.provider.hasNoSky)
generateOre(world, random, chunkX, chunkZ);
}
private void generateOre(World world, Random rand, int chunkX, int chunkZ) {
for (int k = 0; k < this.TICKET; k++) {
int x = chunkX * 16 + rand.nextInt(16);
int y = rand.nextInt(this.MAX_HEIGHT);
int z = chunkZ * 16 + rand.nextInt(16);
new WorldGenMinable(IC2Items.getItem("Basalt")), this.GEN_SIZE).generate(world, rand, x, y, z);
}
}
}
| tried to fix | src/main/java/com/mcgoodtime/gti/common/worldgen/BsaltGen.java | tried to fix |
|
Java | agpl-3.0 | a99bc48f4e409f6da075bcb9abcaafd949f22152 | 0 | bluemoep/LocalTwitter,bluemoep/LocalTwitter | package edu.oldenburg.it.bluemoep;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class TwitterRequest {
protected final String oauth_consumer_key = "XiSYzq3ak6ZVrupuJDk1hh9xF";
protected final String oauth_consumer_secret = "EyHAg9kX47YGpRkA0brxRkJEZEs4o6zXVmSvWTnrNBVSkXvpsX";
protected final String oauth_token = "2558944136-WbSyJGI7iYDD47J6qtZyiwh3Mv7G7jTevqU4RkJ";
protected final String oauth_token_secret = "T5v4Oc3fKoddNUnCnNHkq8EQbJwUO8AvwafRKgceijLRr";
protected OAuthConsumer oAuthConsumer;
protected HashMap<String, String> parameters;
protected String url;
public TwitterRequest(String url) {
oAuthConsumer = new CommonsHttpOAuthConsumer(oauth_consumer_key,
oauth_consumer_secret);
oAuthConsumer.setTokenWithSecret(oauth_token, oauth_token_secret);
parameters = new HashMap<String, String>();
this.url = url;
}
public void addParameter(String key, String value) {
parameters.put(key, value);
}
public HttpResponse doRequest() {
HttpPost httpPost = new HttpPost(url + "?" + getParameterString());
try {
oAuthConsumer.sign(httpPost);
} catch (OAuthMessageSignerException | OAuthExpectationFailedException
| OAuthCommunicationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// send the request
HttpClient httpClient = new DefaultHttpClient();
try {
return httpClient.execute(httpPost);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private String getParameterString() {
StringBuilder sb = new StringBuilder();
Iterator<Entry<String, String>> iterator = parameters.entrySet()
.iterator();
Entry<String, String> entry;
while (iterator.hasNext()) {
entry = iterator.next();
sb.append(entry.getKey()).append("=").append(encode(entry.getValue()));
}
System.out.println(sb.toString());
return sb.toString();
}
// Methode zur encodierung von Strings gem. RFC3986
private String encode(String value) {
String encoded = null;
try {
encoded = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
StringBuilder buf = new StringBuilder(encoded.length());
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
buf.append("%2A");
} else if (focus == '+') {
buf.append("%20");
} else if (focus == '%' && (i + 1) < encoded.length()
&& encoded.charAt(i + 1) == '7'
&& encoded.charAt(i + 2) == 'E') {
buf.append('~');
i += 2;
} else {
buf.append(focus);
}
}
return buf.toString();
}
}
| src/edu/oldenburg/it/bluemoep/TwitterRequest.java | package edu.oldenburg.it.bluemoep;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class TwitterRequest {
protected final String oauth_consumer_key = "XiSYzq3ak6ZVrupuJDk1hh9xF";
protected final String oauth_consumer_secret = "EyHAg9kX47YGpRkA0brxRkJEZEs4o6zXVmSvWTnrNBVSkXvpsX";
protected final String oauth_token = "2558944136-WbSyJGI7iYDD47J6qtZyiwh3Mv7G7jTevqU4RkJ";
protected final String oauth_token_secret = "T5v4Oc3fKoddNUnCnNHkq8EQbJwUO8AvwafRKgceijLRr";
protected OAuthConsumer oAuthConsumer;
protected HashMap<String, String> parameters;
protected String url;
public TwitterRequest(String url) {
oAuthConsumer = new CommonsHttpOAuthConsumer(oauth_consumer_key,
oauth_consumer_secret);
oAuthConsumer.setTokenWithSecret(oauth_token, oauth_token_secret);
parameters = new HashMap<String, String>();
this.url = url;
}
public void addParameter(String key, String value) {
parameters.put(key, value);
}
public HttpResponse doRequest() {
HttpPost httpPost = new HttpPost(url + "?" + getParameterString());
try {
oAuthConsumer.sign(httpPost);
} catch (OAuthMessageSignerException | OAuthExpectationFailedException
| OAuthCommunicationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// send the request
HttpClient httpClient = new DefaultHttpClient();
try {
return httpClient.execute(httpPost);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private String getParameterString() {
StringBuilder sb = new StringBuilder();
Iterator<Entry<String, String>> iterator = parameters.entrySet()
.iterator();
Entry<String, String> entry;
while (iterator.hasNext()) {
entry = iterator.next();
sb.append(entry.getKey()).append(encode(entry.getValue()));
}
return sb.toString();
}
// Methode zur encodierung von Strings gem. RFC3986
private String encode(String value) {
String encoded = null;
try {
encoded = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
StringBuilder buf = new StringBuilder(encoded.length());
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
buf.append("%2A");
} else if (focus == '+') {
buf.append("%20");
} else if (focus == '%' && (i + 1) < encoded.length()
&& encoded.charAt(i + 1) == '7'
&& encoded.charAt(i + 2) == 'E') {
buf.append('~');
i += 2;
} else {
buf.append(focus);
}
}
return buf.toString();
}
}
| TwitterRequest corrected | src/edu/oldenburg/it/bluemoep/TwitterRequest.java | TwitterRequest corrected |
|
Java | agpl-3.0 | d0e47920944e40a79a4d9eecb882c74a4a3ef4d4 | 0 | bitsquare/bitsquare,metabit/bitsquare,haiqu/bitsquare,bisq-network/exchange,ManfredKarrer/exchange,bitsquare/bitsquare,sakazz/exchange,sakazz/exchange,haiqu/bitsquare,ManfredKarrer/exchange,metabit/bitsquare,bisq-network/exchange | /*
* This file is part of Bitsquare.
*
* Bitsquare is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bitsquare 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.common.util;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.*;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Random;
import java.util.concurrent.*;
/**
* General utilities
*/
public class Utilities {
private static final Logger log = LoggerFactory.getLogger(Utilities.class);
private static long lastTimeStamp = System.currentTimeMillis();
public static final String LB = System.getProperty("line.separator");
public static final String LB2 = LB + LB;
public static String objectToJson(Object object) {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new AnnotationExclusionStrategy())
/*.excludeFieldsWithModifiers(Modifier.TRANSIENT)*/
/* .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)*/
.setPrettyPrinting()
.create();
return gson.toJson(object);
}
public static ListeningExecutorService getListeningExecutorService(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
return MoreExecutors.listeningDecorator(getThreadPoolExecutor(name, corePoolSize, maximumPoolSize, keepAliveTimeInSec));
}
public static ThreadPoolExecutor getThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.build();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeInSec,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory);
executor.allowCoreThreadTimeOut(true);
executor.setRejectedExecutionHandler((r, e) -> log.warn("RejectedExecutionHandler called"));
return executor;
}
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.setPriority(Thread.MIN_PRIORITY)
.build();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
executor.setKeepAliveTime(keepAliveTimeInSec, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
executor.setMaximumPoolSize(maximumPoolSize);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
executor.setRejectedExecutionHandler((r, e) -> log.warn("RejectedExecutionHandler called"));
return executor;
}
public static boolean isUnix() {
return isOSX() || isLinux() || getOSName().contains("freebsd");
}
public static boolean isWindows() {
return getOSName().contains("win");
}
public static boolean isOSX() {
return getOSName().contains("mac") || getOSName().contains("darwin");
}
public static boolean isLinux() {
return getOSName().contains("linux");
}
private static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
public static void openURI(URI uri) throws IOException {
if (!isLinux()
&& Desktop.isDesktopSupported()
&& Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
} else {
// Maybe Application.HostServices works in those cases?
// HostServices hostServices = getHostServices();
// hostServices.showDocument(uri.toString());
// On Linux Desktop is poorly implemented.
// See https://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform
if (!DesktopUtil.browse(uri))
throw new IOException("Failed to open URI: " + uri.toString());
}
}
public static void openWebPage(String target) {
try {
openURI(new URI(target));
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
public static void openDirectory(File directory) throws IOException {
if (!isLinux()
&& Desktop.isDesktopSupported()
&& Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
Desktop.getDesktop().open(directory);
} else {
// Maybe Application.HostServices works in those cases?
// HostServices hostServices = getHostServices();
// hostServices.showDocument(uri.toString());
// On Linux Desktop is poorly implemented.
// See https://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform
if (!DesktopUtil.open(directory))
throw new IOException("Failed to open directory: " + directory.toString());
}
}
public static void printSystemLoad() {
Runtime runtime = Runtime.getRuntime();
long free = runtime.freeMemory() / 1024 / 1024;
long total = runtime.totalMemory() / 1024 / 1024;
long used = total - free;
log.info("System load (nr. threads/used memory (MB)): " + Thread.activeCount() + "/" + used);
}
public static void openMail(String to, String subject, String body) {
try {
subject = URLEncoder.encode(subject, "UTF-8").replace("+", "%20");
body = URLEncoder.encode(body, "UTF-8").replace("+", "%20");
Desktop.getDesktop().mail(new URI("mailto:" + to + "?subject=" + subject + "&body=" + body));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
public static void copyToClipboard(String content) {
if (content != null && content.length() > 0) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(content);
clipboard.setContent(clipboardContent);
}
}
public static byte[] concatByteArrays(byte[]... arrays) {
int totalLength = 0;
for (byte[] array : arrays) {
totalLength += array.length;
}
byte[] result = new byte[totalLength];
int currentIndex = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, currentIndex, array.length);
currentIndex += array.length;
}
return result;
}
public static <T> T jsonToObject(String jsonString, Class<T> classOfT) {
Gson gson =
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create();
return gson.fromJson(jsonString, classOfT);
}
/* public static Object deserializeHexStringToObject(String serializedHexString) {
Object result = null;
try {
ByteArrayInputStream byteInputStream =
new ByteArrayInputStream(org.bitcoinj.core.Utils.parseAsHexOrBase58(serializedHexString));
try (ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream)) {
result = objectInputStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
byteInputStream.close();
}
} catch (IOException i) {
i.printStackTrace();
}
return result;
}
public static String serializeObjectToHexString(Serializable serializable) {
String result = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(serializable);
result = org.bitcoinj.core.Utils.HEX.encode(byteArrayOutputStream.toByteArray());
byteArrayOutputStream.close();
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}*/
public static <T extends Serializable> T deserialize(byte[] data) {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInput in = null;
Object result = null;
try {
in = new ObjectInputStream(bis);
result = in.readObject();
if (!(result instanceof Serializable))
throw new RuntimeException("Object not of type Serializable");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException ex) {
// ignore close exception
}
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore close exception
}
}
return (T) result;
}
public static byte[] serialize(Serializable object) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
byte[] result = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(object);
out.flush();
result = bos.toByteArray().clone();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ignore) {
}
try {
bos.close();
} catch (IOException ignore) {
}
}
return result;
}
public static void deleteDirectory(File file) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null)
for (File c : files)
deleteDirectory(c);
}
if (!file.delete())
throw new FileNotFoundException("Failed to delete file: " + file);
}
private static void printElapsedTime(String msg) {
if (!msg.isEmpty()) {
msg += " / ";
}
long timeStamp = System.currentTimeMillis();
log.debug(msg + "Elapsed: " + String.valueOf(timeStamp - lastTimeStamp));
lastTimeStamp = timeStamp;
}
public static void printElapsedTime() {
printElapsedTime("");
}
public static Object copy(Serializable orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
/**
* Empty and delete a folder (and subfolders).
*
* @param folder folder to empty
*/
private static void removeDirectory(final File folder) {
// check if folder file is a real folder
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (File tmpF : list) {
if (tmpF.isDirectory()) {
removeDirectory(tmpF);
}
if (!tmpF.delete())
log.warn("can't delete file : " + tmpF);
}
}
if (!folder.delete())
log.warn("can't delete folder : " + folder);
}
}
public static String readTextFileFromServer(String url, String userAgent) throws IOException {
URLConnection connection = URI.create(url).toURL().openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10));
connection.addRequestProperty("User-Agent", userAgent);
connection.connect();
try (InputStream inputStream = connection.getInputStream()) {
return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
public static void setThreadName(String name) {
Thread.currentThread().setName(name + "-" + new Random().nextInt(10000));
}
private static class AnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(JsonExclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
}
| common/src/main/java/io/bitsquare/common/util/Utilities.java | /*
* This file is part of Bitsquare.
*
* Bitsquare is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bitsquare 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.common.util;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.*;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Random;
import java.util.concurrent.*;
/**
* General utilities
*/
public class Utilities {
private static final Logger log = LoggerFactory.getLogger(Utilities.class);
private static long lastTimeStamp = System.currentTimeMillis();
public static final String LB = System.getProperty("line.separator");
public static final String LB2 = LB + LB;
public static String objectToJson(Object object) {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new AnnotationExclusionStrategy())
/*.excludeFieldsWithModifiers(Modifier.TRANSIENT)*/
/* .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)*/
.setPrettyPrinting()
.create();
return gson.toJson(object);
}
public static ListeningExecutorService getListeningExecutorService(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
return MoreExecutors.listeningDecorator(getThreadPoolExecutor(name, corePoolSize, maximumPoolSize, keepAliveTimeInSec));
}
public static ThreadPoolExecutor getThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.build();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeInSec,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory);
executor.allowCoreThreadTimeOut(true);
executor.setRejectedExecutionHandler((r, e) -> log.warn("RejectedExecutionHandler called"));
return executor;
}
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name,
int corePoolSize,
int maximumPoolSize,
long keepAliveTimeInSec) {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name)
.setDaemon(true)
.setPriority(Thread.MIN_PRIORITY)
.build();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
executor.setKeepAliveTime(keepAliveTimeInSec, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
executor.setMaximumPoolSize(maximumPoolSize);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
executor.setRejectedExecutionHandler((r, e) -> log.warn("RejectedExecutionHandler called"));
return executor;
}
public static boolean isUnix() {
return isOSX() || isLinux() || getOSName().contains("freebsd");
}
public static boolean isWindows() {
return getOSName().contains("win");
}
public static boolean isOSX() {
return getOSName().contains("mac") || getOSName().contains("darwin");
}
public static boolean isLinux() {
return getOSName().contains("linux");
}
private static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
public static void openURI(URI uri) throws IOException {
if (!isLinux()
&& Desktop.isDesktopSupported()
&& Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
} else {
// Maybe Application.HostServices works in those cases?
// HostServices hostServices = getHostServices();
// hostServices.showDocument(uri.toString());
// On Linux Desktop is poorly implemented.
// See https://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform
if (!DesktopUtil.browse(uri))
throw new IOException("Failed to open URI: " + uri.toString());
}
}
public static void openWebPage(String target) {
try {
openURI(new URI(target));
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
public static void printSystemLoad() {
Runtime runtime = Runtime.getRuntime();
long free = runtime.freeMemory() / 1024 / 1024;
long total = runtime.totalMemory() / 1024 / 1024;
long used = total - free;
log.info("System load (nr. threads/used memory (MB)): " + Thread.activeCount() + "/" + used);
}
public static void openMail(String to, String subject, String body) {
try {
subject = URLEncoder.encode(subject, "UTF-8").replace("+", "%20");
body = URLEncoder.encode(body, "UTF-8").replace("+", "%20");
Desktop.getDesktop().mail(new URI("mailto:" + to + "?subject=" + subject + "&body=" + body));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
public static void copyToClipboard(String content) {
if (content != null && content.length() > 0) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(content);
clipboard.setContent(clipboardContent);
}
}
public static byte[] concatByteArrays(byte[]... arrays) {
int totalLength = 0;
for (byte[] array : arrays) {
totalLength += array.length;
}
byte[] result = new byte[totalLength];
int currentIndex = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, currentIndex, array.length);
currentIndex += array.length;
}
return result;
}
public static <T> T jsonToObject(String jsonString, Class<T> classOfT) {
Gson gson =
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create();
return gson.fromJson(jsonString, classOfT);
}
/* public static Object deserializeHexStringToObject(String serializedHexString) {
Object result = null;
try {
ByteArrayInputStream byteInputStream =
new ByteArrayInputStream(org.bitcoinj.core.Utils.parseAsHexOrBase58(serializedHexString));
try (ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream)) {
result = objectInputStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
byteInputStream.close();
}
} catch (IOException i) {
i.printStackTrace();
}
return result;
}
public static String serializeObjectToHexString(Serializable serializable) {
String result = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(serializable);
result = org.bitcoinj.core.Utils.HEX.encode(byteArrayOutputStream.toByteArray());
byteArrayOutputStream.close();
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}*/
public static <T extends Serializable> T deserialize(byte[] data) {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ObjectInput in = null;
Object result = null;
try {
in = new ObjectInputStream(bis);
result = in.readObject();
if (!(result instanceof Serializable))
throw new RuntimeException("Object not of type Serializable");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException ex) {
// ignore close exception
}
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore close exception
}
}
return (T) result;
}
public static byte[] serialize(Serializable object) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
byte[] result = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(object);
out.flush();
result = bos.toByteArray().clone();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ignore) {
}
try {
bos.close();
} catch (IOException ignore) {
}
}
return result;
}
public static void deleteDirectory(File file) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null)
for (File c : files)
deleteDirectory(c);
}
if (!file.delete())
throw new FileNotFoundException("Failed to delete file: " + file);
}
private static void printElapsedTime(String msg) {
if (!msg.isEmpty()) {
msg += " / ";
}
long timeStamp = System.currentTimeMillis();
log.debug(msg + "Elapsed: " + String.valueOf(timeStamp - lastTimeStamp));
lastTimeStamp = timeStamp;
}
public static void printElapsedTime() {
printElapsedTime("");
}
public static Object copy(Serializable orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
/**
* Empty and delete a folder (and subfolders).
*
* @param folder folder to empty
*/
private static void removeDirectory(final File folder) {
// check if folder file is a real folder
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (File tmpF : list) {
if (tmpF.isDirectory()) {
removeDirectory(tmpF);
}
if (!tmpF.delete())
log.warn("can't delete file : " + tmpF);
}
}
if (!folder.delete())
log.warn("can't delete folder : " + folder);
}
}
public static String readTextFileFromServer(String url, String userAgent) throws IOException {
URLConnection connection = URI.create(url).toURL().openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10));
connection.addRequestProperty("User-Agent", userAgent);
connection.connect();
try (InputStream inputStream = connection.getInputStream()) {
return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
public static void setThreadName(String name) {
Thread.currentThread().setName(name + "-" + new Random().nextInt(10000));
}
private static class AnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(JsonExclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
}
| Add open directory method
| common/src/main/java/io/bitsquare/common/util/Utilities.java | Add open directory method |
|
Java | agpl-3.0 | a088d50f10b525be26ff052bf7b9caf560051098 | 0 | vimsvarcode/elmis,OpenLMIS/open-lmis,jasolangi/jasolangi.github.io,vimsvarcode/elmis,USAID-DELIVER-PROJECT/elmis,kelvinmbwilo/vims,kelvinmbwilo/vims,joshzamor/open-lmis,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,joshzamor/open-lmis,joshzamor/open-lmis,vimsvarcode/elmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,kelvinmbwilo/vims,vimsvarcode/elmis,jasolangi/jasolangi.github.io,joshzamor/open-lmis,kelvinmbwilo/vims,OpenLMIS/open-lmis,jasolangi/jasolangi.github.io,vimsvarcode/elmis,OpenLMIS/open-lmis | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.functional;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.UiUtils.TestWebDriver;
import org.openlmis.pageobjects.*;
import org.openqa.selenium.JavascriptExecutor;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import java.util.ArrayList;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.assertEquals;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class DistributionSyncTest extends TestCaseHelper {
public String userSIC, password;
@BeforeMethod(groups = {"distribution"})
public void setUp() throws Exception {
super.setup();
}
@Test(groups = {"distribution"}, dataProvider = "Data-Provider-Function")
public void testMultipleFacilitySync(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond,
String deliveryZoneNameFirst, String deliveryZoneNameSecond,
String facilityCodeFirst, String facilityCodeSecond,
String programFirst, String programSecond, String schedule) throws Exception {
List<String> rightsList = new ArrayList<>();
rightsList.add("MANAGE_DISTRIBUTION");
setupTestDataToInitiateRnRAndDistribution("F10", "F11", true, programFirst, userSIC, "200", rightsList, programSecond, "District1", "Ngorongoro", "Ngorongoro");
setupDataForDeliveryZone(true, deliveryZoneCodeFirst, deliveryZoneCodeSecond,
deliveryZoneNameFirst, deliveryZoneNameSecond,
facilityCodeFirst, facilityCodeSecond,
programFirst, programSecond, schedule);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond);
dbWrapper.insertProductGroup("PG1");
dbWrapper.insertProductWithGroup("Product5", "ProdutName5", "PG1", true);
dbWrapper.insertProductWithGroup("Product6", "ProdutName6", "PG1", true);
dbWrapper.insertProgramProduct("Product5", programFirst, "10", "false");
dbWrapper.insertProgramProduct("Product6", programFirst, "10", "true");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
DistributionPage distributionPage = homePage.navigatePlanDistribution();
distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst);
distributionPage.selectValueFromProgram(programFirst);
distributionPage.clickInitiateDistribution();
distributionPage.clickRecordData();
FacilityListPage facilityListPage = new FacilityListPage(testWebDriver);
facilityListPage.selectFacility("F10");
facilityListPage.verifyFacilityIndicatorColor("Overall", "AMBER");
EPIUse epiUse = new EPIUse(testWebDriver);
epiUse.navigate();
epiUse.verifyProductGroup("PG1-Name", 1);
epiUse.verifyIndicator("RED");
epiUse.enterValueInStockAtFirstOfMonth("10", 1);
epiUse.verifyIndicator("AMBER");
epiUse.enterValueInReceived("20", 1);
epiUse.enterValueInDistributed("30", 1);
epiUse.enterValueInLoss("40", 1);
epiUse.enterValueInStockAtEndOfMonth("50", 1);
epiUse.enterValueInExpirationDate("10/2011", 1);
epiUse.verifyIndicator("GREEN");
GeneralObservationPage generalObservationPage = new GeneralObservationPage(testWebDriver);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigateOfflineDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F10");
facilityListPage.verifyFacilityIndicatorColor("Overall", "GREEN");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F11");
facilityListPage.verifyFacilityIndicatorColor("Overall", "AMBER");
epiUse.navigate();
epiUse.verifyProductGroup("PG1-Name", 1);
epiUse.verifyIndicator("RED");
epiUse.enterValueInStockAtFirstOfMonth("10", 1);
epiUse.verifyIndicator("AMBER");
epiUse.enterValueInReceived("20", 1);
epiUse.enterValueInDistributed("30", 1);
epiUse.enterValueInLoss("40", 1);
epiUse.enterValueInStockAtEndOfMonth("50", 1);
epiUse.enterValueInExpirationDate("10/2011", 1);
epiUse.verifyIndicator("GREEN");
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigateOfflineDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F11");
facilityListPage.verifyFacilityIndicatorColor("Overall", "GREEN");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.syncDistribution();
assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary"));
assertTrue(distributionPage.getSyncMessage().contains("F11-Central Hospital"));
distributionPage.syncDistributionMessageDone();
dbWrapper.verifyFacilityVisits("Some observations", "samuel", "Doe", "Mai ka", "Laal");
distributionPage.clickRecordData();
facilityListPage.selectFacility("F10");
facilityListPage.verifyFacilityIndicatorColor("Overall", "BLUE");
facilityListPage.verifyFacilityIndicatorColor("individual", "BLUE");
generalObservationPage.navigate();
generalObservationPage.verifyAllFieldsDisabled();
epiUse.navigate();
epiUse.verifyAllFieldsDisabled();
homePage.navigatePlanDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F11");
facilityListPage.verifyFacilityIndicatorColor("Overall", "BLUE");
facilityListPage.verifyFacilityIndicatorColor("individual", "BLUE");
generalObservationPage.navigate();
generalObservationPage.verifyAllFieldsDisabled();
epiUse.navigate();
epiUse.verifyAllFieldsDisabled();
homePage.navigatePlanDistribution();
distributionPage.deleteDistribution();
distributionPage.ConfirmDeleteDistribution();
}
@Test(groups = {"distribution"}, dataProvider = "Data-Provider-Function")
public void testDeleteDistributionAfterSync(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond,
String deliveryZoneNameFirst, String deliveryZoneNameSecond,
String facilityCodeFirst, String facilityCodeSecond,
String programFirst, String programSecond, String schedule) throws Exception {
List<String> rightsList = new ArrayList<>();
rightsList.add("MANAGE_DISTRIBUTION");
setupTestDataToInitiateRnRAndDistribution("F10", "F11", true, programFirst, userSIC, "200", rightsList, programSecond, "District1", "Ngorongoro", "Ngorongoro");
setupDataForDeliveryZone(true, deliveryZoneCodeFirst, deliveryZoneCodeSecond,
deliveryZoneNameFirst, deliveryZoneNameSecond,
facilityCodeFirst, facilityCodeSecond,
programFirst, programSecond, schedule);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond);
dbWrapper.insertProductGroup("PG1");
dbWrapper.insertProductWithGroup("Product5", "ProdutName5", "PG1", true);
dbWrapper.insertProductWithGroup("Product6", "ProdutName6", "PG1", true);
dbWrapper.insertProgramProduct("Product5", programFirst, "10", "false");
dbWrapper.insertProgramProduct("Product6", programFirst, "10", "true");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
DistributionPage distributionPage = homePage.navigatePlanDistribution();
distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst);
distributionPage.selectValueFromProgram(programFirst);
distributionPage.clickInitiateDistribution();
distributionPage.clickRecordData();
FacilityListPage facilityListPage = new FacilityListPage(testWebDriver);
facilityListPage.selectFacility("F10");
EPIUse epiUse = new EPIUse(testWebDriver);
epiUse.navigate();
epiUse.checkApplyNRToAllFields(true);
GeneralObservationPage generalObservationPage = new GeneralObservationPage(testWebDriver);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.syncDistribution();
distributionPage.syncDistributionMessageDone();
distributionPage.deleteDistribution();
distributionPage.ConfirmDeleteDistribution();
distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst);
distributionPage.selectValueFromProgram(programFirst);
distributionPage.clickInitiateDistribution();
distributionPage.ConfirmDeleteDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F10");
epiUse.navigate();
epiUse.checkApplyNRToAllFields(true);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
facilityListPage.selectFacility("F11");
epiUse.navigate();
epiUse.checkApplyNRToAllFields(true);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.syncDistribution();
assertEquals(distributionPage.getFacilityAlreadySyncMessage(),"Already synchronized facilities : \n" +
"F10-Village Dispensary");
assertEquals(distributionPage.getSyncMessage(),"Synchronized facilities : \n" +
"F11-Central Hospital");
distributionPage.syncDistributionMessageDone();
}
@AfterMethod(groups = "distribution")
public void tearDown() throws Exception {
testWebDriver.sleep(500);
if (!testWebDriver.getElementById("username").isDisplayed()) {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
((JavascriptExecutor) TestWebDriver.getDriver()).executeScript("indexedDB.deleteDatabase('open_lmis');");
}
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"fieldCoordinator", "Admin123", "DZ1", "DZ2", "Delivery Zone First", "Delivery Zone Second",
"F10", "F11", "VACCINES", "TB", "M"}
};
}
}
| test-modules/functional-tests/src/test/java/org/openlmis/functional/DistributionSyncTest.java | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.functional;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.UiUtils.TestWebDriver;
import org.openlmis.pageobjects.*;
import org.openqa.selenium.JavascriptExecutor;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import java.util.ArrayList;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.assertEquals;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class DistributionSyncTest extends TestCaseHelper {
public String userSIC, password;
@BeforeMethod(groups = {"distribution"})
public void setUp() throws Exception {
super.setup();
}
@Test(groups = {"distribution"}, dataProvider = "Data-Provider-Function")
public void testMultipleFacilitySync(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond,
String deliveryZoneNameFirst, String deliveryZoneNameSecond,
String facilityCodeFirst, String facilityCodeSecond,
String programFirst, String programSecond, String schedule) throws Exception {
List<String> rightsList = new ArrayList<>();
rightsList.add("MANAGE_DISTRIBUTION");
setupTestDataToInitiateRnRAndDistribution("F10", "F11", true, programFirst, userSIC, "200", rightsList, programSecond, "District1", "Ngorongoro", "Ngorongoro");
setupDataForDeliveryZone(true, deliveryZoneCodeFirst, deliveryZoneCodeSecond,
deliveryZoneNameFirst, deliveryZoneNameSecond,
facilityCodeFirst, facilityCodeSecond,
programFirst, programSecond, schedule);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond);
dbWrapper.insertProductGroup("PG1");
dbWrapper.insertProductWithGroup("Product5", "ProdutName5", "PG1", true);
dbWrapper.insertProductWithGroup("Product6", "ProdutName6", "PG1", true);
dbWrapper.insertProgramProduct("Product5", programFirst, "10", "false");
dbWrapper.insertProgramProduct("Product6", programFirst, "10", "true");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
DistributionPage distributionPage = homePage.navigatePlanDistribution();
distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst);
distributionPage.selectValueFromProgram(programFirst);
distributionPage.clickInitiateDistribution();
distributionPage.clickRecordData();
FacilityListPage facilityListPage = new FacilityListPage(testWebDriver);
facilityListPage.selectFacility("F10");
facilityListPage.verifyFacilityIndicatorColor("Overall", "AMBER");
EPIUse epiUse = new EPIUse(testWebDriver);
epiUse.navigate();
epiUse.verifyProductGroup("PG1-Name", 1);
epiUse.verifyIndicator("RED");
epiUse.enterValueInStockAtFirstOfMonth("10", 1);
epiUse.verifyIndicator("AMBER");
epiUse.enterValueInReceived("20", 1);
epiUse.enterValueInDistributed("30", 1);
epiUse.enterValueInLoss("40", 1);
epiUse.enterValueInStockAtEndOfMonth("50", 1);
epiUse.enterValueInExpirationDate("10/2011", 1);
epiUse.verifyIndicator("GREEN");
GeneralObservationPage generalObservationPage = new GeneralObservationPage(testWebDriver);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigateOfflineDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F10");
facilityListPage.verifyFacilityIndicatorColor("Overall", "GREEN");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F11");
facilityListPage.verifyFacilityIndicatorColor("Overall", "AMBER");
epiUse.navigate();
epiUse.verifyProductGroup("PG1-Name", 1);
epiUse.verifyIndicator("RED");
epiUse.enterValueInStockAtFirstOfMonth("10", 1);
epiUse.verifyIndicator("AMBER");
epiUse.enterValueInReceived("20", 1);
epiUse.enterValueInDistributed("30", 1);
epiUse.enterValueInLoss("40", 1);
epiUse.enterValueInStockAtEndOfMonth("50", 1);
epiUse.enterValueInExpirationDate("10/2011", 1);
epiUse.verifyIndicator("GREEN");
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigateOfflineDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F11");
facilityListPage.verifyFacilityIndicatorColor("Overall", "GREEN");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.syncDistribution();
assertTrue(distributionPage.getSyncMessage().contains("F10-Village Dispensary"));
assertTrue(distributionPage.getSyncMessage().contains("F11-Central Hospital"));
distributionPage.syncDistributionMessageDone();
dbWrapper.verifyFacilityVisits("Some observations", "samuel", "Doe", "Mai ka", "Laal");
distributionPage.clickRecordData();
facilityListPage.selectFacility("F10");
facilityListPage.verifyFacilityIndicatorColor("Overall", "BLUE");
facilityListPage.verifyFacilityIndicatorColor("individual", "BLUE");
generalObservationPage.navigate();
generalObservationPage.verifyAllFieldsDisabled();
epiUse.navigate();
epiUse.verifyAllFieldsDisabled();
homePage.navigatePlanDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F11");
facilityListPage.verifyFacilityIndicatorColor("Overall", "BLUE");
facilityListPage.verifyFacilityIndicatorColor("individual", "BLUE");
generalObservationPage.navigate();
generalObservationPage.verifyAllFieldsDisabled();
epiUse.navigate();
epiUse.verifyAllFieldsDisabled();
homePage.navigatePlanDistribution();
distributionPage.deleteDistribution();
distributionPage.ConfirmDeleteDistribution();
}
@Test(groups = {"distribution"}, dataProvider = "Data-Provider-Function")
public void testDeleteDistributionAfterSync(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond,
String deliveryZoneNameFirst, String deliveryZoneNameSecond,
String facilityCodeFirst, String facilityCodeSecond,
String programFirst, String programSecond, String schedule) throws Exception {
List<String> rightsList = new ArrayList<>();
rightsList.add("MANAGE_DISTRIBUTION");
setupTestDataToInitiateRnRAndDistribution("F10", "F11", true, programFirst, userSIC, "200", rightsList, programSecond, "District1", "Ngorongoro", "Ngorongoro");
setupDataForDeliveryZone(true, deliveryZoneCodeFirst, deliveryZoneCodeSecond,
deliveryZoneNameFirst, deliveryZoneNameSecond,
facilityCodeFirst, facilityCodeSecond,
programFirst, programSecond, schedule);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst);
dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond);
dbWrapper.insertProductGroup("PG1");
dbWrapper.insertProductWithGroup("Product5", "ProdutName5", "PG1", true);
dbWrapper.insertProductWithGroup("Product6", "ProdutName6", "PG1", true);
dbWrapper.insertProgramProduct("Product5", programFirst, "10", "false");
dbWrapper.insertProgramProduct("Product6", programFirst, "10", "true");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
DistributionPage distributionPage = homePage.navigatePlanDistribution();
distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst);
distributionPage.selectValueFromProgram(programFirst);
distributionPage.clickInitiateDistribution();
distributionPage.clickRecordData();
FacilityListPage facilityListPage = new FacilityListPage(testWebDriver);
facilityListPage.selectFacility("F10");
EPIUse epiUse = new EPIUse(testWebDriver);
epiUse.navigate();
epiUse.checkApplyNRToAllFields(true);
GeneralObservationPage generalObservationPage = new GeneralObservationPage(testWebDriver);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.syncDistribution();
distributionPage.syncDistributionMessageDone();
distributionPage.deleteDistribution();
distributionPage.ConfirmDeleteDistribution();
distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst);
distributionPage.selectValueFromProgram(programFirst);
distributionPage.clickInitiateDistribution();
distributionPage.ConfirmDeleteDistribution();
distributionPage.clickRecordData();
facilityListPage.selectFacility("F10");
epiUse.navigate();
epiUse.checkApplyNRToAllFields(true);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
facilityListPage.selectFacility("F11");
epiUse.navigate();
epiUse.checkApplyNRToAllFields(true);
generalObservationPage.navigate();
generalObservationPage.setObservations("Some observations");
generalObservationPage.setConfirmedByName("samuel");
generalObservationPage.setConfirmedByTitle("Doe");
generalObservationPage.setVerifiedByName("Mai ka");
generalObservationPage.setVerifiedByTitle("Laal");
homePage.navigateHomePage();
homePage.navigatePlanDistribution();
distributionPage.syncDistribution();
assertEquals(distributionPage.getFacilityAlreadySyncMessage(),"Already synced facilities : \n" +
"F10-Village Dispensary");
assertEquals(distributionPage.getSyncMessage(),"Synced facilities : \n" +
"F11-Central Hospital");
distributionPage.syncDistributionMessageDone();
}
@AfterMethod(groups = "distribution")
public void tearDown() throws Exception {
testWebDriver.sleep(500);
if (!testWebDriver.getElementById("username").isDisplayed()) {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
((JavascriptExecutor) TestWebDriver.getDriver()).executeScript("indexedDB.deleteDatabase('open_lmis');");
}
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"fieldCoordinator", "Admin123", "DZ1", "DZ2", "Delivery Zone First", "Delivery Zone Second",
"F10", "F11", "VACCINES", "TB", "M"}
};
}
}
| Raman - Fixed FT message
| test-modules/functional-tests/src/test/java/org/openlmis/functional/DistributionSyncTest.java | Raman - Fixed FT message |
|
Java | agpl-3.0 | ea0dee324b0fc4b4f2f9b93284b49dbdd88e4cfd | 0 | gavin-romig-koch/victims-upload,gavin-romig-koch/victims-upload,gavin-romig-koch/victims-upload | package com.redhat.chrometwo.api.services;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import com.redhat.chrometwo.api.security.SecurityInterceptor;
import javax.mail.internet.ContentDisposition;
import java.io.ByteArrayInputStream;
import com.redhat.victims.VictimsException;
import com.redhat.victims.VictimsRecord;
import com.redhat.victims.VictimsResultCache;
import com.redhat.victims.VictimsScanner;
import com.redhat.victims.database.VictimsDB;
import com.redhat.victims.database.VictimsDBInterface;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.lang.StringBuilder;
import java.util.Map;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
@Path("/check")
@Stateless
@LocalBean
public class Check {
private int count;
private String checksum(InputStream body) {
String hash = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] buffer = new byte[1024];
int size;
count = 0;
size = body.read(buffer);
count += size;
while (size > 0) {
md.update(buffer);
size = body.read(buffer);
count += size;
}
byte[] digest = md.digest();
hash = String.format("%0" + (digest.length << 1) + "X", new BigInteger(1, digest));
} catch (NoSuchAlgorithmException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return hash;
}
private String checkOne(VictimsDBInterface db, VictimsResultCache cache, String fileName, InputStream inputStream) throws Exception {
StringBuilder result = new StringBuilder();
result.append("filename: ").append(fileName).append("\n");
String key = checksum(inputStream);
result.append("key(" + count + "): ");
result.append(key);
result.append("\n");
if (key != null && cache.exists(key)) {
try {
HashSet<String> cves = cache.get(key);
if (cves != null && cves.size() > 0) {
result.append(String.format("%s VULNERABLE! ", fileName));
for (String cve : cves) {
result.append(cve);
result.append(" ");
}
result.append("\n");
return result.toString();
} else {
result.append(fileName + " ok\n");
}
} catch (VictimsException e) {
result.append("VictimsException while checking cache:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
} else {
result.append("key is not cached\n");
}
// Scan the item
ArrayList<VictimsRecord> records = new ArrayList();
try {
int count = 0;
for (VictimsRecord record : VictimsScanner.getRecords(inputStream, fileName)) {
count++;
result.append("found the " + count + "th record for " + fileName);
try {
HashSet<String> cves = db.getVulnerabilities(record);
if (key != null) {
cache.add(key, cves);
}
if (!cves.isEmpty()) {
result.append(String.format("%s VULNERABLE! ", fileName));
for (String cve : cves) {
result.append(cve);
result.append(" ");
}
result.append("\n");
return result.toString();
} else {
result.append(fileName + " ok\n");
}
} catch (VictimsException e) {
result.append("VictimsException while checking database:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
}
if (count == 0) {
result.append("found no records for ").append(fileName).append("\n");
}
} catch (IOException e) {
result.append("VictimsException while scanning file:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
return result.toString();
}
private String displayHeaders(HttpServletRequest request) throws Exception {
StringBuilder result = new StringBuilder();
for (java.util.Enumeration<java.lang.String> headerNames = request.getHeaderNames();
headerNames.hasMoreElements();) {
String headerName = headerNames.nextElement();
for (java.util.Enumeration<java.lang.String> headers = request.getHeaders(headerName);
headers.hasMoreElements();) {
String header = headers.nextElement();
result.append(headerName + ": " + header + "\n");
}
}
return result.toString();
}
@POST
@Path("/{fileName}")
public String checkFile(InputStream body,
@PathParam("fileName") String fileName,
@Context HttpServletRequest request) throws Exception {
StringBuilder result = new StringBuilder();
result.append("check: ");
result.append(fileName);
result.append("\n");
result.append(displayHeaders(request));
VictimsDBInterface db;
VictimsResultCache cache;
try {
db = VictimsDB.db();
cache = new VictimsResultCache();
} catch (VictimsException e) {
result.append("VictimsException while opening the database:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
result.append(checkOne(db, cache, fileName, body));
result.append("end of results\n");
return result.toString();
}
@POST
@Path("/multi")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public String checkMulti(MultipartFormDataInput inputForm, @Context HttpServletRequest request) throws Exception {
StringBuilder result = new StringBuilder();
result.append("multi: ");
result.append(displayHeaders(request));
VictimsDBInterface db;
VictimsResultCache cache;
try {
db = VictimsDB.db();
cache = new VictimsResultCache();
} catch (VictimsException e) {
result.append("VictimsException while opening the database:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
boolean foundAtLeastOne = false;
Map<String, List<InputPart>> multiValuedMap = inputForm.getFormDataMap();
for (Map.Entry<String, List<InputPart>> entry : multiValuedMap.entrySet()) {
foundAtLeastOne = true;
String name = entry.getKey();
int count = 0;
result.append("found part named: " + name + "\n");
for (InputPart aInputPart : entry.getValue()) {
String dispString = "";
count++;
result.append("found value " + count + ":\n");
for (Map.Entry<String, List<String>> headerEntry : aInputPart.getHeaders().entrySet()) {
for (String headerValue : headerEntry.getValue()) {
result.append(" header " + headerEntry.getKey() + ": " + headerValue).append("\n");
if (headerEntry.getKey().equals("Content-Disposition")) {
dispString += headerValue;
}
}
}
result.append(" mediaType: " + aInputPart.getMediaType() + "\n");
ContentDisposition disp = new ContentDisposition(dispString);
String fileName = disp.getParameter("filename");
if (fileName == null) {
fileName = name;
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(aInputPart.getBodyAsString().getBytes());
result.append(checkOne(db, cache, fileName, inputStream));
}
}
if (!foundAtLeastOne) {
result.append("no parts found\n");
}
result.append("end of results\n");
return result.toString();
}
}
| api/src/main/java/com/redhat/chrometwo/api/services/Check.java | package com.redhat.chrometwo.api.services;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import com.redhat.chrometwo.api.security.SecurityInterceptor;
import javax.mail.internet.ContentDisposition;
import com.redhat.victims.VictimsException;
import com.redhat.victims.VictimsRecord;
import com.redhat.victims.VictimsResultCache;
import com.redhat.victims.VictimsScanner;
import com.redhat.victims.database.VictimsDB;
import com.redhat.victims.database.VictimsDBInterface;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.lang.StringBuilder;
import java.util.Map;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
@Path("/check")
@Stateless
@LocalBean
public class Check {
private int count;
private String checksum(String body) {
String hash = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
count = body.length();
md.update(body.getBytes());
byte[] digest = md.digest();
hash = String.format("%0" + (digest.length << 1) + "X", new BigInteger(1, digest));
} catch (NoSuchAlgorithmException e) {
}
return hash;
}
private String checksum(InputStream body) {
String hash = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] buffer = new byte[1024];
int size;
count = 0;
size = body.read(buffer);
count += size;
while (size > 0) {
md.update(buffer);
size = body.read(buffer);
count += size;
}
byte[] digest = md.digest();
hash = String.format("%0" + (digest.length << 1) + "X", new BigInteger(1, digest));
} catch (NoSuchAlgorithmException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return hash;
}
private String checkOne(VictimsDBInterface db, VictimsResultCache cache, String fileName, String key) throws Exception {
StringBuilder result = new StringBuilder();
result.append("filename: ").append(fileName).append("\n");
result.append("key(" + count + "): ");
result.append(key);
result.append("\n");
if (key != null && cache.exists(key)) {
try {
HashSet<String> cves = cache.get(key);
if (cves != null && cves.size() > 0) {
result.append(String.format("%s VULNERABLE! ", fileName));
for (String cve : cves) {
result.append(cve);
result.append(" ");
}
result.append("\n");
return result.toString();
} else {
result.append(fileName + " ok\n");
}
} catch (VictimsException e) {
result.append("VictimsException while checking cache:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
} else {
result.append("key is not cached\n");
}
// Scan the item
ArrayList<VictimsRecord> records = new ArrayList();
try {
int count = 0;
VictimsScanner.scan(fileName, records);
for (VictimsRecord record : records) {
count++;
result.append("found the " + count + "th record for " + fileName);
try {
HashSet<String> cves = db.getVulnerabilities(record);
if (key != null) {
cache.add(key, cves);
}
if (!cves.isEmpty()) {
result.append(String.format("%s VULNERABLE! ", fileName));
for (String cve : cves) {
result.append(cve);
result.append(" ");
}
result.append("\n");
return result.toString();
} else {
result.append(fileName + " ok\n");
}
} catch (VictimsException e) {
result.append("VictimsException while checking database:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
}
if (count == 0) {
result.append("found no records for " + fileName);
}
} catch (IOException e) {
result.append("VictimsException while scanning file:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
return result.toString();
}
private String displayHeaders(HttpServletRequest request) throws Exception {
StringBuilder result = new StringBuilder();
for (java.util.Enumeration<java.lang.String> headerNames = request.getHeaderNames();
headerNames.hasMoreElements();) {
String headerName = headerNames.nextElement();
for (java.util.Enumeration<java.lang.String> headers = request.getHeaders(headerName);
headers.hasMoreElements();) {
String header = headers.nextElement();
result.append(headerName + ": " + header + "\n");
}
}
return result.toString();
}
@POST
@Path("/{fileName}")
public String checkFile(InputStream body,
@PathParam("fileName") String fileName,
@Context HttpServletRequest request) throws Exception {
StringBuilder result = new StringBuilder();
result.append("check: ");
result.append(fileName);
result.append("\n");
result.append(displayHeaders(request));
VictimsDBInterface db;
VictimsResultCache cache;
try {
db = VictimsDB.db();
cache = new VictimsResultCache();
} catch (VictimsException e) {
result.append("VictimsException while opening the database:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
result.append(checkOne(db, cache, fileName, checksum(body)));
result.append("end of results\n");
return result.toString();
}
@POST
@Path("/multi")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public String checkMulti(MultipartFormDataInput inputForm, @Context HttpServletRequest request) throws Exception {
StringBuilder result = new StringBuilder();
result.append("multi: ");
result.append(displayHeaders(request));
VictimsDBInterface db;
VictimsResultCache cache;
try {
db = VictimsDB.db();
cache = new VictimsResultCache();
} catch (VictimsException e) {
result.append("VictimsException while opening the database:\n");
e.printStackTrace();
return result.append(e.toString()).append("\n").toString();
}
boolean foundAtLeastOne = false;
Map<String, List<InputPart>> multiValuedMap = inputForm.getFormDataMap();
for (Map.Entry<String, List<InputPart>> entry : multiValuedMap.entrySet()) {
foundAtLeastOne = true;
String name = entry.getKey();
int count = 0;
result.append("found part named: " + name + "\n");
for (InputPart aInputPart : entry.getValue()) {
String dispString = "";
count++;
result.append("found value " + count + ":\n");
for (Map.Entry<String, List<String>> headerEntry : aInputPart.getHeaders().entrySet()) {
for (String headerValue : headerEntry.getValue()) {
result.append(" header " + headerEntry.getKey() + ": " + headerValue).append("\n");
if (headerEntry.getKey().equals("Content-Disposition")) {
dispString += headerValue;
}
}
}
result.append(" mediaType: " + aInputPart.getMediaType() + "\n");
ContentDisposition disp = new ContentDisposition(dispString);
String fileName = disp.getParameter("filename");
if (fileName == null) {
fileName = name;
}
result.append(checkOne(db, cache, fileName, checksum(aInputPart.getBodyAsString())));
}
}
if (!foundAtLeastOne) {
result.append("no parts found\n");
}
result.append("end of results\n");
return result.toString();
}
}
| look for multipart/form-data
| api/src/main/java/com/redhat/chrometwo/api/services/Check.java | look for multipart/form-data |
|
Java | apache-2.0 | 7a2547e9be735755408377afa76ccbe38d5f770c | 0 | RiparianData/Timberwolf,RiparianData/Timberwolf | /**
* Copyright 2012 Riparian Data
* http://www.ripariandata.com
* [email protected]
*
* 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.ripariandata.timberwolf.conf4j;
import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
/**
* Inspired by the CmdLineParser of args4j, this takes a class with ConfigEntry
* annotations and a configuration file and sets the fields so annotated with
* the values from the config file.
* <p>
* Since our needs for configuration handling are pretty simple, this does a lot
* less than args4j. It only handles fields, not methods, and doesn't do anything
* other than match names to values.
*/
public class ConfigFileParser
{
private Map<String, FieldSetter> fields = new HashMap<String, FieldSetter>();
public ConfigFileParser(final Object bean)
{
for (Class c = bean.getClass(); c != null; c = c.getSuperclass())
{
for (Field f : c.getDeclaredFields())
{
ConfigEntry entry = f.getAnnotation(ConfigEntry.class);
if (entry != null)
{
fields.put(entry.name(), new FieldSetter(bean, f));
}
}
}
}
/**
* Takes the values from the named configuration file and apply them to the
* target class. Assumes that the file is a java properties file, readable
* by <a href="http://commons.apache.org/configuration/apidocs/org/apache/commons/configuration/PropertiesConfiguration.html">
* org.apache.commons.configuration.PropertiesConfiguration</a>.
*
* @throws ConfigFileMissingException If the named configuration file does not exist.
* @throws ConfigFileException If there was any other problem reading the configuration file.
*/
public void parseConfigFile(final String configFile) throws ConfigFileException
{
File f = new File(configFile);
if (!f.exists())
{
throw new ConfigFileMissingException(configFile, this);
}
Configuration config;
try
{
config = new PropertiesConfiguration(configFile);
}
catch (ConfigurationException e)
{
throw new ConfigFileException("There was an error loading the configuration file at " + configFile,
e, this);
}
parseConfiguration(config);
}
/**
* Takes the values from the given Configuration instance and applies them to
* the target class. Fields in the target class marked with ConfigEntry
* annotations that don't correspond to any properties in the given configuration
* are not modified. Properties in the configuration that don't match any
* fields marked as ConfigEntry are ignored.
*/
public void parseConfiguration(final Configuration config)
{
Iterator<String> keys = config.getKeys();
while (keys.hasNext())
{
String key = keys.next();
if (fields.containsKey(key))
{
fields.get(key).set(config.getProperty(key));
}
}
}
}
| src/main/java/com/ripariandata/timberwolf/conf4j/ConfigFileParser.java | /**
* Copyright 2012 Riparian Data
* http://www.ripariandata.com
* [email protected]
*
* 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.ripariandata.timberwolf.conf4j;
import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
/**
* Inspired by the CmdLineParser of args4j, this takes a class with ConfigEntry
* annotations and a configuration file and sets the fields so annotated with
* the values from the config file.
* <p>
* Since our needs for configuration handling are pretty simple, this does a lot
* less than args4j. It only handles fields, not methods, and doesn't do anything
* other than match names to values.
*/
public class ConfigFileParser
{
private Map<String, FieldSetter> fields = new HashMap<String, FieldSetter>();
public ConfigFileParser(final Object bean)
{
for (Class c = bean.getClass(); c != null; c = c.getSuperclass())
{
for (Field f : c.getDeclaredFields())
{
ConfigEntry entry = f.getAnnotation(ConfigEntry.class);
if (entry != null)
{
fields.put(entry.name(), new FieldSetter(bean, f));
}
}
}
}
/**
* Takes the values from the named configuration file and apply them to the
* target class. Assumes that the file is a java properties file, readable
* by <a href="http://commons.apache.org/configuration/apidocs/org/apache/commons/configuration/PropertiesConfiguration.html">
* org.apache.commons.configuration.PropertiesConfiguration</a>.
*
* @throws ConfigFileMissingException If the named configuration file does not exist.
* @throws ConfigFileException If there was any other problem reading the configuration file.
*/
public void parseConfigFile(final String configFile) throws ConfigFileException
{
File f = new File(configFile);
if (!f.exists())
{
throw new ConfigFileMissingException(configFile, this);
}
Configuration config;
try
{
config = new PropertiesConfiguration(configFile);
}
catch (ConfigurationException e)
{
throw new ConfigFileException("There was an error loading the configuration file at " + configFile, e, this);
}
parseConfiguration(config);
}
/**
* Takes the values from the given Configuration instance and applies them to
* the target class. Fields in the target class marked with ConfigEntry
* annotations that don't correspond to any properties in the given configuration
* are not modified. Properties in the configuration that don't match any
* fields marked as ConfigEntry are ignored.
*/
public void parseConfiguration(final Configuration config)
{
Iterator<String> keys = config.getKeys();
while (keys.hasNext())
{
String key = keys.next();
if (fields.containsKey(key))
{
fields.get(key).set(config.getProperty(key));
}
}
}
}
| Wrapping 121-character line.
| src/main/java/com/ripariandata/timberwolf/conf4j/ConfigFileParser.java | Wrapping 121-character line. |
|
Java | apache-2.0 | dfc4422595b44433ed6fbc066192fc82ccbb4766 | 0 | HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j | /**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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 org.neo4j.kernel.impl.nioneo.store;
import static java.util.Arrays.copyOf;
import java.io.UnsupportedEncodingException;
import java.util.EnumSet;
import org.neo4j.kernel.impl.util.Bits;
/**
* Supports encoding alphanumerical and <code>SP . - + , ' : / _</code>
*
* (This version assumes 14bytes property block, instead of 8bytes)
*
* @author Tobias Ivarsson <[email protected]>
*/
public enum LongerShortString
{
/**
* Binary coded decimal with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- 0 1 2 3 4 5 6 7 8 9 SP . - + , '
* </pre>
*/
NUMERICAL( 1, 4 )
{
@Override
int encTranslate( byte b )
{
if ( b >= '0' && b <= '9' ) return b - '0';
switch ( b )
{
// interm. encoded
case 0: return 0xA;
case 2: return 0xB;
case 3: return 0xC;
case 6: return 0xD;
case 7: return 0xE;
case 8: return 0xF;
default: throw cannotEncode( b );
}
}
@Override
int encPunctuation( byte b )
{
throw cannotEncode( b );
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint < 10 ) return (char) ( codePoint + '0' );
return decPunctuation( ( codePoint - 10 + 6 ) );
}
},
/**
* Binary coded decimal with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- 0 1 2 3 4 5 6 7 8 9 SP - : / + ,
* </pre>
*/
DATE( 2, 4 )
{
@Override
int encTranslate( byte b )
{
if ( b >= '0' && b <= '9' ) return b - '0';
switch ( b )
{
case 0: return 0xA;
case 3: return 0xB;
case 4: return 0xC;
case 5: return 0xD;
case 6: return 0xE;
case 7: return 0xF;
default: throw cannotEncode( b );
}
}
@Override
int encPunctuation( byte b )
{
throw cannotEncode( b );
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint < 0xA ) return (char) ( codePoint + '0' );
switch ( codePoint )
{
case 0xA: return ' ';
case 0xB: return '-';
case 0xC: return ':';
case 0xD: return '/';
case 0xE: return '+';
default: return ',';
}
}
},
/**
* Upper-case characters with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP A B C D E F G H I J K L M N O
* 1- P Q R S T U V W X Y Z _ . - : /
* </pre>
*/
UPPER( 3, 5 )
{
@Override
int encTranslate( byte b )
{
return super.encTranslate( b ) - 0x40;
}
@Override
int encPunctuation( byte b )
{
return b == 0 ? 0x40 : b + 0x5a;
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ' ';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'A' - 1 );
return decPunctuation( codePoint - 0x1A );
}
},
/**
* Lower-case characters with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP a b c d e f g h i j k l m n o
* 1- p q r s t u v w x y z _ . - : /
* </pre>
*/
LOWER( 4, 5 )
{
@Override
int encTranslate( byte b )
{
return super.encTranslate( b ) - 0x60;
}
@Override
int encPunctuation( byte b )
{
return b == 0 ? 0x60 : b + 0x7a;
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ' ';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'a' - 1 );
return decPunctuation( codePoint - 0x1A );
}
},
/**
* Lower-case characters with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- , a b c d e f g h i j k l m n o
* 1- p q r s t u v w x y z _ . - + @
* </pre>
*/
EMAIL( 5, 5 )
{
@Override
int encTranslate( byte b )
{
return super.encTranslate( b ) - 0x60;
}
@Override
int encPunctuation( byte b )
{
int encOffset = 0x60;
if ( b == 7 ) return encOffset;
int offset = encOffset + 0x1B;
switch ( b )
{
case 1: return 0 + offset;
case 2: return 1 + offset;
case 3: return 2 + offset;
case 6: return 3 + offset;
case 9: return 4 + offset;
default: throw cannotEncode( b );
}
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ',';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'a' - 1 );
switch ( codePoint )
{
case 0x1E: return '+';
case 0x1F: return '@';
default: return decPunctuation( codePoint - 0x1A );
}
}
},
/**
* Lower-case characters, digits and punctuation and symbols.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP a b c d e f g h i j k l m n o
* 1- p q r s t u v w x y z
* 2- 0 1 2 3 4 5 6 7 8 9 _ . - : / +
* 3- , ' @ | ; * ? & % # ( ) $ < > =
* </pre>
*/
URI( 6, 6 )
{
@Override
int encTranslate( byte b )
{
if ( b == 0 ) return 0; // space
if ( b >= 0x61 && b <= 0x7A ) return b - 0x60; // lower-case letters
if ( b >= 0x30 && b <= 0x39 ) return b - 0x10; // digits
if ( b >= 0x1 && b <= 0x16 ) return b + 0x29; // symbols
throw cannotEncode( b );
}
@Override
int encPunctuation( byte b )
{
// Handled by encTranslate
throw cannotEncode( b );
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ' ';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'a' - 1 );
if ( codePoint <= 0x29 ) return (char) (codePoint - 0x20 + '0');
if ( codePoint <= 0x2E ) return decPunctuation( codePoint - 0x29 );
return decPunctuation( codePoint - 0x2F + 9);
}
},
/**
* Alpha-numerical characters space and underscore.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP A B C D E F G H I J K L M N O
* 1- P Q R S T U V W X Y Z 0 1 2 3 4
* 2- _ a b c d e f g h i j k l m n o
* 3- p q r s t u v w x y z 5 6 7 8 9
* </pre>
*/
ALPHANUM( 7, 6 )
{
@Override
char decTranslate( byte codePoint )
{
return EUROPEAN.decTranslate( (byte) ( codePoint + 0x40 ) );
}
@Override
int encTranslate( byte b )
{
// Punctuation is in the same places as European
if ( b < 0x20 ) return encPunctuation( b ); // Punctuation
// But the rest is transposed by 0x40
return EUROPEAN.encTranslate( b ) - 0x40;
}
@Override
int encPunctuation( byte b )
{
switch ( b )
{
case 0:
return 0x00; // SPACE
case 1:
return 0x20; // UNDERSCORE
default:
throw cannotEncode( b );
}
}
},
/**
* Alpha-numerical characters space and underscore.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP A B C D E F G H I J K L M N O
* 1- P Q R S T U V W X Y Z _ . - : /
* 2- | a b c d e f g h i j k l m n o
* 3- p q r s t u v w x y z + , ' @ ;
* </pre>
*/
ALPHASYM( 8, 6 )
{
@Override
char decTranslate( byte codePoint )
{
return EUROPEAN.decTranslate( (byte) ( codePoint + 0x40 ) );
}
@Override
int encTranslate( byte b )
{
// Punctuation is in the same places as European
if ( b < 0x20 ) return encPunctuation( b ); // Punctuation
// But the rest is transposed by 0x40
return EUROPEAN.encTranslate( b ) - 0x40;
}
@Override
int encPunctuation( byte b )
{
switch ( b )
{
case 0: return 0x0;
case 1: return 0x1B;
case 2: return 0x1C;
case 3: return 0x1D;
case 4: return 0x1E;
case 5: return 0x1F;
case 6: return 0x3B;
case 7: return 0x3C;
case 8: return 0x3D;
case 9: return 0x3E;
case 10: return 0x3F;
default: throw cannotEncode( b );
}
}
},
/**
* The most common European characters (latin-1 but with less punctuation).
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
* 1- Ð Ñ Ò Ó Ô Õ Ö . Ø Ù Ú Û Ü Ý Þ ß
* 2- à á â ã ä å æ ç è é ê ë ì í î ï
* 3- ð ñ ò ó ô õ ö - ø ù ú û ü ý þ ÿ
* 4- SP A B C D E F G H I J K L M N O
* 5- P Q R S T U V W X Y Z 0 1 2 3 4
* 6- _ a b c d e f g h i j k l m n o
* 7- p q r s t u v w x y z 5 6 7 8 9
* </pre>
*/
EUROPEAN( 9, 7 )
{
@Override
char decTranslate( byte codePoint )
{
if ( codePoint < 0x40 )
{
if ( codePoint == 0x17 ) return '.';
if ( codePoint == 0x37 ) return '-';
return (char) ( codePoint + 0xC0 );
}
else
{
if ( codePoint == 0x40 ) return ' ';
if ( codePoint == 0x60 ) return '_';
if ( codePoint >= 0x5B && codePoint < 0x60 ) return (char) ( '0' + codePoint - 0x5B );
if ( codePoint >= 0x7B && codePoint < 0x80 ) return (char) ( '5' + codePoint - 0x7B );
return (char) codePoint;
}
}
@Override
int encPunctuation( byte b )
{
switch ( b )
{
case 0x00:
return 0x40; // SPACE
case 0x01:
return 0x60; // UNDERSCORE
case 0x02:
return 0x17; // DOT
case 0x03:
return 0x37; // DASH
case 0x07:
// TODO
return 0;
default:
throw cannotEncode( b );
}
}
};
final int encodingHeader;
final short mask;
final short step;
private LongerShortString( int encodingHeader, int step )
{
this.encodingHeader = encodingHeader;
this.mask = (short) Bits.rightOverflowMask( step );
this.step = (short) step;
}
int maxLength( int payloadSize )
{
return ((payloadSize << 3)-24-4-6)/step;
}
final IllegalArgumentException cannotEncode( byte b )
{
return new IllegalArgumentException( "Cannot encode as " + this.name() + ": " + b );
}
/** Lookup table for decoding punctuation */
private static final char[] PUNCTUATION = {
' ', '_', '.', '-', ':', '/',
' ', '.', '-', '+', ',', '\'', '@', '|', ';', '*', '?', '&', '%', '#', '(', ')', '$', '<', '>', '=' };
final char decPunctuation( int code )
{
return PUNCTUATION[code];
}
int encTranslate( byte b )
{
if ( b < 0 ) return ( 0xFF & b ) - 0xC0; // European chars
if ( b < 0x20 ) return encPunctuation( b ); // Punctuation
if ( b >= '0' && b <= '4' ) return 0x5B + b - '0'; // Numbers
if ( b >= '5' && b <= '9' ) return 0x7B + b - '5'; // Numbers
return b; // Alphabetical
}
abstract int encPunctuation( byte b );
abstract char decTranslate( byte codePoint );
/**
* Encodes a short string.
*
* @param string the string to encode.
* @param target the property record to store the encoded string in
* @return <code>true</code> if the string could be encoded as a short
* string, <code>false</code> if it couldn't.
*/
/*
* Intermediate code table
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP _ . - : / + , ' @ | ; * ? & %
* 1- # ( ) $ < > =
* 2-
* 3- 0 1 2 3 4 5 6 7 8 9
* 4- A B C D E F G H I J K L M N O
* 5- P Q R S T U V W X Y Z
* 6- a b c d e f g h i j k l m n o
* 7- p q r s t u v w x y z
* 8-
* 9-
* A-
* B-
* C- À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
* D- Ð Ñ Ò Ó Ô Õ Ö Ø Ù Ú Û Ü Ý Þ ß
* E- à á â ã ä å æ ç è é ê ë ì í î ï
* F- ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ
*/
public static boolean encode( int keyId, String string, PropertyRecord target, int payloadSize )
{
// NUMERICAL can carry most characters, so compare to that
int stringLength = string.length();
// We only use 6 bits for storing the string length
// TODO could be dealt with by having string length zero and go for null bytes,
// at least for LATIN1 (that's what the ShortString implementation initially did)
if ( stringLength > NUMERICAL.maxLength( payloadSize ) || stringLength > 63 ) return false; // Not handled by any encoding
if ( string.equals( "" ) )
{
applyOnRecord( keyId, target, 0, 0, new long[1] );
return true;
}
// Keep track of the possible encodings that can be used for the string
EnumSet<LongerShortString> possible = null;
// First try encoding using Latin-1
int maxBytes = PropertyType.getPayloadSize();
if ( stringLength <= (maxBytes-3-1-1) )
{
if ( encodeLatin1( keyId, string, target, payloadSize ) ) return true;
// If the string was short enough, but still didn't fit in latin-1
// we know that no other encoding will work either, remember that
// so that we can try UTF-8 at the end of this method
possible = EnumSet.noneOf( LongerShortString.class );
}
// Allocate space for the intermediate representation
// (using the intermediate representation table above)
byte[] data = new byte[stringLength];
if ( possible == null )
{
possible = EnumSet.allOf( LongerShortString.class );
for ( LongerShortString possibility : LongerShortString.values() )
{
if ( data.length > possibility.maxLength( payloadSize ) ) possible.remove( possibility );
}
}
LOOP: for ( int i = 0; i < data.length && !possible.isEmpty(); i++ )
{
char c = string.charAt( i );
switch ( c )
{
case ' ':
data[i] = 0;
possible.remove( EMAIL );
break;
case '_':
data[i] = 1;
possible.removeAll( EnumSet.of( NUMERICAL, DATE ) );
break;
case '.':
data[i] = 2;
possible.removeAll( EnumSet.of( ALPHANUM, DATE ) );
break;
case '-':
data[i] = 3;
possible.remove( ALPHANUM );
break;
case ':':
data[i] = 4;
possible.removeAll( EnumSet.of( ALPHANUM, NUMERICAL, EUROPEAN, EMAIL ) );
break;
case '/':
data[i] = 5;
possible.removeAll( EnumSet.of( ALPHANUM, NUMERICAL, EUROPEAN, EMAIL ) );
break;
case '+':
data[i] = 6;
possible.retainAll( EnumSet.of( NUMERICAL, DATE, EMAIL, URI, ALPHASYM ) );
break;
case ',':
data[i] = 7;
possible.retainAll( EnumSet.of( NUMERICAL, DATE, EMAIL, URI, ALPHASYM ) );
break;
case '\'':
data[i] = 8;
possible.retainAll( EnumSet.of( NUMERICAL, URI, ALPHASYM ) );
break;
case '@':
data[i] = 9;
possible.retainAll( EnumSet.of( EMAIL, URI, ALPHASYM ) );
break;
case '|':
data[i] = 0xA;
possible.retainAll( EnumSet.of( ALPHASYM ) );
break;
// These below are all for the URI encoding only (as of yet at least)
case ';':
data[i] = 0xB;
possible.retainAll( EnumSet.of( URI ) );
break;
case '*':
data[i] = 0xC;
possible.retainAll( EnumSet.of( URI ) );
break;
case '?':
data[i] = 0xD;
possible.retainAll( EnumSet.of( URI ) );
break;
case '&':
data[i] = 0xE;
possible.retainAll( EnumSet.of( URI ) );
break;
case '%':
data[i] = 0xF;
possible.retainAll( EnumSet.of( URI ) );
break;
case '#':
data[i] = 0x10;
possible.retainAll( EnumSet.of( URI ) );
break;
case '(':
data[i] = 0x11;
possible.retainAll( EnumSet.of( URI ) );
break;
case ')':
data[i] = 0x12;
possible.retainAll( EnumSet.of( URI ) );
break;
case '$':
data[i] = 0x13;
possible.retainAll( EnumSet.of( URI ) );
break;
case '<':
data[i] = 0x14;
possible.retainAll( EnumSet.of( URI ) );
break;
case '>': data[i] = 0x15;
possible.retainAll( EnumSet.of( URI ) );
break;
case '=': data[i] = 0x16;
possible.retainAll( EnumSet.of( URI ) );
break;
// These above are all for the URI encoding only (as of yet at least)
default:
if ( ( c >= 'A' && c <= 'Z' ) )
{
possible.removeAll( EnumSet.of( NUMERICAL, DATE, LOWER, EMAIL, URI ) );
}
else if ( ( c >= 'a' && c <= 'z' ) )
{
possible.removeAll( EnumSet.of( NUMERICAL, DATE, UPPER ) );
}
else if ( ( c >= '0' && c <= '9' ) )
{
possible.removeAll( EnumSet.of( UPPER, LOWER, EMAIL, ALPHASYM ) );
}
else if ( c >= 'À' && c <= 'ÿ' && c != 0xD7 && c != 0xF7 )
{
possible.retainAll( EnumSet.of( EUROPEAN ) );
}
else
{
possible.clear();
break LOOP; // fall back to UTF-8
}
data[i] = (byte) c;
}
}
for ( LongerShortString encoding : possible )
{
// Will return false if the data is too long for the encoding
if ( encoding.doEncode( keyId, data, target, payloadSize ) ) return true;
}
if ( stringLength <= maxBytes )
{ // We might have a chance with UTF-8 - try it!
return encodeUTF8( keyId, string, target, maxBytes );
}
return false;
}
private static void applyOnRecord( int keyId, PropertyRecord target, int encoding, int stringLength, long[] data )
{
// TODO Make a utility OR:ing in the key/type in the propblock
data[0] |= ((long)keyId << 40);
data[0] |= ( (long) PropertyType.SHORT_STRING.intValue() << 36 );
data[0] |= ( (long) encoding << 32 );
data[0] |= ( (long) stringLength << 26 );
target.setPropBlock( data );
}
/**
* Decode a short string represented as a long[]
*
* @param data the value to decode to a short string.
* @return the decoded short string
*/
public static String decode( PropertyRecord record )
{
Bits bits = new Bits( copyOf( record.getPropBlock(), record.getPropBlock().length ) );
long firstLong = bits.getLongs()[0];
if ( ( firstLong & 0xFFFFFF0FFFFFFFFFL ) == 0 ) return "";
/*
* [kkkk,kkkk][kkkk,kkkk][kkkk,kkkk][tttt, eeee][llll,ll ][ , ][ , ][ , ]
*/
int encoding = (int) ( ( firstLong & 0xF00000000L ) >>> 32 );
int stringLength = (int) ( ( firstLong & 0xFC000000L ) >>> 26 );
LongerShortString table;
switch ( encoding )
{
case 0: return decodeUTF8( bits, stringLength );
case 1: table = NUMERICAL; break;
case 2: table = DATE; break;
case 3: table = UPPER; break;
case 4: table = LOWER; break;
case 5: table = EMAIL; break;
case 6: table = URI; break;
case 7: table = ALPHANUM; break;
case 8: table = ALPHASYM; break;
case 9: table = EUROPEAN; break;
case 10: return decodeLatin1( bits, stringLength );
default: throw new IllegalArgumentException( "Invalid encoding '" + encoding + "'" );
}
char[] result = new char[stringLength];
// encode shifts in the bytes with the first char at the MSB, therefore
// we must "unshift" in the reverse order
for ( int i = result.length - 1; i >= 0; i-- )
{
byte codePoint = bits.getByte( (byte)table.mask );
result[i] = table.decTranslate( codePoint );
bits.shiftRight( table.step );
}
return new String( result );
}
private static Bits newBits( int payloadSize )
{
return new Bits( payloadSize );
}
private static boolean encodeLatin1( int keyId, String string, PropertyRecord target, int payloadSize )
{ // see doEncode
Bits bits = newBits( payloadSize );
for ( int i = 0; i < string.length(); i++ )
{
if ( i > 0 ) bits.shiftLeft( 8 );
char c = string.charAt( i );
if ( c < 0 || c >= 256 ) return false;
bits.or( c, 0xFF );
}
applyOnRecord( keyId, target, 10, string.length(), bits.getLongs() );
return true;
}
private static boolean encodeUTF8( int keyId, String string, PropertyRecord target, int payloadSize )
{
try
{
byte[] bytes = string.getBytes( "UTF-8" );
if ( bytes.length > payloadSize-3-2 ) return false;
Bits bits = newBits( payloadSize );
for ( int i = 0; i < bytes.length; i++ )
{
if ( i > 0 ) bits.shiftLeft( 8 );
bits.or( bytes[i] );
}
applyOnRecord( keyId, target, 0, bytes.length, bits.getLongs() );
return true;
}
catch ( UnsupportedEncodingException e )
{
throw new IllegalStateException( "All JVMs must support UTF-8", e );
}
}
private boolean doEncode( int keyId, byte[] data, PropertyRecord target, int payloadSize )
{
if ( data.length > maxLength( payloadSize ) ) return false;
Bits bits = newBits( payloadSize );
for ( int i = 0; i < data.length; i++ )
{
if ( i != 0 ) bits.shiftLeft( step );
int encodedChar = encTranslate( data[i] );
bits.or( encodedChar, 0xFF );
}
applyOnRecord( keyId, target, encodingHeader, data.length, bits.getLongs() );
return true;
}
private static String decodeLatin1( Bits bits, int stringLength )
{ // see decode
char[] result = new char[stringLength];
for ( int i = result.length - 1; i >= 0; i-- )
{
result[i] = (char) bits.getInt( 0xFF );
bits.shiftRight( 8 );
}
return new String( result );
}
private static String decodeUTF8( Bits bits, int stringLength )
{
byte[] result = new byte[stringLength];
for ( int i = stringLength-1; i >= 0; i-- )
{
result[i] = bits.getByte( (byte)0xFF );
bits.shiftRight( 8 );
}
try
{
return new String( result, "UTF-8" );
}
catch ( UnsupportedEncodingException e )
{
throw new IllegalStateException( "All JVMs must support UTF-8", e );
}
}
}
| community/kernel/src/main/java/org/neo4j/kernel/impl/nioneo/store/LongerShortString.java | /**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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 org.neo4j.kernel.impl.nioneo.store;
import static java.util.Arrays.copyOf;
import java.io.UnsupportedEncodingException;
import java.util.EnumSet;
import org.neo4j.kernel.impl.util.Bits;
/**
* Supports encoding alphanumerical and <code>SP . - + , ' : / _</code>
*
* (This version assumes 14bytes property block, instead of 8bytes)
*
* @author Tobias Ivarsson <[email protected]>
*/
public enum LongerShortString
{
/**
* Binary coded decimal with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- 0 1 2 3 4 5 6 7 8 9 SP . - + , '
* </pre>
*/
NUMERICAL( 1, 4 )
{
@Override
int encTranslate( byte b )
{
if ( b >= '0' && b <= '9' ) return b - '0';
switch ( b )
{
// interm. encoded
case 0: return 0xA;
case 2: return 0xB;
case 3: return 0xC;
case 6: return 0xD;
case 7: return 0xE;
case 8: return 0xF;
default: throw cannotEncode( b );
}
}
@Override
int encPunctuation( byte b )
{
throw cannotEncode( b );
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint < 10 ) return (char) ( codePoint + '0' );
return decPunctuation( ( codePoint - 10 + 6 ) );
}
},
/**
* Binary coded decimal with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- 0 1 2 3 4 5 6 7 8 9 SP - : / + ,
* </pre>
*/
DATE( 2, 4 )
{
@Override
int encTranslate( byte b )
{
if ( b >= '0' && b <= '9' ) return b - '0';
switch ( b )
{
case 0: return 0xA;
case 3: return 0xB;
case 4: return 0xC;
case 5: return 0xD;
case 6: return 0xE;
case 7: return 0xF;
default: throw cannotEncode( b );
}
}
@Override
int encPunctuation( byte b )
{
throw cannotEncode( b );
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint < 0xA ) return (char) ( codePoint + '0' );
switch ( codePoint )
{
case 0xA: return ' ';
case 0xB: return '-';
case 0xC: return ':';
case 0xD: return '/';
case 0xE: return '+';
default: return ',';
}
}
},
/**
* Upper-case characters with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP A B C D E F G H I J K L M N O
* 1- P Q R S T U V W X Y Z _ . - : /
* </pre>
*/
UPPER( 3, 5 )
{
@Override
int encTranslate( byte b )
{
return super.encTranslate( b ) - 0x40;
}
@Override
int encPunctuation( byte b )
{
return b == 0 ? 0x40 : b + 0x5a;
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ' ';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'A' - 1 );
return decPunctuation( codePoint - 0x1A );
}
},
/**
* Lower-case characters with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP a b c d e f g h i j k l m n o
* 1- p q r s t u v w x y z _ . - : /
* </pre>
*/
LOWER( 4, 5 )
{
@Override
int encTranslate( byte b )
{
return super.encTranslate( b ) - 0x60;
}
@Override
int encPunctuation( byte b )
{
return b == 0 ? 0x60 : b + 0x7a;
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ' ';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'a' - 1 );
return decPunctuation( codePoint - 0x1A );
}
},
/**
* Lower-case characters with punctuation.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- , a b c d e f g h i j k l m n o
* 1- p q r s t u v w x y z _ . - + @
* </pre>
*/
EMAIL( 5, 5 )
{
@Override
int encTranslate( byte b )
{
return super.encTranslate( b ) - 0x60;
}
@Override
int encPunctuation( byte b )
{
int encOffset = 0x60;
if ( b == 7 ) return encOffset;
int offset = encOffset + 0x1B;
switch ( b )
{
case 1: return 0 + offset;
case 2: return 1 + offset;
case 3: return 2 + offset;
case 6: return 3 + offset;
case 9: return 4 + offset;
default: throw cannotEncode( b );
}
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ',';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'a' - 1 );
switch ( codePoint )
{
case 0x1E: return '+';
case 0x1F: return '@';
default: return decPunctuation( codePoint - 0x1A );
}
}
},
/**
* Lower-case characters, digits and punctuation and symbols.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP a b c d e f g h i j k l m n o
* 1- p q r s t u v w x y z
* 2- 0 1 2 3 4 5 6 7 8 9 _ . - : / +
* 3- , ' @ | ; * ? & % # ( ) $ < > =
* </pre>
*/
URI( 6, 6 )
{
@Override
int encTranslate( byte b )
{
if ( b == 0 ) return 0; // space
if ( b >= 0x61 && b <= 0x7A ) return b - 0x60; // lower-case letters
if ( b >= 0x30 && b <= 0x39 ) return b - 0x10; // digits
if ( b >= 0x1 && b <= 0x16 ) return b + 0x29; // symbols
throw cannotEncode( b );
}
@Override
int encPunctuation( byte b )
{
// Handled by encTranslate
throw cannotEncode( b );
}
@Override
char decTranslate( byte codePoint )
{
if ( codePoint == 0 ) return ' ';
if ( codePoint <= 0x1A ) return (char) ( codePoint + 'a' - 1 );
if ( codePoint <= 0x29 ) return (char) (codePoint - 0x20 + '0');
if ( codePoint <= 0x2E ) return decPunctuation( codePoint - 0x29 );
return decPunctuation( codePoint - 0x2F + 9);
}
},
/**
* Alpha-numerical characters space and underscore.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP A B C D E F G H I J K L M N O
* 1- P Q R S T U V W X Y Z 0 1 2 3 4
* 2- _ a b c d e f g h i j k l m n o
* 3- p q r s t u v w x y z 5 6 7 8 9
* </pre>
*/
ALPHANUM( 7, 6 )
{
@Override
char decTranslate( byte codePoint )
{
return EUROPEAN.decTranslate( (byte) ( codePoint + 0x40 ) );
}
@Override
int encTranslate( byte b )
{
// Punctuation is in the same places as European
if ( b < 0x20 ) return encPunctuation( b ); // Punctuation
// But the rest is transposed by 0x40
return EUROPEAN.encTranslate( b ) - 0x40;
}
@Override
int encPunctuation( byte b )
{
switch ( b )
{
case 0:
return 0x00; // SPACE
case 1:
return 0x20; // UNDERSCORE
default:
throw cannotEncode( b );
}
}
},
/**
* Alpha-numerical characters space and underscore.
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP A B C D E F G H I J K L M N O
* 1- P Q R S T U V W X Y Z _ . - : /
* 2- | a b c d e f g h i j k l m n o
* 3- p q r s t u v w x y z + , ' @ ;
* </pre>
*/
ALPHASYM( 8, 6 )
{
@Override
char decTranslate( byte codePoint )
{
return EUROPEAN.decTranslate( (byte) ( codePoint + 0x40 ) );
}
@Override
int encTranslate( byte b )
{
// Punctuation is in the same places as European
if ( b < 0x20 ) return encPunctuation( b ); // Punctuation
// But the rest is transposed by 0x40
return EUROPEAN.encTranslate( b ) - 0x40;
}
@Override
int encPunctuation( byte b )
{
switch ( b )
{
case 0: return 0x0;
case 1: return 0x1B;
case 2: return 0x1C;
case 3: return 0x1D;
case 4: return 0x1E;
case 5: return 0x1F;
case 6: return 0x3B;
case 7: return 0x3C;
case 8: return 0x3D;
case 9: return 0x3E;
case 10: return 0x3F;
default: throw cannotEncode( b );
}
}
},
/**
* The most common European characters (latin-1 but with less punctuation).
*
* <pre>
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
* 1- Ð Ñ Ò Ó Ô Õ Ö . Ø Ù Ú Û Ü Ý Þ ß
* 2- à á â ã ä å æ ç è é ê ë ì í î ï
* 3- ð ñ ò ó ô õ ö - ø ù ú û ü ý þ ÿ
* 4- SP A B C D E F G H I J K L M N O
* 5- P Q R S T U V W X Y Z 0 1 2 3 4
* 6- _ a b c d e f g h i j k l m n o
* 7- p q r s t u v w x y z 5 6 7 8 9
* </pre>
*/
EUROPEAN( 9, 7 )
{
@Override
char decTranslate( byte codePoint )
{
if ( codePoint < 0x40 )
{
if ( codePoint == 0x17 ) return '.';
if ( codePoint == 0x37 ) return '-';
return (char) ( codePoint + 0xC0 );
}
else
{
if ( codePoint == 0x40 ) return ' ';
if ( codePoint == 0x60 ) return '_';
if ( codePoint >= 0x5B && codePoint < 0x60 ) return (char) ( '0' + codePoint - 0x5B );
if ( codePoint >= 0x7B && codePoint < 0x80 ) return (char) ( '5' + codePoint - 0x7B );
return (char) codePoint;
}
}
@Override
int encPunctuation( byte b )
{
switch ( b )
{
case 0x00:
return 0x40; // SPACE
case 0x01:
return 0x60; // UNDERSCORE
case 0x02:
return 0x17; // DOT
case 0x03:
return 0x37; // DASH
case 0x07:
// TODO
return 0;
default:
throw cannotEncode( b );
}
}
};
final int encodingHeader;
final short mask;
final short step;
private LongerShortString( int encodingHeader, int step )
{
this.encodingHeader = encodingHeader;
this.mask = (short) Bits.rightOverflowMask( step );
this.step = (short) step;
}
int maxLength( int payloadSize )
{
return ((payloadSize << 3)-24-4-6)/step;
}
final IllegalArgumentException cannotEncode( byte b )
{
return new IllegalArgumentException( "Cannot encode as " + this.name() + ": " + b );
}
/** Lookup table for decoding punctuation */
private static final char[] PUNCTUATION = {
' ', '_', '.', '-', ':', '/',
' ', '.', '-', '+', ',', '\'', '@', '|', ';', '*', '?', '&', '%', '#', '(', ')', '$', '<', '>', '=' };
final char decPunctuation( int code )
{
return PUNCTUATION[code];
}
int encTranslate( byte b )
{
if ( b < 0 ) return ( 0xFF & b ) - 0xC0; // European chars
if ( b < 0x20 ) return encPunctuation( b ); // Punctuation
if ( b >= '0' && b <= '4' ) return 0x5B + b - '0'; // Numbers
if ( b >= '5' && b <= '9' ) return 0x7B + b - '5'; // Numbers
return b; // Alphabetical
}
abstract int encPunctuation( byte b );
abstract char decTranslate( byte codePoint );
/**
* Encodes a short string.
*
* @param string the string to encode.
* @param target the property record to store the encoded string in
* @return <code>true</code> if the string could be encoded as a short
* string, <code>false</code> if it couldn't.
*/
/*
* Intermediate code table
* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
* 0- SP _ . - : / + , ' @ | ; * ? & %
* 1- # ( ) $ < > =
* 2-
* 3- 0 1 2 3 4 5 6 7 8 9
* 4- A B C D E F G H I J K L M N O
* 5- P Q R S T U V W X Y Z
* 6- a b c d e f g h i j k l m n o
* 7- p q r s t u v w x y z
* 8-
* 9-
* A-
* B-
* C- À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
* D- Ð Ñ Ò Ó Ô Õ Ö Ø Ù Ú Û Ü Ý Þ ß
* E- à á â ã ä å æ ç è é ê ë ì í î ï
* F- ð ñ ò ó ô õ ö ø ù ú û ü ý þ ÿ
*/
public static boolean encode( int keyId, String string, PropertyRecord target, int payloadSize )
{
// NUMERICAL can carry most characters, so compare to that
int stringLength = string.length();
// We only use 6 bits for storing the string length
// TODO could be dealt with by having string length zero and go for null bytes,
// at least for LATIN1 (that's what the ShortString implementation initially did)
if ( stringLength > NUMERICAL.maxLength( payloadSize ) || stringLength > 63 ) return false; // Not handled by any encoding
if ( string.equals( "" ) )
{
applyOnRecord( keyId, target, 0, 0, new long[1] );
return true;
}
// Keep track of the possible encodings that can be used for the string
EnumSet<LongerShortString> possible = null;
// First try encoding using Latin-1
int maxBytes = PropertyType.getPayloadSize();
if ( stringLength <= (maxBytes-3-1-1) )
{
if ( encodeLatin1( keyId, string, target, payloadSize ) ) return true;
// If the string was short enough, but still didn't fit in latin-1
// we know that no other encoding will work either, remember that
// so that we can try UTF-8 at the end of this method
possible = EnumSet.noneOf( LongerShortString.class );
}
// Allocate space for the intermediate representation
// (using the intermediate representation table above)
byte[] data = new byte[stringLength];
if ( possible == null )
{
possible = EnumSet.allOf( LongerShortString.class );
for ( LongerShortString possibility : LongerShortString.values() )
{
if ( data.length > possibility.maxLength( payloadSize ) ) possible.remove( possibility );
}
}
LOOP: for ( int i = 0; i < data.length && !possible.isEmpty(); i++ )
{
char c = string.charAt( i );
switch ( c )
{
case ' ':
data[i] = 0;
possible.remove( EMAIL );
break;
case '_':
data[i] = 1;
possible.removeAll( EnumSet.of( NUMERICAL, DATE ) );
break;
case '.':
data[i] = 2;
possible.removeAll( EnumSet.of( ALPHANUM, DATE ) );
break;
case '-':
data[i] = 3;
possible.remove( ALPHANUM );
break;
case ':':
data[i] = 4;
possible.removeAll( EnumSet.of( ALPHANUM, NUMERICAL, EUROPEAN, EMAIL ) );
break;
case '/':
data[i] = 5;
possible.removeAll( EnumSet.of( ALPHANUM, NUMERICAL, EUROPEAN, EMAIL ) );
break;
case '+':
data[i] = 6;
possible.retainAll( EnumSet.of( NUMERICAL, DATE, EMAIL, URI, ALPHASYM ) );
break;
case ',':
data[i] = 7;
possible.retainAll( EnumSet.of( NUMERICAL, DATE, EMAIL, URI, ALPHASYM ) );
break;
case '\'':
data[i] = 8;
possible.retainAll( EnumSet.of( NUMERICAL, URI, ALPHASYM ) );
break;
case '@':
data[i] = 9;
possible.retainAll( EnumSet.of( EMAIL, URI, ALPHASYM ) );
break;
case '|':
data[i] = 0xA;
possible.retainAll( EnumSet.of( ALPHASYM ) );
break;
// These below are all for the URI encoding only (as of yet at least)
case ';':
data[i] = 0xB;
possible.retainAll( EnumSet.of( URI ) );
break;
case '*':
data[i] = 0xC;
possible.retainAll( EnumSet.of( URI ) );
break;
case '?':
data[i] = 0xD;
possible.retainAll( EnumSet.of( URI ) );
break;
case '&':
data[i] = 0xE;
possible.retainAll( EnumSet.of( URI ) );
break;
case '%':
data[i] = 0xF;
possible.retainAll( EnumSet.of( URI ) );
break;
case '#':
data[i] = 0x10;
possible.retainAll( EnumSet.of( URI ) );
break;
case '(':
data[i] = 0x11;
possible.retainAll( EnumSet.of( URI ) );
break;
case ')':
data[i] = 0x12;
possible.retainAll( EnumSet.of( URI ) );
break;
case '$':
data[i] = 0x13;
possible.retainAll( EnumSet.of( URI ) );
break;
case '<':
data[i] = 0x14;
possible.retainAll( EnumSet.of( URI ) );
break;
case '>': data[i] = 0x15;
possible.retainAll( EnumSet.of( URI ) );
break;
case '=': data[i] = 0x16;
possible.retainAll( EnumSet.of( URI ) );
break;
// These above are all for the URI encoding only (as of yet at least)
default:
if ( ( c >= 'A' && c <= 'Z' ) )
{
possible.removeAll( EnumSet.of( NUMERICAL, DATE, LOWER, EMAIL, URI ) );
}
else if ( ( c >= 'a' && c <= 'z' ) )
{
possible.removeAll( EnumSet.of( NUMERICAL, DATE, UPPER ) );
}
else if ( ( c >= '0' && c <= '9' ) )
{
possible.removeAll( EnumSet.of( UPPER, LOWER, EMAIL, ALPHASYM ) );
}
else if ( c >= 'À' && c <= 'ÿ' && c != 0xD7 && c != 0xF7 )
{
possible.retainAll( EnumSet.of( EUROPEAN ) );
}
else
{
possible.clear();
break LOOP; // fall back to UTF-8
}
data[i] = (byte) c;
}
}
for ( LongerShortString encoding : possible )
{
// Will return false if the data is too long for the encoding
if ( encoding.doEncode( keyId, data, target, payloadSize ) ) return true;
}
if ( stringLength <= maxBytes )
{ // We might have a chance with UTF-8 - try it!
return encodeUTF8( keyId, string, target, maxBytes );
}
return false;
}
private static void applyOnRecord( int keyId, PropertyRecord target, int encoding, int stringLength, long[] data )
{
// TODO Make a utility OR:ing in the key/type in the propblock
data[0] |= ((long)keyId << 40);
data[0] |= ( (long) PropertyType.SHORT_STRING.intValue() << 36 );
data[0] |= ( (long) encoding << 32 );
data[0] |= ( (long) stringLength << 26 );
target.setPropBlock( data );
}
/**
* Decode a short string represented as a long[]
*
* @param data the value to decode to a short string.
* @return the decoded short string
*/
public static String decode( PropertyRecord record )
{
Bits bits = new Bits( copyOf( record.getPropBlock(), record.getPropBlock().length ) );
long firstLong = bits.getLongs()[0];
if ( ( firstLong & 0xFFFFFF0FFFFFFFFFL ) == 0 ) return "";
/*
* [kkkk,kkkk][kkkk,kkkk][kkkk,kkkk][tttt, eeee][llll,ll ][ , ][ , ][ , ]
*/
int encoding = (int) ( ( firstLong & 0xF00000000L ) >>> 32 );
int stringLength = (int) ( ( firstLong & 0xFC000000L ) >>> 26 );
LongerShortString table;
switch ( encoding )
{
case 0: return decodeUTF8( bits, stringLength );
case 1: table = NUMERICAL; break;
case 2: table = DATE; break;
case 3: table = UPPER; break;
case 4: table = LOWER; break;
case 5: table = EMAIL; break;
case 6: table = URI; break;
case 7: table = ALPHANUM; break;
case 8: table = ALPHASYM; break;
case 9: table = EUROPEAN; break;
case 10: return decodeLatin1( bits, stringLength );
default: throw new IllegalArgumentException( "Invalid encoding '" + encoding + "'" );
}
char[] result = new char[stringLength];
// encode shifts in the bytes with the first char at the MSB, therefore
// we must "unshift" in the reverse order
for ( int i = result.length - 1; i >= 0; i-- )
{
byte codePoint = bits.getByte( (byte)table.mask );
result[i] = table.decTranslate( codePoint );
bits.shiftRight( table.step );
}
return new String( result );
}
private static Bits newBits( int payloadSize )
{
return new Bits( payloadSize );
}
private static boolean encodeLatin1( int keyId, String string, PropertyRecord target, int payloadSize )
{ // see doEncode
Bits bits = newBits( payloadSize );
for ( int i = 0; i < string.length(); i++ )
{
if ( i > 0 ) bits.shiftLeft( 8 );
char c = string.charAt( i );
if ( c < 0 || c >= 256 ) return false;
bits.or( c, 0xFF );
}
applyOnRecord( keyId, target, 10, string.length(), bits.getLongs() );
return true;
}
private static boolean encodeUTF8( int keyId, String string, PropertyRecord target, int payloadSize )
{
try
{
byte[] bytes = string.getBytes( "UTF-8" );
if ( bytes.length > payloadSize ) return false;
Bits bits = newBits( payloadSize );
for ( int i = 0; i < bytes.length; i++ )
{
if ( i > 0 ) bits.shiftLeft( 8 );
bits.or( bytes[i] );
}
applyOnRecord( keyId, target, 0, bytes.length, bits.getLongs() );
return true;
}
catch ( UnsupportedEncodingException e )
{
throw new IllegalStateException( "All JVMs must support UTF-8", e );
}
}
private boolean doEncode( int keyId, byte[] data, PropertyRecord target, int payloadSize )
{
if ( data.length > maxLength( payloadSize ) ) return false;
Bits bits = newBits( payloadSize );
for ( int i = 0; i < data.length; i++ )
{
if ( i != 0 ) bits.shiftLeft( step );
int encodedChar = encTranslate( data[i] );
bits.or( encodedChar, 0xFF );
}
applyOnRecord( keyId, target, encodingHeader, data.length, bits.getLongs() );
return true;
}
private static String decodeLatin1( Bits bits, int stringLength )
{ // see decode
char[] result = new char[stringLength];
for ( int i = result.length - 1; i >= 0; i-- )
{
result[i] = (char) bits.getInt( 0xFF );
bits.shiftRight( 8 );
}
return new String( result );
}
private static String decodeUTF8( Bits bits, int stringLength )
{
byte[] result = new byte[stringLength];
for ( int i = stringLength-1; i >= 0; i-- )
{
result[i] = bits.getByte( (byte)0xFF );
bits.shiftRight( 8 );
}
try
{
return new String( result, "UTF-8" );
}
catch ( UnsupportedEncodingException e )
{
throw new IllegalStateException( "All JVMs must support UTF-8", e );
}
}
}
| Takes into account the header when trying to encode UTF-8
| community/kernel/src/main/java/org/neo4j/kernel/impl/nioneo/store/LongerShortString.java | Takes into account the header when trying to encode UTF-8 |
|
Java | apache-2.0 | 40ad1368f849c9e9190860fd43cf2393471dacba | 0 | bentrm/camunda-bpm-platform,fouasnon/camunda-bpm-platform,falko/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,nibin/camunda-bpm-platform,Sumitdahiya/camunda,plexiti/camunda-bpm-platform,tcrossland/camunda-bpm-platform,Sumitdahiya/camunda,xasx/camunda-bpm-platform,rainerh/camunda-bpm-platform,camunda/camunda-bpm-platform,fouasnon/camunda-bpm-platform,plexiti/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,nibin/camunda-bpm-platform,menski/camunda-bpm-platform,jangalinski/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,tcrossland/camunda-bpm-platform,rainerh/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,xasx/camunda-bpm-platform,hupda-edpe/c,hupda-edpe/c,fouasnon/camunda-bpm-platform,hupda-edpe/c,langfr/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,skjolber/camunda-bpm-platform,rainerh/camunda-bpm-platform,joansmith/camunda-bpm-platform,menski/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,skjolber/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,menski/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,camunda/camunda-bpm-platform,fouasnon/camunda-bpm-platform,hupda-edpe/c,LuisePufahl/camunda-bpm-platform_batchProcessing,plexiti/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,bentrm/camunda-bpm-platform,holisticon/camunda-bpm-platform,plexiti/camunda-bpm-platform,filiphr/camunda-bpm-platform,langfr/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,nibin/camunda-bpm-platform,jangalinski/camunda-bpm-platform,filiphr/camunda-bpm-platform,xasx/camunda-bpm-platform,xasx/camunda-bpm-platform,menski/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,holisticon/camunda-bpm-platform,tcrossland/camunda-bpm-platform,bentrm/camunda-bpm-platform,camunda/camunda-bpm-platform,holisticon/camunda-bpm-platform,fouasnon/camunda-bpm-platform,joansmith/camunda-bpm-platform,langfr/camunda-bpm-platform,rainerh/camunda-bpm-platform,bentrm/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,skjolber/camunda-bpm-platform,holisticon/camunda-bpm-platform,filiphr/camunda-bpm-platform,tcrossland/camunda-bpm-platform,filiphr/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,langfr/camunda-bpm-platform,tcrossland/camunda-bpm-platform,joansmith/camunda-bpm-platform,hupda-edpe/c,falko/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,bentrm/camunda-bpm-platform,filiphr/camunda-bpm-platform,plexiti/camunda-bpm-platform,langfr/camunda-bpm-platform,plexiti/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,tcrossland/camunda-bpm-platform,skjolber/camunda-bpm-platform,joansmith/camunda-bpm-platform,Sumitdahiya/camunda,filiphr/camunda-bpm-platform,Sumitdahiya/camunda,AlexMinsk/camunda-bpm-platform,xasx/camunda-bpm-platform,bentrm/camunda-bpm-platform,camunda/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,Sumitdahiya/camunda,nibin/camunda-bpm-platform,fouasnon/camunda-bpm-platform,falko/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,hupda-edpe/c,jangalinski/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,jangalinski/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,rainerh/camunda-bpm-platform,skjolber/camunda-bpm-platform,skjolber/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,joansmith/camunda-bpm-platform,langfr/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,falko/camunda-bpm-platform,falko/camunda-bpm-platform,joansmith/camunda-bpm-platform,nagyistoce/camunda-bpm-platform,camunda/camunda-bpm-platform,nibin/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,falko/camunda-bpm-platform,hawky-4s-/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,subhrajyotim/camunda-bpm-platform,holisticon/camunda-bpm-platform,Sumitdahiya/camunda,ingorichtsmeier/camunda-bpm-platform,jangalinski/camunda-bpm-platform,xasx/camunda-bpm-platform,holisticon/camunda-bpm-platform,AlexMinsk/camunda-bpm-platform,rainerh/camunda-bpm-platform,camunda/camunda-bpm-platform,menski/camunda-bpm-platform,LuisePufahl/camunda-bpm-platform_batchProcessing,nibin/camunda-bpm-platform,jangalinski/camunda-bpm-platform | /* 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.camunda.bpm.engine.test.api.repository;
import java.util.Date;
import java.util.List;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.impl.calendar.DateTimeUtil;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.DeploymentQuery;
/**
* @author Tom Baeyens
* @author Ingo Richtsmeier
*/
public class DeploymentQueryTest extends PluggableProcessEngineTestCase {
private String deploymentOneId;
private String deploymentTwoId;
@Override
protected void setUp() throws Exception {
deploymentOneId = repositoryService
.createDeployment()
.name("org/camunda/bpm/engine/test/repository/one.bpmn20.xml")
.addClasspathResource("org/camunda/bpm/engine/test/repository/one.bpmn20.xml")
.deploy()
.getId();
deploymentTwoId = repositoryService
.createDeployment()
.name("org/camunda/bpm/engine/test/repository/two.bpmn20.xml")
.addClasspathResource("org/camunda/bpm/engine/test/repository/two.bpmn20.xml")
.deploy()
.getId();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
repositoryService.deleteDeployment(deploymentOneId, true);
repositoryService.deleteDeployment(deploymentTwoId, true);
}
public void testQueryNoCriteria() {
DeploymentQuery query = repositoryService.createDeploymentQuery();
assertEquals(2, query.list().size());
assertEquals(2, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByDeploymentId() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentId(deploymentOneId);
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidDeploymentId() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentId("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
repositoryService.createDeploymentQuery().deploymentId(null);
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByName() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentName("org/camunda/bpm/engine/test/repository/two.bpmn20.xml");
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidName() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentName("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
repositoryService.createDeploymentQuery().deploymentName(null);
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByNameLike() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentNameLike("%camunda%");
assertEquals(2, query.list().size());
assertEquals(2, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByInvalidNameLike() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentNameLike("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
repositoryService.createDeploymentQuery().deploymentNameLike(null);
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByDeploymentBefore() throws Exception {
Date later = DateTimeUtil.now().plus(10 * 3600).toDate();
Date earlier = DateTimeUtil.now().minus(10 * 3600).toDate();
long count = repositoryService.createDeploymentQuery().deploymentBefore(later).count();
assertEquals(2, count);
count = repositoryService.createDeploymentQuery().deploymentBefore(earlier).count();
assertEquals(0, count);
try {
repositoryService.createDeploymentQuery().deploymentBefore(null);
fail("Exception expected");
} catch (NullValueException e) {
// expected
}
}
public void testQueryDeploymentAfter() throws Exception {
Date later = DateTimeUtil.now().plus(10 * 3600).toDate();
Date earlier = DateTimeUtil.now().minus(10 * 3600).toDate();
long count = repositoryService.createDeploymentQuery().deploymentAfter(later).count();
assertEquals(0, count);
count = repositoryService.createDeploymentQuery().deploymentAfter(earlier).count();
assertEquals(2, count);
try {
repositoryService.createDeploymentQuery().deploymentAfter(null);
fail("Exception expected");
} catch (NullValueException e) {
// expected
}
}
public void testQueryDeploymentBetween() throws Exception {
Date later = DateTimeUtil.now().plus(10 * 3600).toDate();
Date earlier = DateTimeUtil.now().minus(10 * 3600).toDate();
long count = repositoryService
.createDeploymentQuery()
.deploymentAfter(earlier)
.deploymentBefore(later).count();
assertEquals(2, count);
count = repositoryService
.createDeploymentQuery()
.deploymentAfter(later)
.deploymentBefore(later)
.count();
assertEquals(0, count);
count = repositoryService
.createDeploymentQuery()
.deploymentAfter(earlier)
.deploymentBefore(earlier)
.count();
assertEquals(0, count);
}
public void testVerifyDeploymentProperties() {
List<Deployment> deployments = repositoryService.createDeploymentQuery()
.orderByDeploymentName()
.asc()
.list();
Deployment deploymentOne = deployments.get(0);
assertEquals("org/camunda/bpm/engine/test/repository/one.bpmn20.xml", deploymentOne.getName());
assertEquals(deploymentOneId, deploymentOne.getId());
Deployment deploymentTwo = deployments.get(1);
assertEquals("org/camunda/bpm/engine/test/repository/two.bpmn20.xml", deploymentTwo.getName());
assertEquals(deploymentTwoId, deploymentTwo.getId());
deployments = repositoryService.createDeploymentQuery()
.deploymentNameLike("%one%")
.orderByDeploymentName()
.asc()
.list();
assertEquals("org/camunda/bpm/engine/test/repository/one.bpmn20.xml", deployments.get(0).getName());
assertEquals(1, deployments.size());
assertEquals(2, repositoryService.createDeploymentQuery()
.orderByDeploymentId()
.asc()
.list()
.size());
assertEquals(2, repositoryService.createDeploymentQuery()
.orderByDeploymenTime()
.asc()
.list()
.size());
}
}
| engine/src/test/java/org/camunda/bpm/engine/test/api/repository/DeploymentQueryTest.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.camunda.bpm.engine.test.api.repository;
import java.util.Date;
import java.util.List;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.DeploymentQuery;
/**
* @author Tom Baeyens
* @author Ingo Richtsmeier
*/
public class DeploymentQueryTest extends PluggableProcessEngineTestCase {
private String deploymentOneId;
private String deploymentTwoId;
@Override
protected void setUp() throws Exception {
deploymentOneId = repositoryService
.createDeployment()
.name("org/camunda/bpm/engine/test/repository/one.bpmn20.xml")
.addClasspathResource("org/camunda/bpm/engine/test/repository/one.bpmn20.xml")
.deploy()
.getId();
deploymentTwoId = repositoryService
.createDeployment()
.name("org/camunda/bpm/engine/test/repository/two.bpmn20.xml")
.addClasspathResource("org/camunda/bpm/engine/test/repository/two.bpmn20.xml")
.deploy()
.getId();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
repositoryService.deleteDeployment(deploymentOneId, true);
repositoryService.deleteDeployment(deploymentTwoId, true);
}
public void testQueryNoCriteria() {
DeploymentQuery query = repositoryService.createDeploymentQuery();
assertEquals(2, query.list().size());
assertEquals(2, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByDeploymentId() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentId(deploymentOneId);
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidDeploymentId() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentId("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
repositoryService.createDeploymentQuery().deploymentId(null);
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByName() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentName("org/camunda/bpm/engine/test/repository/two.bpmn20.xml");
assertNotNull(query.singleResult());
assertEquals(1, query.list().size());
assertEquals(1, query.count());
}
public void testQueryByInvalidName() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentName("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
repositoryService.createDeploymentQuery().deploymentName(null);
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByNameLike() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentNameLike("%camunda%");
assertEquals(2, query.list().size());
assertEquals(2, query.count());
try {
query.singleResult();
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByInvalidNameLike() {
DeploymentQuery query = repositoryService.createDeploymentQuery().deploymentNameLike("invalid");
assertNull(query.singleResult());
assertEquals(0, query.list().size());
assertEquals(0, query.count());
try {
repositoryService.createDeploymentQuery().deploymentNameLike(null);
fail();
} catch (ProcessEngineException e) {}
}
public void testQueryByDeploymentBefore() throws Exception {
Date now = ClockUtil.getCurrentTime();
Date earlier = new Date(now.getTime() - 3600);
long count = repositoryService.createDeploymentQuery().deploymentBefore(now).count();
assertEquals(2, count);
count = repositoryService.createDeploymentQuery().deploymentBefore(earlier).count();
assertEquals(0, count);
try {
repositoryService.createDeploymentQuery().deploymentBefore(null);
fail("Exception expected");
} catch (NullValueException e) {
// expected
}
}
public void testQueryDeploymentAfter() throws Exception {
Date now = ClockUtil.getCurrentTime();
Date earlier = new Date(ClockUtil.getCurrentTime().getTime() - 3600);
long count = repositoryService.createDeploymentQuery().deploymentAfter(now).count();
assertEquals(0, count);
count = repositoryService.createDeploymentQuery().deploymentAfter(earlier).count();
assertEquals(2, count);
try {
repositoryService.createDeploymentQuery().deploymentAfter(null);
fail("Exception expected");
} catch (NullValueException e) {
// expected
}
}
public void testQueryDeploymentBetween() throws Exception {
Date now = ClockUtil.getCurrentTime();
Date earlier = new Date(ClockUtil.getCurrentTime().getTime() - 3600);
long count = repositoryService
.createDeploymentQuery()
.deploymentAfter(earlier)
.deploymentBefore(now).count();
assertEquals(2, count);
count = repositoryService
.createDeploymentQuery()
.deploymentAfter(now)
.deploymentBefore(now)
.count();
assertEquals(0, count);
count = repositoryService
.createDeploymentQuery()
.deploymentAfter(earlier)
.deploymentBefore(earlier)
.count();
assertEquals(0, count);
}
public void testVerifyDeploymentProperties() {
List<Deployment> deployments = repositoryService.createDeploymentQuery()
.orderByDeploymentName()
.asc()
.list();
Deployment deploymentOne = deployments.get(0);
assertEquals("org/camunda/bpm/engine/test/repository/one.bpmn20.xml", deploymentOne.getName());
assertEquals(deploymentOneId, deploymentOne.getId());
Deployment deploymentTwo = deployments.get(1);
assertEquals("org/camunda/bpm/engine/test/repository/two.bpmn20.xml", deploymentTwo.getName());
assertEquals(deploymentTwoId, deploymentTwo.getId());
deployments = repositoryService.createDeploymentQuery()
.deploymentNameLike("%one%")
.orderByDeploymentName()
.asc()
.list();
assertEquals("org/camunda/bpm/engine/test/repository/one.bpmn20.xml", deployments.get(0).getName());
assertEquals(1, deployments.size());
assertEquals(2, repositoryService.createDeploymentQuery()
.orderByDeploymentId()
.asc()
.list()
.size());
assertEquals(2, repositoryService.createDeploymentQuery()
.orderByDeploymenTime()
.asc()
.list()
.size());
}
}
| fix(engine): use greater timespan in test to work on mysql
related to #CAM-2968
| engine/src/test/java/org/camunda/bpm/engine/test/api/repository/DeploymentQueryTest.java | fix(engine): use greater timespan in test to work on mysql |
|
Java | apache-2.0 | 611eaff9ba03d4ae9d9064502b97d82f4d53db67 | 0 | leapframework/framework,leapframework/framework,leapframework/framework,leapframework/framework | package leap.core.config;
import leap.lang.Out;
import leap.lang.Strings;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
public class JasyptAppPropertyProcessor implements AppPropertyProcessor {
private static final String ENC_PREFIX = "ENC(";
private static final String ENC_SUFFIX = ")";
private static final String PASSWORD_ENV = "jasypt.encryptor.password";
private final StandardPBEStringEncryptor encryptor;
public JasyptAppPropertyProcessor() {
String password = System.getenv(PASSWORD_ENV);
if (Strings.isEmpty(password)) {
password = System.getenv(PASSWORD_ENV.replace('.', '_'));
}
if (!Strings.isEmpty(password)) {
encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword(password);
} else {
encryptor = null;
}
}
@Override
public boolean process(String name, String value, Out<String> newValue) {
if (null == encryptor) {
return false;
}
if (null == value || !value.startsWith(ENC_PREFIX) || !value.endsWith(ENC_SUFFIX)) {
return false;
}
String ciphertext = value.substring(ENC_PREFIX.length(), value.length() - ENC_SUFFIX.length());
if (Strings.isEmpty(ciphertext)) {
newValue.accept(ciphertext);
} else {
try {
newValue.accept(encryptor.decrypt(ciphertext));
} catch (EncryptionOperationNotPossibleException ex) {
ex.printStackTrace();
throw new IllegalStateException("Decryption error property: " + name);
}
}
return true;
}
} | base/core/src/main/java/leap/core/config/JasyptAppPropertyProcessor.java | package leap.core.config;
import leap.lang.Out;
import leap.lang.Strings;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
public class JasyptAppPropertyProcessor implements AppPropertyProcessor {
private static final String ENC_PREFIX = "ENC(";
private static final String ENC_SUFFIX = ")";
private static final String PASSWORD_ENV = "jasypt.encryptor.password";
private final StandardPBEStringEncryptor encryptor;
public JasyptAppPropertyProcessor() {
String password = System.getenv(PASSWORD_ENV);
if (!Strings.isEmpty(password)) {
encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword(password);
} else {
encryptor = null;
}
}
@Override
public boolean process(String name, String value, Out<String> newValue) {
if (null == encryptor) {
return false;
}
if (null == value || !value.startsWith(ENC_PREFIX) || !value.endsWith(ENC_SUFFIX)) {
return false;
}
String ciphertext = value.substring(ENC_PREFIX.length(), value.length() - ENC_SUFFIX.length());
if (Strings.isEmpty(ciphertext)) {
newValue.accept(ciphertext);
} else {
try {
newValue.accept(encryptor.decrypt(ciphertext));
} catch (EncryptionOperationNotPossibleException ex) {
ex.printStackTrace();
throw new IllegalStateException("Decryption error property: " + name);
}
}
return true;
}
} | core: jasypt password env
| base/core/src/main/java/leap/core/config/JasyptAppPropertyProcessor.java | core: jasypt password env |
|
Java | apache-2.0 | c2e2ac47adf4c3dbbdb0ecd54594fc7f07bcb547 | 0 | ResearchWorx/Cresco-GObjectIngestion-Plugin | package com.researchworx.cresco.plugins.gobjectIngestion.folderprocessor;
import com.researchworx.cresco.library.messaging.MsgEvent;
import com.researchworx.cresco.library.utilities.CLogger;
import com.researchworx.cresco.plugins.gobjectIngestion.Plugin;
import com.researchworx.cresco.plugins.gobjectIngestion.objectstorage.Encapsulation;
import com.researchworx.cresco.plugins.gobjectIngestion.objectstorage.ObjectEngine;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class ObjectFS implements Runnable {
private final String transfer_watch_file;
private final String transfer_status_file;
private String bucket_name;
private String incoming_directory;
private String outgoing_directory;
private Plugin plugin;
private CLogger logger;
private String pathStage;
private int pstep;
private String stagePhase;
public ObjectFS(Plugin plugin) {
this.stagePhase = "uninit";
this.pstep = 1;
this.plugin = plugin;
this.logger = new CLogger(ObjectFS.class, plugin.getMsgOutQueue(), plugin.getRegion(), plugin.getAgent(), plugin.getPluginID(), CLogger.Level.Trace);
this.pathStage = String.valueOf(plugin.pathStage);
logger.debug("OutPathPreProcessor Instantiated");
incoming_directory = plugin.getConfig().getStringParam("incoming_directory");
logger.debug("\"pathstage" + pathStage + "\" --> \"incoming_directory\" from config [{}]", incoming_directory);
outgoing_directory = plugin.getConfig().getStringParam("outgoing_directory");
logger.debug("\"pathstage" + pathStage + "\" --> \"outgoing_directory\" from config [{}]", outgoing_directory);
transfer_status_file = plugin.getConfig().getStringParam("transfer_status_file");
logger.debug("\"pathstage" + pathStage + "\" --> \"transfer_status_file\" from config [{}]", transfer_status_file);
transfer_watch_file = plugin.getConfig().getStringParam("transfer_watch_file");
logger.debug("\"pathstage" + pathStage + "\" --> \"transfer_watch_file\" from config [{}]", transfer_watch_file);
bucket_name = plugin.getConfig().getStringParam("bucket");
logger.debug("\"pathstage" + pathStage + "\" --> \"bucket\" from config [{}]", bucket_name);
MsgEvent me = plugin.genGMessage(MsgEvent.Type.INFO, "InPathPreProcessor instantiated");
//me.setParam("transfer_watch_file", transfer_watch_file);
//me.setParam("transfer_status_file", transfer_status_file);
//me.setParam("bucket_name", bucket_name);
me.setParam("pathstage", pathStage);
//me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pstep", String.valueOf(pstep));
plugin.sendMsgEvent(me);
}
@Override
public void run() {
try {
pstep = 2;
logger.trace("Setting [PathProcessorActive] to true");
plugin.PathProcessorActive = true;
logger.trace("Entering while-loop");
while (plugin.PathProcessorActive) {
sendUpdateInfoMessage(null, null, null, String.valueOf(pstep), "Idle");
Thread.sleep(plugin.getConfig().getIntegerParam("scan_interval", 5000));
}
} catch (Exception e) {
sendUpdateErrorMessage(null, null, null, String.valueOf(pstep),
String.format("General Run Exception [%s:%s]", e.getClass().getCanonicalName(), e.getMessage()));
}
}
public void processBaggedSequence(String seqId, String reqId, boolean trackPerf) {
logger.debug("processBaggedSequence('{}','{}',{})", seqId, reqId, trackPerf);
ObjectEngine oe = new ObjectEngine(plugin);
pstep = 3;
int sstep = 0;
String clinical_bucket_name = plugin.getConfig().getStringParam("clinical_bucket");
logger.trace("Checking to see if clinical bucket [{}] exists", clinical_bucket_name);
if (clinical_bucket_name == null || clinical_bucket_name.equals("") ||
!oe.doesBucketExist(clinical_bucket_name)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Clinical bucket [%s] does not exist",
clinical_bucket_name != null ? clinical_bucket_name : "NULL"));
plugin.PathProcessorActive = false;
return;
}
String research_bucket_name = plugin.getConfig().getStringParam("research_bucket");
logger.trace("Checking to see if research bucket [{}] exists", research_bucket_name);
if (research_bucket_name == null || research_bucket_name.equals("") ||
!oe.doesBucketExist(research_bucket_name)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Research bucket [%s] does not exist",
research_bucket_name != null ? research_bucket_name : "NULL"));
plugin.PathProcessorActive = false;
return;
}
sstep = 1;
String remoteDir = seqId;
MsgEvent pse;
String workDirName = null;
try {
workDirName = incoming_directory;
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
File workDir = new File(workDirName);
if (workDir.exists()) {
if (!deleteDirectory(workDir))
logger.error("deleteDirectory('{}') = false", workDir.getAbsolutePath());
}
if (!workDir.mkdir())
logger.error("workDir.mkdir() = false (workDir = '{}')", workDir.getAbsolutePath());
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Retrieving bagged sequence");
sstep = 2;
if (oe.downloadBaggedDirectory(bucket_name, remoteDir, workDirName, seqId, null, reqId,
String.valueOf(sstep))) {
String baggedSequenceFile = workDirName + seqId + ".tar";
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Download successful, unboxing sequence file [%s]", baggedSequenceFile));
/*if (!Encapsulation.unBoxIt(baggedSequenceFile)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Failed to unbox sequence file [%s]", baggedSequenceFile));
pstep = 2;
return;
}*/
Encapsulation.decompress(baggedSequenceFile, workDir);
String unboxed = workDirName + seqId + "/";
if (!new File(unboxed).exists() || !new File(unboxed).isDirectory()) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unboxing to [%s] failed", unboxed));
pstep = 2;
return;
}
logger.trace("unBoxIt result: {}, deleting TAR file", unboxed);
new File(baggedSequenceFile).delete();
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Validating sequence [%s]", unboxed));
if (!Encapsulation.isBag(unboxed)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unboxed sequence [%s] does not contain BagIt data", unboxed));
pstep = 2;
return;
}
if (!Encapsulation.verifyBag(unboxed, true)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unboxed sequence [%s] failed BagIt verification", unboxed));
pstep = 2;
return;
}
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Restoring sequence [%s]", unboxed));
Encapsulation.debagify(unboxed);
workDirName = unboxed;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Sequence [%s] restored to [%s]", seqId, unboxed));
sstep = 3;
}
} catch (Exception e) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Exception encountered: [%s:%s]", e.getClass().getCanonicalName(), e.getMessage()));
}
/*if (sstep == 3) {
try {
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
logger.trace("Starting performance monitoring");
pt = new PerfTracker();
new Thread(pt).start();
}
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Creating output directory");
String resultDirName = outgoing_directory; //create random tmp location
logger.trace("Clearing/resetting output directory");
resultDirName = resultDirName.replace("//", "/");
if (!resultDirName.endsWith("/")) {
resultDirName += "/";
}
File resultDir = new File(resultDirName);
if (resultDir.exists()) {
deleteDirectory(resultDir);
}
logger.trace("Creating output directory: {}", resultDirName);
resultDir.mkdir();
String clinicalResultsDirName = resultDirName + "clinical/";
if (new File(clinicalResultsDirName).exists())
deleteDirectory(new File(clinicalResultsDirName));
new File(clinicalResultsDirName).mkdir();
String researchResultsDirName = resultDirName + "research/";
if (new File(researchResultsDirName).exists())
deleteDirectory(new File(researchResultsDirName));
new File(researchResultsDirName).mkdir();
sstep = 4;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Starting Pre-Processing via Docker Container");
String containerName = "procseq." + seqId;
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
String command = "docker run " +
"-v " + researchResultsDirName + ":/gdata/output/research " +
"-v " + clinicalResultsDirName + ":/gdata/output/clinical " +
"-v " + workDirName + ":/gdata/input " +
"-e INPUT_FOLDER_PATH=/gdata/input/" + remoteDir + " " +
"--name " + containerName + " " +
"-t intrepo.uky.edu:5000/gbase /opt/pretools/raw_data_processing.pl";
logger.trace("Running Docker Command: {}", command);
StringBuilder output = new StringBuilder();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
logger.trace("Attaching output reader");
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
output.append("\n");
String[] outputStr = outputLine.split("\\|\\|");
for (int i = 0; i < outputStr.length; i++)
outputStr[i] = outputStr[i].trim();
if ((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) ||
(outputLine.toLowerCase().startsWith("error")))) {
if (outputStr[0].toLowerCase().equals("info")) {
if (!stagePhase.equals(outputStr[3])) {
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Pipeline now in phase %s", outputStr[3]));
}
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Pre-Processing error: %s", outputLine));
}
}
logger.debug(outputLine);
}
logger.trace("Waiting for Docker process to finish");
p.waitFor();
logger.trace("Docker Exit Code: {}", p.exitValue());
if (trackPerf) {
logger.trace("Ending Performance Monitor");
pt.isActive = false;
logger.trace("Sending Performance Information");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Performance Information");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("perf_log", pt.getResults());
plugin.sendMsgEvent(pse);
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Pipeline Output");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("output_log", output.toString());
plugin.sendMsgEvent(pse);
} catch (IOException ioe) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("File read/write exception [%s:%s]",
ioe.getClass().getCanonicalName(), ioe.getMessage()));
} catch (InterruptedException ie) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Process was interrupted [%s:%s]",
ie.getClass().getCanonicalName(), ie.getMessage()));
} catch (Exception e) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Exception [%s:%s]",
e.getClass().getCanonicalName(), e.getMessage()));
}
logger.trace("Pipeline has finished");
Thread.sleep(2000);
if (p != null) {
switch (p.exitValue()) {
case 0: // Container finished successfully
sstep = 5;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Pipeline has completed");
sstep = 6;
if (new File(resultDirName + "clinical/" + seqId + "/").exists()) {
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Transferring Clinical Results Directory");
if (oe.uploadBaggedDirectory(clinical_bucket_name, resultDirName + "clinical/" +
seqId + "/", seqId, seqId, null, reqId, String.valueOf(sstep))) {
sstep = 7;
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
logger.trace("Sample Directory: " + resultDirName + "clinical/" +
seqId + "/");
String sampleList = getSampleList(resultDirName + "clinical/" + seqId + "/");
pse = plugin.genGMessage(MsgEvent.Type.INFO,
"Clinical Results Directory Transfer Complete");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
if (sampleList != null) {
logger.trace("Samples : " + sampleList);
pse.setParam("sample_list", sampleList);
} else {
pse.setParam("sample_list", "");
}
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
}
if (new File(resultDirName + "research/" + seqId + "/").exists()) {
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Transferring Research Results Directory");
if (oe.uploadBaggedDirectory(research_bucket_name, resultDirName + "research/" +
seqId + "/", seqId, seqId, null, reqId, String.valueOf(sstep))) {
sstep = 8;
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
pse = plugin.genGMessage(MsgEvent.Type.INFO,
"Research Results Directory Transferred");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
}
sstep = 9;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Pre-processing is complete");
break;
case 1: // Container error encountered
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"General Docker error encountered (Err: 1)");
break;
case 100: // Script failure encountered
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Pre-Processor encountered an error (Err: 100)");
break;
case 125: // Container failed to run
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container failed to run (Err: 125)");
break;
case 126: // Container command cannot be invoked
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container command failed to be invoked (Err: 126)");
break;
case 127: // Container command cannot be found
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container command could not be found (Err: 127)");
break;
case 137: // Container was killed
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container was manually stopped (Err: 137)");
break;
default: // Other return code encountered
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unknown container return code (Err: %d)", p.exitValue()));
break;
}
} else {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Error retrieving return code from container");
}
Process postClear = Runtime.getRuntime().exec("docker rm " + containerName);
postClear.waitFor();
} catch (Exception e) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("processBaggedSequence exception encountered [%s:%s]",
e.getClass().getCanonicalName(), e.getMessage()));
}
}*/
pstep = 2;
}
public void processSequence(String seqId, String reqId, boolean trackPerf) {
logger.debug("Call to processSequence seq_id: " + seqId, ", req_id: " + reqId);
pstep = 3;
int sstep = 0;
String clinical_bucket_name = plugin.getConfig().getStringParam("clinical_bucket");
if (clinical_bucket_name == null || clinical_bucket_name.equals("")) {
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Configuration value [clinical_bucket] is not properly set");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(error);
plugin.PathProcessorActive = false;
return;
}
String research_bucket_name = plugin.getConfig().getStringParam("research_bucket");
if (research_bucket_name == null || research_bucket_name.equals("")) {
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Configuration value [research_bucket] is not properly set");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(error);
plugin.PathProcessorActive = false;
return;
}
sstep = 1;
String remoteDir = seqId + "/";
MsgEvent pse;
String workDirName = null;
try {
workDirName = incoming_directory; //create random tmp location
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
File workDir = new File(workDirName);
if (workDir.exists()) {
deleteDirectory(workDir);
}
workDir.mkdir();
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
ObjectEngine oe = new ObjectEngine(plugin);
if (new File(workDirName + seqId).exists()) {
deleteDirectory(new File(workDirName + seqId));
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 2;
oe.downloadDirectory(bucket_name, remoteDir, workDirName, seqId, null);
//logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, workDirName + seqId, filterList)) {
logger.debug("Directory Sycned [inDir = {}]", workDirName);
//Map<String, String> md5map = oe.getDirMD5(inDir, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(inDir + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered");
pse.setParam("indir", workDirName);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 3;
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", ex.getMessage());
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
//if is makes it through process the seq
if (sstep == 3) {
try {
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
logger.trace("Starting performance monitoring");
pt = new PerfTracker();
new Thread(pt).start();
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Creating output directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
String resultDirName = outgoing_directory; //create random tmp location
logger.trace("Clearing/resetting output directory");
resultDirName = resultDirName.replace("//", "/");
if (!resultDirName.endsWith("/")) {
resultDirName += "/";
}
File resultDir = new File(resultDirName);
if (resultDir.exists()) {
deleteDirectory(resultDir);
}
logger.trace("Creating output directory: {}", resultDirName);
resultDir.mkdir();
String clinicalResultsDirName = resultDirName + "clinical/";
if (new File(clinicalResultsDirName).exists())
deleteDirectory(new File(clinicalResultsDirName));
new File(clinicalResultsDirName).mkdir();
String researchResultsDirName = resultDirName + "research/";
if (new File(researchResultsDirName).exists())
deleteDirectory(new File(researchResultsDirName));
new File(researchResultsDirName).mkdir();
sstep = 4;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Starting Pre-Processor via Docker Container");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
String containerName = "procseq." + seqId;
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
String command = "docker run " +
"-v " + researchResultsDirName + ":/gdata/output/research " +
"-v " + clinicalResultsDirName + ":/gdata/output/clinical " +
"-v " + workDirName + ":/gdata/input " +
"-e INPUT_FOLDER_PATH=/gdata/input/" + remoteDir + " " +
"--name " + containerName + " " +
"-t intrepo.uky.edu:5000/gbase /opt/pretools/raw_data_processing.pl";
logger.trace("Running Docker Command: {}", command);
StringBuilder output = new StringBuilder();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
logger.trace("Attaching output reader");
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
output.append("\n");
String[] outputStr = outputLine.split("\\|\\|");
for (int i = 0; i < outputStr.length; i++) {
outputStr[i] = outputStr[i].trim();
}
if ((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) || (outputLine.toLowerCase().startsWith("error")))) {
if (outputStr[0].toLowerCase().equals("info")) {
if (!stagePhase.equals(outputStr[3])) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline now in phase " + outputStr[3]);
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
logger.error("Pre-Processing Error : " + outputLine);
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("error_message", outputLine);
plugin.sendMsgEvent(pse);
}
}
logger.debug(outputLine);
}
logger.trace("Waiting for Docker process to finish");
p.waitFor();
logger.trace("Docker Exit Code: {}", p.exitValue());
if (trackPerf) {
logger.trace("Ending Performance Monitor");
pt.isActive = false;
logger.trace("Sending Performance Information");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Performance Information");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("perf_log", pt.getResults());
plugin.sendMsgEvent(pse);
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Pipeline Output");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("output_log", output.toString());
plugin.sendMsgEvent(pse);
} catch (IOException ioe) {
// WHAT!?! DO SOMETHIN'!
logger.error("File read/write exception: {}", ioe.getMessage());
} catch (InterruptedException ie) {
// WHAT!?! DO SOMETHIN'!
logger.error("Process was interrupted: {}", ie.getMessage());
} catch (Exception e) {
// WHAT!?! DO SOMETHIN'!
logger.error("Exception: {}", e.getMessage());
}
logger.trace("Pipeline has finished");
Thread.sleep(2000);
if (p != null) {
switch (p.exitValue()) {
case 0: // Container finished successfully
sstep = 5;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline has completed");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
ObjectEngine oe = new ObjectEngine(plugin);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Deleting old pre-processed files from Object Store");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
logger.trace("Deleting old clinical files");
oe.deleteBucketDirectoryContents(clinical_bucket_name, seqId);
logger.trace("Deleting old research files");
oe.deleteBucketDirectoryContents(research_bucket_name, seqId);
logger.trace("Uploading results to objectStore");
sstep = 6;
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
logger.trace("Transferring Clinical Results Directory");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Transferring Clinical Results Directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
oe.uploadSequenceDirectory(clinical_bucket_name, resultDirName + "clinical/" + seqId + "/", seqId, seqId, String.valueOf(sstep));
logger.trace("Checking if Clinical Results are Synced Properly");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Checking if Clinical Results are Synced Properly");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 7;
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(clinical_bucket_name, seqId + "/", resultDirName + "clinical/" + seqId + "/", filterList)) {
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
logger.trace("Sample Directory: " + resultDirName + "clinical/" + seqId + "/");
String sampleList = getSampleList(resultDirName + "clinical/" + seqId + "/");
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Clinical Results Directory Transfer Complete");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
if (sampleList != null) {
logger.trace("Samples : " + sampleList);
pse.setParam("sample_list", sampleList);
} else {
pse.setParam("sample_list", "");
}
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
logger.trace("Transferring Research Results Directory");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Transferring Research Results Directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
oe.uploadSequenceDirectory(research_bucket_name, resultDirName + "research/" + seqId + "/", seqId, seqId, String.valueOf(sstep));
logger.trace("Checking if Research Results are Synced Properly");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Checking if Research Results are Synced Properly");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(research_bucket_name, seqId + "/", resultDirName + "research/" + seqId + "/", filterList)) {
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Research Results Directory Transferred");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
logger.trace("Pre-processing is complete");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pre-processing is complete");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 1: // Container error encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "General Docker Error Encountered (Err: 1)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 100: // Script failure encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Pre-processor encountered an error (Err: 100)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 125: // Container failed to run
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container failed to run (Err: 125)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 126: // Container command cannot be invoked
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command failed to be invoked (Err: 126)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 127: // Container command cannot be found
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command could not be found (Err: 127)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 137: // Container was killed
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container was manually stopped (Err: 137)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
default: // Other return code encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Unknown container return code (Err: " + p.exitValue() + ")");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
}
} else {
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error retrieving return code from container");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
Process postClear = Runtime.getRuntime().exec("docker rm " + containerName);
postClear.waitFor();
} catch (Exception e) {
logger.error("processSequence {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
}
pstep = 2;
}
public void endProcessSequence(String seqId, String reqId) {
MsgEvent pse;
try {
String containerName = "procseq." + seqId;
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Thread.sleep(500);
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
if (kill.exitValue() == 0) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pre-processing canceled");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
} catch (Exception e) {
logger.error("processSequence {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("sstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
}
private boolean deleteDirectory(File path) {
boolean deleted = true;
if (path.exists()) {
File[] files = path.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory())
deleteDirectory(file);
else if (!file.delete())
deleted = false;
}
}
}
return (path.delete() && deleted);
}
private class PerfTracker extends Thread {
private boolean isActive = false;
private StringBuilder results = new StringBuilder();
PerfTracker() {
isActive = false;
}
public void run() {
try {
results.append("ts,cpu-idle-load,cpu-user-load,cpu-nice-load,cpu-sys-load,cpu-core-count-physical,cpu-core-count-logical,cpu-core-load,load-sane,memory-total,memory-available,memory-used,process-phase\n");
isActive = true;
Long perfRate = plugin.getConfig().getLongParam("perfrate", 5000L);
while (isActive) {
logPerf();
Thread.sleep(perfRate);
}
} catch (Exception ex) {
logger.error("PerfTracker run(): {}", ex.getMessage());
}
}
public String getResults() {
return results.toString();
}
private void logPerf() {
MsgEvent me = plugin.getSysInfo();
if (me != null) {
/*
Iterator it = me.getParams().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
logger.info(pairs.getKey() + " = " + pairs.getValue());
//String plugin = pairs.getKey().toString();
}
*/
//cpu-per-cpu-load = CPU Load per processor: 1.0% 12.0% 8.0% 7.9% 0.0% 0.0% 0.0% 0.0%
//cpu-core-count = 8
//String sCoreCountp = me.getParam("cpu-core-count-physical");
//String sCoreCountl = me.getParam("cpu-core-count-logical");
String sCoreCountp = me.getParam("cpu-core-count");
String sCoreCountl = me.getParam("cpu-core-count");
int pcoreCount = Integer.parseInt(sCoreCountp);
String cpuPerLoad = me.getParam("cpu-per-cpu-load");
cpuPerLoad = cpuPerLoad.substring(cpuPerLoad.indexOf(": ") + 2);
cpuPerLoad = cpuPerLoad.replace("%", "");
String[] perCpu = cpuPerLoad.split(" ");
String sCputPerLoadGrp = "";
for (String cpu : perCpu) {
//logger.info(cpu);
sCputPerLoadGrp += cpu + ":";
}
sCputPerLoadGrp = sCputPerLoadGrp.substring(0, sCputPerLoadGrp.length() - 1);
String sMemoryTotal = me.getParam("memory-total");
Long memoryTotal = Long.parseLong(sMemoryTotal);
String sMemoryAvailable = me.getParam("memory-available");
Long memoryAvailable = Long.parseLong(sMemoryAvailable);
Long memoryUsed = memoryTotal - memoryAvailable;
String sMemoryUsed = String.valueOf(memoryUsed);
String sCpuIdleLoad = me.getParam("cpu-idle-load");
String sCpuUserLoad = me.getParam("cpu-user-load");
String sCpuNiceLoad = me.getParam("cpu-nice-load");
String sCpuSysLoad = me.getParam("cpu-sys-load");
float cpuIdleLoad = Float.parseFloat(sCpuIdleLoad);
float cpuUserLoad = Float.parseFloat(sCpuUserLoad);
float cpuNiceLoad = Float.parseFloat(sCpuNiceLoad);
float cpuSysLoad = Float.parseFloat(sCpuSysLoad);
float cpuTotalLoad = cpuIdleLoad + cpuUserLoad + cpuNiceLoad + cpuSysLoad;
String smemoryUsed = String.valueOf(memoryUsed / 1024 / 1024);
//String sCpuTotalLoad = String.valueOf(cpuTotalLoad);
boolean loadIsSane = false;
if (cpuTotalLoad == 100.0) {
loadIsSane = true;
}
//logger.info("MEM USED = " + smemoryUsed + " sTotalLoad = " + sCpuTotalLoad + " isSane = " + loadIsSane);
//String header = "ts,cpu-idle-load,cpu-user-load,cpu-nice-load,cpu-sys-load,cpu-core-count-physical,cpu-core-count-logical,cpu-core-load,load-sane,memory-total,memory-available,memory-used,process-phase\n";
String output = System.currentTimeMillis() + "," + sCpuIdleLoad + "," + sCpuUserLoad + "," + sCpuNiceLoad + "," + sCpuSysLoad + "," + sCoreCountp + "," + sCoreCountl + "," + sCputPerLoadGrp + "," + String.valueOf(loadIsSane) + "," + sMemoryTotal + "," + sMemoryAvailable + "," + sMemoryUsed + "," + stagePhase + "\n";
results.append(output);
/*String logPath = plugin.getConfig().getStringParam("perflogpath");
if (logPath != null) {
try {
Path logpath = Paths.get(logPath);
//output += "\n";
if (!logpath.toFile().exists()) {
Files.write(logpath, header.getBytes(), StandardOpenOption.CREATE);
Files.write(logpath, output.getBytes(), StandardOpenOption.APPEND);
} else {
Files.write(logpath, output.getBytes(), StandardOpenOption.APPEND);
}
} catch (Exception e) {
logger.error("Error Static Runner " + e.getMessage());
e.printStackTrace();
//exception handling left as an exercise for the reader
}
}*/
} else {
logger.error("PerfTracker logPerf() : me = null");
}
}
}
public void executeCommand(String inDir, String outDir, boolean trackPerf) {
pstep = 3;
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
pt = new PerfTracker();
new Thread(pt).start();
}
//String command = "docker run -t -v /home/gpackage:/gpackage -v /home/gdata/input/160427_D00765_0033_AHKM2CBCXX/Sample3:/gdata/input -v /home/gdata/output/f8de921b-fdfa-4365-bf7d-39817b9d1883:/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
//String command = "docker run -t -v /home/gpackage:/gpackage -v " + tmpInput + ":/gdata/input -v " + tmpOutput + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
String command = "docker run -t -v /home/gpackage:/gpackage -v " + inDir + ":/gdata/input -v " + outDir + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
StringBuffer output = new StringBuffer();
StringBuffer error = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
long difftime = System.currentTimeMillis();
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
String[] outputStr = outputLine.split("\\|\\|");
//System.out.println(outputStr.length + ": " + outputLine);
//for(String str : outputStr) {
//System.out.println(outputStr.length + " " + str);
//}
for (int i = 0; i < outputStr.length; i++) {
outputStr[i] = outputStr[i].trim();
}
if ((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) || (outputLine.toLowerCase().startsWith("error")))) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
cal.setTime(sdf.parse(outputStr[1].trim()));// all done
long logdiff = (cal.getTimeInMillis() - difftime);
difftime = cal.getTimeInMillis();
if (outputStr[0].toLowerCase().equals("info")) {
//logger.info("Log diff = " + logdiff + " : " + outputStr[2] + " : " + outputStr[3] + " : " + outputStr[4]);
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
logger.error("Pipeline Error : " + outputLine.toString());
}
}
logger.debug(outputLine);
}
/*
if (!output.toString().equals("")) {
//INFO : Mon May 9 20:35:42 UTC 2016 : UKHC Genomics pipeline V-1.0 : run_secondary_analysis.pl : Module Function run_locally() - execution successful
logger.info(output.toString());
// clog.info(output.toString());
}
BufferedReader errorFeed = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String errorLine;
while ((errorLine = errorFeed.readLine()) != null) {
error.append(errorLine);
logger.error(errorLine);
}
if (!error.toString().equals(""))
logger.error(error.toString());
// clog.error(error.toString());
*/
p.waitFor();
if (trackPerf) {
pt.isActive = false;
}
} catch (IOException ioe) {
// WHAT!?! DO SOMETHIN'!
logger.error(ioe.getMessage());
} catch (InterruptedException ie) {
// WHAT!?! DO SOMETHIN'!
logger.error(ie.getMessage());
} catch (Exception e) {
// WHAT!?! DO SOMETHIN'!
logger.error(e.getMessage());
}
pstep = 2;
}
public void processSample(String seqId, String sampleId, String reqId, boolean trackPerf) {
logger.debug("Call to processSample seq_id: {}, sample_id: {}, req_id: {}", seqId, sampleId, reqId);
pstep = 3;
String results_bucket_name = plugin.getConfig().getStringParam("results_bucket");
if (results_bucket_name == null || results_bucket_name.equals("")) {
logger.error("Configuration value [results_bucket] is not properly set, halting agent");
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Configuration value [results_bucket] is not properly set");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("sample_id", sampleId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("ssstep", "0");
plugin.sendMsgEvent(error);
plugin.PathProcessorActive = false;
return;
}
MsgEvent pse;
int ssstep = 1;
String workDirName = null;
try {
workDirName = incoming_directory; //create random tmp location
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
File workDir = new File(workDirName);
if (workDir.exists()) {
deleteDirectory(workDir);
}
workDir.mkdir();
String remoteDir = seqId + "/" + sampleId + "/";
ObjectEngine oe = new ObjectEngine(plugin);
oe.createBucket(results_bucket_name);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
oe.downloadDirectory(bucket_name, remoteDir, workDirName, seqId, sampleId);
workDirName += remoteDir;
File commands_main = new File(workDirName + "commands_main.sh");
if (!commands_main.exists()) {
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Commands file is missing from download");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("sample_id", sampleId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(error);
return;
}
commands_main.setExecutable(true);
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
/*
filterList.add(transfer_status_file);
String inDir = incoming_directory;
if (!inDir.endsWith("/")) {
inDir = inDir + "/";
}
*/
//logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, workDirName, filterList)) {
ssstep = 2;
logger.debug("Directory Sycned [inDir = {}]", workDirName);
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
ssstep = 3;
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", ex.getMessage());
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
//if is makes it through process the sample
if (ssstep == 3) {
try {
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
logger.trace("Starting performance monitoring");
pt = new PerfTracker();
new Thread(pt).start();
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Creating output directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
String resultDirName = outgoing_directory; //create random tmp location
resultDirName = resultDirName.replace("//", "/");
if (!resultDirName.endsWith("/")) {
resultDirName += "/";
}
File resultDir = new File(resultDirName);
if (resultDir.exists()) {
deleteDirectory(resultDir);
}
logger.trace("Creating output directory: {}", resultDirName);
resultDir.mkdir();
ssstep = 4;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Starting Pipeline via Docker Container");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
String containerName = "procsam." + sampleId.replace("/", ".");
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Thread.sleep(500);
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
String command = "docker run -t -v /mnt/localdata/gpackage:/gpackage " +
"-v " + workDirName + ":/gdata/input " +
"-v " + resultDirName + ":/gdata/output " +
"--name procsam." + sampleId.replace("/", ".") + " " +
"intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
logger.trace("Running Docker Command: {}", command);
StringBuilder output = new StringBuilder();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
logger.trace("Attaching output reader");
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
output.append("\n");
String[] outputStr = outputLine.split("\\|\\|");
for (int i = 0; i < outputStr.length; i++) {
outputStr[i] = outputStr[i].trim();
}
if ((outputStr.length == 5) &&
((outputLine.toLowerCase().startsWith("info")) ||
(outputLine.toLowerCase().startsWith("error")))) {
if (outputStr[0].toLowerCase().equals("info")) {
if (!stagePhase.equals(outputStr[3])) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline now in phase " + outputStr[3]);
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
logger.error("Pipeline Error : " + outputLine);
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
pse.setParam("error_message", outputLine);
plugin.sendMsgEvent(pse);
}
}
logger.debug(outputLine);
}
logger.trace("Waiting for Docker process to finish");
p.waitFor();
logger.trace("Docker exit code = {}", p.exitValue());
if (trackPerf) {
logger.trace("Ending Performance Monitor");
pt.isActive = false;
logger.trace("Sending Performance Information");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Performance Information");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
pse.setParam("perf_log", pt.getResults());
plugin.sendMsgEvent(pse);
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Pipeline Output");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
pse.setParam("output_log", output.toString());
plugin.sendMsgEvent(pse);
} catch (IOException ioe) {
// WHAT!?! DO SOMETHIN'!
logger.error("File read/write exception: {}", ioe.getMessage());
} catch (InterruptedException ie) {
// WHAT!?! DO SOMETHIN'!
logger.error("Process was interrupted: {}", ie.getMessage());
} catch (Exception e) {
// WHAT!?! DO SOMETHIN'!
logger.error("Exception: {}", e.getMessage());
}
logger.trace("Pipeline has finished");
Thread.sleep(2000);
if (p != null) {
switch (p.exitValue()) {
case 0: // Container finished successfully
ssstep = 5;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline has completed");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
ObjectEngine oe = new ObjectEngine(plugin);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Cleaning out old results from Object Store");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
oe.deleteBucketDirectoryContents(results_bucket_name, sampleId + "/");
logger.trace("Uploading results to objectStore");
ssstep = 6;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Uploading Results Directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
oe.uploadSampleDirectory(results_bucket_name, resultDirName, "", seqId, sampleId, String.valueOf(ssstep));
List<String> filterList = new ArrayList<>();
filterList.add("pipeline_log.txt");
logger.trace("Add [transfer_status_file] to [filterList]");
logger.trace("Sleeping to ensure completion message is received last");
Thread.sleep(2000);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(results_bucket_name, "", resultDirName, filterList)) {
ssstep = 7;
logger.debug("Results Directory Sycned [inDir = {}]", resultDirName);
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Results Directory Transferred");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
break;
case 1: // Container error encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "General Docker Error Encountered (Err: 1)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 100: // Script failure encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Processing Pipeline encountered an error (Err: 100)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 125: // Container failed to run
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container failed to run (Err: 125)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 126: // Container command cannot be invoked
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command failed to be invoked (Err: 126)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 127: // Container command cannot be found
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command could not be found (Err: 127)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 137: // Container was killed
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container was manually stopped (Err: 137)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
default: // Other return code encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Unknown container return code (Err: " + p.exitValue() + ")");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
}
} else {
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error retrieving exit code of container");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
Thread.sleep(500);
Process postClear = Runtime.getRuntime().exec("docker rm " + containerName);
postClear.waitFor();
} catch (Exception e) {
logger.error("processSample {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
}
pstep = 2;
}
public void endProcessSample(String seqId, String sampleId, String reqId) {
MsgEvent pse;
try {
String containerName = "procsam." + sampleId.replace("/", ".");
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Thread.sleep(500);
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
if (kill.exitValue() == 0) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pre-processing canceled");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
} catch (Exception e) {
logger.error("processSequence {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("ssstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
}
public void downloadResults(String seqId, String reqId) {
logger.debug("Call to downloadResults seq_id: " + seqId, ", req_id: " + reqId);
pstep = 3;
int sstep = 1;
String remoteDir = seqId + "/";
MsgEvent pse;
try {
String workDirName = incoming_directory; //create random tmp location
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
/*
filterList.add(transfer_status_file);
String inDir = incoming_directory;
if (!inDir.endsWith("/")) {
inDir = inDir + "/";
}
//workDirName += remoteDir;
*/
File seqDir = new File(workDirName + seqId);
if (seqDir.exists()) {
deleteDirectory(seqDir);
}
//workDir.mkdir();
ObjectEngine oe = new ObjectEngine(plugin);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 2;
oe.downloadDirectory(bucket_name, remoteDir, workDirName, seqId, null);
//logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, workDirName + seqId, filterList)) {
logger.debug("Directory Sycned [inDir = {}]", workDirName);
//Map<String, String> md5map = oe.getDirMD5(inDir, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(inDir + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered");
pse.setParam("indir", workDirName);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 3;
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", ex.getMessage());
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
pstep = 2;
}
private String getSampleList(String inDir) {
String sampleList = null;
try {
if (!inDir.endsWith("/")) {
inDir += "/";
}
ArrayList<String> samples = new ArrayList();
logger.trace("Processing Sequence Directory : " + inDir);
File file = new File(inDir);
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
List<String> subDirectories = new ArrayList<>();
if (directories != null) {
for (String subDir : directories) {
logger.trace("Searching for sub-directories of {}", inDir + subDir);
subDirectories.add(subDir);
File subFile = new File(inDir + "/" + subDir);
String[] subSubDirs = subFile.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
if (subSubDirs != null) {
for (String subSubDir : subSubDirs) {
logger.trace("Found sub-directory {}", inDir + subDir + "/" + subSubDir);
subDirectories.add(subDir + "/" + subSubDir);
}
}
}
}
for (String subDirectory : subDirectories) {
logger.trace("Processing Sample SubDirectory : " + subDirectory);
String commands_main_filename = inDir + subDirectory + "/commands_main.sh";
String config_files_directoryname = inDir + subDirectory + "/config_files";
File commands_main = new File(commands_main_filename);
File config_files = new File(config_files_directoryname);
logger.trace("commands_main " + commands_main_filename + " exist : " + commands_main.exists());
logger.trace("config_files " + config_files_directoryname + " exist : " + config_files.exists());
if (commands_main.exists() && !commands_main.isDirectory() &&
config_files.exists() && config_files.isDirectory()) {
// do something
samples.add(subDirectory);
logger.trace("Found Sample: " + commands_main_filename + " and " + config_files_directoryname);
}
}
//build list
if (!samples.isEmpty()) {
sampleList = "";
for (String tSample : samples) {
sampleList += tSample + ",";
}
sampleList = sampleList.substring(0, sampleList.length() - 1);
}
} catch (Exception ex) {
logger.error("getSameplList : " + ex.getMessage());
}
return sampleList;
}
private void sendUpdateInfoMessage(String seqId, String sampleId, String reqId, String step, String message) {
if (!message.equals("Idle"))
logger.info("{}", message);
MsgEvent msgEvent = plugin.genGMessage(MsgEvent.Type.INFO, message);
msgEvent.setParam("pathstage", String.valueOf(plugin.pathStage));
msgEvent.setParam("seq_id", seqId);
if (sampleId != null) {
msgEvent.setParam("sample_id", sampleId);
msgEvent.setParam("ssstep", step);
} else if (seqId != null)
msgEvent.setParam("sstep", step);
else
msgEvent.setParam("pstep", step);
if (reqId != null)
msgEvent.setParam("req_id", reqId);
plugin.sendMsgEvent(msgEvent);
}
private void sendUpdateErrorMessage(String seqId, String sampleId, String reqId, String step, String message) {
logger.error("{}", message);
MsgEvent msgEvent = plugin.genGMessage(MsgEvent.Type.ERROR, "");
msgEvent.setParam("pathstage", String.valueOf(plugin.pathStage));
msgEvent.setParam("error_message", message);
msgEvent.setParam("seq_id", seqId);
if (sampleId != null) {
msgEvent.setParam("sample_id", sampleId);
msgEvent.setParam("ssstep", step);
} else if (seqId != null)
msgEvent.setParam("sstep", step);
else
msgEvent.setParam("pstep", step);
if (reqId != null)
msgEvent.setParam("req_id", reqId);
plugin.sendMsgEvent(msgEvent);
}
/*
private void legacy() {
logger.trace("Thread starting");
try {
logger.trace("Setting [PathProcessorActive] to true");
plugin.PathProcessorActive = true;
ObjectEngine oe = new ObjectEngine(plugin);
logger.trace("Entering while-loop");
while (plugin.PathProcessorActive) {
me = plugin.genGMessage(MsgEvent.Type.INFO,"Start Object Scan");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("pstep","2");
plugin.sendMsgEvent(me);
try {
//oe.deleteBucketContents(bucket_name);
logger.trace("Populating [remoteDirs]");
List<String> remoteDirs = oe.listBucketDirs(bucket_name);
for(String remoteDir : remoteDirs) {
logger.trace("Remote Dir : " + remoteDir);
}
logger.trace("Populating [localDirs]");
List<String> localDirs = getWalkPath(incoming_directory);
for(String localDir : localDirs) {
logger.trace("Local Dir : " + localDir);
}
List<String> newDirs = new ArrayList<>();
for (String remoteDir : remoteDirs) {
logger.trace("Checking for existance of RemoteDir [" + remoteDir + "] locally");
if (!localDirs.contains(remoteDir)) {
logger.trace("RemoteDir [" + remoteDir + "] does not exist locally");
if (oe.doesObjectExist(bucket_name, remoteDir + transfer_watch_file)) {
logger.debug("Adding [remoteDir = {}] to [newDirs]", remoteDir);
newDirs.add(remoteDir);
}
}
}
if (!newDirs.isEmpty()) {
logger.trace("[newDirs] has buckets to process");
processBucket(newDirs);
}
Thread.sleep(30000);
} catch (Exception ex) {
logger.error("run : while {}", ex.getMessage());
me = plugin.genGMessage(MsgEvent.Type.ERROR,"Error during Object scan");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("error_message",ex.getMessage());
me.setParam("pstep","2");
plugin.sendMsgEvent(me);
}
//message end of scan
me = plugin.genGMessage(MsgEvent.Type.INFO,"End Object Scan");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("pstep","3");
plugin.sendMsgEvent(me);
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
me = plugin.genGMessage(MsgEvent.Type.ERROR,"Error Path Run");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("error_message",ex.getMessage());
me.setParam("pstep","2");
plugin.sendMsgEvent(me);
}
}
private void processBucket(List<String> newDirs) {
logger.debug("Call to processBucket [newDir = {}]", newDirs.toString());
ObjectEngine oe = new ObjectEngine(plugin);
for (String remoteDir : newDirs) {
logger.debug("Downloading directory {} to [incoming_directory]", remoteDir);
String seqId = remoteDir.substring(remoteDir.lastIndexOf("/") + 1, remoteDir.length());
me = plugin.genGMessage(MsgEvent.Type.INFO,"Directory Transfered");
me.setParam("inDir", remoteDir);
me.setParam("outDir", incoming_directory);
me.setParam("seq_id", seqId);
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("sstep","1");
plugin.sendMsgEvent(me);
oe.downloadDirectory(bucket_name, remoteDir, incoming_directory);
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
filterList.add(transfer_status_file);
String inDir = incoming_directory;
if (!inDir.endsWith("/")) {
inDir = inDir + "/";
}
inDir = inDir + remoteDir;
logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, inDir, filterList)) {
logger.debug("Directory Sycned [inDir = {}]", inDir);
Map<String, String> md5map = oe.getDirMD5(inDir, filterList);
logger.trace("Set MD5 hash");
setTransferFileMD5(inDir + transfer_status_file, md5map);
me = plugin.genGMessage(MsgEvent.Type.INFO,"Directory Transfered");
me.setParam("indir", inDir);
me.setParam("outdir", remoteDir);
me.setParam("seq_id", seqId);
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("sstep","2");
plugin.sendMsgEvent(me);
}
}
}
*/
private void setTransferFileMD5(String dir, Map<String, String> md5map) {
logger.debug("Call to setTransferFileMD5 [dir = {}]", dir);
try {
PrintWriter out = null;
try {
logger.trace("Opening [dir] to write");
out = new PrintWriter(new BufferedWriter(new FileWriter(dir, true)));
for (Map.Entry<String, String> entry : md5map.entrySet()) {
String md5file = entry.getKey().replace(incoming_directory, "");
if (md5file.startsWith("/")) {
md5file = md5file.substring(1);
}
out.write(md5file + ":" + entry.getValue() + "\n");
logger.debug("[md5file = {}, entry = {}] written", md5file, entry.getValue());
}
} finally {
try {
assert out != null;
out.flush();
out.close();
} catch (AssertionError e) {
logger.error("setTransferFileMd5 - PrintWriter was pre-emptively shutdown");
}
}
} catch (Exception ex) {
logger.error("setTransferFile {}", ex.getMessage());
}
}
/*private List<String> getWalkPath(String path) {
logger.debug("Call to getWalkPath [path = {}]", path);
if (!path.endsWith("/")) {
path = path + "/";
}
List<String> dirList = new ArrayList<>();
File root = new File(path);
File[] list = root.listFiles();
if (list == null) {
logger.trace("[list] is null, returning [dirList (empty array)]");
return dirList;
}
for (File f : list) {
if (f.isDirectory()) {
//walkPath( f.getAbsolutePath() );
String dir = f.getAbsolutePath().replace(path, "");
logger.debug("Adding \"{}/\" to [dirList]", dir);
dirList.add(dir + "/");
}
}
return dirList;
}*/
}
| src/main/java/com/researchworx/cresco/plugins/gobjectIngestion/folderprocessor/ObjectFS.java | package com.researchworx.cresco.plugins.gobjectIngestion.folderprocessor;
import com.researchworx.cresco.library.messaging.MsgEvent;
import com.researchworx.cresco.library.utilities.CLogger;
import com.researchworx.cresco.plugins.gobjectIngestion.Plugin;
import com.researchworx.cresco.plugins.gobjectIngestion.objectstorage.Encapsulation;
import com.researchworx.cresco.plugins.gobjectIngestion.objectstorage.ObjectEngine;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class ObjectFS implements Runnable {
private final String transfer_watch_file;
private final String transfer_status_file;
private String bucket_name;
private String incoming_directory;
private String outgoing_directory;
private Plugin plugin;
private CLogger logger;
private String pathStage;
private int pstep;
private String stagePhase;
public ObjectFS(Plugin plugin) {
this.stagePhase = "uninit";
this.pstep = 1;
this.plugin = plugin;
this.logger = new CLogger(ObjectFS.class, plugin.getMsgOutQueue(), plugin.getRegion(), plugin.getAgent(), plugin.getPluginID(), CLogger.Level.Trace);
this.pathStage = String.valueOf(plugin.pathStage);
logger.debug("OutPathPreProcessor Instantiated");
incoming_directory = plugin.getConfig().getStringParam("incoming_directory");
logger.debug("\"pathstage" + pathStage + "\" --> \"incoming_directory\" from config [{}]", incoming_directory);
outgoing_directory = plugin.getConfig().getStringParam("outgoing_directory");
logger.debug("\"pathstage" + pathStage + "\" --> \"outgoing_directory\" from config [{}]", outgoing_directory);
transfer_status_file = plugin.getConfig().getStringParam("transfer_status_file");
logger.debug("\"pathstage" + pathStage + "\" --> \"transfer_status_file\" from config [{}]", transfer_status_file);
transfer_watch_file = plugin.getConfig().getStringParam("transfer_watch_file");
logger.debug("\"pathstage" + pathStage + "\" --> \"transfer_watch_file\" from config [{}]", transfer_watch_file);
bucket_name = plugin.getConfig().getStringParam("bucket");
logger.debug("\"pathstage" + pathStage + "\" --> \"bucket\" from config [{}]", bucket_name);
MsgEvent me = plugin.genGMessage(MsgEvent.Type.INFO, "InPathPreProcessor instantiated");
//me.setParam("transfer_watch_file", transfer_watch_file);
//me.setParam("transfer_status_file", transfer_status_file);
//me.setParam("bucket_name", bucket_name);
me.setParam("pathstage", pathStage);
//me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pstep", String.valueOf(pstep));
plugin.sendMsgEvent(me);
}
@Override
public void run() {
try {
pstep = 2;
logger.trace("Setting [PathProcessorActive] to true");
plugin.PathProcessorActive = true;
logger.trace("Entering while-loop");
while (plugin.PathProcessorActive) {
sendUpdateInfoMessage(null, null, null, String.valueOf(pstep), "Idle");
Thread.sleep(plugin.getConfig().getIntegerParam("scan_interval", 5000));
}
} catch (Exception e) {
sendUpdateErrorMessage(null, null, null, String.valueOf(pstep),
String.format("General Run Exception [%s:%s]", e.getClass().getCanonicalName(), e.getMessage()));
}
}
public void processBaggedSequence(String seqId, String reqId, boolean trackPerf) {
logger.debug("processBaggedSequence('{}','{}',{})", seqId, reqId, trackPerf);
ObjectEngine oe = new ObjectEngine(plugin);
pstep = 3;
int sstep = 0;
String clinical_bucket_name = plugin.getConfig().getStringParam("clinical_bucket");
logger.trace("Checking to see if clinical bucket [{}] exists", clinical_bucket_name);
if (clinical_bucket_name == null || clinical_bucket_name.equals("") ||
!oe.doesBucketExist(clinical_bucket_name)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Clinical bucket [%s] does not exist",
clinical_bucket_name != null ? clinical_bucket_name : "NULL"));
plugin.PathProcessorActive = false;
return;
}
String research_bucket_name = plugin.getConfig().getStringParam("research_bucket");
logger.trace("Checking to see if research bucket [{}] exists", research_bucket_name);
if (research_bucket_name == null || research_bucket_name.equals("") ||
!oe.doesBucketExist(research_bucket_name)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Research bucket [%s] does not exist",
research_bucket_name != null ? research_bucket_name : "NULL"));
plugin.PathProcessorActive = false;
return;
}
sstep = 1;
String remoteDir = seqId;
MsgEvent pse;
String workDirName = null;
try {
workDirName = incoming_directory;
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
File workDir = new File(workDirName);
/*if (workDir.exists()) {
if (!deleteDirectory(workDir))
logger.error("deleteDirectory('{}') = false", workDir.getAbsolutePath());
}
if (!workDir.mkdir())*/
logger.error("workDir.mkdir() = false (workDir = '{}')", workDir.getAbsolutePath());
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Retrieving bagged sequence");
sstep = 2;
if (true /*oe.downloadBaggedDirectory(bucket_name, remoteDir, workDirName, seqId, null, reqId,
String.valueOf(sstep))*/) {
String baggedSequenceFile = workDirName + seqId + ".tar";
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Download successful, unboxing sequence file [%s]", baggedSequenceFile));
/*if (!Encapsulation.unBoxIt(baggedSequenceFile)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Failed to unbox sequence file [%s]", baggedSequenceFile));
pstep = 2;
return;
}
if (!new File(unboxed).exists() || !new File(unboxed).isDirectory()) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unboxing to [%s] failed", unboxed));
pstep = 2;
return;
}*/
/*try (TarArchiveInputStream fin = new TarArchiveInputStream(new FileInputStream(baggedSequenceFile))) {
TarArchiveEntry entry;
while ((entry = fin.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
File curfile = new File(workDir, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
IOUtils.copy(fin, new FileOutputStream(curfile));
}
}*/
Encapsulation.decompress(baggedSequenceFile, workDir);
String unboxed = workDirName + seqId + "/";
logger.trace("unBoxIt result: {}, deleting TAR file", unboxed);
//new File(baggedSequenceFile).delete();
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Validating sequence [%s]", unboxed));
if (!Encapsulation.isBag(unboxed)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unboxed sequence [%s] does not contain BagIt data", unboxed));
pstep = 2;
return;
}
if (!Encapsulation.verifyBag(unboxed, true)) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unboxed sequence [%s] failed BagIt verification", unboxed));
pstep = 2;
return;
}
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Restoring sequence [%s]", unboxed));
Encapsulation.debagify(unboxed);
workDirName = unboxed;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Sequence [%s] restored to [%s]", seqId, unboxed));
sstep = 3;
}
} catch (Exception e) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Exception encountered: [%s:%s]", e.getClass().getCanonicalName(), e.getMessage()));
}
/*if (sstep == 3) {
try {
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
logger.trace("Starting performance monitoring");
pt = new PerfTracker();
new Thread(pt).start();
}
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Creating output directory");
String resultDirName = outgoing_directory; //create random tmp location
logger.trace("Clearing/resetting output directory");
resultDirName = resultDirName.replace("//", "/");
if (!resultDirName.endsWith("/")) {
resultDirName += "/";
}
File resultDir = new File(resultDirName);
if (resultDir.exists()) {
deleteDirectory(resultDir);
}
logger.trace("Creating output directory: {}", resultDirName);
resultDir.mkdir();
String clinicalResultsDirName = resultDirName + "clinical/";
if (new File(clinicalResultsDirName).exists())
deleteDirectory(new File(clinicalResultsDirName));
new File(clinicalResultsDirName).mkdir();
String researchResultsDirName = resultDirName + "research/";
if (new File(researchResultsDirName).exists())
deleteDirectory(new File(researchResultsDirName));
new File(researchResultsDirName).mkdir();
sstep = 4;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Starting Pre-Processing via Docker Container");
String containerName = "procseq." + seqId;
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
String command = "docker run " +
"-v " + researchResultsDirName + ":/gdata/output/research " +
"-v " + clinicalResultsDirName + ":/gdata/output/clinical " +
"-v " + workDirName + ":/gdata/input " +
"-e INPUT_FOLDER_PATH=/gdata/input/" + remoteDir + " " +
"--name " + containerName + " " +
"-t intrepo.uky.edu:5000/gbase /opt/pretools/raw_data_processing.pl";
logger.trace("Running Docker Command: {}", command);
StringBuilder output = new StringBuilder();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
logger.trace("Attaching output reader");
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
output.append("\n");
String[] outputStr = outputLine.split("\\|\\|");
for (int i = 0; i < outputStr.length; i++)
outputStr[i] = outputStr[i].trim();
if ((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) ||
(outputLine.toLowerCase().startsWith("error")))) {
if (outputStr[0].toLowerCase().equals("info")) {
if (!stagePhase.equals(outputStr[3])) {
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Pipeline now in phase %s", outputStr[3]));
}
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Pre-Processing error: %s", outputLine));
}
}
logger.debug(outputLine);
}
logger.trace("Waiting for Docker process to finish");
p.waitFor();
logger.trace("Docker Exit Code: {}", p.exitValue());
if (trackPerf) {
logger.trace("Ending Performance Monitor");
pt.isActive = false;
logger.trace("Sending Performance Information");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Performance Information");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("perf_log", pt.getResults());
plugin.sendMsgEvent(pse);
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Pipeline Output");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("output_log", output.toString());
plugin.sendMsgEvent(pse);
} catch (IOException ioe) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("File read/write exception [%s:%s]",
ioe.getClass().getCanonicalName(), ioe.getMessage()));
} catch (InterruptedException ie) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Process was interrupted [%s:%s]",
ie.getClass().getCanonicalName(), ie.getMessage()));
} catch (Exception e) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Exception [%s:%s]",
e.getClass().getCanonicalName(), e.getMessage()));
}
logger.trace("Pipeline has finished");
Thread.sleep(2000);
if (p != null) {
switch (p.exitValue()) {
case 0: // Container finished successfully
sstep = 5;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Pipeline has completed");
sstep = 6;
if (new File(resultDirName + "clinical/" + seqId + "/").exists()) {
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Transferring Clinical Results Directory");
if (oe.uploadBaggedDirectory(clinical_bucket_name, resultDirName + "clinical/" +
seqId + "/", seqId, seqId, null, reqId, String.valueOf(sstep))) {
sstep = 7;
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
logger.trace("Sample Directory: " + resultDirName + "clinical/" +
seqId + "/");
String sampleList = getSampleList(resultDirName + "clinical/" + seqId + "/");
pse = plugin.genGMessage(MsgEvent.Type.INFO,
"Clinical Results Directory Transfer Complete");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
if (sampleList != null) {
logger.trace("Samples : " + sampleList);
pse.setParam("sample_list", sampleList);
} else {
pse.setParam("sample_list", "");
}
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
}
if (new File(resultDirName + "research/" + seqId + "/").exists()) {
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Transferring Research Results Directory");
if (oe.uploadBaggedDirectory(research_bucket_name, resultDirName + "research/" +
seqId + "/", seqId, seqId, null, reqId, String.valueOf(sstep))) {
sstep = 8;
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
pse = plugin.genGMessage(MsgEvent.Type.INFO,
"Research Results Directory Transferred");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
}
sstep = 9;
sendUpdateInfoMessage(seqId, null, reqId, String.valueOf(sstep),
"Pre-processing is complete");
break;
case 1: // Container error encountered
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"General Docker error encountered (Err: 1)");
break;
case 100: // Script failure encountered
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Pre-Processor encountered an error (Err: 100)");
break;
case 125: // Container failed to run
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container failed to run (Err: 125)");
break;
case 126: // Container command cannot be invoked
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container command failed to be invoked (Err: 126)");
break;
case 127: // Container command cannot be found
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container command could not be found (Err: 127)");
break;
case 137: // Container was killed
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Container was manually stopped (Err: 137)");
break;
default: // Other return code encountered
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("Unknown container return code (Err: %d)", p.exitValue()));
break;
}
} else {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
"Error retrieving return code from container");
}
Process postClear = Runtime.getRuntime().exec("docker rm " + containerName);
postClear.waitFor();
} catch (Exception e) {
sendUpdateErrorMessage(seqId, null, reqId, String.valueOf(sstep),
String.format("processBaggedSequence exception encountered [%s:%s]",
e.getClass().getCanonicalName(), e.getMessage()));
}
}*/
pstep = 2;
}
public void processSequence(String seqId, String reqId, boolean trackPerf) {
logger.debug("Call to processSequence seq_id: " + seqId, ", req_id: " + reqId);
pstep = 3;
int sstep = 0;
String clinical_bucket_name = plugin.getConfig().getStringParam("clinical_bucket");
if (clinical_bucket_name == null || clinical_bucket_name.equals("")) {
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Configuration value [clinical_bucket] is not properly set");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(error);
plugin.PathProcessorActive = false;
return;
}
String research_bucket_name = plugin.getConfig().getStringParam("research_bucket");
if (research_bucket_name == null || research_bucket_name.equals("")) {
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Configuration value [research_bucket] is not properly set");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(error);
plugin.PathProcessorActive = false;
return;
}
sstep = 1;
String remoteDir = seqId + "/";
MsgEvent pse;
String workDirName = null;
try {
workDirName = incoming_directory; //create random tmp location
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
File workDir = new File(workDirName);
if (workDir.exists()) {
deleteDirectory(workDir);
}
workDir.mkdir();
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
ObjectEngine oe = new ObjectEngine(plugin);
if (new File(workDirName + seqId).exists()) {
deleteDirectory(new File(workDirName + seqId));
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 2;
oe.downloadDirectory(bucket_name, remoteDir, workDirName, seqId, null);
//logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, workDirName + seqId, filterList)) {
logger.debug("Directory Sycned [inDir = {}]", workDirName);
//Map<String, String> md5map = oe.getDirMD5(inDir, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(inDir + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered");
pse.setParam("indir", workDirName);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 3;
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", ex.getMessage());
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
//if is makes it through process the seq
if (sstep == 3) {
try {
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
logger.trace("Starting performance monitoring");
pt = new PerfTracker();
new Thread(pt).start();
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Creating output directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
String resultDirName = outgoing_directory; //create random tmp location
logger.trace("Clearing/resetting output directory");
resultDirName = resultDirName.replace("//", "/");
if (!resultDirName.endsWith("/")) {
resultDirName += "/";
}
File resultDir = new File(resultDirName);
if (resultDir.exists()) {
deleteDirectory(resultDir);
}
logger.trace("Creating output directory: {}", resultDirName);
resultDir.mkdir();
String clinicalResultsDirName = resultDirName + "clinical/";
if (new File(clinicalResultsDirName).exists())
deleteDirectory(new File(clinicalResultsDirName));
new File(clinicalResultsDirName).mkdir();
String researchResultsDirName = resultDirName + "research/";
if (new File(researchResultsDirName).exists())
deleteDirectory(new File(researchResultsDirName));
new File(researchResultsDirName).mkdir();
sstep = 4;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Starting Pre-Processor via Docker Container");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
String containerName = "procseq." + seqId;
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
String command = "docker run " +
"-v " + researchResultsDirName + ":/gdata/output/research " +
"-v " + clinicalResultsDirName + ":/gdata/output/clinical " +
"-v " + workDirName + ":/gdata/input " +
"-e INPUT_FOLDER_PATH=/gdata/input/" + remoteDir + " " +
"--name " + containerName + " " +
"-t intrepo.uky.edu:5000/gbase /opt/pretools/raw_data_processing.pl";
logger.trace("Running Docker Command: {}", command);
StringBuilder output = new StringBuilder();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
logger.trace("Attaching output reader");
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
output.append("\n");
String[] outputStr = outputLine.split("\\|\\|");
for (int i = 0; i < outputStr.length; i++) {
outputStr[i] = outputStr[i].trim();
}
if ((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) || (outputLine.toLowerCase().startsWith("error")))) {
if (outputStr[0].toLowerCase().equals("info")) {
if (!stagePhase.equals(outputStr[3])) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline now in phase " + outputStr[3]);
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
logger.error("Pre-Processing Error : " + outputLine);
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("error_message", outputLine);
plugin.sendMsgEvent(pse);
}
}
logger.debug(outputLine);
}
logger.trace("Waiting for Docker process to finish");
p.waitFor();
logger.trace("Docker Exit Code: {}", p.exitValue());
if (trackPerf) {
logger.trace("Ending Performance Monitor");
pt.isActive = false;
logger.trace("Sending Performance Information");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Performance Information");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("perf_log", pt.getResults());
plugin.sendMsgEvent(pse);
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Pipeline Output");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
pse.setParam("output_log", output.toString());
plugin.sendMsgEvent(pse);
} catch (IOException ioe) {
// WHAT!?! DO SOMETHIN'!
logger.error("File read/write exception: {}", ioe.getMessage());
} catch (InterruptedException ie) {
// WHAT!?! DO SOMETHIN'!
logger.error("Process was interrupted: {}", ie.getMessage());
} catch (Exception e) {
// WHAT!?! DO SOMETHIN'!
logger.error("Exception: {}", e.getMessage());
}
logger.trace("Pipeline has finished");
Thread.sleep(2000);
if (p != null) {
switch (p.exitValue()) {
case 0: // Container finished successfully
sstep = 5;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline has completed");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
ObjectEngine oe = new ObjectEngine(plugin);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Deleting old pre-processed files from Object Store");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
logger.trace("Deleting old clinical files");
oe.deleteBucketDirectoryContents(clinical_bucket_name, seqId);
logger.trace("Deleting old research files");
oe.deleteBucketDirectoryContents(research_bucket_name, seqId);
logger.trace("Uploading results to objectStore");
sstep = 6;
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
logger.trace("Transferring Clinical Results Directory");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Transferring Clinical Results Directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
oe.uploadSequenceDirectory(clinical_bucket_name, resultDirName + "clinical/" + seqId + "/", seqId, seqId, String.valueOf(sstep));
logger.trace("Checking if Clinical Results are Synced Properly");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Checking if Clinical Results are Synced Properly");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 7;
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(clinical_bucket_name, seqId + "/", resultDirName + "clinical/" + seqId + "/", filterList)) {
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
logger.trace("Sample Directory: " + resultDirName + "clinical/" + seqId + "/");
String sampleList = getSampleList(resultDirName + "clinical/" + seqId + "/");
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Clinical Results Directory Transfer Complete");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
if (sampleList != null) {
logger.trace("Samples : " + sampleList);
pse.setParam("sample_list", sampleList);
} else {
pse.setParam("sample_list", "");
}
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
logger.trace("Transferring Research Results Directory");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Transferring Research Results Directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
oe.uploadSequenceDirectory(research_bucket_name, resultDirName + "research/" + seqId + "/", seqId, seqId, String.valueOf(sstep));
logger.trace("Checking if Research Results are Synced Properly");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Checking if Research Results are Synced Properly");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(research_bucket_name, seqId + "/", resultDirName + "research/" + seqId + "/", filterList)) {
logger.debug("Results Directory Sycned [inDir = {}]", resultDir);
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Research Results Directory Transferred");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
logger.trace("Pre-processing is complete");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pre-processing is complete");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 1: // Container error encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "General Docker Error Encountered (Err: 1)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 100: // Script failure encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Pre-processor encountered an error (Err: 100)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 125: // Container failed to run
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container failed to run (Err: 125)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 126: // Container command cannot be invoked
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command failed to be invoked (Err: 126)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 127: // Container command cannot be found
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command could not be found (Err: 127)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
case 137: // Container was killed
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container was manually stopped (Err: 137)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
default: // Other return code encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Unknown container return code (Err: " + p.exitValue() + ")");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
break;
}
} else {
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error retrieving return code from container");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
Process postClear = Runtime.getRuntime().exec("docker rm " + containerName);
postClear.waitFor();
} catch (Exception e) {
logger.error("processSequence {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
}
pstep = 2;
}
public void endProcessSequence(String seqId, String reqId) {
MsgEvent pse;
try {
String containerName = "procseq." + seqId;
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Thread.sleep(500);
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
if (kill.exitValue() == 0) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pre-processing canceled");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
} catch (Exception e) {
logger.error("processSequence {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("sstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
}
private boolean deleteDirectory(File path) {
boolean deleted = true;
if (path.exists()) {
File[] files = path.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory())
deleteDirectory(file);
else if (!file.delete())
deleted = false;
}
}
}
return (path.delete() && deleted);
}
private class PerfTracker extends Thread {
private boolean isActive = false;
private StringBuilder results = new StringBuilder();
PerfTracker() {
isActive = false;
}
public void run() {
try {
results.append("ts,cpu-idle-load,cpu-user-load,cpu-nice-load,cpu-sys-load,cpu-core-count-physical,cpu-core-count-logical,cpu-core-load,load-sane,memory-total,memory-available,memory-used,process-phase\n");
isActive = true;
Long perfRate = plugin.getConfig().getLongParam("perfrate", 5000L);
while (isActive) {
logPerf();
Thread.sleep(perfRate);
}
} catch (Exception ex) {
logger.error("PerfTracker run(): {}", ex.getMessage());
}
}
public String getResults() {
return results.toString();
}
private void logPerf() {
MsgEvent me = plugin.getSysInfo();
if (me != null) {
/*
Iterator it = me.getParams().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
logger.info(pairs.getKey() + " = " + pairs.getValue());
//String plugin = pairs.getKey().toString();
}
*/
//cpu-per-cpu-load = CPU Load per processor: 1.0% 12.0% 8.0% 7.9% 0.0% 0.0% 0.0% 0.0%
//cpu-core-count = 8
//String sCoreCountp = me.getParam("cpu-core-count-physical");
//String sCoreCountl = me.getParam("cpu-core-count-logical");
String sCoreCountp = me.getParam("cpu-core-count");
String sCoreCountl = me.getParam("cpu-core-count");
int pcoreCount = Integer.parseInt(sCoreCountp);
String cpuPerLoad = me.getParam("cpu-per-cpu-load");
cpuPerLoad = cpuPerLoad.substring(cpuPerLoad.indexOf(": ") + 2);
cpuPerLoad = cpuPerLoad.replace("%", "");
String[] perCpu = cpuPerLoad.split(" ");
String sCputPerLoadGrp = "";
for (String cpu : perCpu) {
//logger.info(cpu);
sCputPerLoadGrp += cpu + ":";
}
sCputPerLoadGrp = sCputPerLoadGrp.substring(0, sCputPerLoadGrp.length() - 1);
String sMemoryTotal = me.getParam("memory-total");
Long memoryTotal = Long.parseLong(sMemoryTotal);
String sMemoryAvailable = me.getParam("memory-available");
Long memoryAvailable = Long.parseLong(sMemoryAvailable);
Long memoryUsed = memoryTotal - memoryAvailable;
String sMemoryUsed = String.valueOf(memoryUsed);
String sCpuIdleLoad = me.getParam("cpu-idle-load");
String sCpuUserLoad = me.getParam("cpu-user-load");
String sCpuNiceLoad = me.getParam("cpu-nice-load");
String sCpuSysLoad = me.getParam("cpu-sys-load");
float cpuIdleLoad = Float.parseFloat(sCpuIdleLoad);
float cpuUserLoad = Float.parseFloat(sCpuUserLoad);
float cpuNiceLoad = Float.parseFloat(sCpuNiceLoad);
float cpuSysLoad = Float.parseFloat(sCpuSysLoad);
float cpuTotalLoad = cpuIdleLoad + cpuUserLoad + cpuNiceLoad + cpuSysLoad;
String smemoryUsed = String.valueOf(memoryUsed / 1024 / 1024);
//String sCpuTotalLoad = String.valueOf(cpuTotalLoad);
boolean loadIsSane = false;
if (cpuTotalLoad == 100.0) {
loadIsSane = true;
}
//logger.info("MEM USED = " + smemoryUsed + " sTotalLoad = " + sCpuTotalLoad + " isSane = " + loadIsSane);
//String header = "ts,cpu-idle-load,cpu-user-load,cpu-nice-load,cpu-sys-load,cpu-core-count-physical,cpu-core-count-logical,cpu-core-load,load-sane,memory-total,memory-available,memory-used,process-phase\n";
String output = System.currentTimeMillis() + "," + sCpuIdleLoad + "," + sCpuUserLoad + "," + sCpuNiceLoad + "," + sCpuSysLoad + "," + sCoreCountp + "," + sCoreCountl + "," + sCputPerLoadGrp + "," + String.valueOf(loadIsSane) + "," + sMemoryTotal + "," + sMemoryAvailable + "," + sMemoryUsed + "," + stagePhase + "\n";
results.append(output);
/*String logPath = plugin.getConfig().getStringParam("perflogpath");
if (logPath != null) {
try {
Path logpath = Paths.get(logPath);
//output += "\n";
if (!logpath.toFile().exists()) {
Files.write(logpath, header.getBytes(), StandardOpenOption.CREATE);
Files.write(logpath, output.getBytes(), StandardOpenOption.APPEND);
} else {
Files.write(logpath, output.getBytes(), StandardOpenOption.APPEND);
}
} catch (Exception e) {
logger.error("Error Static Runner " + e.getMessage());
e.printStackTrace();
//exception handling left as an exercise for the reader
}
}*/
} else {
logger.error("PerfTracker logPerf() : me = null");
}
}
}
public void executeCommand(String inDir, String outDir, boolean trackPerf) {
pstep = 3;
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
pt = new PerfTracker();
new Thread(pt).start();
}
//String command = "docker run -t -v /home/gpackage:/gpackage -v /home/gdata/input/160427_D00765_0033_AHKM2CBCXX/Sample3:/gdata/input -v /home/gdata/output/f8de921b-fdfa-4365-bf7d-39817b9d1883:/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
//String command = "docker run -t -v /home/gpackage:/gpackage -v " + tmpInput + ":/gdata/input -v " + tmpOutput + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
String command = "docker run -t -v /home/gpackage:/gpackage -v " + inDir + ":/gdata/input -v " + outDir + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
StringBuffer output = new StringBuffer();
StringBuffer error = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
long difftime = System.currentTimeMillis();
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
String[] outputStr = outputLine.split("\\|\\|");
//System.out.println(outputStr.length + ": " + outputLine);
//for(String str : outputStr) {
//System.out.println(outputStr.length + " " + str);
//}
for (int i = 0; i < outputStr.length; i++) {
outputStr[i] = outputStr[i].trim();
}
if ((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) || (outputLine.toLowerCase().startsWith("error")))) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
cal.setTime(sdf.parse(outputStr[1].trim()));// all done
long logdiff = (cal.getTimeInMillis() - difftime);
difftime = cal.getTimeInMillis();
if (outputStr[0].toLowerCase().equals("info")) {
//logger.info("Log diff = " + logdiff + " : " + outputStr[2] + " : " + outputStr[3] + " : " + outputStr[4]);
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
logger.error("Pipeline Error : " + outputLine.toString());
}
}
logger.debug(outputLine);
}
/*
if (!output.toString().equals("")) {
//INFO : Mon May 9 20:35:42 UTC 2016 : UKHC Genomics pipeline V-1.0 : run_secondary_analysis.pl : Module Function run_locally() - execution successful
logger.info(output.toString());
// clog.info(output.toString());
}
BufferedReader errorFeed = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String errorLine;
while ((errorLine = errorFeed.readLine()) != null) {
error.append(errorLine);
logger.error(errorLine);
}
if (!error.toString().equals(""))
logger.error(error.toString());
// clog.error(error.toString());
*/
p.waitFor();
if (trackPerf) {
pt.isActive = false;
}
} catch (IOException ioe) {
// WHAT!?! DO SOMETHIN'!
logger.error(ioe.getMessage());
} catch (InterruptedException ie) {
// WHAT!?! DO SOMETHIN'!
logger.error(ie.getMessage());
} catch (Exception e) {
// WHAT!?! DO SOMETHIN'!
logger.error(e.getMessage());
}
pstep = 2;
}
public void processSample(String seqId, String sampleId, String reqId, boolean trackPerf) {
logger.debug("Call to processSample seq_id: {}, sample_id: {}, req_id: {}", seqId, sampleId, reqId);
pstep = 3;
String results_bucket_name = plugin.getConfig().getStringParam("results_bucket");
if (results_bucket_name == null || results_bucket_name.equals("")) {
logger.error("Configuration value [results_bucket] is not properly set, halting agent");
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Configuration value [results_bucket] is not properly set");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("sample_id", sampleId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("ssstep", "0");
plugin.sendMsgEvent(error);
plugin.PathProcessorActive = false;
return;
}
MsgEvent pse;
int ssstep = 1;
String workDirName = null;
try {
workDirName = incoming_directory; //create random tmp location
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
File workDir = new File(workDirName);
if (workDir.exists()) {
deleteDirectory(workDir);
}
workDir.mkdir();
String remoteDir = seqId + "/" + sampleId + "/";
ObjectEngine oe = new ObjectEngine(plugin);
oe.createBucket(results_bucket_name);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
oe.downloadDirectory(bucket_name, remoteDir, workDirName, seqId, sampleId);
workDirName += remoteDir;
File commands_main = new File(workDirName + "commands_main.sh");
if (!commands_main.exists()) {
MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Commands file is missing from download");
error.setParam("req_id", reqId);
error.setParam("seq_id", seqId);
error.setParam("sample_id", sampleId);
error.setParam("transfer_status_file", transfer_status_file);
error.setParam("bucket_name", bucket_name);
error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
error.setParam("pathstage", pathStage);
error.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(error);
return;
}
commands_main.setExecutable(true);
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
/*
filterList.add(transfer_status_file);
String inDir = incoming_directory;
if (!inDir.endsWith("/")) {
inDir = inDir + "/";
}
*/
//logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, workDirName, filterList)) {
ssstep = 2;
logger.debug("Directory Sycned [inDir = {}]", workDirName);
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
ssstep = 3;
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", ex.getMessage());
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
//if is makes it through process the sample
if (ssstep == 3) {
try {
//start perf mon
PerfTracker pt = null;
if (trackPerf) {
logger.trace("Starting performance monitoring");
pt = new PerfTracker();
new Thread(pt).start();
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Creating output directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
String resultDirName = outgoing_directory; //create random tmp location
resultDirName = resultDirName.replace("//", "/");
if (!resultDirName.endsWith("/")) {
resultDirName += "/";
}
File resultDir = new File(resultDirName);
if (resultDir.exists()) {
deleteDirectory(resultDir);
}
logger.trace("Creating output directory: {}", resultDirName);
resultDir.mkdir();
ssstep = 4;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Starting Pipeline via Docker Container");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
String containerName = "procsam." + sampleId.replace("/", ".");
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Thread.sleep(500);
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
String command = "docker run -t -v /mnt/localdata/gpackage:/gpackage " +
"-v " + workDirName + ":/gdata/input " +
"-v " + resultDirName + ":/gdata/output " +
"--name procsam." + sampleId.replace("/", ".") + " " +
"intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh";
logger.trace("Running Docker Command: {}", command);
StringBuilder output = new StringBuilder();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
logger.trace("Attaching output reader");
BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputLine;
while ((outputLine = outputFeed.readLine()) != null) {
output.append(outputLine);
output.append("\n");
String[] outputStr = outputLine.split("\\|\\|");
for (int i = 0; i < outputStr.length; i++) {
outputStr[i] = outputStr[i].trim();
}
if ((outputStr.length == 5) &&
((outputLine.toLowerCase().startsWith("info")) ||
(outputLine.toLowerCase().startsWith("error")))) {
if (outputStr[0].toLowerCase().equals("info")) {
if (!stagePhase.equals(outputStr[3])) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline now in phase " + outputStr[3]);
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
stagePhase = outputStr[3];
} else if (outputStr[0].toLowerCase().equals("error")) {
logger.error("Pipeline Error : " + outputLine);
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "");
pse.setParam("indir", workDirName);
pse.setParam("outdir", resultDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
pse.setParam("error_message", outputLine);
plugin.sendMsgEvent(pse);
}
}
logger.debug(outputLine);
}
logger.trace("Waiting for Docker process to finish");
p.waitFor();
logger.trace("Docker exit code = {}", p.exitValue());
if (trackPerf) {
logger.trace("Ending Performance Monitor");
pt.isActive = false;
logger.trace("Sending Performance Information");
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Performance Information");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
pse.setParam("perf_log", pt.getResults());
plugin.sendMsgEvent(pse);
}
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Sending Pipeline Output");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
pse.setParam("output_log", output.toString());
plugin.sendMsgEvent(pse);
} catch (IOException ioe) {
// WHAT!?! DO SOMETHIN'!
logger.error("File read/write exception: {}", ioe.getMessage());
} catch (InterruptedException ie) {
// WHAT!?! DO SOMETHIN'!
logger.error("Process was interrupted: {}", ie.getMessage());
} catch (Exception e) {
// WHAT!?! DO SOMETHIN'!
logger.error("Exception: {}", e.getMessage());
}
logger.trace("Pipeline has finished");
Thread.sleep(2000);
if (p != null) {
switch (p.exitValue()) {
case 0: // Container finished successfully
ssstep = 5;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline has completed");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
ObjectEngine oe = new ObjectEngine(plugin);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Cleaning out old results from Object Store");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
oe.deleteBucketDirectoryContents(results_bucket_name, sampleId + "/");
logger.trace("Uploading results to objectStore");
ssstep = 6;
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Uploading Results Directory");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
oe.uploadSampleDirectory(results_bucket_name, resultDirName, "", seqId, sampleId, String.valueOf(ssstep));
List<String> filterList = new ArrayList<>();
filterList.add("pipeline_log.txt");
logger.trace("Add [transfer_status_file] to [filterList]");
logger.trace("Sleeping to ensure completion message is received last");
Thread.sleep(2000);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(results_bucket_name, "", resultDirName, filterList)) {
ssstep = 7;
logger.debug("Results Directory Sycned [inDir = {}]", resultDirName);
//Map<String, String> md5map = oe.getDirMD5(workDirName, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(workDirName + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Results Directory Transferred");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
break;
case 1: // Container error encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "General Docker Error Encountered (Err: 1)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 100: // Script failure encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Processing Pipeline encountered an error (Err: 100)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 125: // Container failed to run
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container failed to run (Err: 125)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 126: // Container command cannot be invoked
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command failed to be invoked (Err: 126)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 127: // Container command cannot be found
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container command could not be found (Err: 127)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
case 137: // Container was killed
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Container was manually stopped (Err: 137)");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
default: // Other return code encountered
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Unknown container return code (Err: " + p.exitValue() + ")");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
break;
}
} else {
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error retrieving exit code of container");
pse.setParam("indir", workDirName);
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
Thread.sleep(500);
Process postClear = Runtime.getRuntime().exec("docker rm " + containerName);
postClear.waitFor();
} catch (Exception e) {
logger.error("processSample {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("results_bucket_name", results_bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("ssstep", String.valueOf(ssstep));
plugin.sendMsgEvent(pse);
}
}
pstep = 2;
}
public void endProcessSample(String seqId, String sampleId, String reqId) {
MsgEvent pse;
try {
String containerName = "procsam." + sampleId.replace("/", ".");
Process kill = Runtime.getRuntime().exec("docker kill " + containerName);
kill.waitFor();
Thread.sleep(500);
Process clear = Runtime.getRuntime().exec("docker rm " + containerName);
clear.waitFor();
if (kill.exitValue() == 0) {
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pre-processing canceled");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("ssstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
} catch (Exception e) {
logger.error("processSequence {}", e.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("req_id", reqId);
pse.setParam("seq_id", seqId);
pse.setParam("sample_id", sampleId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", e.getMessage());
pse.setParam("ssstep", String.valueOf(0));
plugin.sendMsgEvent(pse);
}
}
public void downloadResults(String seqId, String reqId) {
logger.debug("Call to downloadResults seq_id: " + seqId, ", req_id: " + reqId);
pstep = 3;
int sstep = 1;
String remoteDir = seqId + "/";
MsgEvent pse;
try {
String workDirName = incoming_directory; //create random tmp location
workDirName = workDirName.replace("//", "/");
if (!workDirName.endsWith("/")) {
workDirName += "/";
}
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
/*
filterList.add(transfer_status_file);
String inDir = incoming_directory;
if (!inDir.endsWith("/")) {
inDir = inDir + "/";
}
//workDirName += remoteDir;
*/
File seqDir = new File(workDirName + seqId);
if (seqDir.exists()) {
deleteDirectory(seqDir);
}
//workDir.mkdir();
ObjectEngine oe = new ObjectEngine(plugin);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering");
//me.setParam("inDir", remoteDir);
//me.setParam("outDir", incoming_directory);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 2;
oe.downloadDirectory(bucket_name, remoteDir, workDirName, seqId, null);
//logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, workDirName + seqId, filterList)) {
logger.debug("Directory Sycned [inDir = {}]", workDirName);
//Map<String, String> md5map = oe.getDirMD5(inDir, filterList);
//logger.trace("Set MD5 hash");
//setTransferFileMD5(inDir + transfer_status_file, md5map);
pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered");
pse.setParam("indir", workDirName);
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
sstep = 3;
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Error Path Run");
pse.setParam("seq_id", seqId);
pse.setParam("req_id", reqId);
pse.setParam("transfer_watch_file", transfer_watch_file);
pse.setParam("transfer_status_file", transfer_status_file);
pse.setParam("bucket_name", bucket_name);
pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
pse.setParam("pathstage", pathStage);
pse.setParam("error_message", ex.getMessage());
pse.setParam("sstep", String.valueOf(sstep));
plugin.sendMsgEvent(pse);
}
pstep = 2;
}
private String getSampleList(String inDir) {
String sampleList = null;
try {
if (!inDir.endsWith("/")) {
inDir += "/";
}
ArrayList<String> samples = new ArrayList();
logger.trace("Processing Sequence Directory : " + inDir);
File file = new File(inDir);
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
List<String> subDirectories = new ArrayList<>();
if (directories != null) {
for (String subDir : directories) {
logger.trace("Searching for sub-directories of {}", inDir + subDir);
subDirectories.add(subDir);
File subFile = new File(inDir + "/" + subDir);
String[] subSubDirs = subFile.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
if (subSubDirs != null) {
for (String subSubDir : subSubDirs) {
logger.trace("Found sub-directory {}", inDir + subDir + "/" + subSubDir);
subDirectories.add(subDir + "/" + subSubDir);
}
}
}
}
for (String subDirectory : subDirectories) {
logger.trace("Processing Sample SubDirectory : " + subDirectory);
String commands_main_filename = inDir + subDirectory + "/commands_main.sh";
String config_files_directoryname = inDir + subDirectory + "/config_files";
File commands_main = new File(commands_main_filename);
File config_files = new File(config_files_directoryname);
logger.trace("commands_main " + commands_main_filename + " exist : " + commands_main.exists());
logger.trace("config_files " + config_files_directoryname + " exist : " + config_files.exists());
if (commands_main.exists() && !commands_main.isDirectory() &&
config_files.exists() && config_files.isDirectory()) {
// do something
samples.add(subDirectory);
logger.trace("Found Sample: " + commands_main_filename + " and " + config_files_directoryname);
}
}
//build list
if (!samples.isEmpty()) {
sampleList = "";
for (String tSample : samples) {
sampleList += tSample + ",";
}
sampleList = sampleList.substring(0, sampleList.length() - 1);
}
} catch (Exception ex) {
logger.error("getSameplList : " + ex.getMessage());
}
return sampleList;
}
private void sendUpdateInfoMessage(String seqId, String sampleId, String reqId, String step, String message) {
if (!message.equals("Idle"))
logger.info("{}", message);
MsgEvent msgEvent = plugin.genGMessage(MsgEvent.Type.INFO, message);
msgEvent.setParam("pathstage", String.valueOf(plugin.pathStage));
msgEvent.setParam("seq_id", seqId);
if (sampleId != null) {
msgEvent.setParam("sample_id", sampleId);
msgEvent.setParam("ssstep", step);
} else if (seqId != null)
msgEvent.setParam("sstep", step);
else
msgEvent.setParam("pstep", step);
if (reqId != null)
msgEvent.setParam("req_id", reqId);
plugin.sendMsgEvent(msgEvent);
}
private void sendUpdateErrorMessage(String seqId, String sampleId, String reqId, String step, String message) {
logger.error("{}", message);
MsgEvent msgEvent = plugin.genGMessage(MsgEvent.Type.ERROR, "");
msgEvent.setParam("pathstage", String.valueOf(plugin.pathStage));
msgEvent.setParam("error_message", message);
msgEvent.setParam("seq_id", seqId);
if (sampleId != null) {
msgEvent.setParam("sample_id", sampleId);
msgEvent.setParam("ssstep", step);
} else if (seqId != null)
msgEvent.setParam("sstep", step);
else
msgEvent.setParam("pstep", step);
if (reqId != null)
msgEvent.setParam("req_id", reqId);
plugin.sendMsgEvent(msgEvent);
}
/*
private void legacy() {
logger.trace("Thread starting");
try {
logger.trace("Setting [PathProcessorActive] to true");
plugin.PathProcessorActive = true;
ObjectEngine oe = new ObjectEngine(plugin);
logger.trace("Entering while-loop");
while (plugin.PathProcessorActive) {
me = plugin.genGMessage(MsgEvent.Type.INFO,"Start Object Scan");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("pstep","2");
plugin.sendMsgEvent(me);
try {
//oe.deleteBucketContents(bucket_name);
logger.trace("Populating [remoteDirs]");
List<String> remoteDirs = oe.listBucketDirs(bucket_name);
for(String remoteDir : remoteDirs) {
logger.trace("Remote Dir : " + remoteDir);
}
logger.trace("Populating [localDirs]");
List<String> localDirs = getWalkPath(incoming_directory);
for(String localDir : localDirs) {
logger.trace("Local Dir : " + localDir);
}
List<String> newDirs = new ArrayList<>();
for (String remoteDir : remoteDirs) {
logger.trace("Checking for existance of RemoteDir [" + remoteDir + "] locally");
if (!localDirs.contains(remoteDir)) {
logger.trace("RemoteDir [" + remoteDir + "] does not exist locally");
if (oe.doesObjectExist(bucket_name, remoteDir + transfer_watch_file)) {
logger.debug("Adding [remoteDir = {}] to [newDirs]", remoteDir);
newDirs.add(remoteDir);
}
}
}
if (!newDirs.isEmpty()) {
logger.trace("[newDirs] has buckets to process");
processBucket(newDirs);
}
Thread.sleep(30000);
} catch (Exception ex) {
logger.error("run : while {}", ex.getMessage());
me = plugin.genGMessage(MsgEvent.Type.ERROR,"Error during Object scan");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("error_message",ex.getMessage());
me.setParam("pstep","2");
plugin.sendMsgEvent(me);
}
//message end of scan
me = plugin.genGMessage(MsgEvent.Type.INFO,"End Object Scan");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("pstep","3");
plugin.sendMsgEvent(me);
}
} catch (Exception ex) {
logger.error("run {}", ex.getMessage());
me = plugin.genGMessage(MsgEvent.Type.ERROR,"Error Path Run");
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("error_message",ex.getMessage());
me.setParam("pstep","2");
plugin.sendMsgEvent(me);
}
}
private void processBucket(List<String> newDirs) {
logger.debug("Call to processBucket [newDir = {}]", newDirs.toString());
ObjectEngine oe = new ObjectEngine(plugin);
for (String remoteDir : newDirs) {
logger.debug("Downloading directory {} to [incoming_directory]", remoteDir);
String seqId = remoteDir.substring(remoteDir.lastIndexOf("/") + 1, remoteDir.length());
me = plugin.genGMessage(MsgEvent.Type.INFO,"Directory Transfered");
me.setParam("inDir", remoteDir);
me.setParam("outDir", incoming_directory);
me.setParam("seq_id", seqId);
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("sstep","1");
plugin.sendMsgEvent(me);
oe.downloadDirectory(bucket_name, remoteDir, incoming_directory);
List<String> filterList = new ArrayList<>();
logger.trace("Add [transfer_status_file] to [filterList]");
filterList.add(transfer_status_file);
String inDir = incoming_directory;
if (!inDir.endsWith("/")) {
inDir = inDir + "/";
}
inDir = inDir + remoteDir;
logger.debug("[inDir = {}]", inDir);
oe = new ObjectEngine(plugin);
if (oe.isSyncDir(bucket_name, remoteDir, inDir, filterList)) {
logger.debug("Directory Sycned [inDir = {}]", inDir);
Map<String, String> md5map = oe.getDirMD5(inDir, filterList);
logger.trace("Set MD5 hash");
setTransferFileMD5(inDir + transfer_status_file, md5map);
me = plugin.genGMessage(MsgEvent.Type.INFO,"Directory Transfered");
me.setParam("indir", inDir);
me.setParam("outdir", remoteDir);
me.setParam("seq_id", seqId);
me.setParam("transfer_watch_file",transfer_watch_file);
me.setParam("transfer_status_file", transfer_status_file);
me.setParam("bucket_name",bucket_name);
me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint"));
me.setParam("pathstage",pathStage);
me.setParam("sstep","2");
plugin.sendMsgEvent(me);
}
}
}
*/
private void setTransferFileMD5(String dir, Map<String, String> md5map) {
logger.debug("Call to setTransferFileMD5 [dir = {}]", dir);
try {
PrintWriter out = null;
try {
logger.trace("Opening [dir] to write");
out = new PrintWriter(new BufferedWriter(new FileWriter(dir, true)));
for (Map.Entry<String, String> entry : md5map.entrySet()) {
String md5file = entry.getKey().replace(incoming_directory, "");
if (md5file.startsWith("/")) {
md5file = md5file.substring(1);
}
out.write(md5file + ":" + entry.getValue() + "\n");
logger.debug("[md5file = {}, entry = {}] written", md5file, entry.getValue());
}
} finally {
try {
assert out != null;
out.flush();
out.close();
} catch (AssertionError e) {
logger.error("setTransferFileMd5 - PrintWriter was pre-emptively shutdown");
}
}
} catch (Exception ex) {
logger.error("setTransferFile {}", ex.getMessage());
}
}
/*private List<String> getWalkPath(String path) {
logger.debug("Call to getWalkPath [path = {}]", path);
if (!path.endsWith("/")) {
path = path + "/";
}
List<String> dirList = new ArrayList<>();
File root = new File(path);
File[] list = root.listFiles();
if (list == null) {
logger.trace("[list] is null, returning [dirList (empty array)]");
return dirList;
}
for (File f : list) {
if (f.isDirectory()) {
//walkPath( f.getAbsolutePath() );
String dir = f.getAbsolutePath().replace(path, "");
logger.debug("Adding \"{}/\" to [dirList]", dir);
dirList.add(dir + "/");
}
}
return dirList;
}*/
}
| Moving testing forward
| src/main/java/com/researchworx/cresco/plugins/gobjectIngestion/folderprocessor/ObjectFS.java | Moving testing forward |
|
Java | apache-2.0 | 363a30670cb31e8e3b49bca71583401b0a8e79d5 | 0 | hussam-m/IntroNet | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package server;
/**
*
* @author hussam
*/
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
| Server/src/server/Server.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package server;
/**
*
* @author hussam
*/
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
| Create Java project | Server/src/server/Server.java | Create Java project |
|
Java | apache-2.0 | 10ebe08b8c10a390baeb0ad2cd607cc285eb1d91 | 0 | tipsy/javalin,tipsy/javalin,tipsy/javalin,tipsy/javalin | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*
*/
package io.javalin;
import io.javalin.apibuilder.ApiBuilder;
import io.javalin.apibuilder.EndpointGroup;
import io.javalin.core.ErrorMapper;
import io.javalin.core.EventManager;
import io.javalin.core.ExceptionMapper;
import io.javalin.core.HandlerEntry;
import io.javalin.core.HandlerType;
import io.javalin.core.JavalinServlet;
import io.javalin.core.PathMatcher;
import io.javalin.core.util.CorsBeforeHandler;
import io.javalin.core.util.CorsOptionsHandler;
import io.javalin.core.util.JettyServerUtil;
import io.javalin.core.util.LogUtil;
import io.javalin.core.util.RouteOverviewRenderer;
import io.javalin.core.util.SinglePageHandler;
import io.javalin.core.util.Util;
import io.javalin.security.AccessManager;
import io.javalin.security.CoreRoles;
import io.javalin.security.Role;
import io.javalin.security.SecurityUtil;
import io.javalin.serversentevent.SseClient;
import io.javalin.serversentevent.SseHandler;
import io.javalin.staticfiles.JettyResourceHandler;
import io.javalin.staticfiles.Location;
import io.javalin.staticfiles.StaticFileConfig;
import io.javalin.websocket.WsEntry;
import io.javalin.websocket.WsHandler;
import io.javalin.websocket.WsPathMatcher;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.javalin.security.SecurityUtil.roles;
public class Javalin {
private static Logger log = LoggerFactory.getLogger(Javalin.class);
protected Server jettyServer;
protected SessionHandler jettySessionHandler;
protected Set<StaticFileConfig> staticFileConfig = new HashSet<>();
protected boolean ignoreTrailingSlashes = true;
protected int port = 7000;
protected String contextPath = "/";
protected String defaultContentType = "text/plain";
protected long maxRequestCacheBodySize = 4096;
protected boolean debugLogging = false;
protected boolean dynamicGzipEnabled = true;
protected boolean autogeneratedEtagsEnabled = false;
protected boolean hideBanner = false;
protected boolean prefer405over404 = false;
protected boolean caseSensitiveUrls = false;
protected boolean started = false;
protected AccessManager accessManager = SecurityUtil::noopAccessManager;
protected RequestLogger requestLogger = null;
protected SinglePageHandler singlePageHandler = new SinglePageHandler();
protected PathMatcher pathMatcher = new PathMatcher();
protected WsPathMatcher wsPathMatcher = new WsPathMatcher();
protected ExceptionMapper exceptionMapper = new ExceptionMapper();
protected ErrorMapper errorMapper = new ErrorMapper();
protected EventManager eventManager = new EventManager();
protected List<HandlerMetaInfo> handlerMetaInfo = new ArrayList<>();
protected Map<Class, Object> appAttributes = new HashMap<>();
protected Consumer<WebSocketServletFactory> wsFactoryConfig = WebSocketServletFactory::getPolicy;
protected Javalin(Server jettyServer, SessionHandler jettySessionHandler) {
this.jettyServer = jettyServer;
this.jettySessionHandler = jettySessionHandler;
}
protected Javalin() {
this(JettyServerUtil.defaultServer(), JettyServerUtil.defaultSessionHandler());
}
/**
* Creates an instance of the application for further configuration.
* The server does not run until {@link Javalin#start()} is called.
*
* @return instance of application for configuration.
* @see Javalin#start()
* @see Javalin#start(int)
*/
public static Javalin create() {
Util.INSTANCE.printHelpfulMessageIfNoServerHasBeenStartedAfterOneSecond();
return new Javalin();
}
/**
* Synchronously starts the application instance on the specified port.
*
* @param port to run on
* @return running application instance.
* @see Javalin#create()
* @see Javalin#start()
*/
public Javalin start(int port) {
return port(port).start();
}
/**
* Synchronously starts the application instance.
*
* @return running application instance.
* @see Javalin#create()
*/
public Javalin start() {
if (!started) {
if (!hideBanner) {
log.info(Util.INSTANCE.javalinBanner());
}
Util.INSTANCE.printHelpfulMessageIfLoggerIsMissing();
Util.INSTANCE.setNoJettyStarted(false);
eventManager.fireEvent(JavalinEvent.SERVER_STARTING);
try {
log.info("Starting Javalin ...");
port = JettyServerUtil.initialize(
jettyServer,
jettySessionHandler,
port,
contextPath,
createServlet(),
wsPathMatcher,
wsFactoryConfig,
log
);
log.info("Javalin has started \\o/");
started = true;
eventManager.fireEvent(JavalinEvent.SERVER_STARTED);
} catch (Exception e) {
log.error("Failed to start Javalin");
eventManager.fireEvent(JavalinEvent.SERVER_START_FAILED);
if (e.getMessage() != null && e.getMessage().contains("Failed to bind to")) {
throw new RuntimeException("Port already in use. Make sure no other process is using port " + port + " and try again.", e);
} else if (e.getMessage() != null && e.getMessage().contains("Permission denied")) {
throw new RuntimeException("Port 1-1023 require elevated privileges (process must be started by admin).", e);
}
throw new RuntimeException(e);
}
}
return this;
}
@NotNull
public JavalinServlet createServlet() {
return new JavalinServlet(
this,
pathMatcher,
exceptionMapper,
errorMapper,
debugLogging,
requestLogger,
dynamicGzipEnabled,
autogeneratedEtagsEnabled,
defaultContentType,
maxRequestCacheBodySize,
prefer405over404,
singlePageHandler,
new JettyResourceHandler(staticFileConfig, jettyServer, ignoreTrailingSlashes)
);
}
/**
* Synchronously stops the application instance.
*
* @return stopped application instance.
*/
public Javalin stop() {
eventManager.fireEvent(JavalinEvent.SERVER_STOPPING);
log.info("Stopping Javalin ...");
try {
jettyServer.stop();
} catch (Exception e) {
log.error("Javalin failed to stop gracefully", e);
}
log.info("Javalin has stopped");
eventManager.fireEvent(JavalinEvent.SERVER_STOPPED);
return this;
}
/**
* Configure the instance to return 405 (Method Not Allowed) instead of 404 (Not Found) whenever a request method doesn't exists but there are handlers for other methods on the same requested path.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin prefer405over404() {
ensureActionIsPerformedBeforeServerStart("Telling Javalin to return 405 instead of 404 when applicable");
prefer405over404 = true;
return this;
}
/**
* Configure the instance to not use lower-case paths for path matching and parsing.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableCaseSensitiveUrls() {
ensureActionIsPerformedBeforeServerStart("Enabling case sensitive urls");
caseSensitiveUrls = true;
return this;
}
/**
* Configure instance to not show banner in logs.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin disableStartupBanner() {
ensureActionIsPerformedBeforeServerStart("Telling Javalin to not show banner in logs");
hideBanner = true;
return this;
}
/**
* Configure instance to treat '/test/' and '/test' as different URLs.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin dontIgnoreTrailingSlashes() {
ensureActionIsPerformedBeforeServerStart("Telling Javalin to not ignore slashes");
pathMatcher.setIgnoreTrailingSlashes(false);
ignoreTrailingSlashes = false;
return this;
}
/**
* Configure instance to use a custom jetty Server.
*
* @see <a href="https://javalin.io/documentation#custom-server">Documentation example</a>
* The method must be called before {@link Javalin#start()}.
*/
public Javalin server(@NotNull Supplier<Server> server) {
ensureActionIsPerformedBeforeServerStart("Setting a custom server");
jettyServer = server.get();
return this;
}
/**
* Configure instance to use a custom jetty SessionHandler.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin sessionHandler(@NotNull Supplier<SessionHandler> sessionHandler) {
ensureActionIsPerformedBeforeServerStart("Setting a custom session handler");
jettySessionHandler = Util.INSTANCE.getValidSessionHandlerOrThrow(sessionHandler);
return this;
}
/**
* Configure the WebSocketServletFactory of the instance
* The method must be called before {@link Javalin#start()}.
*/
public Javalin wsFactoryConfig(@NotNull Consumer<WebSocketServletFactory> wsFactoryConfig) {
ensureActionIsPerformedBeforeServerStart("Setting a custom WebSocket factory config");
this.wsFactoryConfig = wsFactoryConfig;
return this;
}
/**
* Configure instance to serve static files from path in classpath.
* The method can be called multiple times for different locations.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#static-files">Static files in docs</a>
*/
public Javalin enableStaticFiles(@NotNull String classpathPath) {
return enableStaticFiles(classpathPath, Location.CLASSPATH);
}
/**
* Configure instance to serve static files from path in the specified location.
* The method can be called multiple times for different locations.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#static-files">Static files in docs</a>
*/
public Javalin enableStaticFiles(@NotNull String path, @NotNull Location location) {
ensureActionIsPerformedBeforeServerStart("Enabling static files");
staticFileConfig.add(new StaticFileConfig(path, location));
return this;
}
/**
* Configure instance to serve WebJars.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableWebJars() {
return enableStaticFiles("/webjars", Location.CLASSPATH);
}
/**
* Any request that would normally result in a 404 for the path and its subpaths
* instead results in a 200 with the file-content from path in classpath as response body.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableSinglePageMode(@NotNull String path, @NotNull String filePath) {
return enableSinglePageMode(path, filePath, Location.CLASSPATH);
}
/**
* Any request that would normally result in a 404 for the path and its subpaths
* instead results in a 200 with the file-content as response body.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableSinglePageMode(@NotNull String path, @NotNull String filePath, @NotNull Location location) {
ensureActionIsPerformedBeforeServerStart("Enabling single page mode");
singlePageHandler.add(path, filePath, location);
return this;
}
/**
* Configure instance to run on specified context path (common prefix).
* The method must be called before {@link Javalin#start()}.
*/
public Javalin contextPath(@NotNull String contextPath) {
ensureActionIsPerformedBeforeServerStart("Setting the context path");
this.contextPath = Util.INSTANCE.normalizeContextPath(contextPath);
return this;
}
/**
* Get which port instance is running on
* Mostly useful if you start the instance with port(0) (random port)
*/
public int port() {
return port;
}
/**
* Configure instance to run on specified port.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin port(int port) {
ensureActionIsPerformedBeforeServerStart("Setting the port");
this.port = port;
return this;
}
/**
* Configure instance to log debug information for each request.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableDebugLogging() {
ensureActionIsPerformedBeforeServerStart("Enabling debug-logging");
this.debugLogging = true;
wsLogger(LogUtil::wsDebugLogger);
return this;
}
/**
* Configure instance use specified request-logger
* The method must be called before {@link Javalin#start()}.
* Will override the default logger of {@link Javalin#enableDebugLogging()}.
*/
public Javalin requestLogger(@NotNull RequestLogger requestLogger) {
ensureActionIsPerformedBeforeServerStart("Setting a custom request logger");
this.requestLogger = requestLogger;
return this;
}
/**
* Configure instance to accept cross origin requests for specified origins.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableCorsForOrigin(@NotNull String... origin) {
ensureActionIsPerformedBeforeServerStart("Enabling CORS");
if (origin.length == 0) throw new IllegalArgumentException("Origins cannot be empty.");
this.before("*", new CorsBeforeHandler(origin));
this.options("*", new CorsOptionsHandler(), roles(CoreRoles.NO_WRAP));
return this;
}
/**
* Configure instance to accept cross origin requests for all origins.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableCorsForAllOrigins() {
return enableCorsForOrigin("*");
}
/**
* Configure instance to not gzip dynamic responses.
* By default Javalin gzips all responses larger than 1500 bytes.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin disableDynamicGzip() {
ensureActionIsPerformedBeforeServerStart("Disabling dynamic GZIP");
this.dynamicGzipEnabled = false;
return this;
}
/**
* Configure instance to automatically add ETags for GET requests.
* Static files already have ETags, this will calculate a checksum for
* dynamic GET responses and return 304 if the content has not changed.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableAutogeneratedEtags() {
ensureActionIsPerformedBeforeServerStart("Enabling autogenerated etags");
this.autogeneratedEtagsEnabled = true;
return this;
}
/**
* Configure instance to display a visual overview of all its mapped routes
* on the specified path.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableRouteOverview(@NotNull String path) {
return enableRouteOverview(path, new HashSet<>());
}
/**
* Configure instance to display a visual overview of all its mapped routes
* on the specified path with the specified roles
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableRouteOverview(@NotNull String path, @NotNull Set<Role> permittedRoles) {
ensureActionIsPerformedBeforeServerStart("Enabling route overview");
return this.get(path, new RouteOverviewRenderer(this), permittedRoles);
}
/**
* Configure instance to use the specified content-type as a default
* value for all responses. This can be overridden in any Handler.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin defaultContentType(@NotNull String contentType) {
ensureActionIsPerformedBeforeServerStart("Changing default content type");
this.defaultContentType = contentType;
return this;
}
/**
* Configure instance to stop caching requests larger than the specified body size.
* The default value is 4096 bytes.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin maxBodySizeForRequestCache(long bodySizeInBytes) {
ensureActionIsPerformedBeforeServerStart("Changing request cache body size");
this.maxRequestCacheBodySize = bodySizeInBytes;
return this;
}
/**
* Registers an attribute on the instance.
* Instance is available on the {@link Context} through {@link Context#appAttribute}.
* Ex: app.attribute(MyExt.class, myExtInstance())
* The method must be called before {@link Javalin#start()}.
*/
public Javalin attribute(Class clazz, Object obj) {
ensureActionIsPerformedBeforeServerStart("Registering app attributes");
appAttributes.put(clazz, obj);
return this;
}
/**
* Retrieve an attribute stored on the instance.
* Available on the {@link Context} through {@link Context#appAttribute}.
* Ex: app.attribute(MyExt.class).myMethod()
* Ex: ctx.appAttribute(MyExt.class).myMethod()
*/
@SuppressWarnings("unchecked")
public <T> T attribute(Class<T> clazz) {
return (T) appAttributes.get(clazz);
}
/**
* Configure instance to not cache any requests.
* If you call this method you will not be able to log request-bodies.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin disableRequestCache() {
return maxBodySizeForRequestCache(0);
}
private void ensureActionIsPerformedBeforeServerStart(@NotNull String action) {
if (started) {
throw new IllegalStateException(action + " must be done before starting the server.");
}
}
/**
* Sets the access manager for the instance. Secured endpoints require one to be set.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#access-manager">Access manager in docs</a>
* @see AccessManager
*/
public Javalin accessManager(@NotNull AccessManager accessManager) {
ensureActionIsPerformedBeforeServerStart("Setting an AccessManager");
this.accessManager = accessManager;
return this;
}
/**
* Adds an exception mapper to the instance.
* Useful for turning exceptions into standardized errors/messages/pages
*
* @see <a href="https://javalin.io/documentation#exception-mapping">Exception mapping in docs</a>
*/
public <T extends Exception> Javalin exception(@NotNull Class<T> exceptionClass, @NotNull ExceptionHandler<? super T> exceptionHandler) {
exceptionMapper.getExceptionMap().put(exceptionClass, (ExceptionHandler<Exception>) exceptionHandler);
return this;
}
/**
* Adds a lifecycle event listener.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#lifecycle-events">Events in docs</a>
*/
public Javalin event(@NotNull JavalinEvent javalinEvent, @NotNull EventListener eventListener) {
ensureActionIsPerformedBeforeServerStart("Event-mapping");
eventManager.getListenerMap().get(javalinEvent).add(eventListener);
return this;
}
/**
* Configures a web socket handler to be called after every web socket event
* The method must be called before {@link Javalin#start()}.
* Will override the default logger of {@link Javalin#enableDebugLogging()}.
*/
public Javalin wsLogger(@NotNull Consumer<WsHandler> ws) {
ensureActionIsPerformedBeforeServerStart("Adding a WebSocket logger");
WsHandler wsLogger = new WsHandler();
ws.accept(wsLogger);
wsPathMatcher.setWsLogger(wsLogger);
return this;
}
/**
* Adds an error mapper to the instance.
* Useful for turning error-codes (404, 500) into standardized messages/pages
*
* @see <a href="https://javalin.io/documentation#error-mapping">Error mapping in docs</a>
*/
public Javalin error(int statusCode, @NotNull ErrorHandler errorHandler) {
errorMapper.getErrorHandlerMap().put(statusCode, errorHandler);
return this;
}
/**
* Registers an {@link Extension} with the instance.
* You're free to implement the extension as a class or a lambda expression
*/
public Javalin register(Extension extension) {
extension.registerOnJavalin(this);
return this;
}
/**
* Creates a temporary static instance in the scope of the endpointGroup.
* Allows you to call get(handler), post(handler), etc. without without using the instance prefix.
*
* @see <a href="https://javalin.io/documentation#handler-groups">Handler groups in documentation</a>
* @see ApiBuilder
*/
public Javalin routes(@NotNull EndpointGroup endpointGroup) {
ApiBuilder.setStaticJavalin(this);
endpointGroup.addEndpoints();
ApiBuilder.clearStaticJavalin();
return this;
}
/**
* Adds a request handler for the specified handlerType and path to the instance.
* Requires an access manager to be set on the instance.
* This is the method that all the verb-methods (get/post/put/etc) call.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin addHandler(@NotNull HandlerType handlerType, @NotNull String path, @NotNull Handler handler, @NotNull Set<Role> roles) {
boolean shouldWrap = handlerType.isHttpMethod() && !roles.contains(CoreRoles.NO_WRAP); // don't wrap CORS options
String prefixedPath = Util.prefixContextPath(contextPath, path);
Handler protectedHandler = shouldWrap ? ctx -> accessManager.manage(handler, ctx, roles) : handler;
pathMatcher.add(new HandlerEntry(handlerType, prefixedPath, protectedHandler, handler, caseSensitiveUrls));
handlerMetaInfo.add(new HandlerMetaInfo(handlerType, prefixedPath, handler, roles));
return this;
}
/**
* Adds a request handler for the specified handlerType and path to the instance.
* This is the method that all the verb-methods (get/post/put/etc) call.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin addHandler(@NotNull HandlerType httpMethod, @NotNull String path, @NotNull Handler handler) {
return addHandler(httpMethod, path, handler, new HashSet<>()); // no roles set for this route (open to everyone)
}
// HTTP verbs
/**
* Adds a GET request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin get(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.GET, path, handler);
}
/**
* Adds a POST request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin post(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.POST, path, handler);
}
/**
* Adds a PUT request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin put(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.PUT, path, handler);
}
/**
* Adds a PATCH request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin patch(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.PATCH, path, handler);
}
/**
* Adds a DELETE request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin delete(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.DELETE, path, handler);
}
/**
* Adds a HEAD request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin head(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.HEAD, path, handler);
}
/**
* Adds a TRACE request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin trace(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.TRACE, path, handler);
}
/**
* Adds a CONNECT request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin connect(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.CONNECT, path, handler);
}
/**
* Adds a OPTIONS request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin options(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.OPTIONS, path, handler);
}
// Secured HTTP verbs
/**
* Adds a GET request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin get(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.GET, path, handler, permittedRoles);
}
/**
* Adds a POST request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin post(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.POST, path, handler, permittedRoles);
}
/**
* Adds a PUT request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin put(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.PUT, path, handler, permittedRoles);
}
/**
* Adds a PATCH request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin patch(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.PATCH, path, handler, permittedRoles);
}
/**
* Adds a DELETE request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin delete(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.DELETE, path, handler, permittedRoles);
}
/**
* Adds a HEAD request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin head(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.HEAD, path, handler, permittedRoles);
}
/**
* Adds a TRACE request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin trace(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.TRACE, path, handler, permittedRoles);
}
/**
* Adds a CONNECT request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin connect(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.CONNECT, path, handler, permittedRoles);
}
/**
* Adds a OPTIONS request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin options(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.OPTIONS, path, handler, permittedRoles);
}
// Filters
/**
* Adds a BEFORE request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin before(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.BEFORE, path, handler);
}
/**
* Adds a BEFORE request handler for all routes in the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin before(@NotNull Handler handler) {
return before("*", handler);
}
/**
* Adds an AFTER request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin after(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.AFTER, path, handler);
}
/**
* Adds an AFTER request handler for all routes in the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin after(@NotNull Handler handler) {
return after("*", handler);
}
/**
* Adds a WebSocket handler on the specified path.
*
* @see <a href="https://javalin.io/documentation#websockets">WebSockets in docs</a>
*/
public Javalin ws(@NotNull String path, @NotNull Consumer<WsHandler> ws) {
String prefixedPath = Util.prefixContextPath(contextPath, path);
WsHandler configuredWebSocket = new WsHandler();
ws.accept(configuredWebSocket);
wsPathMatcher.add(new WsEntry(prefixedPath, configuredWebSocket, caseSensitiveUrls));
handlerMetaInfo.add(new HandlerMetaInfo(HandlerType.WEBSOCKET, prefixedPath, ws, new HashSet<>()));
return this;
}
/**
* Gets the list of HandlerMetaInfo-objects
*/
public List<HandlerMetaInfo> getHandlerMetaInfo() {
return new ArrayList<>(handlerMetaInfo);
}
/**
* Adds a lambda handler for a Server Sent Event connection on the specified path.
*/
public Javalin sse(@NotNull String path, @NotNull Consumer<SseClient> client) {
return sse(path, client, new HashSet<>());
}
/**
* Adds a lambda handler for a Server Sent Event connection on the specified path.
* Requires an access manager to be set on the instance.
*/
public Javalin sse(@NotNull String path, @NotNull Consumer<SseClient> client, @NotNull Set<Role> permittedRoles) {
return get(path, new SseHandler(client), permittedRoles);
}
}
| src/main/java/io/javalin/Javalin.java | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*
*/
package io.javalin;
import io.javalin.apibuilder.ApiBuilder;
import io.javalin.apibuilder.EndpointGroup;
import io.javalin.core.ErrorMapper;
import io.javalin.core.EventManager;
import io.javalin.core.ExceptionMapper;
import io.javalin.core.HandlerEntry;
import io.javalin.core.HandlerType;
import io.javalin.core.JavalinServlet;
import io.javalin.core.PathMatcher;
import io.javalin.core.util.CorsBeforeHandler;
import io.javalin.core.util.CorsOptionsHandler;
import io.javalin.core.util.JettyServerUtil;
import io.javalin.core.util.LogUtil;
import io.javalin.core.util.RouteOverviewRenderer;
import io.javalin.core.util.SinglePageHandler;
import io.javalin.core.util.Util;
import io.javalin.security.AccessManager;
import io.javalin.security.CoreRoles;
import io.javalin.security.Role;
import io.javalin.security.SecurityUtil;
import io.javalin.serversentevent.SseClient;
import io.javalin.serversentevent.SseHandler;
import io.javalin.staticfiles.JettyResourceHandler;
import io.javalin.staticfiles.Location;
import io.javalin.staticfiles.StaticFileConfig;
import io.javalin.websocket.WsEntry;
import io.javalin.websocket.WsHandler;
import io.javalin.websocket.WsPathMatcher;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.javalin.security.SecurityUtil.roles;
public class Javalin {
private static Logger log = LoggerFactory.getLogger(Javalin.class);
protected Server jettyServer;
protected SessionHandler jettySessionHandler;
protected Set<StaticFileConfig> staticFileConfig = new HashSet<>();
protected boolean ignoreTrailingSlashes = true;
protected int port = 7000;
protected String contextPath = "/";
protected String defaultContentType = "text/plain";
protected long maxRequestCacheBodySize = 4096;
protected boolean debugLogging = false;
protected boolean dynamicGzipEnabled = true;
protected boolean autogeneratedEtagsEnabled = false;
protected boolean hideBanner = false;
protected boolean prefer405over404 = false;
protected boolean caseSensitiveUrls = false;
protected boolean started = false;
protected AccessManager accessManager = SecurityUtil::noopAccessManager;
protected RequestLogger requestLogger = null;
protected SinglePageHandler singlePageHandler = new SinglePageHandler();
protected PathMatcher pathMatcher = new PathMatcher();
protected WsPathMatcher wsPathMatcher = new WsPathMatcher();
protected ExceptionMapper exceptionMapper = new ExceptionMapper();
protected ErrorMapper errorMapper = new ErrorMapper();
protected EventManager eventManager = new EventManager();
protected List<HandlerMetaInfo> handlerMetaInfo = new ArrayList<>();
protected Map<Class, Object> appAttributes = new HashMap<>();
protected Consumer<WebSocketServletFactory> wsFactoryConfig = WebSocketServletFactory::getPolicy;
protected Javalin(Server jettyServer, SessionHandler jettySessionHandler) {
this.jettyServer = jettyServer;
this.jettySessionHandler = jettySessionHandler;
}
protected Javalin() {
this(JettyServerUtil.defaultServer(), JettyServerUtil.defaultSessionHandler());
}
/**
* Creates an instance of the application for further configuration.
* The server does not run until {@link Javalin#start()} is called.
*
* @return instance of application for configuration.
* @see Javalin#start()
* @see Javalin#start(int)
*/
public static Javalin create() {
Util.INSTANCE.printHelpfulMessageIfNoServerHasBeenStartedAfterOneSecond();
return new Javalin();
}
/**
* Synchronously starts the application instance on the specified port.
*
* @param port to run on
* @return running application instance.
* @see Javalin#create()
* @see Javalin#start()
*/
public Javalin start(int port) {
return port(port).start();
}
/**
* Synchronously starts the application instance.
*
* @return running application instance.
* @see Javalin#create()
*/
public Javalin start() {
if (!started) {
if (!hideBanner) {
log.info(Util.INSTANCE.javalinBanner());
}
Util.INSTANCE.printHelpfulMessageIfLoggerIsMissing();
Util.INSTANCE.setNoJettyStarted(false);
eventManager.fireEvent(JavalinEvent.SERVER_STARTING);
try {
log.info("Starting Javalin ...");
port = JettyServerUtil.initialize(
jettyServer,
jettySessionHandler,
port,
contextPath,
createServlet(),
wsPathMatcher,
wsFactoryConfig,
log
);
log.info("Javalin has started \\o/");
started = true;
eventManager.fireEvent(JavalinEvent.SERVER_STARTED);
} catch (Exception e) {
log.error("Failed to start Javalin");
eventManager.fireEvent(JavalinEvent.SERVER_START_FAILED);
if (e.getMessage() != null && e.getMessage().contains("Failed to bind to")) {
throw new RuntimeException("Port already in use. Make sure no other process is using port " + port + " and try again.", e);
} else if (e.getMessage() != null && e.getMessage().contains("Permission denied")) {
throw new RuntimeException("Port 1-1023 require elevated privileges (process must be started by admin).");
}
throw new RuntimeException(e);
}
}
return this;
}
@NotNull
public JavalinServlet createServlet() {
return new JavalinServlet(
this,
pathMatcher,
exceptionMapper,
errorMapper,
debugLogging,
requestLogger,
dynamicGzipEnabled,
autogeneratedEtagsEnabled,
defaultContentType,
maxRequestCacheBodySize,
prefer405over404,
singlePageHandler,
new JettyResourceHandler(staticFileConfig, jettyServer, ignoreTrailingSlashes)
);
}
/**
* Synchronously stops the application instance.
*
* @return stopped application instance.
*/
public Javalin stop() {
eventManager.fireEvent(JavalinEvent.SERVER_STOPPING);
log.info("Stopping Javalin ...");
try {
jettyServer.stop();
} catch (Exception e) {
log.error("Javalin failed to stop gracefully", e);
}
log.info("Javalin has stopped");
eventManager.fireEvent(JavalinEvent.SERVER_STOPPED);
return this;
}
/**
* Configure the instance to return 405 (Method Not Allowed) instead of 404 (Not Found) whenever a request method doesn't exists but there are handlers for other methods on the same requested path.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin prefer405over404() {
ensureActionIsPerformedBeforeServerStart("Telling Javalin to return 405 instead of 404 when applicable");
prefer405over404 = true;
return this;
}
/**
* Configure the instance to not use lower-case paths for path matching and parsing.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableCaseSensitiveUrls() {
ensureActionIsPerformedBeforeServerStart("Enabling case sensitive urls");
caseSensitiveUrls = true;
return this;
}
/**
* Configure instance to not show banner in logs.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin disableStartupBanner() {
ensureActionIsPerformedBeforeServerStart("Telling Javalin to not show banner in logs");
hideBanner = true;
return this;
}
/**
* Configure instance to treat '/test/' and '/test' as different URLs.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin dontIgnoreTrailingSlashes() {
ensureActionIsPerformedBeforeServerStart("Telling Javalin to not ignore slashes");
pathMatcher.setIgnoreTrailingSlashes(false);
ignoreTrailingSlashes = false;
return this;
}
/**
* Configure instance to use a custom jetty Server.
*
* @see <a href="https://javalin.io/documentation#custom-server">Documentation example</a>
* The method must be called before {@link Javalin#start()}.
*/
public Javalin server(@NotNull Supplier<Server> server) {
ensureActionIsPerformedBeforeServerStart("Setting a custom server");
jettyServer = server.get();
return this;
}
/**
* Configure instance to use a custom jetty SessionHandler.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin sessionHandler(@NotNull Supplier<SessionHandler> sessionHandler) {
ensureActionIsPerformedBeforeServerStart("Setting a custom session handler");
jettySessionHandler = Util.INSTANCE.getValidSessionHandlerOrThrow(sessionHandler);
return this;
}
/**
* Configure the WebSocketServletFactory of the instance
* The method must be called before {@link Javalin#start()}.
*/
public Javalin wsFactoryConfig(@NotNull Consumer<WebSocketServletFactory> wsFactoryConfig) {
ensureActionIsPerformedBeforeServerStart("Setting a custom WebSocket factory config");
this.wsFactoryConfig = wsFactoryConfig;
return this;
}
/**
* Configure instance to serve static files from path in classpath.
* The method can be called multiple times for different locations.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#static-files">Static files in docs</a>
*/
public Javalin enableStaticFiles(@NotNull String classpathPath) {
return enableStaticFiles(classpathPath, Location.CLASSPATH);
}
/**
* Configure instance to serve static files from path in the specified location.
* The method can be called multiple times for different locations.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#static-files">Static files in docs</a>
*/
public Javalin enableStaticFiles(@NotNull String path, @NotNull Location location) {
ensureActionIsPerformedBeforeServerStart("Enabling static files");
staticFileConfig.add(new StaticFileConfig(path, location));
return this;
}
/**
* Configure instance to serve WebJars.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableWebJars() {
return enableStaticFiles("/webjars", Location.CLASSPATH);
}
/**
* Any request that would normally result in a 404 for the path and its subpaths
* instead results in a 200 with the file-content from path in classpath as response body.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableSinglePageMode(@NotNull String path, @NotNull String filePath) {
return enableSinglePageMode(path, filePath, Location.CLASSPATH);
}
/**
* Any request that would normally result in a 404 for the path and its subpaths
* instead results in a 200 with the file-content as response body.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableSinglePageMode(@NotNull String path, @NotNull String filePath, @NotNull Location location) {
ensureActionIsPerformedBeforeServerStart("Enabling single page mode");
singlePageHandler.add(path, filePath, location);
return this;
}
/**
* Configure instance to run on specified context path (common prefix).
* The method must be called before {@link Javalin#start()}.
*/
public Javalin contextPath(@NotNull String contextPath) {
ensureActionIsPerformedBeforeServerStart("Setting the context path");
this.contextPath = Util.INSTANCE.normalizeContextPath(contextPath);
return this;
}
/**
* Get which port instance is running on
* Mostly useful if you start the instance with port(0) (random port)
*/
public int port() {
return port;
}
/**
* Configure instance to run on specified port.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin port(int port) {
ensureActionIsPerformedBeforeServerStart("Setting the port");
this.port = port;
return this;
}
/**
* Configure instance to log debug information for each request.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableDebugLogging() {
ensureActionIsPerformedBeforeServerStart("Enabling debug-logging");
this.debugLogging = true;
wsLogger(LogUtil::wsDebugLogger);
return this;
}
/**
* Configure instance use specified request-logger
* The method must be called before {@link Javalin#start()}.
* Will override the default logger of {@link Javalin#enableDebugLogging()}.
*/
public Javalin requestLogger(@NotNull RequestLogger requestLogger) {
ensureActionIsPerformedBeforeServerStart("Setting a custom request logger");
this.requestLogger = requestLogger;
return this;
}
/**
* Configure instance to accept cross origin requests for specified origins.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableCorsForOrigin(@NotNull String... origin) {
ensureActionIsPerformedBeforeServerStart("Enabling CORS");
if (origin.length == 0) throw new IllegalArgumentException("Origins cannot be empty.");
this.before("*", new CorsBeforeHandler(origin));
this.options("*", new CorsOptionsHandler(), roles(CoreRoles.NO_WRAP));
return this;
}
/**
* Configure instance to accept cross origin requests for all origins.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableCorsForAllOrigins() {
return enableCorsForOrigin("*");
}
/**
* Configure instance to not gzip dynamic responses.
* By default Javalin gzips all responses larger than 1500 bytes.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin disableDynamicGzip() {
ensureActionIsPerformedBeforeServerStart("Disabling dynamic GZIP");
this.dynamicGzipEnabled = false;
return this;
}
/**
* Configure instance to automatically add ETags for GET requests.
* Static files already have ETags, this will calculate a checksum for
* dynamic GET responses and return 304 if the content has not changed.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableAutogeneratedEtags() {
ensureActionIsPerformedBeforeServerStart("Enabling autogenerated etags");
this.autogeneratedEtagsEnabled = true;
return this;
}
/**
* Configure instance to display a visual overview of all its mapped routes
* on the specified path.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableRouteOverview(@NotNull String path) {
return enableRouteOverview(path, new HashSet<>());
}
/**
* Configure instance to display a visual overview of all its mapped routes
* on the specified path with the specified roles
* The method must be called before {@link Javalin#start()}.
*/
public Javalin enableRouteOverview(@NotNull String path, @NotNull Set<Role> permittedRoles) {
ensureActionIsPerformedBeforeServerStart("Enabling route overview");
return this.get(path, new RouteOverviewRenderer(this), permittedRoles);
}
/**
* Configure instance to use the specified content-type as a default
* value for all responses. This can be overridden in any Handler.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin defaultContentType(@NotNull String contentType) {
ensureActionIsPerformedBeforeServerStart("Changing default content type");
this.defaultContentType = contentType;
return this;
}
/**
* Configure instance to stop caching requests larger than the specified body size.
* The default value is 4096 bytes.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin maxBodySizeForRequestCache(long bodySizeInBytes) {
ensureActionIsPerformedBeforeServerStart("Changing request cache body size");
this.maxRequestCacheBodySize = bodySizeInBytes;
return this;
}
/**
* Registers an attribute on the instance.
* Instance is available on the {@link Context} through {@link Context#appAttribute}.
* Ex: app.attribute(MyExt.class, myExtInstance())
* The method must be called before {@link Javalin#start()}.
*/
public Javalin attribute(Class clazz, Object obj) {
ensureActionIsPerformedBeforeServerStart("Registering app attributes");
appAttributes.put(clazz, obj);
return this;
}
/**
* Retrieve an attribute stored on the instance.
* Available on the {@link Context} through {@link Context#appAttribute}.
* Ex: app.attribute(MyExt.class).myMethod()
* Ex: ctx.appAttribute(MyExt.class).myMethod()
*/
@SuppressWarnings("unchecked")
public <T> T attribute(Class<T> clazz) {
return (T) appAttributes.get(clazz);
}
/**
* Configure instance to not cache any requests.
* If you call this method you will not be able to log request-bodies.
* The method must be called before {@link Javalin#start()}.
*/
public Javalin disableRequestCache() {
return maxBodySizeForRequestCache(0);
}
private void ensureActionIsPerformedBeforeServerStart(@NotNull String action) {
if (started) {
throw new IllegalStateException(action + " must be done before starting the server.");
}
}
/**
* Sets the access manager for the instance. Secured endpoints require one to be set.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#access-manager">Access manager in docs</a>
* @see AccessManager
*/
public Javalin accessManager(@NotNull AccessManager accessManager) {
ensureActionIsPerformedBeforeServerStart("Setting an AccessManager");
this.accessManager = accessManager;
return this;
}
/**
* Adds an exception mapper to the instance.
* Useful for turning exceptions into standardized errors/messages/pages
*
* @see <a href="https://javalin.io/documentation#exception-mapping">Exception mapping in docs</a>
*/
public <T extends Exception> Javalin exception(@NotNull Class<T> exceptionClass, @NotNull ExceptionHandler<? super T> exceptionHandler) {
exceptionMapper.getExceptionMap().put(exceptionClass, (ExceptionHandler<Exception>) exceptionHandler);
return this;
}
/**
* Adds a lifecycle event listener.
* The method must be called before {@link Javalin#start()}.
*
* @see <a href="https://javalin.io/documentation#lifecycle-events">Events in docs</a>
*/
public Javalin event(@NotNull JavalinEvent javalinEvent, @NotNull EventListener eventListener) {
ensureActionIsPerformedBeforeServerStart("Event-mapping");
eventManager.getListenerMap().get(javalinEvent).add(eventListener);
return this;
}
/**
* Configures a web socket handler to be called after every web socket event
* The method must be called before {@link Javalin#start()}.
* Will override the default logger of {@link Javalin#enableDebugLogging()}.
*/
public Javalin wsLogger(@NotNull Consumer<WsHandler> ws) {
ensureActionIsPerformedBeforeServerStart("Adding a WebSocket logger");
WsHandler wsLogger = new WsHandler();
ws.accept(wsLogger);
wsPathMatcher.setWsLogger(wsLogger);
return this;
}
/**
* Adds an error mapper to the instance.
* Useful for turning error-codes (404, 500) into standardized messages/pages
*
* @see <a href="https://javalin.io/documentation#error-mapping">Error mapping in docs</a>
*/
public Javalin error(int statusCode, @NotNull ErrorHandler errorHandler) {
errorMapper.getErrorHandlerMap().put(statusCode, errorHandler);
return this;
}
/**
* Registers an {@link Extension} with the instance.
* You're free to implement the extension as a class or a lambda expression
*/
public Javalin register(Extension extension) {
extension.registerOnJavalin(this);
return this;
}
/**
* Creates a temporary static instance in the scope of the endpointGroup.
* Allows you to call get(handler), post(handler), etc. without without using the instance prefix.
*
* @see <a href="https://javalin.io/documentation#handler-groups">Handler groups in documentation</a>
* @see ApiBuilder
*/
public Javalin routes(@NotNull EndpointGroup endpointGroup) {
ApiBuilder.setStaticJavalin(this);
endpointGroup.addEndpoints();
ApiBuilder.clearStaticJavalin();
return this;
}
/**
* Adds a request handler for the specified handlerType and path to the instance.
* Requires an access manager to be set on the instance.
* This is the method that all the verb-methods (get/post/put/etc) call.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin addHandler(@NotNull HandlerType handlerType, @NotNull String path, @NotNull Handler handler, @NotNull Set<Role> roles) {
boolean shouldWrap = handlerType.isHttpMethod() && !roles.contains(CoreRoles.NO_WRAP); // don't wrap CORS options
String prefixedPath = Util.prefixContextPath(contextPath, path);
Handler protectedHandler = shouldWrap ? ctx -> accessManager.manage(handler, ctx, roles) : handler;
pathMatcher.add(new HandlerEntry(handlerType, prefixedPath, protectedHandler, handler, caseSensitiveUrls));
handlerMetaInfo.add(new HandlerMetaInfo(handlerType, prefixedPath, handler, roles));
return this;
}
/**
* Adds a request handler for the specified handlerType and path to the instance.
* This is the method that all the verb-methods (get/post/put/etc) call.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin addHandler(@NotNull HandlerType httpMethod, @NotNull String path, @NotNull Handler handler) {
return addHandler(httpMethod, path, handler, new HashSet<>()); // no roles set for this route (open to everyone)
}
// HTTP verbs
/**
* Adds a GET request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin get(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.GET, path, handler);
}
/**
* Adds a POST request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin post(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.POST, path, handler);
}
/**
* Adds a PUT request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin put(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.PUT, path, handler);
}
/**
* Adds a PATCH request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin patch(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.PATCH, path, handler);
}
/**
* Adds a DELETE request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin delete(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.DELETE, path, handler);
}
/**
* Adds a HEAD request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin head(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.HEAD, path, handler);
}
/**
* Adds a TRACE request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin trace(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.TRACE, path, handler);
}
/**
* Adds a CONNECT request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin connect(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.CONNECT, path, handler);
}
/**
* Adds a OPTIONS request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin options(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.OPTIONS, path, handler);
}
// Secured HTTP verbs
/**
* Adds a GET request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin get(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.GET, path, handler, permittedRoles);
}
/**
* Adds a POST request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin post(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.POST, path, handler, permittedRoles);
}
/**
* Adds a PUT request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin put(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.PUT, path, handler, permittedRoles);
}
/**
* Adds a PATCH request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin patch(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.PATCH, path, handler, permittedRoles);
}
/**
* Adds a DELETE request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin delete(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.DELETE, path, handler, permittedRoles);
}
/**
* Adds a HEAD request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin head(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.HEAD, path, handler, permittedRoles);
}
/**
* Adds a TRACE request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin trace(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.TRACE, path, handler, permittedRoles);
}
/**
* Adds a CONNECT request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin connect(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.CONNECT, path, handler, permittedRoles);
}
/**
* Adds a OPTIONS request handler with the given roles for the specified path to the instance.
* Requires an access manager to be set on the instance.
*
* @see AccessManager
* @see Javalin#accessManager(AccessManager)
* @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
*/
public Javalin options(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
return addHandler(HandlerType.OPTIONS, path, handler, permittedRoles);
}
// Filters
/**
* Adds a BEFORE request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin before(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.BEFORE, path, handler);
}
/**
* Adds a BEFORE request handler for all routes in the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin before(@NotNull Handler handler) {
return before("*", handler);
}
/**
* Adds an AFTER request handler for the specified path to the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin after(@NotNull String path, @NotNull Handler handler) {
return addHandler(HandlerType.AFTER, path, handler);
}
/**
* Adds an AFTER request handler for all routes in the instance.
*
* @see <a href="https://javalin.io/documentation#before-handlers">Handlers in docs</a>
*/
public Javalin after(@NotNull Handler handler) {
return after("*", handler);
}
/**
* Adds a WebSocket handler on the specified path.
*
* @see <a href="https://javalin.io/documentation#websockets">WebSockets in docs</a>
*/
public Javalin ws(@NotNull String path, @NotNull Consumer<WsHandler> ws) {
String prefixedPath = Util.prefixContextPath(contextPath, path);
WsHandler configuredWebSocket = new WsHandler();
ws.accept(configuredWebSocket);
wsPathMatcher.add(new WsEntry(prefixedPath, configuredWebSocket, caseSensitiveUrls));
handlerMetaInfo.add(new HandlerMetaInfo(HandlerType.WEBSOCKET, prefixedPath, ws, new HashSet<>()));
return this;
}
/**
* Gets the list of HandlerMetaInfo-objects
*/
public List<HandlerMetaInfo> getHandlerMetaInfo() {
return new ArrayList<>(handlerMetaInfo);
}
/**
* Adds a lambda handler for a Server Sent Event connection on the specified path.
*/
public Javalin sse(@NotNull String path, @NotNull Consumer<SseClient> client) {
return sse(path, client, new HashSet<>());
}
/**
* Adds a lambda handler for a Server Sent Event connection on the specified path.
* Requires an access manager to be set on the instance.
*/
public Javalin sse(@NotNull String path, @NotNull Consumer<SseClient> client, @NotNull Set<Role> permittedRoles) {
return get(path, new SseHandler(client), permittedRoles);
}
}
| [core] Add missing exception to throws in start()
| src/main/java/io/javalin/Javalin.java | [core] Add missing exception to throws in start() |
|
Java | apache-2.0 | fb5c165a9d1081048b05b7f4b1ef6fb04735e114 | 0 | 11xor6/presto,smartnews/presto,11xor6/presto,smartnews/presto,losipiuk/presto,martint/presto,Praveen2112/presto,dain/presto,electrum/presto,martint/presto,erichwang/presto,treasure-data/presto,smartnews/presto,treasure-data/presto,losipiuk/presto,martint/presto,dain/presto,losipiuk/presto,ebyhr/presto,erichwang/presto,dain/presto,electrum/presto,losipiuk/presto,hgschmie/presto,electrum/presto,hgschmie/presto,ebyhr/presto,electrum/presto,Praveen2112/presto,erichwang/presto,dain/presto,11xor6/presto,Praveen2112/presto,electrum/presto,Praveen2112/presto,11xor6/presto,treasure-data/presto,dain/presto,erichwang/presto,treasure-data/presto,ebyhr/presto,treasure-data/presto,Praveen2112/presto,martint/presto,hgschmie/presto,smartnews/presto,hgschmie/presto,hgschmie/presto,losipiuk/presto,treasure-data/presto,ebyhr/presto,smartnews/presto,ebyhr/presto,11xor6/presto,martint/presto,erichwang/presto | /*
* 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 io.prestosql.plugin.hive;
import com.google.common.collect.ImmutableSet;
import io.airlift.log.Logger;
import io.prestosql.plugin.hive.metastore.Column;
import io.prestosql.plugin.hive.metastore.Partition;
import io.prestosql.plugin.hive.metastore.Table;
import io.prestosql.spi.connector.ConnectorSession;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.io.compress.GzipCodec;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.TextInputFormat;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import static io.prestosql.plugin.hive.HiveSessionProperties.isS3SelectPushdownEnabled;
import static io.prestosql.plugin.hive.HiveUtil.getCompressionCodec;
import static io.prestosql.plugin.hive.HiveUtil.getDeserializerClassName;
import static io.prestosql.plugin.hive.HiveUtil.getInputFormatName;
import static io.prestosql.plugin.hive.metastore.MetastoreUtil.getHiveSchema;
import static java.util.Objects.requireNonNull;
import static org.apache.hadoop.hive.serde.serdeConstants.BIGINT_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.BOOLEAN_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.DATE_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.DECIMAL_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.INT_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.SMALLINT_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.STRING_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.TINYINT_TYPE_NAME;
/**
* S3SelectPushdown uses Amazon S3 Select to push down queries to Amazon S3. This allows Presto to retrieve only a
* subset of data rather than retrieving the full S3 object thus improving Presto query performance.
*/
public class S3SelectPushdown
{
private static final Logger LOG = Logger.get(S3SelectPushdown.class);
private static final Set<String> SUPPORTED_S3_PREFIXES = ImmutableSet.of("s3://", "s3a://", "s3n://");
private static final Set<String> SUPPORTED_SERDES = ImmutableSet.of(LazySimpleSerDe.class.getName());
private static final Set<String> SUPPORTED_INPUT_FORMATS = ImmutableSet.of(TextInputFormat.class.getName());
/*
* Double and Real Types lose precision. Thus, they are not pushed down to S3. Please use Decimal Type if push down is desired.
*
* Pushing down timestamp to s3select is problematic due to following reasons:
* 1) Presto bug: TIMESTAMP behaviour does not match sql standard (https://github.com/prestodb/presto/issues/7122)
* 2) Presto uses the timezone from client to convert the timestamp if no timezone is provided, however, s3select is a different service and this could lead to unexpected results.
* 3) ION SQL compare timestamps using precision, timestamps with different precisions are not equal even actually they present the same instant of time. This could lead to unexpected results.
*/
private static final Set<String> SUPPORTED_COLUMN_TYPES = ImmutableSet.of(
BOOLEAN_TYPE_NAME,
INT_TYPE_NAME,
TINYINT_TYPE_NAME,
SMALLINT_TYPE_NAME,
BIGINT_TYPE_NAME,
STRING_TYPE_NAME,
DECIMAL_TYPE_NAME,
DATE_TYPE_NAME);
private S3SelectPushdown() {}
private static boolean isSerdeSupported(Properties schema)
{
String serdeName = getDeserializerClassName(schema);
return SUPPORTED_SERDES.contains(serdeName);
}
private static boolean isInputFormatSupported(Properties schema)
{
String inputFormat = getInputFormatName(schema);
return SUPPORTED_INPUT_FORMATS.contains(inputFormat);
}
public static boolean isCompressionCodecSupported(InputFormat<?, ?> inputFormat, Path path)
{
if (inputFormat instanceof TextInputFormat) {
return getCompressionCodec((TextInputFormat) inputFormat, path)
.map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec))
.orElse(true);
}
return false;
}
private static boolean areColumnTypesSupported(List<Column> columns)
{
requireNonNull(columns, "columns is null");
if (columns.isEmpty()) {
return false;
}
for (Column column : columns) {
String type = column.getType().getHiveTypeName().toString();
if (column.getType().getTypeInfo() instanceof DecimalTypeInfo) {
// skip precision and scale when check decimal type
type = DECIMAL_TYPE_NAME;
}
if (!SUPPORTED_COLUMN_TYPES.contains(type)) {
return false;
}
}
return true;
}
private static boolean isS3Storage(String path)
{
return SUPPORTED_S3_PREFIXES.stream().anyMatch(path::startsWith);
}
static boolean shouldEnablePushdownForTable(ConnectorSession session, Table table, String path, Optional<Partition> optionalPartition)
{
if (!isS3SelectPushdownEnabled(session)) {
return false;
}
if (path == null) {
return false;
}
// Hive table partitions could be on different storages,
// as a result, we have to check each individual optionalPartition
Properties schema = optionalPartition
.map(partition -> getHiveSchema(partition, table))
.orElseGet(() -> getHiveSchema(table));
return shouldEnablePushdownForTable(table, path, schema);
}
private static boolean shouldEnablePushdownForTable(Table table, String path, Properties schema)
{
return isS3Storage(path) &&
isSerdeSupported(schema) &&
isInputFormatSupported(schema) &&
areColumnTypesSupported(table.getDataColumns());
}
}
| presto-hive/src/main/java/io/prestosql/plugin/hive/S3SelectPushdown.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 io.prestosql.plugin.hive;
import com.google.common.collect.ImmutableSet;
import io.airlift.log.Logger;
import io.prestosql.plugin.hive.metastore.Column;
import io.prestosql.plugin.hive.metastore.Partition;
import io.prestosql.plugin.hive.metastore.Table;
import io.prestosql.spi.connector.ConnectorSession;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.io.compress.GzipCodec;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.TextInputFormat;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import static io.prestosql.plugin.hive.HiveSessionProperties.isS3SelectPushdownEnabled;
import static io.prestosql.plugin.hive.HiveUtil.getCompressionCodec;
import static io.prestosql.plugin.hive.HiveUtil.getDeserializerClassName;
import static io.prestosql.plugin.hive.HiveUtil.getInputFormatName;
import static io.prestosql.plugin.hive.metastore.MetastoreUtil.getHiveSchema;
import static org.apache.hadoop.hive.serde.serdeConstants.BIGINT_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.BOOLEAN_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.DATE_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.DECIMAL_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.INT_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.SMALLINT_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.STRING_TYPE_NAME;
import static org.apache.hadoop.hive.serde.serdeConstants.TINYINT_TYPE_NAME;
/**
* S3SelectPushdown uses Amazon S3 Select to push down queries to Amazon S3. This allows Presto to retrieve only a
* subset of data rather than retrieving the full S3 object thus improving Presto query performance.
*/
public class S3SelectPushdown
{
private static final Logger LOG = Logger.get(S3SelectPushdown.class);
private static final Set<String> SUPPORTED_S3_PREFIXES = ImmutableSet.of("s3://", "s3a://", "s3n://");
private static final Set<String> SUPPORTED_SERDES = ImmutableSet.of(LazySimpleSerDe.class.getName());
private static final Set<String> SUPPORTED_INPUT_FORMATS = ImmutableSet.of(TextInputFormat.class.getName());
/*
* Double and Real Types lose precision. Thus, they are not pushed down to S3. Please use Decimal Type if push down is desired.
*
* Pushing down timestamp to s3select is problematic due to following reasons:
* 1) Presto bug: TIMESTAMP behaviour does not match sql standard (https://github.com/prestodb/presto/issues/7122)
* 2) Presto uses the timezone from client to convert the timestamp if no timezone is provided, however, s3select is a different service and this could lead to unexpected results.
* 3) ION SQL compare timestamps using precision, timestamps with different precisions are not equal even actually they present the same instant of time. This could lead to unexpected results.
*/
private static final Set<String> SUPPORTED_COLUMN_TYPES = ImmutableSet.of(
BOOLEAN_TYPE_NAME,
INT_TYPE_NAME,
TINYINT_TYPE_NAME,
SMALLINT_TYPE_NAME,
BIGINT_TYPE_NAME,
STRING_TYPE_NAME,
DECIMAL_TYPE_NAME,
DATE_TYPE_NAME);
private S3SelectPushdown() {}
private static boolean isSerdeSupported(Properties schema)
{
String serdeName = getDeserializerClassName(schema);
return SUPPORTED_SERDES.contains(serdeName);
}
private static boolean isInputFormatSupported(Properties schema)
{
String inputFormat = getInputFormatName(schema);
return SUPPORTED_INPUT_FORMATS.contains(inputFormat);
}
public static boolean isCompressionCodecSupported(InputFormat<?, ?> inputFormat, Path path)
{
if (inputFormat instanceof TextInputFormat) {
return getCompressionCodec((TextInputFormat) inputFormat, path)
.map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec))
.orElse(true);
}
return false;
}
private static boolean areColumnTypesSupported(List<Column> columns)
{
if (columns == null || columns.isEmpty()) {
return false;
}
for (Column column : columns) {
String type = column.getType().getHiveTypeName().toString();
if (column.getType().getTypeInfo() instanceof DecimalTypeInfo) {
// skip precision and scale when check decimal type
type = DECIMAL_TYPE_NAME;
}
if (!SUPPORTED_COLUMN_TYPES.contains(type)) {
return false;
}
}
return true;
}
private static boolean isS3Storage(String path)
{
return SUPPORTED_S3_PREFIXES.stream().anyMatch(path::startsWith);
}
static boolean shouldEnablePushdownForTable(ConnectorSession session, Table table, String path, Optional<Partition> optionalPartition)
{
if (!isS3SelectPushdownEnabled(session)) {
return false;
}
if (path == null) {
return false;
}
// Hive table partitions could be on different storages,
// as a result, we have to check each individual optionalPartition
Properties schema = optionalPartition
.map(partition -> getHiveSchema(partition, table))
.orElseGet(() -> getHiveSchema(table));
return shouldEnablePushdownForTable(table, path, schema);
}
private static boolean shouldEnablePushdownForTable(Table table, String path, Properties schema)
{
return isS3Storage(path) &&
isSerdeSupported(schema) &&
isInputFormatSupported(schema) &&
areColumnTypesSupported(table.getDataColumns());
}
}
| Remove unnecessary lenient treatment of null value
`columns` is non-null here.
| presto-hive/src/main/java/io/prestosql/plugin/hive/S3SelectPushdown.java | Remove unnecessary lenient treatment of null value |
|
Java | apache-2.0 | 91f7a5ae4b09180d7aea8e774dbaeb2d69ed5f80 | 0 | harismexis/CameraHttp | package eu.cuteapps.camerahttp.constants;
public class Prefs {
public static final String PREF_BACK_CAMERA_PICTURE_SIZE_WIDTH = "back_camera_picture_size_width";
public static final String PREF_BACK_CAMERA_PICTURE_SIZE_HEIGHT = "back_camera_picture_size_height";
public static final String PREF_BACK_CAMERA_VIDEO_SIZE_WIDTH = "back_camera_video_size_width";
public static final String PREF_BACK_CAMERA_VIDEO_SIZE_HEIGHT = "back_camera_video_size_height";
public static final String PREF_FRONT_CAMERA_PICTURE_SIZE_WIDTH = "front_camera_picture_size_width";
public static final String PREF_FRONT_CAMERA_PICTURE_SIZE_HEIGHT = "front_camera_picture_size_height";
public static final String PREF_FRONT_CAMERA_VIDEO_SIZE_WIDTH = "front_camera_video_size_width";
public static final String PREF_FRONT_CAMERA_VIDEO_SIZE_HEIGHT = "front_camera_video_size_height";
public static final String PREF_PHOTO_CAMERA_FLASH_MODE = "photo_camera_flash_mode";
public static final String PREF_VIDEO_CAMERA_FLASH_MODE = "video_camera_flash_mode";
public static final String PREF_IS_FACING_BACK_CAMERA = "is_facing_back_camera";
public static final String PREF_IS_VIDEO_CAMERA_MODE = "is_video_camera_mode";
public static final String PREF_STORE_CAPTURES_TO_DB = "store_captures_to_db";
public static final String PREF_LAST_CAPTURED_FILE_PATH = "last_captured_file_path";
public static final String PREF_PERIODIC_CAPTURE_INTERVAL = "periodic_capture_interval";
public static final String PREF_DELAY_AFTER_CAPTURE = "delay_after_capture";
public static final String PREF_ZOOM = "zoom";
public static final String PREF_EXPOSURE_COMPENSATION = "exposure_compensation";
public static final String PREF_SCENE_MODE = "scene_mode";
public static final String PREF_WHITE_BALANCE = "white_balance";
public static final String PREF_COLOR_EFFECT = "color_effect";
public static final String PREF_SHUTTER_SOUND = "shutter_sound";
public static final String PREF_SERVER_URL = "server_url";
}
| app/src/main/java/eu/cuteapps/camerahttp/constants/Prefs.java | package eu.cuteapps.camerahttp.constants;
public class Prefs {
public static final String PREF_BACK_CAMERA_PICTURE_SIZE_WIDTH = "back_camera_picture_size_width";
public static final String PREF_BACK_CAMERA_PICTURE_SIZE_HEIGHT = "back_camera_picture_size_height";
public static final String PREF_BACK_CAMERA_VIDEO_SIZE_WIDTH = "back_camera_video_size_width";
public static final String PREF_BACK_CAMERA_VIDEO_SIZE_HEIGHT = "back_camera_video_size_height";
public static final String PREF_FRONT_CAMERA_PICTURE_SIZE_WIDTH = "front_camera_picture_size_width";
public static final String PREF_FRONT_CAMERA_PICTURE_SIZE_HEIGHT = "front_camera_picture_size_height";
public static final String PREF_FRONT_CAMERA_VIDEO_SIZE_WIDTH = "front_camera_video_size_width";
public static final String PREF_FRONT_CAMERA_VIDEO_SIZE_HEIGHT = "front_camera_video_size_height";
public static final String PREF_PHOTO_CAMERA_FLASH_MODE = "photo_camera_flash_mode";
public static final String PREF_VIDEO_CAMERA_FLASH_MODE = "video_camera_flash_mode";
public static final String PREF_IS_FACING_BACK_CAMERA = "is_facing_back_camera";
public static final String PREF_IS_VIDEO_CAMERA_MODE = "is_video_camera_mode";
public static final String PREF_STORE_CAPTURES_TO_DB = "store_captures_to_db";
public static final String PREF_LAST_CAPTURED_FILE_PATH = "last_captured_file_path";
public static final String PREF_PERIODIC_CAPTURE_INTERVAL = "periodic_capture_interval";
public static final String PREF_DELAY_AFTER_CAPTURE = "delay_after_capture";
public static final String PREF_ZOOM = "zoom";
public static final String PREF_EXPOSURE_COMPENSATION = "exposure_compensation";
public static final String PREF_SCENE_MODE = "scene_mode";
public static final String PREF_WHITE_BALANCE = "white_balance";
public static final String PREF_COLOR_EFFECT = "color_effect";
public static final String PREF_SHUTTER_SOUND = "shutter_sound";
public static final String PREF_SERVER_URL = "server_url";
}
| Update preference names
| app/src/main/java/eu/cuteapps/camerahttp/constants/Prefs.java | Update preference names |
|
Java | apache-2.0 | e205182aba20c563ae3cbcfeca6304057927c011 | 0 | project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform | package gr.ntua.cslab.asap.staticLibraries;
import gr.ntua.cslab.asap.operators.AbstractOperator;
import gr.ntua.cslab.asap.operators.Dataset;
import gr.ntua.cslab.asap.operators.Operator;
import gr.ntua.cslab.asap.rest.beans.OperatorDescription;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sourceforge.jeval.function.string.Length;
import org.apache.log4j.Logger;
public class OperatorLibrary {
private static HashMap<String,Operator> operators;
public static String operatorDirectory;
private static Logger logger = Logger.getLogger(OperatorLibrary.class.getName());
public static int moveid=0;
public static void initialize(String directory) throws Exception{
operatorDirectory = directory;
operators = new HashMap<String,Operator>();
File folder = new File(directory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
Logger.getLogger(OperatorLibrary.class.getName()).info("Loading operator: " + listOfFiles[i].getName());
Operator temp = new Operator(listOfFiles[i].getName(), listOfFiles[i].toString());
temp.readFromDir();
operators.put(temp.opName, temp);
}
}
}
public static void refresh(){
}
public static List<String> getOperators(){
List<String> ret = new ArrayList<String>();
for(Operator op : operators.values()){
ret.add(op.opName);
}
return ret;
}
public static List<Operator> getMatchesNoIncrementID(AbstractOperator abstractOperator) throws Exception{
//logger.info("Check matches: "+abstractOperator.opName);
List<Operator> ret = new ArrayList<Operator>();
for(Operator op : operators.values()){
if(abstractOperator.checkMatch(op)){
Operator temp = new Operator(op.opName, op.directory);
temp.optree=op.optree.clone();
temp.inputSpace=op.inputSpace;
temp.outputSpace=op.outputSpace;
temp.models=op.models;
ret.add(temp);
}
}
for(Operator o :ret){
logger.info("Found: "+o.opName);
}
return ret;
}
public static List<Operator> getMatches(AbstractOperator abstractOperator) throws Exception{
//logger.info("Check matches: "+abstractOperator.opName);
List<Operator> ret = new ArrayList<Operator>();
for(Operator op : operators.values()){
if(abstractOperator.checkMatch(op)){
Operator temp = new Operator(op.opName+"_"+moveid, op.directory);
moveid++;
temp.optree=op.optree.clone();
temp.inputSpace=op.inputSpace;
temp.outputSpace=op.outputSpace;
temp.models=op.models;
ret.add(temp);
}
}
for(Operator o :ret){
logger.info("Found: "+o.opName);
}
return ret;
}
public static List<Operator> getMatchesNoTempID(AbstractOperator abstractOperator) throws Exception{
//logger.info("Check matches: "+abstractOperator.opName);
List<Operator> ret = new ArrayList<Operator>();
for(Operator op : operators.values()){
if(abstractOperator.checkMatch(op)){
Operator temp = new Operator(op.opName, op.directory);
moveid++;
temp.optree=op.optree.clone();
temp.inputSpace=op.inputSpace;
temp.outputSpace=op.outputSpace;
temp.models=op.models;
ret.add(temp);
}
}
for(Operator o :ret){
logger.info("Found: "+o.opName);
}
return ret;
}
public static List<Operator> checkMove(Dataset from, Dataset to) throws Exception {
logger.info("Check move from: "+from+" to: "+to);
AbstractOperator abstractMove = new AbstractOperator("move");
abstractMove.moveOperator(from,to);
return getMatches(abstractMove);
}
public static String getOperatorDescription(String id) {
Operator op = operators.get(id);
if(op==null)
return "No description available";
return op.toKeyValues("\n");
}
public static OperatorDescription getOperatorDescriptionJSON(String id) {
Operator op = operators.get(id);
if(op==null)
return new OperatorDescription("", "");
return op.toOperatorDescription();
}
public static void add(Operator o) {
operators.put(o.opName, o);
}
public static void editOperator(String opname, String opString) throws Exception {
String dir = "asapLibrary/operators/"+opname;
Operator old = operators.remove(opname);
old.writeModels(dir);
Operator o = new Operator(opname,dir);
InputStream is = new ByteArrayInputStream(opString.getBytes());
o.readPropertiesFromStream(is);
o.writeDescriptionToPropertiesFile(dir);
Operator temp = new Operator(opname, dir);
temp.readFromDir();
operators.put(temp.opName, temp);
}
public static void addOperator(String opname, String opString) throws Exception {
Operator o = new Operator(opname,"asapLibrary/operators/"+opname);
InputStream is = new ByteArrayInputStream(opString.getBytes());
o.readPropertiesFromStream(is);
o.writeToPropertiesFile("asapLibrary/operators/"+o.opName);
o.configureModel();
add(o);
is.close();
}
public static void deleteOperator(String opname) {
Operator op = operators.remove(opname);
op.deleteDiskData();
}
public static Operator getOperator(String opname) {
return operators.get(opname);
}
public static String getProfile(String opname, String variable, String profileType) throws Exception {
Operator op = operators.get(opname);
op.configureModel();
if(profileType.equals("Compare models")){
/*File csv = new File(operatorDirectory+"/"+op.opName+"/data/"+variable+".csv");
if(csv.exists()){
op.writeCSVfileUniformSampleOfModel(variable, 1.0, "www/test.csv", ",",true);
append("www/test.csv",csv.toString(),",", op.inputSpace);
}
else{
op.writeCSVfileUniformSampleOfModel(variable, 1.0, "www/test.csv", ",",false);
}*/
op.writeCSVfileUniformSampleOfModel(variable, 1.0, "www/test.csv", ",",true);
}
else if(profileType.equals("View model")){
op.writeCSVfileUniformSampleOfModel(variable, 1.0, "www/test.csv", ",",false);
}
else{
File csv = new File(operatorDirectory+"/"+op.opName+"/data/"+variable+".csv");
if(csv.exists()){
op.writeCSVfileUniformSampleOfModel(variable, 0.0, "www/test.csv", ",",true);
append("www/test.csv",csv.toString(),",", op.inputSpace);
}
else{
op.writeCSVfileUniformSampleOfModel(variable, 0.0, "www/test.csv", ",",true);
}
}
//op.writeCSVfileUniformSampleOfModel(1.0, "www/test.csv", ",");
return "/test.csv";
/*if(opname.equals("Sort"))
return "/terasort.csv";
else
return "/iris.csv";*/
}
private static void append(String toCSV, String fromCSV,String delimiter, HashMap<String, String> inputSpace) throws Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(toCSV, true)));
BufferedReader br = new BufferedReader(new FileReader(fromCSV));
String line = br.readLine();
String[] variables = line.split(delimiter);
HashMap<String, Integer> varMapping = new HashMap<String, Integer>();
for (int i = 0; i < variables.length; i++) {
int j = 0;
for(String k: inputSpace.keySet()){
if(variables[i].equals(k)){
varMapping.put(k, j);
break;
}
j++;
}
}
//System.out.println(varMapping);
line = br.readLine();
while (line != null) {
String[] sample = line.split(delimiter);
String[] ls = new String[sample.length-1];
for (int i = 0; i < sample.length-1; i++) {
//System.out.println(variables[i]+" "+sample[i]);
ls[varMapping.get(variables[i])]= sample[i];
}
String n = "";
for(String s : ls){
n+=s+delimiter;
}
n+=sample[sample.length-1]+delimiter;
//System.out.println(n);
out.append(n+"Samples");
out.append(System.lineSeparator());
line = br.readLine();
}
out.close();
br.close();
}
/*protected static void writeCSV(String file, ){
}*/
}
| asap-platform/asap-beans/src/main/java/gr/ntua/cslab/asap/staticLibraries/OperatorLibrary.java | package gr.ntua.cslab.asap.staticLibraries;
import gr.ntua.cslab.asap.operators.AbstractOperator;
import gr.ntua.cslab.asap.operators.Dataset;
import gr.ntua.cslab.asap.operators.Operator;
import gr.ntua.cslab.asap.rest.beans.OperatorDescription;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sourceforge.jeval.function.string.Length;
import org.apache.log4j.Logger;
public class OperatorLibrary {
private static HashMap<String,Operator> operators;
public static String operatorDirectory;
private static Logger logger = Logger.getLogger(OperatorLibrary.class.getName());
public static int moveid=0;
public static void initialize(String directory) throws Exception{
operatorDirectory = directory;
operators = new HashMap<String,Operator>();
File folder = new File(directory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
Logger.getLogger(OperatorLibrary.class.getName()).info("Loading operator: " + listOfFiles[i].getName());
Operator temp = new Operator(listOfFiles[i].getName(), listOfFiles[i].toString());
temp.readFromDir();
operators.put(temp.opName, temp);
}
}
}
public static void refresh(){
}
public static List<String> getOperators(){
List<String> ret = new ArrayList<String>();
for(Operator op : operators.values()){
ret.add(op.opName);
}
return ret;
}
public static List<Operator> getMatchesNoIncrementID(AbstractOperator abstractOperator) throws Exception{
//logger.info("Check matches: "+abstractOperator.opName);
List<Operator> ret = new ArrayList<Operator>();
for(Operator op : operators.values()){
if(abstractOperator.checkMatch(op)){
Operator temp = new Operator(op.opName, op.directory);
temp.optree=op.optree.clone();
temp.inputSpace=op.inputSpace;
temp.outputSpace=op.outputSpace;
temp.models=op.models;
ret.add(temp);
}
}
for(Operator o :ret){
logger.info("Found: "+o.opName);
}
return ret;
}
public static List<Operator> getMatches(AbstractOperator abstractOperator) throws Exception{
//logger.info("Check matches: "+abstractOperator.opName);
List<Operator> ret = new ArrayList<Operator>();
for(Operator op : operators.values()){
if(abstractOperator.checkMatch(op)){
Operator temp = new Operator(op.opName+"_"+moveid, op.directory);
moveid++;
temp.optree=op.optree.clone();
temp.inputSpace=op.inputSpace;
temp.outputSpace=op.outputSpace;
temp.models=op.models;
ret.add(temp);
}
}
for(Operator o :ret){
logger.info("Found: "+o.opName);
}
return ret;
}
public static List<Operator> getMatchesNoTempID(AbstractOperator abstractOperator) throws Exception{
//logger.info("Check matches: "+abstractOperator.opName);
List<Operator> ret = new ArrayList<Operator>();
for(Operator op : operators.values()){
if(abstractOperator.checkMatch(op)){
Operator temp = new Operator(op.opName, op.directory);
moveid++;
temp.optree=op.optree.clone();
temp.inputSpace=op.inputSpace;
temp.outputSpace=op.outputSpace;
temp.models=op.models;
ret.add(temp);
}
}
for(Operator o :ret){
logger.info("Found: "+o.opName);
}
return ret;
}
public static List<Operator> checkMove(Dataset from, Dataset to) throws Exception {
logger.info("Check move from: "+from+" to: "+to);
AbstractOperator abstractMove = new AbstractOperator("move");
abstractMove.moveOperator(from,to);
return getMatches(abstractMove);
}
public static String getOperatorDescription(String id) {
Operator op = operators.get(id);
if(op==null)
return "No description available";
return op.toKeyValues("\n");
}
public static OperatorDescription getOperatorDescriptionJSON(String id) {
Operator op = operators.get(id);
if(op==null)
return new OperatorDescription("", "");
return op.toOperatorDescription();
}
public static void add(Operator o) {
operators.put(o.opName, o);
}
public static void editOperator(String opname, String opString) throws Exception {
String dir = "asapLibrary/operators/"+opname;
Operator old = operators.remove(opname);
old.writeModels(dir);
Operator o = new Operator(opname,dir);
InputStream is = new ByteArrayInputStream(opString.getBytes());
o.readPropertiesFromStream(is);
o.writeDescriptionToPropertiesFile(dir);
Operator temp = new Operator(opname, dir);
temp.readFromDir();
operators.put(temp.opName, temp);
}
public static void addOperator(String opname, String opString) throws Exception {
Operator o = new Operator(opname,"asapLibrary/operators/"+opname);
InputStream is = new ByteArrayInputStream(opString.getBytes());
o.readPropertiesFromStream(is);
o.writeToPropertiesFile("asapLibrary/operators/"+o.opName);
o.configureModel();
add(o);
is.close();
}
public static void deleteOperator(String opname) {
Operator op = operators.remove(opname);
op.deleteDiskData();
}
public static Operator getOperator(String opname) {
return operators.get(opname);
}
public static String getProfile(String opname, String variable, String profileType) throws Exception {
Operator op = operators.get(opname);
op.configureModel();
if(profileType.equals("Compare models")){
File csv = new File(operatorDirectory+"/"+op.opName+"/data/"+variable+".csv");
if(csv.exists()){
op.writeCSVfileUniformSampleOfModel(variable, 1.0, "www/test.csv", ",",true);
append("www/test.csv",csv.toString(),",", op.inputSpace);
}
else{
op.writeCSVfileUniformSampleOfModel(variable, 1.0, "www/test.csv", ",",false);
}
}
else if(profileType.equals("View model")){
op.writeCSVfileUniformSampleOfModel(variable, 1.0, "www/test.csv", ",",false);
}
else{
File csv = new File(operatorDirectory+"/"+op.opName+"/data/"+variable+".csv");
if(csv.exists()){
op.writeCSVfileUniformSampleOfModel(variable, 0.0, "www/test.csv", ",",true);
append("www/test.csv",csv.toString(),",", op.inputSpace);
}
else{
op.writeCSVfileUniformSampleOfModel(variable, 0.0, "www/test.csv", ",",true);
}
}
//op.writeCSVfileUniformSampleOfModel(1.0, "www/test.csv", ",");
return "/test.csv";
/*if(opname.equals("Sort"))
return "/terasort.csv";
else
return "/iris.csv";*/
}
private static void append(String toCSV, String fromCSV,String delimiter, HashMap<String, String> inputSpace) throws Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(toCSV, true)));
BufferedReader br = new BufferedReader(new FileReader(fromCSV));
String line = br.readLine();
String[] variables = line.split(delimiter);
HashMap<String, Integer> varMapping = new HashMap<String, Integer>();
for (int i = 0; i < variables.length; i++) {
int j = 0;
for(String k: inputSpace.keySet()){
if(variables[i].equals(k)){
varMapping.put(k, j);
break;
}
j++;
}
}
//System.out.println(varMapping);
line = br.readLine();
while (line != null) {
String[] sample = line.split(delimiter);
String[] ls = new String[sample.length-1];
for (int i = 0; i < sample.length-1; i++) {
//System.out.println(variables[i]+" "+sample[i]);
ls[varMapping.get(variables[i])]= sample[i];
}
String n = "";
for(String s : ls){
n+=s+delimiter;
}
n+=sample[sample.length-1]+delimiter;
//System.out.println(n);
out.append(n+"Samples");
out.append(System.lineSeparator());
line = br.readLine();
}
out.close();
br.close();
}
/*protected static void writeCSV(String file, ){
}*/
}
| operator libary
| asap-platform/asap-beans/src/main/java/gr/ntua/cslab/asap/staticLibraries/OperatorLibrary.java | operator libary |
|
Java | apache-2.0 | 57043f0669c9073fc8d9d27137105b4860478306 | 0 | tadayosi/camel,DariusX/camel,royopa/camel,eformat/camel,lburgazzoli/camel,NickCis/camel,YMartsynkevych/camel,dsimansk/camel,JYBESSON/camel,jollygeorge/camel,snadakuduru/camel,NetNow/camel,alvinkwekel/camel,pax95/camel,sirlatrom/camel,gnodet/camel,jonmcewen/camel,grange74/camel,CodeSmell/camel,iweiss/camel,YoshikiHigo/camel,koscejev/camel,DariusX/camel,christophd/camel,jkorab/camel,dpocock/camel,tarilabs/camel,zregvart/camel,coderczp/camel,eformat/camel,tadayosi/camel,YMartsynkevych/camel,snurmine/camel,prashant2402/camel,neoramon/camel,royopa/camel,RohanHart/camel,grgrzybek/camel,gilfernandes/camel,gilfernandes/camel,jpav/camel,neoramon/camel,maschmid/camel,driseley/camel,MohammedHammam/camel,davidwilliams1978/camel,sabre1041/camel,royopa/camel,tarilabs/camel,kevinearls/camel,tarilabs/camel,ramonmaruko/camel,tkopczynski/camel,nicolaferraro/camel,adessaigne/camel,davidkarlsen/camel,cunningt/camel,gyc567/camel,anoordover/camel,zregvart/camel,tdiesler/camel,brreitme/camel,stravag/camel,jkorab/camel,ssharma/camel,veithen/camel,neoramon/camel,logzio/camel,drsquidop/camel,allancth/camel,koscejev/camel,aaronwalker/camel,haku/camel,isururanawaka/camel,drsquidop/camel,mnki/camel,ge0ffrey/camel,trohovsky/camel,driseley/camel,NetNow/camel,bhaveshdt/camel,veithen/camel,jamesnetherton/camel,jkorab/camel,sebi-hgdata/camel,JYBESSON/camel,jlpedrosa/camel,mnki/camel,koscejev/camel,Thopap/camel,yogamaha/camel,maschmid/camel,scranton/camel,chanakaudaya/camel,askannon/camel,snurmine/camel,NickCis/camel,jmandawg/camel,pax95/camel,mnki/camel,apache/camel,onders86/camel,christophd/camel,dvankleef/camel,duro1/camel,lowwool/camel,pmoerenhout/camel,objectiser/camel,allancth/camel,bfitzpat/camel,gilfernandes/camel,edigrid/camel,nboukhed/camel,christophd/camel,NetNow/camel,iweiss/camel,veithen/camel,sverkera/camel,yury-vashchyla/camel,tdiesler/camel,scranton/camel,chirino/camel,grange74/camel,gautric/camel,MohammedHammam/camel,CandleCandle/camel,punkhorn/camel-upstream,iweiss/camel,gnodet/camel,haku/camel,gautric/camel,yogamaha/camel,rparree/camel,arnaud-deprez/camel,mzapletal/camel,curso007/camel,punkhorn/camel-upstream,aaronwalker/camel,punkhorn/camel-upstream,nikhilvibhav/camel,lburgazzoli/apache-camel,jonmcewen/camel,alvinkwekel/camel,stalet/camel,atoulme/camel,ssharma/camel,eformat/camel,gnodet/camel,Thopap/camel,dkhanolkar/camel,mike-kukla/camel,pplatek/camel,objectiser/camel,edigrid/camel,RohanHart/camel,noelo/camel,atoulme/camel,jmandawg/camel,chirino/camel,jamesnetherton/camel,chanakaudaya/camel,trohovsky/camel,oalles/camel,josefkarasek/camel,bgaudaen/camel,sabre1041/camel,mike-kukla/camel,CandleCandle/camel,lburgazzoli/camel,iweiss/camel,gnodet/camel,woj-i/camel,kevinearls/camel,akhettar/camel,mohanaraosv/camel,partis/camel,curso007/camel,satishgummadelli/camel,apache/camel,rmarting/camel,bdecoste/camel,josefkarasek/camel,yuruki/camel,YMartsynkevych/camel,tarilabs/camel,JYBESSON/camel,CandleCandle/camel,prashant2402/camel,ge0ffrey/camel,aaronwalker/camel,jpav/camel,adessaigne/camel,yury-vashchyla/camel,jameszkw/camel,chirino/camel,lowwool/camel,oalles/camel,FingolfinTEK/camel,koscejev/camel,logzio/camel,lasombra/camel,qst-jdc-labs/camel,prashant2402/camel,mcollovati/camel,brreitme/camel,YMartsynkevych/camel,hqstevenson/camel,skinzer/camel,iweiss/camel,jlpedrosa/camel,CodeSmell/camel,ramonmaruko/camel,ullgren/camel,cunningt/camel,nikvaessen/camel,erwelch/camel,scranton/camel,rparree/camel,isururanawaka/camel,nikhilvibhav/camel,dmvolod/camel,oscerd/camel,MrCoder/camel,mike-kukla/camel,yuruki/camel,YoshikiHigo/camel,nikvaessen/camel,jameszkw/camel,akhettar/camel,adessaigne/camel,rmarting/camel,ge0ffrey/camel,YoshikiHigo/camel,isavin/camel,davidkarlsen/camel,ekprayas/camel,engagepoint/camel,RohanHart/camel,drsquidop/camel,eformat/camel,satishgummadelli/camel,pmoerenhout/camel,CandleCandle/camel,nboukhed/camel,davidwilliams1978/camel,sirlatrom/camel,pplatek/camel,josefkarasek/camel,dpocock/camel,nikvaessen/camel,satishgummadelli/camel,logzio/camel,pkletsko/camel,JYBESSON/camel,dsimansk/camel,gyc567/camel,joakibj/camel,brreitme/camel,maschmid/camel,mnki/camel,acartapanis/camel,royopa/camel,qst-jdc-labs/camel,gyc567/camel,FingolfinTEK/camel,bdecoste/camel,dkhanolkar/camel,veithen/camel,sirlatrom/camel,veithen/camel,joakibj/camel,NickCis/camel,NetNow/camel,stravag/camel,tkopczynski/camel,oscerd/camel,ge0ffrey/camel,MohammedHammam/camel,woj-i/camel,salikjan/camel,jpav/camel,ekprayas/camel,chanakaudaya/camel,borcsokj/camel,sverkera/camel,apache/camel,dsimansk/camel,nicolaferraro/camel,davidwilliams1978/camel,davidkarlsen/camel,gilfernandes/camel,yury-vashchyla/camel,skinzer/camel,anton-k11/camel,jamesnetherton/camel,dpocock/camel,FingolfinTEK/camel,sebi-hgdata/camel,MohammedHammam/camel,manuelh9r/camel,allancth/camel,atoulme/camel,johnpoth/camel,satishgummadelli/camel,arnaud-deprez/camel,tkopczynski/camel,stalet/camel,askannon/camel,ekprayas/camel,oscerd/camel,snurmine/camel,driseley/camel,dmvolod/camel,yogamaha/camel,curso007/camel,drsquidop/camel,Fabryprog/camel,tlehoux/camel,bfitzpat/camel,tkopczynski/camel,atoulme/camel,kevinearls/camel,sebi-hgdata/camel,manuelh9r/camel,lasombra/camel,snurmine/camel,borcsokj/camel,coderczp/camel,noelo/camel,jlpedrosa/camel,nikvaessen/camel,joakibj/camel,NickCis/camel,dkhanolkar/camel,woj-i/camel,sabre1041/camel,bfitzpat/camel,mgyongyosi/camel,yury-vashchyla/camel,pplatek/camel,anton-k11/camel,dsimansk/camel,christophd/camel,atoulme/camel,MrCoder/camel,rparree/camel,cunningt/camel,akhettar/camel,dvankleef/camel,anoordover/camel,gautric/camel,skinzer/camel,coderczp/camel,ramonmaruko/camel,logzio/camel,yury-vashchyla/camel,borcsokj/camel,jollygeorge/camel,CodeSmell/camel,noelo/camel,hqstevenson/camel,allancth/camel,mcollovati/camel,pplatek/camel,stalet/camel,jkorab/camel,curso007/camel,isururanawaka/camel,arnaud-deprez/camel,dpocock/camel,logzio/camel,jmandawg/camel,tarilabs/camel,josefkarasek/camel,rmarting/camel,scranton/camel,manuelh9r/camel,ramonmaruko/camel,ssharma/camel,grange74/camel,jonmcewen/camel,yuruki/camel,tkopczynski/camel,satishgummadelli/camel,grgrzybek/camel,tlehoux/camel,oalles/camel,mike-kukla/camel,hqstevenson/camel,lburgazzoli/apache-camel,rmarting/camel,isururanawaka/camel,JYBESSON/camel,jpav/camel,woj-i/camel,brreitme/camel,iweiss/camel,oscerd/camel,erwelch/camel,arnaud-deprez/camel,pmoerenhout/camel,lburgazzoli/camel,brreitme/camel,jkorab/camel,woj-i/camel,pkletsko/camel,MrCoder/camel,pax95/camel,tdiesler/camel,dkhanolkar/camel,edigrid/camel,arnaud-deprez/camel,NetNow/camel,apache/camel,mzapletal/camel,acartapanis/camel,logzio/camel,jonmcewen/camel,sirlatrom/camel,yogamaha/camel,askannon/camel,qst-jdc-labs/camel,jpav/camel,rmarting/camel,logzio/camel,adessaigne/camel,gilfernandes/camel,royopa/camel,mohanaraosv/camel,yuruki/camel,partis/camel,dpocock/camel,duro1/camel,oalles/camel,stalet/camel,DariusX/camel,FingolfinTEK/camel,koscejev/camel,bgaudaen/camel,ullgren/camel,cunningt/camel,sirlatrom/camel,mohanaraosv/camel,bfitzpat/camel,mcollovati/camel,ekprayas/camel,trohovsky/camel,dmvolod/camel,lasombra/camel,rparree/camel,ullgren/camel,sabre1041/camel,ramonmaruko/camel,tdiesler/camel,tlehoux/camel,mgyongyosi/camel,curso007/camel,bfitzpat/camel,isururanawaka/camel,haku/camel,hqstevenson/camel,CodeSmell/camel,sebi-hgdata/camel,coderczp/camel,scranton/camel,yury-vashchyla/camel,bdecoste/camel,ekprayas/camel,YMartsynkevych/camel,w4tson/camel,jollygeorge/camel,chirino/camel,mohanaraosv/camel,yogamaha/camel,nikhilvibhav/camel,snadakuduru/camel,woj-i/camel,partis/camel,tadayosi/camel,nicolaferraro/camel,duro1/camel,jpav/camel,erwelch/camel,bhaveshdt/camel,dmvolod/camel,manuelh9r/camel,veithen/camel,anoordover/camel,jonmcewen/camel,lowwool/camel,pkletsko/camel,JYBESSON/camel,pkletsko/camel,davidwilliams1978/camel,adessaigne/camel,jonmcewen/camel,askannon/camel,MrCoder/camel,alvinkwekel/camel,stalet/camel,pmoerenhout/camel,prashant2402/camel,lasombra/camel,edigrid/camel,askannon/camel,driseley/camel,stalet/camel,snurmine/camel,johnpoth/camel,w4tson/camel,jkorab/camel,lburgazzoli/apache-camel,objectiser/camel,cunningt/camel,chirino/camel,NetNow/camel,manuelh9r/camel,stravag/camel,dsimansk/camel,joakibj/camel,bgaudaen/camel,tdiesler/camel,jamesnetherton/camel,oalles/camel,snadakuduru/camel,jlpedrosa/camel,pmoerenhout/camel,bdecoste/camel,bhaveshdt/camel,isururanawaka/camel,engagepoint/camel,dvankleef/camel,askannon/camel,partis/camel,haku/camel,gilfernandes/camel,acartapanis/camel,bhaveshdt/camel,onders86/camel,skinzer/camel,onders86/camel,apache/camel,Fabryprog/camel,sabre1041/camel,mnki/camel,oscerd/camel,lowwool/camel,oscerd/camel,mnki/camel,gautric/camel,igarashitm/camel,aaronwalker/camel,duro1/camel,mohanaraosv/camel,manuelh9r/camel,coderczp/camel,acartapanis/camel,maschmid/camel,maschmid/camel,qst-jdc-labs/camel,bhaveshdt/camel,NickCis/camel,grgrzybek/camel,sebi-hgdata/camel,engagepoint/camel,drsquidop/camel,sebi-hgdata/camel,jmandawg/camel,dvankleef/camel,rmarting/camel,nikhilvibhav/camel,isavin/camel,tlehoux/camel,lasombra/camel,lasombra/camel,mcollovati/camel,noelo/camel,MrCoder/camel,ge0ffrey/camel,isavin/camel,Thopap/camel,qst-jdc-labs/camel,hqstevenson/camel,zregvart/camel,jameszkw/camel,mzapletal/camel,CandleCandle/camel,stravag/camel,grange74/camel,lowwool/camel,chanakaudaya/camel,neoramon/camel,alvinkwekel/camel,davidwilliams1978/camel,prashant2402/camel,christophd/camel,borcsokj/camel,igarashitm/camel,aaronwalker/camel,trohovsky/camel,anton-k11/camel,mohanaraosv/camel,stravag/camel,jameszkw/camel,jarst/camel,YoshikiHigo/camel,akhettar/camel,dkhanolkar/camel,dpocock/camel,tlehoux/camel,MohammedHammam/camel,Fabryprog/camel,YoshikiHigo/camel,tadayosi/camel,Thopap/camel,MohammedHammam/camel,onders86/camel,engagepoint/camel,kevinearls/camel,jollygeorge/camel,borcsokj/camel,jmandawg/camel,dsimansk/camel,dkhanolkar/camel,w4tson/camel,akhettar/camel,FingolfinTEK/camel,joakibj/camel,Fabryprog/camel,pplatek/camel,mzapletal/camel,mgyongyosi/camel,chirino/camel,jameszkw/camel,gyc567/camel,ge0ffrey/camel,ssharma/camel,borcsokj/camel,trohovsky/camel,tdiesler/camel,anoordover/camel,bgaudaen/camel,pkletsko/camel,mgyongyosi/camel,yuruki/camel,drsquidop/camel,nikvaessen/camel,erwelch/camel,curso007/camel,jamesnetherton/camel,royopa/camel,gyc567/camel,mzapletal/camel,nboukhed/camel,igarashitm/camel,pax95/camel,bdecoste/camel,prashant2402/camel,johnpoth/camel,sverkera/camel,jarst/camel,kevinearls/camel,grange74/camel,rparree/camel,ssharma/camel,tarilabs/camel,duro1/camel,sverkera/camel,salikjan/camel,zregvart/camel,edigrid/camel,mike-kukla/camel,DariusX/camel,gyc567/camel,jarst/camel,johnpoth/camel,erwelch/camel,qst-jdc-labs/camel,nboukhed/camel,isavin/camel,adessaigne/camel,gnodet/camel,arnaud-deprez/camel,noelo/camel,davidwilliams1978/camel,sabre1041/camel,scranton/camel,ullgren/camel,ramonmaruko/camel,aaronwalker/camel,anoordover/camel,sirlatrom/camel,oalles/camel,allancth/camel,neoramon/camel,igarashitm/camel,dmvolod/camel,edigrid/camel,grgrzybek/camel,grange74/camel,igarashitm/camel,bdecoste/camel,RohanHart/camel,YMartsynkevych/camel,tadayosi/camel,christophd/camel,duro1/camel,dvankleef/camel,partis/camel,johnpoth/camel,maschmid/camel,lburgazzoli/camel,koscejev/camel,lburgazzoli/camel,tkopczynski/camel,noelo/camel,erwelch/camel,ssharma/camel,grgrzybek/camel,haku/camel,isavin/camel,onders86/camel,jlpedrosa/camel,onders86/camel,cunningt/camel,pax95/camel,jollygeorge/camel,dvankleef/camel,RohanHart/camel,jmandawg/camel,snurmine/camel,pplatek/camel,skinzer/camel,jameszkw/camel,objectiser/camel,pplatek/camel,hqstevenson/camel,lburgazzoli/apache-camel,haku/camel,bgaudaen/camel,w4tson/camel,joakibj/camel,trohovsky/camel,lowwool/camel,satishgummadelli/camel,engagepoint/camel,bfitzpat/camel,allancth/camel,kevinearls/camel,bhaveshdt/camel,driseley/camel,anton-k11/camel,punkhorn/camel-upstream,RohanHart/camel,rparree/camel,bgaudaen/camel,dmvolod/camel,apache/camel,FingolfinTEK/camel,lburgazzoli/camel,anoordover/camel,Thopap/camel,jollygeorge/camel,acartapanis/camel,eformat/camel,eformat/camel,MrCoder/camel,brreitme/camel,YoshikiHigo/camel,nicolaferraro/camel,josefkarasek/camel,driseley/camel,snadakuduru/camel,yuruki/camel,lburgazzoli/apache-camel,jarst/camel,anton-k11/camel,sverkera/camel,CandleCandle/camel,snadakuduru/camel,mgyongyosi/camel,pmoerenhout/camel,acartapanis/camel,stravag/camel,snadakuduru/camel,gautric/camel,mgyongyosi/camel,coderczp/camel,neoramon/camel,pax95/camel,mzapletal/camel,davidkarlsen/camel,jlpedrosa/camel,isavin/camel,sverkera/camel,yogamaha/camel,w4tson/camel,NickCis/camel,nboukhed/camel,tlehoux/camel,chanakaudaya/camel,atoulme/camel,igarashitm/camel,nboukhed/camel,pkletsko/camel,w4tson/camel,jarst/camel,chanakaudaya/camel,nikvaessen/camel,ekprayas/camel,grgrzybek/camel,Thopap/camel,anton-k11/camel,johnpoth/camel,skinzer/camel,tadayosi/camel,lburgazzoli/apache-camel,jarst/camel,akhettar/camel,partis/camel,jamesnetherton/camel,mike-kukla/camel,josefkarasek/camel,gautric/camel | /**
* 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.camel.blueprint;
import org.apache.camel.TypeConverter;
import org.apache.camel.core.osgi.OsgiCamelContextHelper;
import org.apache.camel.core.osgi.OsgiCamelContextNameStrategy;
import org.apache.camel.core.osgi.OsgiClassResolver;
import org.apache.camel.core.osgi.OsgiFactoryFinderResolver;
import org.apache.camel.core.osgi.OsgiPackageScanClassResolver;
import org.apache.camel.core.osgi.OsgiTypeConverter;
import org.apache.camel.core.osgi.utils.BundleContextUtils;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.Registry;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BlueprintCamelContext extends DefaultCamelContext {
private static final transient Logger LOG = LoggerFactory.getLogger(BlueprintCamelContext.class);
private BundleContext bundleContext;
private BlueprintContainer blueprintContainer;
public BlueprintCamelContext() {
}
public BlueprintCamelContext(BundleContext bundleContext, BlueprintContainer blueprintContainer) {
this.bundleContext = bundleContext;
this.blueprintContainer = blueprintContainer;
setNameStrategy(new OsgiCamelContextNameStrategy(bundleContext));
setClassResolver(new OsgiClassResolver(bundleContext));
setFactoryFinderResolver(new OsgiFactoryFinderResolver(bundleContext));
setPackageScanClassResolver(new OsgiPackageScanClassResolver(bundleContext));
setComponentResolver(new BlueprintComponentResolver(bundleContext));
setLanguageResolver(new BlueprintLanguageResolver(bundleContext));
setDataFormatResolver(new BlueprintDataFormatResolver(bundleContext));
}
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
public BlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(BlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public void init() throws Exception {
maybeStart();
}
private void maybeStart() throws Exception {
if (!isStarted() && !isStarting()) {
start();
} else {
// ignore as Camel is already started
LOG.trace("Ignoring maybeStart() as Apache Camel is already started");
}
}
public void destroy() throws Exception {
stop();
}
@Override
protected TypeConverter createTypeConverter() {
// CAMEL-3614: make sure we use a bundle context which imports org.apache.camel.impl.converter package
BundleContext ctx = BundleContextUtils.getBundleContext(getClass());
if (ctx == null) {
ctx = bundleContext;
}
return new OsgiTypeConverter(ctx, getInjector());
}
@Override
protected Registry createRegistry() {
Registry reg = new BlueprintContainerRegistry(getBlueprintContainer());
return OsgiCamelContextHelper.wrapRegistry(this, reg, bundleContext);
}
}
| components/camel-blueprint/src/main/java/org/apache/camel/blueprint/BlueprintCamelContext.java | /**
* 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.camel.blueprint;
import org.apache.camel.TypeConverter;
import org.apache.camel.core.osgi.OsgiCamelContextHelper;
import org.apache.camel.core.osgi.OsgiCamelContextNameStrategy;
import org.apache.camel.core.osgi.OsgiClassResolver;
import org.apache.camel.core.osgi.OsgiFactoryFinderResolver;
import org.apache.camel.core.osgi.OsgiPackageScanClassResolver;
import org.apache.camel.core.osgi.OsgiTypeConverter;
import org.apache.camel.core.osgi.utils.BundleContextUtils;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.Registry;
import org.osgi.framework.BundleContext;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BlueprintCamelContext extends DefaultCamelContext {
private static final transient Logger LOG = LoggerFactory.getLogger(BlueprintCamelContext.class);
private BundleContext bundleContext;
private BlueprintContainer blueprintContainer;
public BlueprintCamelContext() {
}
public BlueprintCamelContext(BundleContext bundleContext, BlueprintContainer blueprintContainer) {
this.bundleContext = bundleContext;
this.blueprintContainer = blueprintContainer;
setNameStrategy(new OsgiCamelContextNameStrategy(bundleContext));
setClassResolver(new OsgiClassResolver(bundleContext));
setFactoryFinderResolver(new OsgiFactoryFinderResolver(bundleContext));
setPackageScanClassResolver(new OsgiPackageScanClassResolver(bundleContext));
setComponentResolver(new BlueprintComponentResolver(bundleContext));
setLanguageResolver(new BlueprintLanguageResolver(bundleContext));
setDataFormatResolver(new BlueprintDataFormatResolver(bundleContext));
}
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
public BlueprintContainer getBlueprintContainer() {
return blueprintContainer;
}
public void setBlueprintContainer(BlueprintContainer blueprintContainer) {
this.blueprintContainer = blueprintContainer;
}
public void init() throws Exception {
maybeStart();
}
private void maybeStart() throws Exception {
if (!isStarted() && !isStarting()) {
start();
} else {
// ignore as Camel is already started
LOG.trace("Ignoring maybeStart() as Apache Camel is already started");
}
}
public void destroy() throws Exception {
stop();
}
@Override
protected TypeConverter createTypeConverter() {
// CAMEL-3614: make sure we use a bundle context which imports org.apache.camel.impl.converter package
BundleContext ctx = BundleContextUtils.getBundleContext(getClass());
if (ctx == null) {
ctx = bundleContext;
}
return new OsgiTypeConverter(ctx, getInjector());
}
@Override
protected Registry createRegistry() {
Registry reg = new BlueprintContainerRegistry(getBlueprintContainer());
return OsgiCamelContextHelper.wrapRegistry(this, reg, bundleContext);
}
}
| Fixed CS.
git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@1066736 13f79535-47bb-0310-9956-ffa450edef68
| components/camel-blueprint/src/main/java/org/apache/camel/blueprint/BlueprintCamelContext.java | Fixed CS. |
|
Java | apache-2.0 | 00e3d47900afefee6ddd96e6604b4b26a49a5c85 | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.dns;
import java.util.Comparator;
import java.util.Objects;
/**
* A basic representation of a DNS resource record, containing the record type, name and data.
*
* @author mpolden
*/
public class Record implements Comparable<Record> {
private static final Comparator<Record> comparator = Comparator.comparing(Record::type)
.thenComparing(Record::name)
.thenComparing(Record::data);
private final Type type;
private final RecordName name;
private final RecordData data;
public Record(Type type, RecordName name, RecordData data) {
this.type = Objects.requireNonNull(type, "type cannot be null");
this.name = Objects.requireNonNull(name, "name cannot be null");
this.data = Objects.requireNonNull(data, "data cannot be null");
}
/** DNS type of this */
public Type type() {
return type;
}
/** Data in this, e.g. IP address for records of type A */
public RecordData data() {
return data;
}
/** Name of this, e.g. a FQDN for records of type A */
public RecordName name() {
return name;
}
public enum Type {
A,
AAAA,
ALIAS,
CNAME,
MX,
NS,
PTR,
SOA,
SRV,
TXT,
SPF,
NAPTR,
CAA,
}
@Override
public String toString() {
return String.format("%s %s -> %s", type, name, data);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return type == record.type &&
name.equals(record.name) &&
data.equals(record.data);
}
@Override
public int hashCode() {
return Objects.hash(type, name, data);
}
@Override
public int compareTo(Record that) {
return comparator.compare(this, that);
}
}
| controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/dns/Record.java | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.dns;
import java.util.Comparator;
import java.util.Objects;
/**
* A basic representation of a DNS resource record, containing the record type, name and data.
*
* @author mpolden
*/
public class Record implements Comparable<Record> {
private static final Comparator<Record> comparator = Comparator.comparing(Record::type)
.thenComparing(Record::name)
.thenComparing(Record::data);
private final Type type;
private final RecordName name;
private final RecordData data;
public Record(Type type, RecordName name, RecordData data) {
this.type = Objects.requireNonNull(type, "type cannot be null");
this.name = Objects.requireNonNull(name, "name cannot be null");
this.data = Objects.requireNonNull(data, "data cannot be null");
}
/** DNS type of this */
public Type type() {
return type;
}
/** Data in this, e.g. IP address for records of type A */
public RecordData data() {
return data;
}
/** Name of this, e.g. a FQDN for records of type A */
public RecordName name() {
return name;
}
public enum Type {
A,
AAAA,
ALIAS,
CNAME,
MX,
NS,
PTR,
SOA,
SRV,
TXT
}
@Override
public String toString() {
return String.format("%s %s -> %s", type, name, data);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return type == record.type &&
name.equals(record.name) &&
data.equals(record.data);
}
@Override
public int hashCode() {
return Objects.hash(type, name, data);
}
@Override
public int compareTo(Record that) {
return comparator.compare(this, that);
}
}
| Add missing DNS record types
| controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/dns/Record.java | Add missing DNS record types |
|
Java | apache-2.0 | cc245d32920d73b058a7bd83dc9cefb82a9e61bf | 0 | LeonArcher/cryptochat,LeonArcher/cryptochat | package com.streamdata.apps.cryptochat.messaging;
import com.streamdata.apps.cryptochat.models.Message;
import com.streamdata.apps.cryptochat.scheduling.Callback;
import java.util.ArrayList;
/**
* Class for periodic launch of receive messages task through message controller
*/
public class PeriodicMessageRetrieverService {
private static final int RETRIEVE_RATE_MS = 5000;
private final MessageController messageController;
private RetrieveInitiatorThread initiator = null;
public PeriodicMessageRetrieverService(MessageController messageController) {
this.messageController = messageController;
}
public void start(Callback<ArrayList<Message>> retrieveCallback,
String receiverId, String targetId) {
if (initiator != null) {
initiator.finish();
}
initiator = new RetrieveInitiatorThread(
receiverId,
targetId,
messageController,
retrieveCallback
);
initiator.start();
}
public void stop() {
if (initiator == null) {
return;
}
initiator.finish();
initiator = null;
}
private static class RetrieveInitiatorThread extends Thread {
private volatile boolean mFinish = false;
private final MessageController messageController;
private final String receiverId;
private final String targetId;
private final Callback<ArrayList<Message>> getNewMessagesCallback;
public RetrieveInitiatorThread(String receiverId, String targetId,
MessageController messageController,
Callback<ArrayList<Message>> getNewMessagesCallback) {
this.messageController = messageController;
this.receiverId = receiverId;
this.targetId = targetId;
this.getNewMessagesCallback = getNewMessagesCallback;
}
@Override
public void run() {
do {
if (!mFinish) {
messageController.getNewMessages(receiverId, targetId, getNewMessagesCallback);
} else {
return;
}
try {
Thread.sleep(RETRIEVE_RATE_MS);
} catch (InterruptedException e) {
// TODO: handle exception?
}
} while (true);
}
public void finish() {
mFinish = true;
}
}
}
| app/src/main/java/com/streamdata/apps/cryptochat/messaging/PeriodicMessageRetrieverService.java | package com.streamdata.apps.cryptochat.messaging;
/**
* TODO: Add a class header comment!
*/
public class PeriodicMessageRetrieverService {
}
| Message retriever service implemented.
| app/src/main/java/com/streamdata/apps/cryptochat/messaging/PeriodicMessageRetrieverService.java | Message retriever service implemented. |
|
Java | apache-2.0 | e6967d95cc6833309a56857a7a1873534daa1047 | 0 | huilam/jsoncrud | /*
Copyright (c) 2017 [email protected]
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 shall be used for Good, not Evil.
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 hl.jsoncrud;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
import hl.common.JdbcDBMgr;
public class CRUDMgr {
private final static String JSONFILTER_FROM = "from";
private final static String JSONFILTER_TO = "to";
private final static String JSONFILTER_STARTWITH = "startwith";
private final static String JSONFILTER_ENDWITH = "endwith";
private final static String JSONFILTER_CONTAIN = "contain";
private final static String SQLLIKE_WILDCARD = "%";
private final static String JSONVAL_WILDCARD = "*";
private final static String JSONFILTER_CASE_INSENSITIVE = "ci";
private final static String JSONFILTER_NOT = "not";
private Map<String, JdbcDBMgr> mapDBMgr = null;
private Map<String, Map<String, String>> mapJson2ColName = null;
private Map<String, Map<String, String>> mapColName2Json = null;
private Map<String, Map<String, String>> mapJson2Sql = null;
private Map<String, Map<String,DBColMeta>> mapTableCols = null;
private Pattern pattSQLjsonname = null;
private Pattern pattJsonColMapping = null;
private Pattern pattJsonSQL = null;
private Pattern pattJsonNameFilter = null;
private Pattern pattInsertSQLtableFields = null;
private JsonCrudConfig jsoncrudConfig = null;
private String config_prop_filename = null;
public final static String _PAGINATION_CONFIGKEY = "list.pagination";
public String _LIST_META = "meta";
public String _LIST_RESULT = "result";
public String _LIST_TOTAL = "total";
public String _LIST_FETCHSIZE = "fetchsize";
public String _LIST_START = "start";
public String _LIST_ORDERBY = "orderby";
public final static String _DB_VALIDATION_ERRCODE_CONFIGKEY = "dbschema.validation_errcode";
public static String ERRCODE_NOT_NULLABLE = "not_nullable";
public static String ERRCODE_EXCEED_SIZE = "exceed_size";
public static String ERRCODE_INVALID_TYPE = "invalid_type";
public static String ERRCODE_SYSTEM_FIELD = "system_field";
public CRUDMgr()
{
config_prop_filename = null;
init();
}
public String getVersionInfo()
{
JSONObject jsonVer = new JSONObject();
jsonVer.put("framework", "jsoncrud");
jsonVer.put("version", "0.1.9 beta");
return jsonVer.toString();
}
public CRUDMgr(String aPropFileName)
{
config_prop_filename = aPropFileName;
if(aPropFileName!=null && aPropFileName.trim().length()>0)
{
try {
jsoncrudConfig = new JsonCrudConfig(aPropFileName);
} catch (IOException e) {
throw new RuntimeException("Error loading "+aPropFileName, e);
}
}
init();
}
private void init()
{
mapDBMgr = new HashMap<String, JdbcDBMgr>();
mapJson2ColName = new HashMap<String, Map<String, String>>();
mapColName2Json = new HashMap<String, Map<String, String>>();
mapJson2Sql = new HashMap<String, Map<String, String>>();
mapTableCols = new HashMap<String, Map<String, DBColMeta>>();
//
pattJsonColMapping = Pattern.compile("jsonattr\\.([a-zA-Z_-]+?)\\.colname");
pattJsonSQL = Pattern.compile("jsonattr\\.([a-zA-Z_-]+?)\\.sql");
//
pattSQLjsonname = Pattern.compile("\\{(.+?)\\}");
pattInsertSQLtableFields = Pattern.compile("insert\\s+?into\\s+?([a-zA-Z_]+?)\\s+?\\((.+?)\\)");
//
pattJsonNameFilter = Pattern.compile("([a-zA-Z_-]+?)\\.("
+JSONFILTER_FROM+"|"+JSONFILTER_TO+"|"
+JSONFILTER_STARTWITH+"|"+JSONFILTER_ENDWITH+"|"+JSONFILTER_CONTAIN+"|"+JSONFILTER_NOT+"|"
+JSONFILTER_CASE_INSENSITIVE+")"
+"(?:\\.("+JSONFILTER_CASE_INSENSITIVE+"|"+JSONFILTER_NOT+"))?"
+"(?:\\.("+JSONFILTER_CASE_INSENSITIVE+"|"+JSONFILTER_NOT+"))?");
try {
reloadProps();
if(jsoncrudConfig.getAllConfig().size()==0)
{
throw new IOException("Fail to load properties file - "+config_prop_filename);
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
initPaginationConfig();
initValidationErrCodeConfig();
}
private void initValidationErrCodeConfig()
{
Map<String, String> mapErrCodes = jsoncrudConfig.getConfig(_DB_VALIDATION_ERRCODE_CONFIGKEY);
if(mapErrCodes!=null && mapErrCodes.size()>0)
{
String sMetaKey = null;
sMetaKey = mapErrCodes.get(ERRCODE_EXCEED_SIZE);
if(sMetaKey!=null)
ERRCODE_EXCEED_SIZE = sMetaKey;
sMetaKey = mapErrCodes.get(ERRCODE_INVALID_TYPE);
if(sMetaKey!=null)
ERRCODE_INVALID_TYPE = sMetaKey;
sMetaKey = mapErrCodes.get(ERRCODE_NOT_NULLABLE);
if(sMetaKey!=null)
ERRCODE_NOT_NULLABLE = sMetaKey;
sMetaKey = mapErrCodes.get(ERRCODE_SYSTEM_FIELD);
if(sMetaKey!=null)
ERRCODE_SYSTEM_FIELD = sMetaKey;
}
}
private void initPaginationConfig()
{
Map<String, String> mapPagination = jsoncrudConfig.getConfig(_PAGINATION_CONFIGKEY);
if(mapPagination!=null && mapPagination.size()>0)
{
String sMetaKey = null;
sMetaKey = mapPagination.get(_LIST_META);
if(sMetaKey!=null)
_LIST_META = sMetaKey;
sMetaKey = mapPagination.get(_LIST_RESULT);
if(sMetaKey!=null)
_LIST_RESULT = sMetaKey;
sMetaKey = mapPagination.get(_LIST_TOTAL);
if(sMetaKey!=null)
_LIST_TOTAL = sMetaKey;
sMetaKey = mapPagination.get(_LIST_FETCHSIZE);
if(sMetaKey!=null)
_LIST_FETCHSIZE = sMetaKey;
sMetaKey = mapPagination.get(_LIST_START);
if(sMetaKey!=null)
_LIST_START = sMetaKey;
sMetaKey = mapPagination.get(_LIST_ORDERBY);
if(sMetaKey!=null)
_LIST_ORDERBY = sMetaKey;
}
}
public JSONObject create(String aCrudKey, JSONObject aDataJson) throws JsonCrudException
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
aDataJson = castJson2DBVal(aCrudKey, aDataJson);
StringBuffer sbColName = new StringBuffer();
StringBuffer sbParams = new StringBuffer();
StringBuffer sbRollbackParentSQL = new StringBuffer();
List<Object> listValues = new ArrayList<Object>();
List<String> listUnmatchedJsonName = new ArrayList<String>();
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
for(String sJsonName : aDataJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
if(sColName!=null)
{
//
if(sbColName.length()>0)
{
sbColName.append(",");
sbParams.append(",");
}
sbColName.append(sColName);
sbParams.append("?");
//
//
sbRollbackParentSQL.append(" AND ").append(sColName).append(" = ? ");
//
listValues.add(aDataJson.get(sJsonName));
}
else
{
listUnmatchedJsonName.add(sJsonName);
}
}
String sSQL = "INSERT INTO "+sTableName+"("+sbColName.toString()+") values ("+sbParams.toString()+")";
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jArrCreated = null;
try {
jArrCreated = dbmgr.executeUpdate(sSQL, listValues);
}
catch(Throwable ex)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(listValues), ex);
}
if(jArrCreated.length()>0)
{
Map<String, String> mapCrudCol2Json = mapColName2Json.get(aCrudKey);
JSONObject jsonCreated = jArrCreated.getJSONObject(0);
for(String sColName : jsonCreated.keySet())
{
String sMappedKey = mapCrudCol2Json.get(sColName);
if(sMappedKey==null)
sMappedKey = sColName;
aDataJson.put(sMappedKey, jsonCreated.get(sColName));
}
//child create
if(listUnmatchedJsonName.size()>0)
{
JSONArray jsonArrReturn = retrieve(aCrudKey, aDataJson);
for(int i=0 ; i<jsonArrReturn.length(); i++ )
{
JSONObject jsonReturn = jsonArrReturn.getJSONObject(i);
//merging json obj
for(String sDataJsonKey : aDataJson.keySet())
{
jsonReturn.put(sDataJsonKey, aDataJson.get(sDataJsonKey));
}
for(String sJsonName2 : listUnmatchedJsonName)
{
List<Object[]> listParams2 = getSubQueryParams(map, jsonReturn, sJsonName2);
String sObjInsertSQL = map.get("jsonattr."+sJsonName2+"."+JsonCrudConfig._PROP_KEY_OBJ_SQL);
long lupdatedRow = 0;
try {
lupdatedRow = updateChildObject(dbmgr, sObjInsertSQL, listParams2);
}
catch(Throwable ex)
{
try {
//rollback parent
sbRollbackParentSQL.insert(0, "DELETE FROM "+sTableName+" WHERE 1=1 ");
JSONArray jArrRollbackRows = dbmgr.executeUpdate(sbRollbackParentSQL.toString(), listValues);
if(jArrCreated.length() != jArrRollbackRows.length())
{
throw new JsonCrudException("Record fail to Rollback!");
}
}
catch(Throwable ex2)
{
throw new JsonCrudException("[Rollback Failed], parent:[sql:"+sbRollbackParentSQL.toString()+",params:"+listParamsToString(listValues)+"], child:[sql:"+sObjInsertSQL+",params:"+listParamsToString(listParams2)+"]", ex);
}
throw new JsonCrudException("[Rollback Success] : child : sql:"+sObjInsertSQL+", params:"+listParamsToString(listParams2), ex);
}
}
}
}
JSONArray jsonArray = retrieve(aCrudKey, aDataJson);
if(jsonArray==null || jsonArray.length()==0)
return null;
else
return (JSONObject) jsonArray.get(0);
}
else
{
return null;
}
}
public JSONObject retrieveFirst(String aCrudKey, JSONObject aWhereJson) throws JsonCrudException
{
JSONArray jsonArr = retrieve(aCrudKey, aWhereJson);
if(jsonArr!=null && jsonArr.length()>0)
{
return (JSONObject) jsonArr.get(0);
}
return null;
}
public JSONArray retrieve(String aCrudKey, JSONObject aWhereJson) throws JsonCrudException
{
JSONObject json = retrieve(aCrudKey, aWhereJson, 0, 0, null);
if(json==null)
{
return new JSONArray();
}
return (JSONArray) json.get(_LIST_RESULT);
}
public JSONArray retrieve(String aCrudKey, JSONObject aWhereJson, String[] aOrderBy) throws JsonCrudException
{
JSONObject json = retrieve(aCrudKey, aWhereJson, 0, 0, aOrderBy);
if(json==null)
{
return new JSONArray();
}
return (JSONArray) json.get(_LIST_RESULT);
}
public JSONObject retrieve(String aCrudKey, String aSQL, Object[] aObjParams,
long aStartFrom, long aFetchSize) throws JsonCrudException
{
JSONObject jsonReturn = null;
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = aSQL;
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
if(aStartFrom<=0)
aStartFrom = 1;
JSONArray jsonArr = new JSONArray();
try{
Map<String, String> mapCrudCol2Json = mapColName2Json.get(aCrudKey);
Map<String, String> mapCrudSql = mapJson2Sql.get(aCrudKey);
conn = dbmgr.getConnection();
stmt = conn.prepareStatement(sSQL);
stmt = JdbcDBMgr.setParams(stmt, aObjParams);
rs = stmt.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
long lTotalResult = 0;
while(rs.next())
{
lTotalResult++;
if(lTotalResult < aStartFrom)
continue;
JSONObject jsonOnbj = new JSONObject();
for(int i=0; i<meta.getColumnCount(); i++)
{
String sColName = meta.getColumnLabel(i+1);
String sJsonName = mapCrudCol2Json.get(sColName);
if(sJsonName==null)
sJsonName = sColName;
jsonOnbj.put(sJsonName, rs.getObject(sColName));
}
if(mapCrudSql.size()>0)
{
for(String sJsonName : mapCrudSql.keySet())
{
if(!jsonOnbj.has(sJsonName))
{
List<Object> listParams2 = new ArrayList<Object>();
String sSQL2 = mapCrudSql.get(sJsonName);
Matcher m = pattSQLjsonname.matcher(sSQL2);
while(m.find())
{
String sBracketJsonName = m.group(1);
if(jsonOnbj.has(sBracketJsonName))
{
listParams2.add(jsonOnbj.get(sBracketJsonName));
}
}
sSQL2 = sSQL2.replaceAll("\\{.+?\\}", "?");
if(sSQL2.indexOf("?")>-1 && listParams2.size()>0)
{
JSONArray jsonArrayChild = retrieveChild(dbmgr, sSQL2, listParams2);
if(jsonArrayChild!=null && jsonArrayChild.length()>0)
{
String sChildFormat = map.get(
"jsonattr."+sJsonName+"."+JsonCrudConfig._PROP_KEY_FORMAT);
Object o = jsonArrayChild.get(0);
if(o!=null && !isEmptyJson(o.toString()))
{
if(sChildFormat!=null)
{
if(sChildFormat.trim().equals("[]"))
{
jsonOnbj.put(sJsonName, jsonArrayChild);
}
else if(sChildFormat.trim().equals("{}"))
{
jsonOnbj.put(sJsonName, jsonArrayChild.getJSONObject(0));
}
}
else
{
/*
if(o instanceof JSONArray)
{
JSONArray jsonArrO = (JSONArray) o;
String sJsonArray = jsonArrO.toString();
if(sJsonArray.length()>2)
{
o = sJsonArray.substring(1, sJsonArray.length()-2);
}
else o = "";
}
if(o instanceof JSONObject)
{
JSONObject jsonO = (JSONObject) o;
String sJsonObj = jsonO.toString();
if(sJsonObj.length()>2)
{
o = sJsonObj.substring(1, sJsonObj.length()-2);
}
else o = "";
}
*/
jsonOnbj.put(sJsonName, o);
}
}
}
}
}
}
}
jsonArr.put(jsonOnbj);
if(aFetchSize>0 && jsonArr.length()>=aFetchSize)
{
break;
}
}
while(rs.next()){
lTotalResult++;
}
if(jsonArr.length()>0)
{
jsonReturn = new JSONObject();
jsonReturn.put(_LIST_RESULT, jsonArr);
//
JSONObject jsonMeta = new JSONObject();
jsonMeta.put(_LIST_TOTAL, lTotalResult);
jsonMeta.put(_LIST_START, aStartFrom);
//
if(aFetchSize>0)
jsonMeta.put(_LIST_FETCHSIZE, aFetchSize);
//
jsonReturn.put(_LIST_META, jsonMeta);
}
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(aObjParams), sqlEx);
}
finally
{
try {
dbmgr.closeQuietly(conn, stmt, rs);
} catch (SQLException e) {
throw new JsonCrudException(e);
}
}
return jsonReturn;
}
private JSONArray retrieveChild(JdbcDBMgr aJdbcMgr, String aSQL, List<Object> aObjParamList) throws SQLException
{
Connection conn2 = null;
PreparedStatement stmt2 = null;
ResultSet rs2 = null;
JSONArray jsonArr2 = new JSONArray();
JSONObject json2 = new JSONObject();
try{
conn2 = aJdbcMgr.getConnection();
stmt2 = conn2.prepareStatement(aSQL);
stmt2 = JdbcDBMgr.setParams(stmt2, aObjParamList);
rs2 = stmt2.executeQuery();
int iTotalCols = rs2.getMetaData().getColumnCount();
if(iTotalCols<1 || iTotalCols>2)
{
throw new SQLException("Only 1 or 2 return columns from subquery are supported !");
}
while(rs2.next())
{
String s = rs2.getString(1);
if(iTotalCols==1)
{
//["1"]
jsonArr2.put(s);
}
else if(iTotalCols==2)
{
//{"key1":"val1", "key2":"val2"}
Object o = rs2.getObject(2);
if(o!=null)
{
json2.put(s, o);
}
}
}
if(iTotalCols==2)
{
//[{"key1":"val1", "key2":"val2"}]
jsonArr2.put(json2);
}
}catch(SQLException sqlEx)
{
throw new SQLException("sql:"+aSQL+", params:"+listParamsToString(aObjParamList), sqlEx);
}
finally{
aJdbcMgr.closeQuietly(conn2, stmt2, rs2);
}
return jsonArr2;
}
public JSONObject retrieve(String aCrudKey, JSONObject aWhereJson,
long aStartFrom, long aFetchSize, String[] aOrderBy) throws JsonCrudException
{
aWhereJson = castJson2DBVal(aCrudKey, aWhereJson);
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
// WHERE
StringBuffer sbWhere = new StringBuffer();
for(String sOrgJsonName : aWhereJson.keySet())
{
boolean isCaseInSensitive = false;
boolean isNotCondition = false;
String sOperator = " = ";
String sJsonName = sOrgJsonName;
Object oJsonValue = aWhereJson.get(sOrgJsonName);
if(sJsonName.indexOf(".")>-1)
{
Matcher m = pattJsonNameFilter.matcher(sJsonName);
if(m.find())
{
sJsonName = m.group(1);
String sJsonOperator = m.group(2);
String sJsonCIorNOT_1 = m.group(3);
String sJsonCIorNOT_2 = m.group(4);
if(JSONFILTER_CASE_INSENSITIVE.equalsIgnoreCase(sJsonCIorNOT_1) || JSONFILTER_CASE_INSENSITIVE.equalsIgnoreCase(sJsonCIorNOT_2)
|| JSONFILTER_CASE_INSENSITIVE.equals(sJsonOperator))
{
isCaseInSensitive = true;
}
if(JSONFILTER_NOT.equalsIgnoreCase(sJsonCIorNOT_1) || JSONFILTER_NOT.equalsIgnoreCase(sJsonCIorNOT_2)
|| JSONFILTER_NOT.equals(sJsonOperator))
{
isNotCondition = true;
}
if(JSONFILTER_FROM.equals(sJsonOperator))
{
sOperator = " >= ";
}
else if(JSONFILTER_TO.equals(sJsonOperator))
{
sOperator = " <= ";
}
else if(JSONFILTER_TO.equals(sJsonOperator))
{
sOperator = " <= ";
}
else if(oJsonValue!=null && oJsonValue instanceof String)
{
if(JSONFILTER_STARTWITH.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = oJsonValue+SQLLIKE_WILDCARD;
}
else if (JSONFILTER_ENDWITH.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = SQLLIKE_WILDCARD+oJsonValue;
}
else if (JSONFILTER_CONTAIN.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = SQLLIKE_WILDCARD+oJsonValue+SQLLIKE_WILDCARD;
}
}
}
}
if(oJsonValue!=null && (oJsonValue instanceof String) && (oJsonValue.toString().indexOf(JSONVAL_WILDCARD)>-1))
{
sOperator = " like ";
oJsonValue = oJsonValue.toString().replaceAll(Pattern.quote(JSONVAL_WILDCARD), SQLLIKE_WILDCARD);
}
String sColName = mapCrudJsonCol.get(sJsonName);
//
if(sColName!=null)
{
sbWhere.append(" AND ");
if(isNotCondition)
{
sbWhere.append(" NOT (");
}
if(isCaseInSensitive && (oJsonValue instanceof String))
{
sbWhere.append(" UPPER(").append(sColName).append(") ").append(sOperator).append(" UPPER(?) ");
}
else
{
sbWhere.append(sColName).append(sOperator).append(" ? ");
}
if(isNotCondition)
{
sbWhere.append(" )");
}
//
oJsonValue = castJson2DBVal(aCrudKey, sJsonName, oJsonValue);
listValues.add(oJsonValue);
}
}
StringBuffer sbOrderBy = new StringBuffer();
if(aOrderBy!=null && aOrderBy.length>0)
{
for(String sOrderBy : aOrderBy)
{
String sOrderSeqKeyword = "";
int iOrderSeq = sOrderBy.indexOf('.');
if(iOrderSeq>-1)
{
sOrderSeqKeyword = sOrderBy.substring(iOrderSeq+1);
}
else if(iOrderSeq==-1)
{
iOrderSeq = sOrderBy.length();
}
String sJsonAttr = sOrderBy.substring(0, iOrderSeq);
String sOrderColName = mapCrudJsonCol.get(sJsonAttr);
if(sOrderColName!=null)
{
if(sbOrderBy.length()>0)
{
sbOrderBy.append(",");
}
sbOrderBy.append(sOrderColName);
if(sOrderSeqKeyword.length()>0)
sbOrderBy.append(" ").append(sOrderSeqKeyword);
}
}
if(sbOrderBy.length()>0)
{
sbWhere.append(" ORDER BY ").append(sbOrderBy.toString());
}
}
String sSQL = "SELECT * FROM "+sTableName+" WHERE 1=1 "+sbWhere.toString();
JSONObject jsonReturn = retrieve(aCrudKey, sSQL, listValues.toArray(new Object[listValues.size()]), aStartFrom, aFetchSize);
if(jsonReturn!=null && jsonReturn.has(_LIST_META))
{
JSONObject jsonMeta = jsonReturn.getJSONObject(_LIST_META);
if(aOrderBy!=null)
{
StringBuffer sbOrderBys = new StringBuffer();
for(String sOrderBy : aOrderBy)
{
if(sbOrderBys.length()>0)
sbOrderBys.append(",");
sbOrderBys.append(sOrderBy);
}
if(sbOrderBys.length()>0)
jsonMeta.put(_LIST_ORDERBY, sbOrderBys.toString());
}
//
jsonReturn.put(_LIST_META, jsonMeta);
}
return jsonReturn;
//
}
public JSONArray update(String aCrudKey, JSONObject aDataJson, JSONObject aWhereJson) throws Exception
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
aDataJson = castJson2DBVal(aCrudKey, aDataJson);
aWhereJson = castJson2DBVal(aCrudKey, aWhereJson);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
List<String> listUnmatchedJsonName = new ArrayList<String>();
//SET
StringBuffer sbSets = new StringBuffer();
for(String sJsonName : aDataJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
//
if(sColName!=null)
{
//
if(sbSets.length()>0)
sbSets.append(",");
sbSets.append(sColName).append(" = ? ");
//
listValues.add(aDataJson.get(sJsonName));
}
else
{
listUnmatchedJsonName.add(sJsonName);
}
}
// WHERE
StringBuffer sbWhere = new StringBuffer();
for(String sJsonName : aWhereJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
//
if(sColName==null)
{
throw new JsonCrudException("Missing Json to dbcol mapping ("+sJsonName+":"+aWhereJson.get(sJsonName)+") ! - "+aCrudKey);
}
sbWhere.append(" AND ").append(sColName).append(" = ? ");
//
listValues.add(aWhereJson.get(sJsonName));
}
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = "UPDATE "+sTableName+" SET "+sbSets.toString()+" WHERE 1=1 "+sbWhere.toString();
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jArrUpdated = new JSONArray();
long lAffectedRow2 = 0;
try{
if(sbSets.length()>0)
{
jArrUpdated = dbmgr.executeUpdate(sSQL, listValues);
}
if(jArrUpdated.length()>0 || sbSets.length()==0)
{
//child update
JSONArray jsonArrReturn = retrieve(aCrudKey, aWhereJson);
for(int i=0 ; i<jsonArrReturn.length(); i++ )
{
JSONObject jsonReturn = jsonArrReturn.getJSONObject(i);
//merging json obj
for(String sDataJsonKey : aDataJson.keySet())
{
jsonReturn.put(sDataJsonKey, aDataJson.get(sDataJsonKey));
}
for(String sJsonName2 : listUnmatchedJsonName)
{
List<Object[]> listParams2 = getSubQueryParams(map, jsonReturn, sJsonName2);
String sObjInsertSQL = map.get("jsonattr."+sJsonName2+"."+JsonCrudConfig._PROP_KEY_OBJ_SQL);
lAffectedRow2 += updateChildObject(dbmgr, sObjInsertSQL, listParams2);
}
}
}
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(listValues), sqlEx);
}
if(jArrUpdated.length()>0 || lAffectedRow2>0)
{
JSONArray jsonArray = retrieve(aCrudKey, aWhereJson);
return jsonArray;
}
else
{
return null;
}
}
public JSONArray delete(String aCrudKey, JSONObject aWhereJson) throws Exception
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
aWhereJson = castJson2DBVal(aCrudKey, aWhereJson);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
StringBuffer sbWhere = new StringBuffer();
for(String sJsonName : aWhereJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
//
sbWhere.append(" AND ").append(sColName).append(" = ? ");
//
listValues.add(aWhereJson.get(sJsonName));
}
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = "DELETE FROM "+sTableName+" WHERE 1=1 "+sbWhere.toString();
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jsonArray = null;
jsonArray = retrieve(aCrudKey, aWhereJson);
if(jsonArray.length()>0)
{
JSONArray jArrAffectedRow = new JSONArray();
try {
jArrAffectedRow = dbmgr.executeUpdate(sSQL, listValues);
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(listValues), sqlEx);
}
if(jArrAffectedRow.length()>0)
{
return jsonArray;
}
}
return null;
}
private void clearAll()
{
mapDBMgr.clear();
mapJson2ColName.clear();
mapColName2Json.clear();
mapJson2Sql.clear();
mapTableCols.clear();
}
public Map<String, String> getAllConfig()
{
return jsoncrudConfig.getAllConfig();
}
private JdbcDBMgr initNRegJdbcDBMgr(String aJdbcConfigKey, Map<String, String> mapJdbcConfig) throws SQLException
{
JdbcDBMgr dbmgr = mapDBMgr.get(aJdbcConfigKey);
if(dbmgr==null)
{
String sJdbcClassName = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME);
String sJdbcUrl = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_URL);
String sJdbcUid = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_UID);
String sJdbcPwd = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_PWD);
if(sJdbcClassName!=null && sJdbcUrl!=null)
{
try {
dbmgr = new JdbcDBMgr(sJdbcClassName, sJdbcUrl, sJdbcUid, sJdbcPwd);
}catch(Exception ex)
{
throw new SQLException("Error initialize JDBC - "+aJdbcConfigKey, ex);
}
//
int lconnpoolsize = -1;
String sConnPoolSize = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CONNPOOL);
if(sConnPoolSize!=null)
{
try{
lconnpoolsize = Integer.parseInt(sConnPoolSize);
if(lconnpoolsize>-1)
{
dbmgr.setDBConnPoolSize(lconnpoolsize);
}
}
catch(NumberFormatException ex){}
}
}
if(dbmgr!=null)
{
mapDBMgr.put(aJdbcConfigKey, dbmgr);
}
}
return dbmgr;
}
public void reloadProps() throws Exception
{
clearAll();
if(jsoncrudConfig==null)
{
jsoncrudConfig = new JsonCrudConfig(config_prop_filename);
}
for(String sKey : jsoncrudConfig.getConfigKeys())
{
if(!sKey.startsWith(JsonCrudConfig._PROP_KEY_CRUD+"."))
{
if(sKey.startsWith(JsonCrudConfig._PROP_KEY_JDBC))
{
Map<String, String> map = jsoncrudConfig.getConfig(sKey);
initNRegJdbcDBMgr(sKey, map);
}
//only process crud.xxx
continue;
}
Map<String, String> mapCrudConfig = jsoncrudConfig.getConfig(sKey);
String sDBConfigName = mapCrudConfig.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
//
JdbcDBMgr dbmgr = mapDBMgr.get(sDBConfigName);
if(dbmgr==null)
{
Map<String, String> mapDBConfig = jsoncrudConfig.getConfig(sDBConfigName);
if(mapDBConfig==null)
throw new JsonCrudException("Invalid "+JsonCrudConfig._PROP_KEY_DBCONFIG+" - "+sDBConfigName);
String sJdbcClassname = mapDBConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME);
if(sJdbcClassname!=null)
{
dbmgr = initNRegJdbcDBMgr(sDBConfigName, mapDBConfig);
}
else
{
throw new JsonCrudException("Invalid "+JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME+" - "+sJdbcClassname);
}
}
if(dbmgr!=null)
{
Map<String, String> mapCrudJson2Col = new HashMap<String, String> ();
Map<String, String> mapCrudCol2Json = new HashMap<String, String> ();
Map<String, String> mapCrudJsonSql = new HashMap<String, String> ();
for(String sCrudCfgKey : mapCrudConfig.keySet())
{
Matcher m = pattJsonColMapping.matcher(sCrudCfgKey);
if(m.find())
{
String jsonname = m.group(1);
String dbcolname = mapCrudConfig.get(sCrudCfgKey);
mapCrudJson2Col.put(jsonname, dbcolname);
mapCrudCol2Json.put(dbcolname, jsonname);
continue;
}
//
m = pattJsonSQL.matcher(sCrudCfgKey);
if(m.find())
{
String jsonname = m.group(1);
String sql = mapCrudConfig.get(sCrudCfgKey);
if(sql==null) sql = "";
else sql = sql.trim();
if(sql.length()>0)
{
mapCrudJsonSql.put(jsonname, sql);
}
continue;
}
//
}
mapJson2ColName.put(sKey, mapCrudJson2Col);
mapColName2Json.put(sKey, mapCrudCol2Json);
mapJson2Sql.put(sKey, mapCrudJsonSql);
//
String sTableName = mapCrudConfig.get(JsonCrudConfig._PROP_KEY_TABLENAME);
System.out.print("[init] "+sKey+" - "+sTableName+" ... ");
Map<String, DBColMeta> mapCols = getTableMetaData(sKey, dbmgr, sTableName);
if(mapCols!=null)
{
System.out.println(mapCols.size()+" cols meta loaded.");
mapTableCols.put(sKey, mapCols);
}
}
}
}
public Map<String, String> validateDataWithSchema(String aCrudKey, JSONObject aJsonData)
{
return validateDataWithSchema(aCrudKey, aJsonData, false);
}
public Map<String, String> validateDataWithSchema(String aCrudKey, JSONObject aJsonData, boolean isDebugMode)
{
Map<String, String> mapError = new HashMap<String, String>();
if(aJsonData!=null)
{
Map<String, String> mapJsonToCol = mapJson2ColName.get(aCrudKey);
StringBuffer sbErrInfo = new StringBuffer();
Map<String, DBColMeta> mapCols = mapTableCols.get(aCrudKey);
if(mapCols!=null && mapCols.size()>0)
{
for(String sJsonKey : aJsonData.keySet())
{
String sJsonColName = mapJsonToCol.get(sJsonKey);
if(sJsonColName==null)
{
//skip not mapping found
continue;
}
DBColMeta col = mapCols.get(sJsonColName);
if(col!=null)
{
Object oVal = aJsonData.get(sJsonKey);
////// Check if Nullable //////////
if(!col.getColnullable())
{
if(oVal==null || oVal.toString().trim().length()==0)
{
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_NOT_NULLABLE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' cannot be empty. ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
}
if(oVal==null)
continue;
////// Check Data Type //////////
boolean isInvalidDataType = false;
if(oVal instanceof String)
{
isInvalidDataType = !col.isString();
}
else if (oVal instanceof Boolean)
{
isInvalidDataType = (!col.isBit() && !col.isBoolean());
}
else if (oVal instanceof Long
|| oVal instanceof Double
|| oVal instanceof Float
|| oVal instanceof Integer)
{
isInvalidDataType = !col.isNumeric();
}
if(isInvalidDataType)
{
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_INVALID_TYPE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' invalid type, expect:").append(col.getColtypename()).append(" actual:").append(oVal.getClass().getSimpleName()).append(". ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
////// Check Data Size //////////
String sVal = oVal.toString();
if(sVal.length()>col.getColsize())
{
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_EXCEED_SIZE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' exceed allowed size, expect:").append(col.getColsize()).append(" actual:").append(sVal.length()).append(". ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
///// Check if Data is autoincremental //////
if(col.getColautoincrement())
{
//
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_SYSTEM_FIELD);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' not allowed (auto increment field). ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
}
}
}
}
return mapError;
}
public JSONObject castJson2DBVal(String aCrudKey, JSONObject jsonObj)
{
if(jsonObj==null)
return null;
for(String sKey : jsonObj.keySet())
{
Object o = jsonObj.get(sKey);
o = castJson2DBVal(aCrudKey, sKey, o);
jsonObj.put(sKey, o);
}
return jsonObj;
}
public Object castJson2DBVal(String aCrudKey, String aJsonName, Object aVal)
{
if(!(aVal instanceof String))
return aVal;
//only cast string value
aJsonName = getJsonNameNoFilter(aJsonName);
Object oVal = aVal;
DBColMeta col = getDBColMetaByJsonName(aCrudKey, aJsonName);
if(col!=null)
{
String sVal = String.valueOf(aVal);
if(col.isNumeric())
{
if(sVal.indexOf('.')>-1)
oVal = Float.parseFloat(sVal);
else
oVal = Long.parseLong(sVal);
}
else if(col.isBoolean() || col.isBit())
{
oVal = Boolean.parseBoolean(sVal);
}
}
return oVal;
}
public DBColMeta getDBColMetaByColName(String aCrudKey, String aColName)
{
Map<String,DBColMeta> cols = mapTableCols.get(aCrudKey);
for(DBColMeta col : cols.values())
{
if(col.getColname().equalsIgnoreCase(aColName))
{
return col;
}
}
return null;
}
public DBColMeta getDBColMetaByJsonName(String aCrudKey, String aJsonName)
{
aJsonName = getJsonNameNoFilter(aJsonName);
//
Map<String,DBColMeta> cols = mapTableCols.get(aCrudKey);
Map<String,String> mapCol2Json = mapColName2Json.get(aCrudKey);
for(DBColMeta col : cols.values())
{
String sColJsonName = mapCol2Json.get(col.getColname());
if(sColJsonName!=null && sColJsonName.equalsIgnoreCase(aJsonName))
{
return col;
}
}
return null;
}
private Map<String, DBColMeta> getTableMetaData(String aKey, JdbcDBMgr aDBMgr, String aTableName) throws SQLException
{
Map<String, DBColMeta> mapDBColJson = new HashMap<String, DBColMeta>();
String sSQL = "SELECT * FROM "+aTableName+" WHERE 1=2";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = aDBMgr.getConnection();
stmt = conn.prepareStatement(sSQL);
rs = stmt.executeQuery();
Map<String, String> mapColJsonName = mapColName2Json.get(aKey);
ResultSetMetaData meta = rs.getMetaData();
for(int i=0; i<meta.getColumnCount(); i++)
{
int idx = i+1;
DBColMeta coljson = new DBColMeta();
coljson.setColseq(idx);
coljson.setTablename(meta.getTableName(idx));
coljson.setColname(meta.getColumnLabel(idx));
coljson.setColclassname(meta.getColumnClassName(idx));
coljson.setColtypename(meta.getColumnTypeName(idx));
coljson.setColtype(String.valueOf(meta.getColumnType(idx)));
coljson.setColsize(meta.getColumnDisplaySize(idx));
coljson.setColnullable(ResultSetMetaData.columnNullable == meta.isNullable(idx));
coljson.setColautoincrement(meta.isAutoIncrement(idx));
//
String sJsonName = mapColJsonName.get(coljson.getColname());
if(sJsonName!=null)
{
coljson.setJsonname(sJsonName);
}
//
mapDBColJson.put(coljson.getColname(), coljson);
}
}
finally
{
aDBMgr.closeQuietly(conn, stmt, rs);
}
if(mapDBColJson.size()==0)
return null;
else
{
return mapDBColJson;
}
}
public boolean isDebugMode(String aCrudConfigKey)
{
Map<String, String> mapCrudConfig = jsoncrudConfig.getConfig(aCrudConfigKey);
if(mapCrudConfig!=null)
{
return Boolean.parseBoolean(mapCrudConfig.get(JsonCrudConfig._PROP_KEY_DEBUG));
}
return false;
}
private String listParamsToString(List listParams)
{
if(listParams!=null)
return listParamsToString(listParams.toArray(new Object[listParams.size()]));
else
return null;
}
private String listParamsToString(Object[] aObjParams)
{
JSONArray jsonArr = new JSONArray();
if(aObjParams!=null && aObjParams.length>0)
{
for(int i=0; i<aObjParams.length; i++)
{
Object o = aObjParams[i];
if(o.getClass().isArray())
{
Object[] objs = (Object[]) o;
JSONArray jsonArr2 = new JSONArray();
for(int j=0; j<objs.length; j++)
{
jsonArr2.put(objs[j].toString());
}
jsonArr.put(jsonArr2);
}
else
{
jsonArr.put(o);
}
}
}
return jsonArr.toString();
}
private long updateChildObject(JdbcDBMgr aDBMgr, String aObjInsertSQL, List<Object[]> aListParams) throws Exception
{
long lAffectedRow = 0;
String sChildTableName = null;
String sChildTableFields = null;
Matcher m = pattInsertSQLtableFields.matcher(aObjInsertSQL.toLowerCase());
if(m.find())
{
sChildTableName = m.group(1);
sChildTableFields = m.group(2);
}
StringBuffer sbWhere = new StringBuffer();
StringTokenizer tk = new StringTokenizer(sChildTableFields,",");
while(tk.hasMoreTokens())
{
if(sbWhere.length()>0)
{
sbWhere.append(" AND ");
}
else
{
sbWhere.append("(");
}
String sField = tk.nextToken();
sbWhere.append(sField).append(" = ? ");
}
sbWhere.append(")");
if(aListParams!=null && aListParams.size()>0)
{
/////
List<Object> listFlattenParam = new ArrayList<Object>();
//
StringBuffer sbObjSQL2 = new StringBuffer();
sbObjSQL2.append("SELECT * FROM ").append(sChildTableName).append(" WHERE 1=1 ");
sbObjSQL2.append(" AND ").append(sbWhere);
//
List<Object[]> listParams_new = new ArrayList<Object[]>();
for(Object[] obj2 : aListParams)
{
for(Object o : obj2)
{
if((o instanceof String) && o.toString().equals(""))
{
o = null;
}
listFlattenParam.add(o);
}
if(aDBMgr.getQueryCount(sbObjSQL2.toString(), obj2)==0)
{
listParams_new.add(obj2);
}
}
aListParams.clear();
aListParams.addAll(listParams_new);
listParams_new.clear();
aObjInsertSQL = aObjInsertSQL.replaceAll("\\{.+?\\}", "?");
try{
lAffectedRow += aDBMgr.executeBatchUpdate(aObjInsertSQL, aListParams);
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+aObjInsertSQL+", params:"+listParamsToString(aListParams), sqlEx);
}
}
return lAffectedRow;
}
private List<Object[]> getSubQueryParams(Map<String, String> aCrudCfgMap, JSONObject aJsonParentData, String aJsonName) throws JsonCrudException
{
String sPrefix = "jsonattr."+aJsonName+".";
String sObjSQL = aCrudCfgMap.get(sPrefix+JsonCrudConfig._PROP_KEY_OBJ_SQL);
String sObjMapping = aCrudCfgMap.get(sPrefix+JsonCrudConfig._PROP_KEY_OBJ_MAPPING);
String sObjKeyName = null;
String sObjValName = null;
List<Object[]> listAllParams = new ArrayList<Object[]>();
List<Object> listParamObj = new ArrayList<Object>();
if(sObjSQL!=null && sObjMapping!=null)
{
Object obj = aJsonParentData.get(aJsonName);
Iterator iter = null;
boolean isKeyValPair = (obj instanceof JSONObject);
JSONObject jsonKeyVal = null;
if(isKeyValPair)
{
//Key-Value pair
JSONObject jsonObjMapping = new JSONObject(sObjMapping);
sObjKeyName = jsonObjMapping.keySet().iterator().next();
sObjValName = (String) jsonObjMapping.get(sObjKeyName);
jsonKeyVal = (JSONObject) obj;
iter = jsonKeyVal.keySet().iterator();
}
else if(obj instanceof JSONArray)
{
//Single level Array
JSONArray jsonObjMapping = new JSONArray(sObjMapping);
sObjKeyName = (String) jsonObjMapping.iterator().next();
JSONArray jsonArr = (JSONArray) obj;
iter = jsonArr.iterator();
}
while(iter.hasNext())
{
String sKey = (String) iter.next();
listParamObj.clear();
Matcher m = pattSQLjsonname.matcher(sObjSQL);
while(m.find())
{
String sBracketJsonName = m.group(1);
if(aJsonParentData.has(sBracketJsonName))
{
listParamObj.add(aJsonParentData.get(sBracketJsonName));
}
else if(sBracketJsonName.equals(sObjKeyName))
{
listParamObj.add(sKey);
}
else if(jsonKeyVal!=null && sBracketJsonName.equals(sObjValName))
{
listParamObj.add(jsonKeyVal.get(sKey));
}
}
listAllParams.add(listParamObj.toArray(new Object[listParamObj.size()]));
}
}
if(sObjKeyName==null)
throw new JsonCrudException("No object mapping found ! - "+aJsonName);
///
return listAllParams;
}
private boolean isEmptyJson(String aJsonString)
{
if(aJsonString==null || aJsonString.trim().length()==0)
return true;
aJsonString = aJsonString.replaceAll("\\s", "");
while(aJsonString.startsWith("{") || aJsonString.startsWith("["))
{
if(aJsonString.length()==2)
return true;
if("{\"\":\"\"}".equalsIgnoreCase(aJsonString))
{
return true;
}
aJsonString = aJsonString.substring(1, aJsonString.length()-1);
}
return false;
}
private String getJsonNameNoFilter(String aJsonName)
{
int iPos = aJsonName.indexOf(".");
if(iPos >-1)
{
aJsonName = aJsonName.substring(0,iPos);
}
return aJsonName;
}
public JdbcDBMgr getJdbcMgr(String aJdbcConfigName)
{
return mapDBMgr.get(aJdbcConfigName);
}
}
| src/hl/jsoncrud/CRUDMgr.java | /*
Copyright (c) 2017 [email protected]
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 shall be used for Good, not Evil.
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 hl.jsoncrud;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
import hl.common.JdbcDBMgr;
public class CRUDMgr {
private final static String JSONFILTER_FROM = "from";
private final static String JSONFILTER_TO = "to";
private final static String JSONFILTER_STARTWITH = "startwith";
private final static String JSONFILTER_ENDWITH = "endwith";
private final static String JSONFILTER_CONTAIN = "contain";
private final static String SQLLIKE_WILDCARD = "%";
private final static String JSONVAL_WILDCARD = "*";
private final static String JSONFILTER_CASE_INSENSITIVE = "ci";
private final static String JSONFILTER_NOT = "not";
private Map<String, JdbcDBMgr> mapDBMgr = null;
private Map<String, Map<String, String>> mapJson2ColName = null;
private Map<String, Map<String, String>> mapColName2Json = null;
private Map<String, Map<String, String>> mapJson2Sql = null;
private Map<String, Map<String,DBColMeta>> mapTableCols = null;
private Pattern pattSQLjsonname = null;
private Pattern pattJsonColMapping = null;
private Pattern pattJsonSQL = null;
private Pattern pattJsonNameFilter = null;
private Pattern pattInsertSQLtableFields = null;
private JsonCrudConfig jsoncrudConfig = null;
private String config_prop_filename = null;
public final static String _PAGINATION_CONFIGKEY = "list.pagination";
public String _LIST_META = "meta";
public String _LIST_RESULT = "result";
public String _LIST_TOTAL = "total";
public String _LIST_FETCHSIZE = "fetchsize";
public String _LIST_START = "start";
public String _LIST_ORDERBY = "orderby";
public final static String _DB_VALIDATION_ERRCODE_CONFIGKEY = "dbschema.validation_errcode";
public static String ERRCODE_NOT_NULLABLE = "not_nullable";
public static String ERRCODE_EXCEED_SIZE = "exceed_size";
public static String ERRCODE_INVALID_TYPE = "invalid_type";
public static String ERRCODE_SYSTEM_FIELD = "system_field";
public CRUDMgr()
{
config_prop_filename = null;
init();
}
public String getVersionInfo()
{
JSONObject jsonVer = new JSONObject();
jsonVer.put("framework", "jsoncrud");
jsonVer.put("version", "0.1.9 beta");
return jsonVer.toString();
}
public CRUDMgr(String aPropFileName)
{
config_prop_filename = aPropFileName;
if(aPropFileName!=null && aPropFileName.trim().length()>0)
{
try {
jsoncrudConfig = new JsonCrudConfig(aPropFileName);
} catch (IOException e) {
throw new RuntimeException("Error loading "+aPropFileName, e);
}
}
init();
}
private void init()
{
mapDBMgr = new HashMap<String, JdbcDBMgr>();
mapJson2ColName = new HashMap<String, Map<String, String>>();
mapColName2Json = new HashMap<String, Map<String, String>>();
mapJson2Sql = new HashMap<String, Map<String, String>>();
mapTableCols = new HashMap<String, Map<String, DBColMeta>>();
//
pattJsonColMapping = Pattern.compile("jsonattr\\.([a-zA-Z_-]+?)\\.colname");
pattJsonSQL = Pattern.compile("jsonattr\\.([a-zA-Z_-]+?)\\.sql");
//
pattSQLjsonname = Pattern.compile("\\{(.+?)\\}");
pattInsertSQLtableFields = Pattern.compile("insert\\s+?into\\s+?([a-zA-Z_]+?)\\s+?\\((.+?)\\)");
//
pattJsonNameFilter = Pattern.compile("([a-zA-Z_-]+?)\\.("
+JSONFILTER_FROM+"|"+JSONFILTER_TO+"|"
+JSONFILTER_STARTWITH+"|"+JSONFILTER_ENDWITH+"|"+JSONFILTER_CONTAIN+"|"+JSONFILTER_NOT+"|"
+JSONFILTER_CASE_INSENSITIVE+")"
+"(?:\\.("+JSONFILTER_CASE_INSENSITIVE+"|"+JSONFILTER_NOT+"))?"
+"(?:\\.("+JSONFILTER_CASE_INSENSITIVE+"|"+JSONFILTER_NOT+"))?");
try {
reloadProps();
if(jsoncrudConfig.getAllConfig().size()==0)
{
throw new IOException("Fail to load properties file - "+config_prop_filename);
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
initPaginationConfig();
initValidationErrCodeConfig();
}
private void initValidationErrCodeConfig()
{
Map<String, String> mapErrCodes = jsoncrudConfig.getConfig(_DB_VALIDATION_ERRCODE_CONFIGKEY);
if(mapErrCodes!=null && mapErrCodes.size()>0)
{
String sMetaKey = null;
sMetaKey = mapErrCodes.get(ERRCODE_EXCEED_SIZE);
if(sMetaKey!=null)
ERRCODE_EXCEED_SIZE = sMetaKey;
sMetaKey = mapErrCodes.get(ERRCODE_INVALID_TYPE);
if(sMetaKey!=null)
ERRCODE_INVALID_TYPE = sMetaKey;
sMetaKey = mapErrCodes.get(ERRCODE_NOT_NULLABLE);
if(sMetaKey!=null)
ERRCODE_NOT_NULLABLE = sMetaKey;
sMetaKey = mapErrCodes.get(ERRCODE_SYSTEM_FIELD);
if(sMetaKey!=null)
ERRCODE_SYSTEM_FIELD = sMetaKey;
}
}
private void initPaginationConfig()
{
Map<String, String> mapPagination = jsoncrudConfig.getConfig(_PAGINATION_CONFIGKEY);
if(mapPagination!=null && mapPagination.size()>0)
{
String sMetaKey = null;
sMetaKey = mapPagination.get(_LIST_META);
if(sMetaKey!=null)
_LIST_META = sMetaKey;
sMetaKey = mapPagination.get(_LIST_RESULT);
if(sMetaKey!=null)
_LIST_RESULT = sMetaKey;
sMetaKey = mapPagination.get(_LIST_TOTAL);
if(sMetaKey!=null)
_LIST_TOTAL = sMetaKey;
sMetaKey = mapPagination.get(_LIST_FETCHSIZE);
if(sMetaKey!=null)
_LIST_FETCHSIZE = sMetaKey;
sMetaKey = mapPagination.get(_LIST_START);
if(sMetaKey!=null)
_LIST_START = sMetaKey;
sMetaKey = mapPagination.get(_LIST_ORDERBY);
if(sMetaKey!=null)
_LIST_ORDERBY = sMetaKey;
}
}
public JSONObject create(String aCrudKey, JSONObject aDataJson) throws JsonCrudException
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
aDataJson = castJson2DBVal(aCrudKey, aDataJson);
StringBuffer sbColName = new StringBuffer();
StringBuffer sbParams = new StringBuffer();
StringBuffer sbRollbackParentSQL = new StringBuffer();
List<Object> listValues = new ArrayList<Object>();
List<String> listUnmatchedJsonName = new ArrayList<String>();
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
for(String sJsonName : aDataJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
if(sColName!=null)
{
//
if(sbColName.length()>0)
{
sbColName.append(",");
sbParams.append(",");
}
sbColName.append(sColName);
sbParams.append("?");
//
//
sbRollbackParentSQL.append(" AND ").append(sColName).append(" = ? ");
//
listValues.add(aDataJson.get(sJsonName));
}
else
{
listUnmatchedJsonName.add(sJsonName);
}
}
String sSQL = "INSERT INTO "+sTableName+"("+sbColName.toString()+") values ("+sbParams.toString()+")";
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jArrCreated = null;
try {
jArrCreated = dbmgr.executeUpdate(sSQL, listValues);
}
catch(Throwable ex)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(listValues), ex);
}
if(jArrCreated.length()>0)
{
Map<String, String> mapCrudCol2Json = mapColName2Json.get(aCrudKey);
JSONObject jsonCreated = jArrCreated.getJSONObject(0);
for(String sColName : jsonCreated.keySet())
{
String sMappedKey = mapCrudCol2Json.get(sColName);
if(sMappedKey==null)
sMappedKey = sColName;
aDataJson.put(sMappedKey, jsonCreated.get(sColName));
}
//child create
if(listUnmatchedJsonName.size()>0)
{
JSONArray jsonArrReturn = retrieve(aCrudKey, aDataJson);
for(int i=0 ; i<jsonArrReturn.length(); i++ )
{
JSONObject jsonReturn = jsonArrReturn.getJSONObject(i);
//merging json obj
for(String sDataJsonKey : aDataJson.keySet())
{
jsonReturn.put(sDataJsonKey, aDataJson.get(sDataJsonKey));
}
for(String sJsonName2 : listUnmatchedJsonName)
{
List<Object[]> listParams2 = getSubQueryParams(map, jsonReturn, sJsonName2);
String sObjInsertSQL = map.get("jsonattr."+sJsonName2+"."+JsonCrudConfig._PROP_KEY_OBJ_SQL);
long lupdatedRow = 0;
try {
lupdatedRow = updateChildObject(dbmgr, sObjInsertSQL, listParams2);
}
catch(Throwable ex)
{
try {
//rollback parent
sbRollbackParentSQL.insert(0, "DELETE FROM "+sTableName+" WHERE 1=1 ");
JSONArray jArrRollbackRows = dbmgr.executeUpdate(sbRollbackParentSQL.toString(), listValues);
if(jArrCreated.length() != jArrRollbackRows.length())
{
throw new JsonCrudException("Record fail to Rollback!");
}
}
catch(Throwable ex2)
{
throw new JsonCrudException("[Rollback Failed], parent:[sql:"+sbRollbackParentSQL.toString()+",params:"+listParamsToString(listValues)+"], child:[sql:"+sObjInsertSQL+",params:"+listParamsToString(listParams2)+"]", ex);
}
throw new JsonCrudException("[Rollback Success] : child : sql:"+sObjInsertSQL+", params:"+listParamsToString(listParams2), ex);
}
}
}
}
JSONArray jsonArray = retrieve(aCrudKey, aDataJson);
if(jsonArray==null || jsonArray.length()==0)
return null;
else
return (JSONObject) jsonArray.get(0);
}
else
{
return null;
}
}
public JSONObject retrieveFirst(String aCrudKey, JSONObject aWhereJson) throws JsonCrudException
{
JSONArray jsonArr = retrieve(aCrudKey, aWhereJson);
if(jsonArr!=null && jsonArr.length()>0)
{
return (JSONObject) jsonArr.get(0);
}
return null;
}
public JSONArray retrieve(String aCrudKey, JSONObject aWhereJson) throws JsonCrudException
{
JSONObject json = retrieve(aCrudKey, aWhereJson, 0, 0, null);
if(json==null)
{
return new JSONArray();
}
return (JSONArray) json.get(_LIST_RESULT);
}
public JSONArray retrieve(String aCrudKey, JSONObject aWhereJson, String[] aOrderBy) throws JsonCrudException
{
JSONObject json = retrieve(aCrudKey, aWhereJson, 0, 0, aOrderBy);
if(json==null)
{
return new JSONArray();
}
return (JSONArray) json.get(_LIST_RESULT);
}
public JSONObject retrieve(String aCrudKey, String aSQL, Object[] aObjParams,
long aStartFrom, long aFetchSize) throws JsonCrudException
{
JSONObject jsonReturn = null;
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = aSQL;
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
if(aStartFrom<=0)
aStartFrom = 1;
JSONArray jsonArr = new JSONArray();
try{
Map<String, String> mapCrudCol2Json = mapColName2Json.get(aCrudKey);
Map<String, String> mapCrudSql = mapJson2Sql.get(aCrudKey);
conn = dbmgr.getConnection();
stmt = conn.prepareStatement(sSQL);
stmt = JdbcDBMgr.setParams(stmt, aObjParams);
rs = stmt.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
long lTotalResult = 0;
while(rs.next())
{
lTotalResult++;
if(lTotalResult < aStartFrom)
continue;
JSONObject jsonOnbj = new JSONObject();
for(int i=0; i<meta.getColumnCount(); i++)
{
String sColName = meta.getColumnLabel(i+1);
String sJsonName = mapCrudCol2Json.get(sColName);
if(sJsonName==null)
sJsonName = sColName;
jsonOnbj.put(sJsonName, rs.getObject(sColName));
}
if(mapCrudSql.size()>0)
{
for(String sJsonName : mapCrudSql.keySet())
{
if(!jsonOnbj.has(sJsonName))
{
List<Object> listParams2 = new ArrayList<Object>();
String sSQL2 = mapCrudSql.get(sJsonName);
Matcher m = pattSQLjsonname.matcher(sSQL2);
while(m.find())
{
String sBracketJsonName = m.group(1);
if(jsonOnbj.has(sBracketJsonName))
{
listParams2.add(jsonOnbj.get(sBracketJsonName));
}
}
sSQL2 = sSQL2.replaceAll("\\{.+?\\}", "?");
if(sSQL2.indexOf("?")>-1 && listParams2.size()>0)
{
JSONArray jsonArrayChild = retrieveChild(dbmgr, sSQL2, listParams2);
if(jsonArrayChild!=null && jsonArrayChild.length()>0)
{
String sChildFormat = map.get(
"jsonattr."+sJsonName+"."+JsonCrudConfig._PROP_KEY_FORMAT);
Object o = jsonArrayChild.get(0);
if(o!=null && !isEmptyJson(o.toString()))
{
if(sChildFormat!=null)
{
if(sChildFormat.trim().equals("[]"))
{
jsonOnbj.put(sJsonName, jsonArrayChild);
}
else if(sChildFormat.trim().equals("{}"))
{
jsonOnbj.put(sJsonName, jsonArrayChild.getJSONObject(0));
}
}
else
{
if(o instanceof JSONArray)
{
String sJsonArray = ((JSONArray)o).toString();
if(sJsonArray.length()>2)
{
o = sJsonArray.substring(1, sJsonArray.length()-2);
}
else o = "";
}
if(o instanceof JSONObject)
{
String sJsonObj = ((JSONObject)o).toString();
if(sJsonObj.length()>2)
{
o = sJsonObj.substring(1, sJsonObj.length()-2);
}
else o = "";
}
jsonOnbj.put(sJsonName, o.toString());
}
}
}
}
}
}
}
jsonArr.put(jsonOnbj);
if(aFetchSize>0 && jsonArr.length()>=aFetchSize)
{
break;
}
}
while(rs.next()){
lTotalResult++;
}
if(jsonArr.length()>0)
{
jsonReturn = new JSONObject();
jsonReturn.put(_LIST_RESULT, jsonArr);
//
JSONObject jsonMeta = new JSONObject();
jsonMeta.put(_LIST_TOTAL, lTotalResult);
jsonMeta.put(_LIST_START, aStartFrom);
//
if(aFetchSize>0)
jsonMeta.put(_LIST_FETCHSIZE, aFetchSize);
//
jsonReturn.put(_LIST_META, jsonMeta);
}
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(aObjParams), sqlEx);
}
finally
{
try {
dbmgr.closeQuietly(conn, stmt, rs);
} catch (SQLException e) {
throw new JsonCrudException(e);
}
}
return jsonReturn;
}
private JSONArray retrieveChild(JdbcDBMgr aJdbcMgr, String aSQL, List<Object> aObjParamList) throws SQLException
{
Connection conn2 = null;
PreparedStatement stmt2 = null;
ResultSet rs2 = null;
JSONArray jsonArr2 = new JSONArray();
JSONObject json2 = new JSONObject();
try{
conn2 = aJdbcMgr.getConnection();
stmt2 = conn2.prepareStatement(aSQL);
stmt2 = JdbcDBMgr.setParams(stmt2, aObjParamList);
rs2 = stmt2.executeQuery();
int iTotalCols = rs2.getMetaData().getColumnCount();
if(iTotalCols<1 || iTotalCols>2)
{
throw new SQLException("Only 1 or 2 return columns from subquery are supported !");
}
while(rs2.next())
{
String s = rs2.getString(1);
if(iTotalCols==1)
{
//["1"]
jsonArr2.put(s);
}
else if(iTotalCols==2)
{
//{"key1":"val1", "key2":"val2"}
Object o = rs2.getObject(2);
if(o!=null)
{
json2.put(s, o);
}
}
}
if(iTotalCols==2)
{
//[{"key1":"val1", "key2":"val2"}]
jsonArr2.put(json2);
}
}catch(SQLException sqlEx)
{
throw new SQLException("sql:"+aSQL+", params:"+listParamsToString(aObjParamList), sqlEx);
}
finally{
aJdbcMgr.closeQuietly(conn2, stmt2, rs2);
}
return jsonArr2;
}
public JSONObject retrieve(String aCrudKey, JSONObject aWhereJson,
long aStartFrom, long aFetchSize, String[] aOrderBy) throws JsonCrudException
{
aWhereJson = castJson2DBVal(aCrudKey, aWhereJson);
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
// WHERE
StringBuffer sbWhere = new StringBuffer();
for(String sOrgJsonName : aWhereJson.keySet())
{
boolean isCaseInSensitive = false;
boolean isNotCondition = false;
String sOperator = " = ";
String sJsonName = sOrgJsonName;
Object oJsonValue = aWhereJson.get(sOrgJsonName);
if(sJsonName.indexOf(".")>-1)
{
Matcher m = pattJsonNameFilter.matcher(sJsonName);
if(m.find())
{
sJsonName = m.group(1);
String sJsonOperator = m.group(2);
String sJsonCIorNOT_1 = m.group(3);
String sJsonCIorNOT_2 = m.group(4);
if(JSONFILTER_CASE_INSENSITIVE.equalsIgnoreCase(sJsonCIorNOT_1) || JSONFILTER_CASE_INSENSITIVE.equalsIgnoreCase(sJsonCIorNOT_2)
|| JSONFILTER_CASE_INSENSITIVE.equals(sJsonOperator))
{
isCaseInSensitive = true;
}
if(JSONFILTER_NOT.equalsIgnoreCase(sJsonCIorNOT_1) || JSONFILTER_NOT.equalsIgnoreCase(sJsonCIorNOT_2)
|| JSONFILTER_NOT.equals(sJsonOperator))
{
isNotCondition = true;
}
if(JSONFILTER_FROM.equals(sJsonOperator))
{
sOperator = " >= ";
}
else if(JSONFILTER_TO.equals(sJsonOperator))
{
sOperator = " <= ";
}
else if(JSONFILTER_TO.equals(sJsonOperator))
{
sOperator = " <= ";
}
else if(oJsonValue!=null && oJsonValue instanceof String)
{
if(JSONFILTER_STARTWITH.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = oJsonValue+SQLLIKE_WILDCARD;
}
else if (JSONFILTER_ENDWITH.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = SQLLIKE_WILDCARD+oJsonValue;
}
else if (JSONFILTER_CONTAIN.equals(sJsonOperator))
{
sOperator = " like ";
oJsonValue = SQLLIKE_WILDCARD+oJsonValue+SQLLIKE_WILDCARD;
}
}
}
}
if(oJsonValue!=null && (oJsonValue instanceof String) && (oJsonValue.toString().indexOf(JSONVAL_WILDCARD)>-1))
{
sOperator = " like ";
oJsonValue = oJsonValue.toString().replaceAll(Pattern.quote(JSONVAL_WILDCARD), SQLLIKE_WILDCARD);
}
String sColName = mapCrudJsonCol.get(sJsonName);
//
if(sColName!=null)
{
sbWhere.append(" AND ");
if(isNotCondition)
{
sbWhere.append(" NOT (");
}
if(isCaseInSensitive && (oJsonValue instanceof String))
{
sbWhere.append(" UPPER(").append(sColName).append(") ").append(sOperator).append(" UPPER(?) ");
}
else
{
sbWhere.append(sColName).append(sOperator).append(" ? ");
}
if(isNotCondition)
{
sbWhere.append(" )");
}
//
oJsonValue = castJson2DBVal(aCrudKey, sJsonName, oJsonValue);
listValues.add(oJsonValue);
}
}
StringBuffer sbOrderBy = new StringBuffer();
if(aOrderBy!=null && aOrderBy.length>0)
{
for(String sOrderBy : aOrderBy)
{
String sOrderSeqKeyword = "";
int iOrderSeq = sOrderBy.indexOf('.');
if(iOrderSeq>-1)
{
sOrderSeqKeyword = sOrderBy.substring(iOrderSeq+1);
}
else if(iOrderSeq==-1)
{
iOrderSeq = sOrderBy.length();
}
String sJsonAttr = sOrderBy.substring(0, iOrderSeq);
String sOrderColName = mapCrudJsonCol.get(sJsonAttr);
if(sOrderColName!=null)
{
if(sbOrderBy.length()>0)
{
sbOrderBy.append(",");
}
sbOrderBy.append(sOrderColName);
if(sOrderSeqKeyword.length()>0)
sbOrderBy.append(" ").append(sOrderSeqKeyword);
}
}
if(sbOrderBy.length()>0)
{
sbWhere.append(" ORDER BY ").append(sbOrderBy.toString());
}
}
String sSQL = "SELECT * FROM "+sTableName+" WHERE 1=1 "+sbWhere.toString();
JSONObject jsonReturn = retrieve(aCrudKey, sSQL, listValues.toArray(new Object[listValues.size()]), aStartFrom, aFetchSize);
if(jsonReturn!=null && jsonReturn.has(_LIST_META))
{
JSONObject jsonMeta = jsonReturn.getJSONObject(_LIST_META);
if(aOrderBy!=null)
{
StringBuffer sbOrderBys = new StringBuffer();
for(String sOrderBy : aOrderBy)
{
if(sbOrderBys.length()>0)
sbOrderBys.append(",");
sbOrderBys.append(sOrderBy);
}
if(sbOrderBys.length()>0)
jsonMeta.put(_LIST_ORDERBY, sbOrderBys.toString());
}
//
jsonReturn.put(_LIST_META, jsonMeta);
}
return jsonReturn;
//
}
public JSONArray update(String aCrudKey, JSONObject aDataJson, JSONObject aWhereJson) throws Exception
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
aDataJson = castJson2DBVal(aCrudKey, aDataJson);
aWhereJson = castJson2DBVal(aCrudKey, aWhereJson);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
List<String> listUnmatchedJsonName = new ArrayList<String>();
//SET
StringBuffer sbSets = new StringBuffer();
for(String sJsonName : aDataJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
//
if(sColName!=null)
{
//
if(sbSets.length()>0)
sbSets.append(",");
sbSets.append(sColName).append(" = ? ");
//
listValues.add(aDataJson.get(sJsonName));
}
else
{
listUnmatchedJsonName.add(sJsonName);
}
}
// WHERE
StringBuffer sbWhere = new StringBuffer();
for(String sJsonName : aWhereJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
//
if(sColName==null)
{
throw new JsonCrudException("Missing Json to dbcol mapping ("+sJsonName+":"+aWhereJson.get(sJsonName)+") ! - "+aCrudKey);
}
sbWhere.append(" AND ").append(sColName).append(" = ? ");
//
listValues.add(aWhereJson.get(sJsonName));
}
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = "UPDATE "+sTableName+" SET "+sbSets.toString()+" WHERE 1=1 "+sbWhere.toString();
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jArrUpdated = new JSONArray();
long lAffectedRow2 = 0;
try{
if(sbSets.length()>0)
{
jArrUpdated = dbmgr.executeUpdate(sSQL, listValues);
}
if(jArrUpdated.length()>0 || sbSets.length()==0)
{
//child update
JSONArray jsonArrReturn = retrieve(aCrudKey, aWhereJson);
for(int i=0 ; i<jsonArrReturn.length(); i++ )
{
JSONObject jsonReturn = jsonArrReturn.getJSONObject(i);
//merging json obj
for(String sDataJsonKey : aDataJson.keySet())
{
jsonReturn.put(sDataJsonKey, aDataJson.get(sDataJsonKey));
}
for(String sJsonName2 : listUnmatchedJsonName)
{
List<Object[]> listParams2 = getSubQueryParams(map, jsonReturn, sJsonName2);
String sObjInsertSQL = map.get("jsonattr."+sJsonName2+"."+JsonCrudConfig._PROP_KEY_OBJ_SQL);
lAffectedRow2 += updateChildObject(dbmgr, sObjInsertSQL, listParams2);
}
}
}
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(listValues), sqlEx);
}
if(jArrUpdated.length()>0 || lAffectedRow2>0)
{
JSONArray jsonArray = retrieve(aCrudKey, aWhereJson);
return jsonArray;
}
else
{
return null;
}
}
public JSONArray delete(String aCrudKey, JSONObject aWhereJson) throws Exception
{
Map<String, String> map = jsoncrudConfig.getConfig(aCrudKey);
if(map==null || map.size()==0)
throw new JsonCrudException("Invalid crud configuration key ! - "+aCrudKey);
aWhereJson = castJson2DBVal(aCrudKey, aWhereJson);
List<Object> listValues = new ArrayList<Object>();
Map<String, String> mapCrudJsonCol = mapJson2ColName.get(aCrudKey);
StringBuffer sbWhere = new StringBuffer();
for(String sJsonName : aWhereJson.keySet())
{
String sColName = mapCrudJsonCol.get(sJsonName);
//
sbWhere.append(" AND ").append(sColName).append(" = ? ");
//
listValues.add(aWhereJson.get(sJsonName));
}
String sTableName = map.get(JsonCrudConfig._PROP_KEY_TABLENAME);
//boolean isDebug = "true".equalsIgnoreCase(map.get(JsonCrudConfig._PROP_KEY_DEBUG));
String sSQL = "DELETE FROM "+sTableName+" WHERE 1=1 "+sbWhere.toString();
String sJdbcName = map.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
JdbcDBMgr dbmgr = mapDBMgr.get(sJdbcName);
JSONArray jsonArray = null;
jsonArray = retrieve(aCrudKey, aWhereJson);
if(jsonArray.length()>0)
{
JSONArray jArrAffectedRow = new JSONArray();
try {
jArrAffectedRow = dbmgr.executeUpdate(sSQL, listValues);
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+sSQL+", params:"+listParamsToString(listValues), sqlEx);
}
if(jArrAffectedRow.length()>0)
{
return jsonArray;
}
}
return null;
}
private void clearAll()
{
mapDBMgr.clear();
mapJson2ColName.clear();
mapColName2Json.clear();
mapJson2Sql.clear();
mapTableCols.clear();
}
public Map<String, String> getAllConfig()
{
return jsoncrudConfig.getAllConfig();
}
private JdbcDBMgr initNRegJdbcDBMgr(String aJdbcConfigKey, Map<String, String> mapJdbcConfig) throws SQLException
{
JdbcDBMgr dbmgr = mapDBMgr.get(aJdbcConfigKey);
if(dbmgr==null)
{
String sJdbcClassName = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME);
String sJdbcUrl = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_URL);
String sJdbcUid = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_UID);
String sJdbcPwd = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_PWD);
if(sJdbcClassName!=null && sJdbcUrl!=null)
{
try {
dbmgr = new JdbcDBMgr(sJdbcClassName, sJdbcUrl, sJdbcUid, sJdbcPwd);
}catch(Exception ex)
{
throw new SQLException("Error initialize JDBC - "+aJdbcConfigKey, ex);
}
//
int lconnpoolsize = -1;
String sConnPoolSize = mapJdbcConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CONNPOOL);
if(sConnPoolSize!=null)
{
try{
lconnpoolsize = Integer.parseInt(sConnPoolSize);
if(lconnpoolsize>-1)
{
dbmgr.setDBConnPoolSize(lconnpoolsize);
}
}
catch(NumberFormatException ex){}
}
}
if(dbmgr!=null)
{
mapDBMgr.put(aJdbcConfigKey, dbmgr);
}
}
return dbmgr;
}
public void reloadProps() throws Exception
{
clearAll();
if(jsoncrudConfig==null)
{
jsoncrudConfig = new JsonCrudConfig(config_prop_filename);
}
for(String sKey : jsoncrudConfig.getConfigKeys())
{
if(!sKey.startsWith(JsonCrudConfig._PROP_KEY_CRUD+"."))
{
if(sKey.startsWith(JsonCrudConfig._PROP_KEY_JDBC))
{
Map<String, String> map = jsoncrudConfig.getConfig(sKey);
initNRegJdbcDBMgr(sKey, map);
}
//only process crud.xxx
continue;
}
Map<String, String> mapCrudConfig = jsoncrudConfig.getConfig(sKey);
String sDBConfigName = mapCrudConfig.get(JsonCrudConfig._PROP_KEY_DBCONFIG);
//
JdbcDBMgr dbmgr = mapDBMgr.get(sDBConfigName);
if(dbmgr==null)
{
Map<String, String> mapDBConfig = jsoncrudConfig.getConfig(sDBConfigName);
if(mapDBConfig==null)
throw new JsonCrudException("Invalid "+JsonCrudConfig._PROP_KEY_DBCONFIG+" - "+sDBConfigName);
String sJdbcClassname = mapDBConfig.get(JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME);
if(sJdbcClassname!=null)
{
dbmgr = initNRegJdbcDBMgr(sDBConfigName, mapDBConfig);
}
else
{
throw new JsonCrudException("Invalid "+JsonCrudConfig._PROP_KEY_JDBC_CLASSNAME+" - "+sJdbcClassname);
}
}
if(dbmgr!=null)
{
Map<String, String> mapCrudJson2Col = new HashMap<String, String> ();
Map<String, String> mapCrudCol2Json = new HashMap<String, String> ();
Map<String, String> mapCrudJsonSql = new HashMap<String, String> ();
for(String sCrudCfgKey : mapCrudConfig.keySet())
{
Matcher m = pattJsonColMapping.matcher(sCrudCfgKey);
if(m.find())
{
String jsonname = m.group(1);
String dbcolname = mapCrudConfig.get(sCrudCfgKey);
mapCrudJson2Col.put(jsonname, dbcolname);
mapCrudCol2Json.put(dbcolname, jsonname);
continue;
}
//
m = pattJsonSQL.matcher(sCrudCfgKey);
if(m.find())
{
String jsonname = m.group(1);
String sql = mapCrudConfig.get(sCrudCfgKey);
if(sql==null) sql = "";
else sql = sql.trim();
if(sql.length()>0)
{
mapCrudJsonSql.put(jsonname, sql);
}
continue;
}
//
}
mapJson2ColName.put(sKey, mapCrudJson2Col);
mapColName2Json.put(sKey, mapCrudCol2Json);
mapJson2Sql.put(sKey, mapCrudJsonSql);
//
String sTableName = mapCrudConfig.get(JsonCrudConfig._PROP_KEY_TABLENAME);
System.out.print("[init] "+sKey+" - "+sTableName+" ... ");
Map<String, DBColMeta> mapCols = getTableMetaData(sKey, dbmgr, sTableName);
if(mapCols!=null)
{
System.out.println(mapCols.size()+" cols meta loaded.");
mapTableCols.put(sKey, mapCols);
}
}
}
}
public Map<String, String> validateDataWithSchema(String aCrudKey, JSONObject aJsonData)
{
return validateDataWithSchema(aCrudKey, aJsonData, false);
}
public Map<String, String> validateDataWithSchema(String aCrudKey, JSONObject aJsonData, boolean isDebugMode)
{
Map<String, String> mapError = new HashMap<String, String>();
if(aJsonData!=null)
{
Map<String, String> mapJsonToCol = mapJson2ColName.get(aCrudKey);
StringBuffer sbErrInfo = new StringBuffer();
Map<String, DBColMeta> mapCols = mapTableCols.get(aCrudKey);
if(mapCols!=null && mapCols.size()>0)
{
for(String sJsonKey : aJsonData.keySet())
{
String sJsonColName = mapJsonToCol.get(sJsonKey);
if(sJsonColName==null)
{
//skip not mapping found
continue;
}
DBColMeta col = mapCols.get(sJsonColName);
if(col!=null)
{
Object oVal = aJsonData.get(sJsonKey);
////// Check if Nullable //////////
if(!col.getColnullable())
{
if(oVal==null || oVal.toString().trim().length()==0)
{
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_NOT_NULLABLE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' cannot be empty. ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
}
if(oVal==null)
continue;
////// Check Data Type //////////
boolean isInvalidDataType = false;
if(oVal instanceof String)
{
isInvalidDataType = !col.isString();
}
else if (oVal instanceof Boolean)
{
isInvalidDataType = (!col.isBit() && !col.isBoolean());
}
else if (oVal instanceof Long
|| oVal instanceof Double
|| oVal instanceof Float
|| oVal instanceof Integer)
{
isInvalidDataType = !col.isNumeric();
}
if(isInvalidDataType)
{
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_INVALID_TYPE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' invalid type, expect:").append(col.getColtypename()).append(" actual:").append(oVal.getClass().getSimpleName()).append(". ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
////// Check Data Size //////////
String sVal = oVal.toString();
if(sVal.length()>col.getColsize())
{
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_EXCEED_SIZE);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' exceed allowed size, expect:").append(col.getColsize()).append(" actual:").append(sVal.length()).append(". ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
///// Check if Data is autoincremental //////
if(col.getColautoincrement())
{
//
sbErrInfo.setLength(0);
sbErrInfo.append(ERRCODE_SYSTEM_FIELD);
if(isDebugMode)
{
sbErrInfo.append(" - '").append(col.getColname()).append("' not allowed (auto increment field). ").append(col);
}
mapError.put(sJsonKey, sbErrInfo.toString());
}
}
}
}
}
return mapError;
}
public JSONObject castJson2DBVal(String aCrudKey, JSONObject jsonObj)
{
if(jsonObj==null)
return null;
for(String sKey : jsonObj.keySet())
{
Object o = jsonObj.get(sKey);
o = castJson2DBVal(aCrudKey, sKey, o);
jsonObj.put(sKey, o);
}
return jsonObj;
}
public Object castJson2DBVal(String aCrudKey, String aJsonName, Object aVal)
{
if(!(aVal instanceof String))
return aVal;
//only cast string value
aJsonName = getJsonNameNoFilter(aJsonName);
Object oVal = aVal;
DBColMeta col = getDBColMetaByJsonName(aCrudKey, aJsonName);
if(col!=null)
{
String sVal = String.valueOf(aVal);
if(col.isNumeric())
{
if(sVal.indexOf('.')>-1)
oVal = Float.parseFloat(sVal);
else
oVal = Long.parseLong(sVal);
}
else if(col.isBoolean() || col.isBit())
{
oVal = Boolean.parseBoolean(sVal);
}
}
return oVal;
}
public DBColMeta getDBColMetaByColName(String aCrudKey, String aColName)
{
Map<String,DBColMeta> cols = mapTableCols.get(aCrudKey);
for(DBColMeta col : cols.values())
{
if(col.getColname().equalsIgnoreCase(aColName))
{
return col;
}
}
return null;
}
public DBColMeta getDBColMetaByJsonName(String aCrudKey, String aJsonName)
{
aJsonName = getJsonNameNoFilter(aJsonName);
//
Map<String,DBColMeta> cols = mapTableCols.get(aCrudKey);
Map<String,String> mapCol2Json = mapColName2Json.get(aCrudKey);
for(DBColMeta col : cols.values())
{
String sColJsonName = mapCol2Json.get(col.getColname());
if(sColJsonName!=null && sColJsonName.equalsIgnoreCase(aJsonName))
{
return col;
}
}
return null;
}
private Map<String, DBColMeta> getTableMetaData(String aKey, JdbcDBMgr aDBMgr, String aTableName) throws SQLException
{
Map<String, DBColMeta> mapDBColJson = new HashMap<String, DBColMeta>();
String sSQL = "SELECT * FROM "+aTableName+" WHERE 1=2";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = aDBMgr.getConnection();
stmt = conn.prepareStatement(sSQL);
rs = stmt.executeQuery();
Map<String, String> mapColJsonName = mapColName2Json.get(aKey);
ResultSetMetaData meta = rs.getMetaData();
for(int i=0; i<meta.getColumnCount(); i++)
{
int idx = i+1;
DBColMeta coljson = new DBColMeta();
coljson.setColseq(idx);
coljson.setTablename(meta.getTableName(idx));
coljson.setColname(meta.getColumnLabel(idx));
coljson.setColclassname(meta.getColumnClassName(idx));
coljson.setColtypename(meta.getColumnTypeName(idx));
coljson.setColtype(String.valueOf(meta.getColumnType(idx)));
coljson.setColsize(meta.getColumnDisplaySize(idx));
coljson.setColnullable(ResultSetMetaData.columnNullable == meta.isNullable(idx));
coljson.setColautoincrement(meta.isAutoIncrement(idx));
//
String sJsonName = mapColJsonName.get(coljson.getColname());
if(sJsonName!=null)
{
coljson.setJsonname(sJsonName);
}
//
mapDBColJson.put(coljson.getColname(), coljson);
}
}
finally
{
aDBMgr.closeQuietly(conn, stmt, rs);
}
if(mapDBColJson.size()==0)
return null;
else
{
return mapDBColJson;
}
}
public boolean isDebugMode(String aCrudConfigKey)
{
Map<String, String> mapCrudConfig = jsoncrudConfig.getConfig(aCrudConfigKey);
if(mapCrudConfig!=null)
{
return Boolean.parseBoolean(mapCrudConfig.get(JsonCrudConfig._PROP_KEY_DEBUG));
}
return false;
}
private String listParamsToString(List listParams)
{
if(listParams!=null)
return listParamsToString(listParams.toArray(new Object[listParams.size()]));
else
return null;
}
private String listParamsToString(Object[] aObjParams)
{
JSONArray jsonArr = new JSONArray();
if(aObjParams!=null && aObjParams.length>0)
{
for(int i=0; i<aObjParams.length; i++)
{
Object o = aObjParams[i];
if(o.getClass().isArray())
{
Object[] objs = (Object[]) o;
JSONArray jsonArr2 = new JSONArray();
for(int j=0; j<objs.length; j++)
{
jsonArr2.put(objs[j].toString());
}
jsonArr.put(jsonArr2);
}
else
{
jsonArr.put(o);
}
}
}
return jsonArr.toString();
}
private long updateChildObject(JdbcDBMgr aDBMgr, String aObjInsertSQL, List<Object[]> aListParams) throws Exception
{
long lAffectedRow = 0;
String sChildTableName = null;
String sChildTableFields = null;
Matcher m = pattInsertSQLtableFields.matcher(aObjInsertSQL.toLowerCase());
if(m.find())
{
sChildTableName = m.group(1);
sChildTableFields = m.group(2);
}
StringBuffer sbWhere = new StringBuffer();
StringTokenizer tk = new StringTokenizer(sChildTableFields,",");
while(tk.hasMoreTokens())
{
if(sbWhere.length()>0)
{
sbWhere.append(" AND ");
}
else
{
sbWhere.append("(");
}
String sField = tk.nextToken();
sbWhere.append(sField).append(" = ? ");
}
sbWhere.append(")");
if(aListParams!=null && aListParams.size()>0)
{
/////
List<Object> listFlattenParam = new ArrayList<Object>();
//
StringBuffer sbObjSQL2 = new StringBuffer();
sbObjSQL2.append("SELECT * FROM ").append(sChildTableName).append(" WHERE 1=1 ");
sbObjSQL2.append(" AND ").append(sbWhere);
//
List<Object[]> listParams_new = new ArrayList<Object[]>();
for(Object[] obj2 : aListParams)
{
for(Object o : obj2)
{
if((o instanceof String) && o.toString().equals(""))
{
o = null;
}
listFlattenParam.add(o);
}
if(aDBMgr.getQueryCount(sbObjSQL2.toString(), obj2)==0)
{
listParams_new.add(obj2);
}
}
aListParams.clear();
aListParams.addAll(listParams_new);
listParams_new.clear();
aObjInsertSQL = aObjInsertSQL.replaceAll("\\{.+?\\}", "?");
try{
lAffectedRow += aDBMgr.executeBatchUpdate(aObjInsertSQL, aListParams);
}
catch(SQLException sqlEx)
{
throw new JsonCrudException("sql:"+aObjInsertSQL+", params:"+listParamsToString(aListParams), sqlEx);
}
}
return lAffectedRow;
}
private List<Object[]> getSubQueryParams(Map<String, String> aCrudCfgMap, JSONObject aJsonParentData, String aJsonName) throws JsonCrudException
{
String sPrefix = "jsonattr."+aJsonName+".";
String sObjSQL = aCrudCfgMap.get(sPrefix+JsonCrudConfig._PROP_KEY_OBJ_SQL);
String sObjMapping = aCrudCfgMap.get(sPrefix+JsonCrudConfig._PROP_KEY_OBJ_MAPPING);
String sObjKeyName = null;
String sObjValName = null;
List<Object[]> listAllParams = new ArrayList<Object[]>();
List<Object> listParamObj = new ArrayList<Object>();
if(sObjSQL!=null && sObjMapping!=null)
{
Object obj = aJsonParentData.get(aJsonName);
Iterator iter = null;
boolean isKeyValPair = (obj instanceof JSONObject);
JSONObject jsonKeyVal = null;
if(isKeyValPair)
{
//Key-Value pair
JSONObject jsonObjMapping = new JSONObject(sObjMapping);
sObjKeyName = jsonObjMapping.keySet().iterator().next();
sObjValName = (String) jsonObjMapping.get(sObjKeyName);
jsonKeyVal = (JSONObject) obj;
iter = jsonKeyVal.keySet().iterator();
}
else if(obj instanceof JSONArray)
{
//Single level Array
JSONArray jsonObjMapping = new JSONArray(sObjMapping);
sObjKeyName = (String) jsonObjMapping.iterator().next();
JSONArray jsonArr = (JSONArray) obj;
iter = jsonArr.iterator();
}
while(iter.hasNext())
{
String sKey = (String) iter.next();
listParamObj.clear();
Matcher m = pattSQLjsonname.matcher(sObjSQL);
while(m.find())
{
String sBracketJsonName = m.group(1);
if(aJsonParentData.has(sBracketJsonName))
{
listParamObj.add(aJsonParentData.get(sBracketJsonName));
}
else if(sBracketJsonName.equals(sObjKeyName))
{
listParamObj.add(sKey);
}
else if(jsonKeyVal!=null && sBracketJsonName.equals(sObjValName))
{
listParamObj.add(jsonKeyVal.get(sKey));
}
}
listAllParams.add(listParamObj.toArray(new Object[listParamObj.size()]));
}
}
if(sObjKeyName==null)
throw new JsonCrudException("No object mapping found ! - "+aJsonName);
///
return listAllParams;
}
private boolean isEmptyJson(String aJsonString)
{
if(aJsonString==null || aJsonString.trim().length()==0)
return true;
aJsonString = aJsonString.replaceAll("\\s", "");
while(aJsonString.startsWith("{") || aJsonString.startsWith("["))
{
if(aJsonString.length()==2)
return true;
if("{\"\":\"\"}".equalsIgnoreCase(aJsonString))
{
return true;
}
aJsonString = aJsonString.substring(1, aJsonString.length()-1);
}
return false;
}
private String getJsonNameNoFilter(String aJsonName)
{
int iPos = aJsonName.indexOf(".");
if(iPos >-1)
{
aJsonName = aJsonName.substring(0,iPos);
}
return aJsonName;
}
public JdbcDBMgr getJdbcMgr(String aJdbcConfigName)
{
return mapDBMgr.get(aJdbcConfigName);
}
}
| remove function that cast child data to string | src/hl/jsoncrud/CRUDMgr.java | remove function that cast child data to string |
|
Java | apache-2.0 | f78b338cfabd4b990fccecffcf13c8b04035d481 | 0 | javamelody/javamelody,javamelody/javamelody,javamelody/javamelody | /*
* Copyright 2008-2010 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Java Melody 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
/**
* Informations sur Tomcat, sans code html de présentation.
* L'état d'une instance est initialisé à son instanciation et non mutable;
* il est donc de fait thread-safe.
* Cet état est celui d'un serveur Tomcat, similaire à celui fourni dans le manager de Tomcat.
* Les instances sont sérialisables pour pouvoir être transmises au serveur de collecte.
* @author Emeric Vernat
*/
final class TomcatInformations implements Serializable {
// cette classe utilise la même technique avec les MBeans Tomcat que la webapp manager de Tomcat
// http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusManagerServlet.java
// http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusTransformer.java
// http://svn.apache.org/repos/asf/tomcat/trunk/webapps/manager/xform.xsl
private static final boolean TOMCAT_USED = System.getProperty("catalina.home") != null;
private static final long serialVersionUID = -6145865427461051370L;
@SuppressWarnings("all")
private static final List<ObjectName> THREAD_POOLS = new ArrayList<ObjectName>();
@SuppressWarnings("all")
private static final List<ObjectName> GLOBAL_REQUEST_PROCESSORS = new ArrayList<ObjectName>();
private final String name;
private final int maxThreads;
private final int currentThreadCount;
private final int currentThreadsBusy;
private final long bytesReceived;
private final long bytesSent;
private final int requestCount;
private final int errorCount;
private final long processingTime;
private final long maxTime;
private TomcatInformations(MBeanServer mBeanServer, ObjectName threadPool) throws JMException {
super();
name = threadPool.getKeyProperty("name");
maxThreads = (Integer) mBeanServer.getAttribute(threadPool, "maxThreads");
currentThreadCount = (Integer) mBeanServer.getAttribute(threadPool, "currentThreadCount");
currentThreadsBusy = (Integer) mBeanServer.getAttribute(threadPool, "currentThreadsBusy");
ObjectName grp = null;
for (final ObjectName globalRequestProcessor : GLOBAL_REQUEST_PROCESSORS) {
if (name.equals(globalRequestProcessor.getKeyProperty("name"))) {
grp = globalRequestProcessor;
break;
}
}
if (grp != null) {
bytesReceived = (Long) mBeanServer.getAttribute(grp, "bytesReceived");
bytesSent = (Long) mBeanServer.getAttribute(grp, "bytesSent");
requestCount = (Integer) mBeanServer.getAttribute(grp, "requestCount");
errorCount = (Integer) mBeanServer.getAttribute(grp, "errorCount");
processingTime = (Long) mBeanServer.getAttribute(grp, "processingTime");
maxTime = (Long) mBeanServer.getAttribute(grp, "maxTime");
} else {
bytesReceived = 0;
bytesSent = 0;
requestCount = 0;
errorCount = 0;
processingTime = 0;
maxTime = 0;
}
}
static List<TomcatInformations> buildTomcatInformationsList() {
if (!TOMCAT_USED) {
return Collections.emptyList();
}
try {
synchronized (THREAD_POOLS) {
if (THREAD_POOLS.isEmpty() || GLOBAL_REQUEST_PROCESSORS.isEmpty()) {
initMBeans();
}
}
final MBeanServer mBeanServer = getMBeanServer();
final List<TomcatInformations> tomcatInformationsList = new ArrayList<TomcatInformations>(
THREAD_POOLS.size());
// rq: le processor correspondant au threadPool peut se retrouver selon
// threadPool.getKeyProperty("name").equals(globalRequestProcessor.getKeyProperty("name"))
for (final ObjectName threadPool : THREAD_POOLS) {
tomcatInformationsList.add(new TomcatInformations(mBeanServer, threadPool));
}
return tomcatInformationsList;
} catch (final JMException e) {
// n'est pas censé arriver
throw new IllegalStateException(e);
}
}
// visibilité package pour réinitialisation en test unitaire
static void initMBeans() throws MalformedObjectNameException {
// rq: en général, il y a 2 connecteurs (http et ajp 1.3) définis dans server.xml et donc
// 2 threadPools et 2 globalRequestProcessors de même nom : http-8080 et jk-8009 (ajp13)
final MBeanServer mBeanServer = getMBeanServer();
final Set<ObjectInstance> threadPoolInstances = mBeanServer.queryMBeans(new ObjectName(
"*:type=ThreadPool,*"), null);
final List<ObjectName> threadPools = new ArrayList<ObjectName>(threadPoolInstances.size());
for (final ObjectInstance oi : threadPoolInstances) {
threadPools.add(oi.getObjectName());
}
final Set<ObjectInstance> globalRequestProcessorInstances = mBeanServer.queryMBeans(
new ObjectName("*:type=GlobalRequestProcessor,*"), null);
final List<ObjectName> globalRequestProcessors = new ArrayList<ObjectName>(
globalRequestProcessorInstances.size());
for (final ObjectInstance oi : globalRequestProcessorInstances) {
globalRequestProcessors.add(oi.getObjectName());
}
THREAD_POOLS.clear();
GLOBAL_REQUEST_PROCESSORS.clear();
THREAD_POOLS.addAll(threadPools);
GLOBAL_REQUEST_PROCESSORS.addAll(globalRequestProcessors);
}
/**
* Retourne le javax.management.MBeanServer en le créant si nécessaire.
* @return MBeanServer
*/
private static MBeanServer getMBeanServer() {
final List<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
if (!mBeanServers.isEmpty()) {
// il existe déjà un MBeanServer créé précédemment par Tomcat ou bien ci-dessous
return mBeanServers.get(0);
}
final MBeanServer server = MBeanServerFactory.createMBeanServer();
LOG.debug("javax.management.MBeanServer created");
return server;
}
String getName() {
return name;
}
int getMaxThreads() {
return maxThreads;
}
int getCurrentThreadCount() {
return currentThreadCount;
}
int getCurrentThreadsBusy() {
return currentThreadsBusy;
}
long getBytesReceived() {
return bytesReceived;
}
long getBytesSent() {
return bytesSent;
}
int getRequestCount() {
return requestCount;
}
int getErrorCount() {
return errorCount;
}
long getProcessingTime() {
return processingTime;
}
long getMaxTime() {
return maxTime;
}
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + getName() + ", maxThreads="
+ getMaxThreads() + ", currentThreadCount=" + getCurrentThreadCount()
+ ", currentThreadsBusy=" + getCurrentThreadsBusy() + ", bytesReceived="
+ getBytesReceived() + ", bytesSent=" + getBytesSent() + ", requestCount="
+ getRequestCount() + ", errorCount=" + getErrorCount() + ", processingTime="
+ getProcessingTime() + ", maxTime=" + getMaxTime() + ']';
}
}
| javamelody-core/src/main/java/net/bull/javamelody/TomcatInformations.java | /*
* Copyright 2008-2010 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Java Melody 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
/**
* Informations sur Tomcat, sans code html de présentation.
* L'état d'une instance est initialisé à son instanciation et non mutable;
* il est donc de fait thread-safe.
* Cet état est celui d'un serveur Tomcat, similaire à celui fourni dans le manager de Tomcat.
* Les instances sont sérialisables pour pouvoir être transmises au serveur de collecte.
* @author Emeric Vernat
*/
final class TomcatInformations implements Serializable {
// cette classe utilise la même technique avec les MBeans Tomcat que la webapp manager de Tomcat
// http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusManagerServlet.java
// http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/manager/StatusTransformer.java
// http://svn.apache.org/repos/asf/tomcat/trunk/webapps/manager/xform.xsl
private static final boolean TOMCAT_USED = System.getProperty("catalina.home") != null;
private static final long serialVersionUID = -6145865427461051370L;
@SuppressWarnings("all")
private static final List<ObjectName> THREAD_POOLS = new ArrayList<ObjectName>();
@SuppressWarnings("all")
private static final List<ObjectName> GLOBAL_REQUEST_PROCESSORS = new ArrayList<ObjectName>();
private final String name;
private final int maxThreads;
private final int currentThreadCount;
private final int currentThreadsBusy;
private final long bytesReceived;
private final long bytesSent;
private final int requestCount;
private final int errorCount;
private final long processingTime;
private final long maxTime;
private TomcatInformations(MBeanServer mBeanServer, ObjectName threadPool) throws JMException {
super();
name = threadPool.getKeyProperty("name");
maxThreads = (Integer) mBeanServer.getAttribute(threadPool, "maxThreads");
currentThreadCount = (Integer) mBeanServer.getAttribute(threadPool, "currentThreadCount");
currentThreadsBusy = (Integer) mBeanServer.getAttribute(threadPool, "currentThreadsBusy");
ObjectName grp = null;
for (final ObjectName globalRequestProcessor : GLOBAL_REQUEST_PROCESSORS) {
if (name.equals(globalRequestProcessor.getKeyProperty("name"))) {
grp = globalRequestProcessor;
}
}
if (grp != null) {
bytesReceived = (Long) mBeanServer.getAttribute(grp, "bytesReceived");
bytesSent = (Long) mBeanServer.getAttribute(grp, "bytesSent");
requestCount = (Integer) mBeanServer.getAttribute(grp, "requestCount");
errorCount = (Integer) mBeanServer.getAttribute(grp, "errorCount");
processingTime = (Long) mBeanServer.getAttribute(grp, "processingTime");
maxTime = (Long) mBeanServer.getAttribute(grp, "maxTime");
} else {
bytesReceived = 0;
bytesSent = 0;
requestCount = 0;
errorCount = 0;
processingTime = 0;
maxTime = 0;
}
}
static List<TomcatInformations> buildTomcatInformationsList() {
if (!TOMCAT_USED) {
return Collections.emptyList();
}
try {
synchronized (THREAD_POOLS) {
if (THREAD_POOLS.isEmpty() || GLOBAL_REQUEST_PROCESSORS.isEmpty()) {
initMBeans();
}
}
final MBeanServer mBeanServer = getMBeanServer();
final List<TomcatInformations> tomcatInformationsList = new ArrayList<TomcatInformations>(
THREAD_POOLS.size());
// rq: le processor correspondant au threadPool peut se retrouver selon
// threadPool.getKeyProperty("name").equals(globalRequestProcessor.getKeyProperty("name"))
for (final ObjectName threadPool : THREAD_POOLS) {
tomcatInformationsList.add(new TomcatInformations(mBeanServer, threadPool));
}
return tomcatInformationsList;
} catch (final JMException e) {
// n'est pas censé arriver
throw new IllegalStateException(e);
}
}
// visibilité package pour réinitialisation en test unitaire
static void initMBeans() throws MalformedObjectNameException {
// rq: en général, il y a 2 connecteurs (http et ajp 1.3) définis dans server.xml et donc
// 2 threadPools et 2 globalRequestProcessors de même nom : http-8080 et jk-8009 (ajp13)
final MBeanServer mBeanServer = getMBeanServer();
final Set<ObjectInstance> threadPoolInstances = mBeanServer.queryMBeans(new ObjectName(
"*:type=ThreadPool,*"), null);
final List<ObjectName> threadPools = new ArrayList<ObjectName>(threadPoolInstances.size());
for (final ObjectInstance oi : threadPoolInstances) {
threadPools.add(oi.getObjectName());
}
final Set<ObjectInstance> globalRequestProcessorInstances = mBeanServer.queryMBeans(
new ObjectName("*:type=GlobalRequestProcessor,*"), null);
final List<ObjectName> globalRequestProcessors = new ArrayList<ObjectName>(
globalRequestProcessorInstances.size());
for (final ObjectInstance oi : globalRequestProcessorInstances) {
globalRequestProcessors.add(oi.getObjectName());
}
THREAD_POOLS.clear();
GLOBAL_REQUEST_PROCESSORS.clear();
THREAD_POOLS.addAll(threadPools);
GLOBAL_REQUEST_PROCESSORS.addAll(globalRequestProcessors);
}
/**
* Retourne le javax.management.MBeanServer en le créant si nécessaire.
* @return MBeanServer
*/
private static MBeanServer getMBeanServer() {
final List<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
if (!mBeanServers.isEmpty()) {
// il existe déjà un MBeanServer créé précédemment par Tomcat ou bien ci-dessous
return mBeanServers.get(0);
}
final MBeanServer server = MBeanServerFactory.createMBeanServer();
LOG.debug("javax.management.MBeanServer created");
return server;
}
String getName() {
return name;
}
int getMaxThreads() {
return maxThreads;
}
int getCurrentThreadCount() {
return currentThreadCount;
}
int getCurrentThreadsBusy() {
return currentThreadsBusy;
}
long getBytesReceived() {
return bytesReceived;
}
long getBytesSent() {
return bytesSent;
}
int getRequestCount() {
return requestCount;
}
int getErrorCount() {
return errorCount;
}
long getProcessingTime() {
return processingTime;
}
long getMaxTime() {
return maxTime;
}
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + getName() + ", maxThreads="
+ getMaxThreads() + ", currentThreadCount=" + getCurrentThreadCount()
+ ", currentThreadsBusy=" + getCurrentThreadsBusy() + ", bytesReceived="
+ getBytesReceived() + ", bytesSent=" + getBytesSent() + ", requestCount="
+ getRequestCount() + ", errorCount=" + getErrorCount() + ", processingTime="
+ getProcessingTime() + ", maxTime=" + getMaxTime() + ']';
}
}
| optimisation | javamelody-core/src/main/java/net/bull/javamelody/TomcatInformations.java | optimisation |
|
Java | apache-2.0 | 17006335e5b687a8a268d1571ae04a98235e6394 | 0 | joetrite/nifi,zhengsg/nifi,tijoparacka/nifi,InspurUSA/nifi,mans2singh/nifi,Wesley-Lawrence/nifi,mcgilman/nifi,apsaltis/nifi,joetrite/nifi,mcgilman/nifi,MikeThomsen/nifi,mattyb149/nifi,MikeThomsen/nifi,trixpan/nifi,qfdk/nifi,ijokarumawak/nifi,jfrazee/nifi,josephxsxn/nifi,jjmeyer0/nifi,zhengsg/nifi,aperepel/nifi,ijokarumawak/nifi,josephxsxn/nifi,zhengsg/nifi,trixpan/nifi,WilliamNouet/nifi,Xsixteen/nifi,aperepel/nifi,jtstorck/nifi,alopresto/nifi,Xsixteen/nifi,YolandaMDavis/nifi,jtstorck/nifi,jtstorck/nifi,joewitt/incubator-nifi,joetrite/nifi,mans2singh/nifi,ijokarumawak/nifi,WilliamNouet/ApacheNiFi,dlukyanov/nifi,m-hogue/nifi,m-hogue/nifi,YolandaMDavis/nifi,jjmeyer0/nifi,joewitt/incubator-nifi,apsaltis/nifi,tijoparacka/nifi,pvillard31/nifi,qfdk/nifi,zhengsg/nifi,ShellyLC/nifi,mcgilman/nifi,Xsixteen/nifi,patricker/nifi,bbende/nifi,jskora/nifi,tijoparacka/nifi,PuspenduBanerjee/nifi,jfrazee/nifi,bbende/nifi,apsaltis/nifi,peter-gergely-horvath/nifi,InspurUSA/nifi,jskora/nifi,peter-gergely-horvath/nifi,qfdk/nifi,m-hogue/nifi,jfrazee/nifi,WilliamNouet/ApacheNiFi,joewitt/incubator-nifi,zhengsg/nifi,dlukyanov/nifi,apsaltis/nifi,alopresto/nifi,tequalsme/nifi,mcgilman/nifi,YolandaMDavis/nifi,YolandaMDavis/nifi,peter-gergely-horvath/nifi,peter-gergely-horvath/nifi,pvillard31/nifi,patricker/nifi,YolandaMDavis/nifi,WilliamNouet/ApacheNiFi,WilliamNouet/nifi,thesolson/nifi,WilliamNouet/nifi,trixpan/nifi,jfrazee/nifi,alopresto/nifi,Xsixteen/nifi,alopresto/nifi,jtstorck/nifi,InspurUSA/nifi,alopresto/nifi,jtstorck/nifi,InspurUSA/nifi,pvillard31/nifi,tequalsme/nifi,patricker/nifi,pvillard31/nifi,WilliamNouet/nifi,ijokarumawak/nifi,alopresto/nifi,jfrazee/nifi,patricker/nifi,tijoparacka/nifi,mattyb149/nifi,thesolson/nifi,tijoparacka/nifi,michalklempa/nifi,ShellyLC/nifi,bbende/nifi,mcgilman/nifi,Wesley-Lawrence/nifi,mcgilman/nifi,qfdk/nifi,mattyb149/nifi,YolandaMDavis/nifi,ShellyLC/nifi,MikeThomsen/nifi,MikeThomsen/nifi,jjmeyer0/nifi,ijokarumawak/nifi,m-hogue/nifi,qfdk/nifi,thesolson/nifi,jfrazee/nifi,MikeThomsen/nifi,WilliamNouet/ApacheNiFi,mans2singh/nifi,tequalsme/nifi,speddy93/nifi,Xsixteen/nifi,ijokarumawak/nifi,joetrite/nifi,jfrazee/nifi,apsaltis/nifi,Wesley-Lawrence/nifi,jjmeyer0/nifi,WilliamNouet/ApacheNiFi,mattyb149/nifi,Wesley-Lawrence/nifi,joewitt/incubator-nifi,dlukyanov/nifi,PuspenduBanerjee/nifi,aperepel/nifi,thesolson/nifi,jjmeyer0/nifi,mattyb149/nifi,joewitt/incubator-nifi,zhengsg/nifi,michalklempa/nifi,jskora/nifi,Wesley-Lawrence/nifi,josephxsxn/nifi,bbende/nifi,speddy93/nifi,MikeThomsen/nifi,speddy93/nifi,PuspenduBanerjee/nifi,m-hogue/nifi,joetrite/nifi,jfrazee/nifi,YolandaMDavis/nifi,alopresto/nifi,apsaltis/nifi,m-hogue/nifi,qfdk/nifi,patricker/nifi,PuspenduBanerjee/nifi,tijoparacka/nifi,mattyb149/nifi,mcgilman/nifi,patricker/nifi,jskora/nifi,jtstorck/nifi,josephxsxn/nifi,peter-gergely-horvath/nifi,pvillard31/nifi,mattyb149/nifi,mans2singh/nifi,speddy93/nifi,michalklempa/nifi,josephxsxn/nifi,pvillard31/nifi,PuspenduBanerjee/nifi,joewitt/incubator-nifi,WilliamNouet/ApacheNiFi,m-hogue/nifi,bbende/nifi,WilliamNouet/nifi,jskora/nifi,tequalsme/nifi,josephxsxn/nifi,ShellyLC/nifi,speddy93/nifi,jskora/nifi,patricker/nifi,peter-gergely-horvath/nifi,aperepel/nifi,dlukyanov/nifi,pvillard31/nifi,ShellyLC/nifi,tequalsme/nifi,aperepel/nifi,michalklempa/nifi,Xsixteen/nifi,speddy93/nifi,dlukyanov/nifi,aperepel/nifi,ShellyLC/nifi,pvillard31/nifi,PuspenduBanerjee/nifi,trixpan/nifi,trixpan/nifi,Wesley-Lawrence/nifi,dlukyanov/nifi,MikeThomsen/nifi,thesolson/nifi,thesolson/nifi,InspurUSA/nifi,WilliamNouet/nifi,michalklempa/nifi,bbende/nifi,tequalsme/nifi,InspurUSA/nifi,jtstorck/nifi,mans2singh/nifi,trixpan/nifi,jjmeyer0/nifi,mans2singh/nifi,michalklempa/nifi,joetrite/nifi | /*
* 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.nifi.provenance;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import java.util.Collection;
/**
* ProvenanceReporter generates and records Provenance-related events. A
* ProvenanceReporter is always tied to a {@link ProcessSession}. Any events
* that are generated are reported to Provenance only after the session has been
* committed. If the session is rolled back, the events related to that session
* are purged.
*/
public interface ProvenanceReporter {
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
*/
void receive(FlowFile flowFile, String transitUri);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from the specified URI and that
* the source system used the specified identifier (a URI with namespace) to
* refer to the data.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param sourceSystemFlowFileIdentifier the URI/identifier that the source
* system uses to refer to the data; if this value is non-null and is not a
* URI, the prefix "urn:tdo:" will be used to form a URI.
*/
void receive(FlowFile flowFile, String transitUri, String sourceSystemFlowFileIdentifier);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void receive(FlowFile flowFile, String transitUri, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source and
* provides additional details about the receipt of the FlowFile, such as a
* remote system's Distinguished Name.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details details about the receive event; for example, it may be
* relevant to include the DN of the sending system
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void receive(FlowFile flowFile, String transitUri, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source and
* provides additional details about the receipt of the FlowFile, such as a
* remote system's Distinguished Name.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param sourceSystemFlowFileIdentifier the URI/identifier that the source
* system uses to refer to the data; if this value is non-null and is not a
* URI, the prefix "urn:tdo:" will be used to form a URI.
* @param details details about the receive event; for example, it may be
* relevant to include the DN of the sending system
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void receive(FlowFile flowFile, String transitUri, String sourceSystemFlowFileIdentifier, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#FETCH FETCH} that indicates that the content of the given
* FlowFile was overwritten with the data received from an external source.
*
* @param flowFile the FlowFile whose content was replaced
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred.
*/
void fetch(FlowFile flowFile, String transitUri);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#FETCH FETCH} that indicates that the content of the given
* FlowFile was overwritten with the data received from an external source.
*
* @param flowFile the FlowFile whose content was replaced
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred.
* @param transmissionMillis the number of milliseconds taken to transfer the data
*/
void fetch(FlowFile flowFile, String transitUri, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#FETCH FETCH} that indicates that the content of the given
* FlowFile was overwritten with the data received from an external source.
*
* @param flowFile the FlowFile whose content was replaced
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred.
* @param details details about the event
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void fetch(FlowFile flowFile, String transitUri, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
*/
void send(FlowFile flowFile, String transitUri);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
*/
void send(FlowFile flowFile, String transitUri, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
*/
void send(FlowFile flowFile, String transitUri, long transmissionMillis);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
*/
void send(FlowFile flowFile, String transitUri, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, boolean force);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, String details, boolean force);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, long transmissionMillis, boolean force);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, String details, long transmissionMillis, boolean force);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#ADDINFO ADDINFO} that provides a linkage
* between the given FlowFile and alternate identifier. This information can
* be useful if published to an external, enterprise-wide Provenance
* tracking system that is able to associate the data between different
* processes.
*
* @param flowFile the FlowFile for which the association should be made
* @param alternateIdentifierNamespace the namespace of the alternate system
* @param alternateIdentifier the identifier that the alternate system uses
* when referring to the data that is encompassed by this FlowFile
*/
void associate(FlowFile flowFile, String alternateIdentifierNamespace, String alternateIdentifier);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
*/
void fork(FlowFile parent, Collection<FlowFile> children);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
* @param details any details pertinent to the fork
*/
void fork(FlowFile parent, Collection<FlowFile> children, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
* @param forkDuration the number of milliseconds that it took to perform
* the task
*/
void fork(FlowFile parent, Collection<FlowFile> children, long forkDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
* @param details any details pertinent to the fork
* @param forkDuration the number of milliseconds that it took to perform
* the task
*/
void fork(FlowFile parent, Collection<FlowFile> children, String details, long forkDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
*/
void join(Collection<FlowFile> parents, FlowFile child);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
* @param details any details pertinent to the event
*/
void join(Collection<FlowFile> parents, FlowFile child, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
* @param joinDuration the number of milliseconds that it took to join the
* FlowFiles
*/
void join(Collection<FlowFile> parents, FlowFile child, long joinDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
* @param details any details pertinent to the event
* @param joinDuration the number of milliseconds that it took to join the
* FlowFiles
*/
void join(Collection<FlowFile> parents, FlowFile child, String details, long joinDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#CLONE CLONE}
* that establishes that the given child is an exact replica of the parent.
* In general, this method does not need to be called by Processors, as the
* {@link ProcessSession} will handle this automatically for you when
* calling {@link ProcessSession#clone(FlowFile)}
*
* @param parent the FlowFile that was cloned
* @param child the clone
*/
void clone(FlowFile parent, FlowFile child);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
*/
void modifyContent(FlowFile flowFile);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
* @param details Any details about how the content of the FlowFile has been
* modified. Details should not be specified if they can be inferred by
* other information in the event, such as the name of the Processor, as
* specifying this information will add undue overhead
*/
void modifyContent(FlowFile flowFile, String details);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
* @param processingMillis the number of milliseconds spent processing the
* FlowFile
*/
void modifyContent(FlowFile flowFile, long processingMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
* @param details Any details about how the content of the FlowFile has been
* modified. Details should not be specified if they can be inferred by
* other information in the event, such as the name of the Processor, as
* specifying this information will add undue overhead
* @param processingMillis the number of milliseconds spent processing the
* FlowFile
*/
void modifyContent(FlowFile flowFile, String details, long processingMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#ATTRIBUTES_MODIFIED ATTRIBUTES_MODIFIED} that
* indicates that the Attributes of the given FlowFile were updated. It is
* not necessary to emit such an event for a FlowFile if other Events are
* already emitted by a Processor. For example, one should call both
* {@link #modifyContent(FlowFile)} and {@link #modifyAttributes(FlowFile)}
* for the same FlowFile in the same Processor. Rather, the Processor should
* call just the {@link #modifyContent(FlowFile)}, as the call to
* {@link #modifyContent(FlowFile)} will generate a Provenance Event that
* already contains all FlowFile attributes. As such, emitting another event
* that contains those attributes is unneeded and can result in a
* significant amount of overhead for storage and processing.
*
* @param flowFile the FlowFile whose attributes were modified
*/
void modifyAttributes(FlowFile flowFile);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#ATTRIBUTES_MODIFIED ATTRIBUTES_MODIFIED} that
* indicates that the Attributes of the given FlowFile were updated. It is
* not necessary to emit such an event for a FlowFile if other Events are
* already emitted by a Processor. For example, one should call both
* {@link #modifyContent(FlowFile)} and {@link #modifyAttributes(FlowFile)}
* for the same FlowFile in the same Processor. Rather, the Processor should
* call just the {@link #modifyContent(FlowFile)}, as the call to
* {@link #modifyContent(FlowFile)} will generate a Provenance Event that
* already contains all FlowFile attributes. As such, emitting another event
* that contains those attributes is unneeded and can result in a
* significant amount of overhead for storage and processing.
*
* @param flowFile the FlowFile whose attributes were modified
* @param details any details should be provided about the attribute
* modification
*/
void modifyAttributes(FlowFile flowFile, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended for Processors
* whose sole job it is to route FlowFiles and should NOT be used as a way
* to indicate that the given FlowFile was routed to a standard 'success' or
* 'failure' relationship. Doing so can be problematic, as DataFlow Managers
* often will loop 'failure' relationships back to the same processor. As
* such, emitting a Route event to indicate that a FlowFile was routed to
* 'failure' can result in creating thousands of Provenance Events for a
* given FlowFile, resulting in a very difficult-to- understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
*/
void route(FlowFile flowFile, Relationship relationship);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended ONLY for
* Processors whose sole job it is to route FlowFiles and should NOT be used
* as a way to indicate that hte given FlowFile was routed to a standard
* 'success' or 'failure' relationship. Doing so can be problematic, as
* DataFlow Managers often will loop 'failure' relationships back to the
* same processor. As such, emitting a Route event to indicate that a
* FlowFile was routed to 'failure' can result in creating thousands of
* Provenance Events for a given FlowFile, resulting in a very difficult-to-
* understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
* @param details any details pertinent to the Route event, such as why the
* FlowFile was routed to the specified Relationship
*/
void route(FlowFile flowFile, Relationship relationship, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended ONLY for
* Processors whose sole job it is to route FlowFiles and should NOT be used
* as a way to indicate that hte given FlowFile was routed to a standard
* 'success' or 'failure' relationship. Doing so can be problematic, as
* DataFlow Managers often will loop 'failure' relationships back to the
* same processor. As such, emitting a Route event to indicate that a
* FlowFile was routed to 'failure' can result in creating thousands of
* Provenance Events for a given FlowFile, resulting in a very difficult-to-
* understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
* @param processingDuration the number of milliseconds that it took to
* determine how to route the FlowFile
*/
void route(FlowFile flowFile, Relationship relationship, long processingDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended ONLY for
* Processors whose sole job it is to route FlowFiles and should NOT be used
* as a way to indicate that hte given FlowFile was routed to a standard
* 'success' or 'failure' relationship. Doing so can be problematic, as
* DataFlow Managers often will loop 'failure' relationships back to the
* same processor. As such, emitting a Route event to indicate that a
* FlowFile was routed to 'failure' can result in creating thousands of
* Provenance Events for a given FlowFile, resulting in a very difficult-to-
* understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
* @param details any details pertinent to the Route event, such as why the
* FlowFile was routed to the specified Relationship
* @param processingDuration the number of milliseconds that it took to
* determine how to route the FlowFile
*/
void route(FlowFile flowFile, Relationship relationship, String details, long processingDuration);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CREATE CREATE} that indicates that the given
* FlowFile was created by NiFi from data that was not received from an
* external entity. If the data was received from an external source, use
* the {@link #receive(FlowFile, String)} event instead
*
* @param flowFile the FlowFile that was created
*/
void create(FlowFile flowFile);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CREATE CREATE} that indicates that the given
* FlowFile was created by NiFi from data that was not received from an
* external entity. If the data was received from an external source, use
* the {@link #receive(FlowFile, String, String, long)} event instead
*
* @param flowFile the FlowFile that was created
* @param details any relevant details about the CREATE event
*/
void create(FlowFile flowFile, String details);
}
| nifi-api/src/main/java/org/apache/nifi/provenance/ProvenanceReporter.java | /*
* 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.nifi.provenance;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import java.util.Collection;
/**
* ProvenanceReporter generates and records Provenance-related events. A
* ProvenanceReporter is always tied to a {@link ProcessSession}. Any events
* that are generated are reported to Provenance only after the session has been
* committed. If the session is rolled back, the events related to that session
* are purged.
*/
public interface ProvenanceReporter {
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
*/
void receive(FlowFile flowFile, String transitUri);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from the specified URI and that
* the source system used the specified identifier (a URI with namespace) to
* refer to the data.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param sourceSystemFlowFileIdentifier the URI/identifier that the source
* system uses to refer to the data; if this value is non-null and is not a
* URI, the prefix "urn:tdo:" will be used to form a URI.
*/
void receive(FlowFile flowFile, String transitUri, String sourceSystemFlowFileIdentifier);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void receive(FlowFile flowFile, String transitUri, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source and
* provides additional details about the receipt of the FlowFile, such as a
* remote system's Distinguished Name.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details details about the receive event; for example, it may be
* relevant to include the DN of the sending system
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void receive(FlowFile flowFile, String transitUri, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#RECEIVE RECEIVE} that indicates that the given
* FlowFile was created from data received from an external source and
* provides additional details about the receipt of the FlowFile, such as a
* remote system's Distinguished Name.
*
* @param flowFile the FlowFile that was received
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param sourceSystemFlowFileIdentifier the URI/identifier that the source
* system uses to refer to the data; if this value is non-null and is not a
* URI, the prefix "urn:tdo:" will be used to form a URI.
* @param details details about the receive event; for example, it may be
* relevant to include the DN of the sending system
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void receive(FlowFile flowFile, String transitUri, String sourceSystemFlowFileIdentifier, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#FETCH FETCH} that indicates that the content of the given
* FlowFile was overwritten with the data received from an external source.
*
* @param flowFile the FlowFile whose content was replaced
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred.
*/
void fetch(FlowFile flowFile, String transitUri);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#FETCH FETCH} that indicates that the content of the given
* FlowFile was overwritten with the data received from an external source.
*
* @param flowFile the FlowFile whose content was replaced
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred.
* @param transmissionMillis the number of milliseconds taken to transfer the data
*/
void fetch(FlowFile flowFile, String transitUri, long transmissionMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#FETCH FETCH} that indicates that the content of the given
* FlowFile was overwritten with the data received from an external source.
*
* @param flowFile the FlowFile whose content was replaced
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred.
* @param details details about the event
* @param transmissionMillis the number of milliseconds taken to transfer
* the data
*/
void fetch(FlowFile flowFile, String transitUri, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
*/
void send(FlowFile flowFile, String transitUri);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
*/
void send(FlowFile flowFile, String transitUri, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
*/
void send(FlowFile flowFile, String transitUri, long transmissionMillis);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
*/
void send(FlowFile flowFile, String transitUri, String details, long transmissionMillis);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, boolean force);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, String details, boolean force);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, long transmissionMillis, boolean force);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#SEND SEND}
* that indicates that a copy of the given FlowFile was sent to an external
* destination. The external destination may be a remote system or may be a
* local destination, such as the local file system but is external to NiFi.
*
* @param flowFile the FlowFile that was sent
* @param transitUri A URI that provides information about the System and
* Protocol information over which the transfer occurred. The intent of this
* field is such that both the sender and the receiver can publish the
* events to an external Enterprise-wide system that is then able to
* correlate the SEND and RECEIVE events.
* @param details additional details related to the SEND event, such as a
* remote system's Distinguished Name
* @param transmissionMillis the number of milliseconds spent sending the
* data to the remote system
* @param force if <code>true</code>, this event will be added to the
* Provenance Repository immediately and will still be persisted if the
* {@link org.apache.nifi.processor.ProcessSession ProcessSession} to which this
* ProvenanceReporter is associated is rolled back. Otherwise, the Event
* will be recorded only on a successful session commit.
*/
void send(FlowFile flowFile, String transitUri, String details, long transmissionMillis, boolean force);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#ADDINFO ADDINFO} that provides a linkage
* between the given FlowFile and alternate identifier. This information can
* be useful if published to an external, enterprise-wide Provenance
* tracking system that is able to associate the data between different
* processes.
*
* @param flowFile the FlowFile for which the association should be made
* @param alternateIdentifierNamespace the namespace of the alternate system
* @param alternateIdentifier the identifier that the alternate system uses
* when referring to the data that is encompassed by this FlowFile
*/
void associate(FlowFile flowFile, String alternateIdentifierNamespace, String alternateIdentifier);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
*/
void fork(FlowFile parent, Collection<FlowFile> children);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
* @param details any details pertinent to the fork
*/
void fork(FlowFile parent, Collection<FlowFile> children, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
* @param forkDuration the number of milliseconds that it took to perform
* the task
*/
void fork(FlowFile parent, Collection<FlowFile> children, long forkDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#FORK FORK}
* that establishes that the given parent was split into multiple child
* FlowFiles. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parent the FlowFile from which the children are derived
* @param children the FlowFiles that are derived from the parent.
* @param details any details pertinent to the fork
* @param forkDuration the number of milliseconds that it took to perform
* the task
*/
void fork(FlowFile parent, Collection<FlowFile> children, String details, long forkDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
*/
void join(Collection<FlowFile> parents, FlowFile child);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
* @param details any details pertinent to the event
*/
void join(Collection<FlowFile> parents, FlowFile child, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
* @param joinDuration the number of milliseconds that it took to join the
* FlowFiles
*/
void join(Collection<FlowFile> parents, FlowFile child, long joinDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#JOIN JOIN}
* that establishes that the given parents were joined together to create a
* new child FlowFile. In general, this method does not need to be called by
* Processors, as the ProcessSession will handle this automatically for you
* when calling {@link ProcessSession#create(FlowFile)}.
*
* @param parents the FlowFiles that are being joined together to create the
* child
* @param child the FlowFile that is being created by joining the parents
* @param details any details pertinent to the event
* @param joinDuration the number of milliseconds that it took to join the
* FlowFiles
*/
void join(Collection<FlowFile> parents, FlowFile child, String details, long joinDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#CLONE CLONE}
* that establishes that the given child is an exact replica of the parent.
* In general, this method does not need to be called by Processors, as the
* {@link ProcessSession} will handle this automatically for you when
* calling {@link ProcessSession#clone(FlowFile)}
*
* @param parent the FlowFile that was cloned
* @param child the clone
*/
void clone(FlowFile parent, FlowFile child);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
*/
void modifyContent(FlowFile flowFile);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
* @param details Any details about how the content of the FlowFile has been
* modified. Details should not be specified if they can be inferred by
* other information in the event, such as the name of the Processor, as
* specifying this information will add undue overhead
*/
void modifyContent(FlowFile flowFile, String details);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
* @param processingMillis the number of milliseconds spent processing the
* FlowFile
*/
void modifyContent(FlowFile flowFile, long processingMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CONTENT_MODIFIED CONTENT_MODIFIED} that
* indicates that the content of the given FlowFile has been modified. One
* of the <code>modifyContent</code> methods should be called any time that
* the contents of a FlowFile are modified.
*
* @param flowFile the FlowFile whose content is being modified
* @param details Any details about how the content of the FlowFile has been
* modified. Details should not be specified if they can be inferred by
* other information in the event, such as the name of the Processor, as
* specifying this information will add undue overhead
* @param processingMillis the number of milliseconds spent processing the
* FlowFile
*/
void modifyContent(FlowFile flowFile, String details, long processingMillis);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#ATTRIBUTES_MODIFIED ATTRIBUTES_MODIFIED} that
* indicates that the Attributes of the given FlowFile were updated. It is
* not necessary to emit such an event for a FlowFile if other Events are
* already emitted by a Processor. For example, one should call both
* {@link #modifyContent(FlowFile)} and {@link #modifyAttributes(FlowFile)}
* for the same FlowFile in the same Processor. Rather, the Processor should
* call just the {@link #modifyContent(FlowFile)}, as the call to
* {@link #modifyContent(FlowFile)} will generate a Provenance Event that
* already contains all FlowFile attributes. As such, emitting another event
* that contains those attributes is unneeded and can result in a
* significant amount of overhead for storage and processing.
*
* @param flowFile the FlowFile whose attributes were modified
*/
void modifyAttributes(FlowFile flowFile);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#ATTRIBUTES_MODIFIED ATTRIBUTES_MODIFIED} that
* indicates that the Attributes of the given FlowFile were updated. It is
* not necessary to emit such an event for a FlowFile if other Events are
* already emitted by a Processor. For example, one should call both
* {@link #modifyContent(FlowFile)} and {@link #modifyAttributes(FlowFile)}
* for the same FlowFile in the same Processor. Rather, the Processor should
* call just the {@link #modifyContent(FlowFile)}, as the call to
* {@link #modifyContent(FlowFile)} will generate a Provenance Event that
* already contains all FlowFile attributes. As such, emitting another event
* that contains those attributes is unneeded and can result in a
* significant amount of overhead for storage and processing.
*
* @param flowFile the FlowFile whose attributes were modified
* @param details any details should be provided about the attribute
* modification
*/
void modifyAttributes(FlowFile flowFile, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended for Processors
* whose sole job it is to route FlowFiles and should NOT be used as a way
* to indicate that the given FlowFile was routed to a standard 'success' or
* 'failure' relationship. Doing so can be problematic, as DataFlow Managers
* often will loop 'failure' relationships back to the same processor. As
* such, emitting a Route event to indicate that a FlowFile was routed to
* 'failure' can result in creating thousands of Provenance Events for a
* given FlowFile, resulting in a very difficult-to- understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
*/
void route(FlowFile flowFile, Relationship relationship);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended ONLY for
* Processors whose sole job it is to route FlowFiles and should NOT be used
* as a way to indicate that hte given FlowFile was routed to a standard
* 'success' or 'failure' relationship. Doing so can be problematic, as
* DataFlow Managers often will loop 'failure' relationships back to the
* same processor. As such, emitting a Route event to indicate that a
* FlowFile was routed to 'failure' can result in creating thousands of
* Provenance Events for a given FlowFile, resulting in a very difficult-to-
* understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
* @param details any details pertinent to the Route event, such as why the
* FlowFile was routed to the specified Relationship
*/
void route(FlowFile flowFile, Relationship relationship, String details);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended ONLY for
* Processors whose sole job it is to route FlowFiles and should NOT be used
* as a way to indicate that hte given FlowFile was routed to a standard
* 'success' or 'failure' relationship. Doing so can be problematic, as
* DataFlow Managers often will loop 'failure' relationships back to the
* same processor. As such, emitting a Route event to indicate that a
* FlowFile was routed to 'failure' can result in creating thousands of
* Provenance Events for a given FlowFile, resulting in a very difficult-to-
* understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
* @param processingDuration the number of milliseconds that it took to
* determine how to route the FlowFile
*/
void route(FlowFile flowFile, Relationship relationship, long processingDuration);
/**
* Emits a Provenance Event of type {@link ProvenanceEventType#ROUTE ROUTE}
* that indicates that the given FlowFile was routed to the given
* {@link Relationship}. <b>Note: </b> this Event is intended ONLY for
* Processors whose sole job it is to route FlowFiles and should NOT be used
* as a way to indicate that hte given FlowFile was routed to a standard
* 'success' or 'failure' relationship. Doing so can be problematic, as
* DataFlow Managers often will loop 'failure' relationships back to the
* same processor. As such, emitting a Route event to indicate that a
* FlowFile was routed to 'failure' can result in creating thousands of
* Provenance Events for a given FlowFile, resulting in a very difficult-to-
* understand lineage.
*
* @param flowFile the FlowFile being routed
* @param relationship the Relationship to which the FlowFile was routed
* @param details any details pertinent to the Route event, such as why the
* FlowFile was routed to the specified Relationship
* @param processingDuration the number of milliseconds that it took to
* determine how to route the FlowFile
*/
void route(FlowFile flowFile, Relationship relationship, String details, long processingDuration);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CREATE CREATE} that indicates that the given
* FlowFile was created by NiFi from data that was not received from an
* external entity. If the data was received from an external source, use
* the {@link #receive(FlowFile, String)} event instead
*
* @param flowFile the FlowFile that was created
*/
void create(FlowFile flowFile);
/**
* Emits a Provenance Event of type
* {@link ProvenanceEventType#CREATE CREATE} that indicates that the given
* FlowFile was created by NiFi from data that was not received from an
* external entity. If the data was received from an external source, use
* the {@link #receive(FlowFile, String, String, long)} event instead
*
* @param flowFile the FlowFile that was created
* @param details any relevant details about the CREATE event
*/
void create(FlowFile flowFile, String details);
}
| NIFI-10: Fixed checkstyle violation
| nifi-api/src/main/java/org/apache/nifi/provenance/ProvenanceReporter.java | NIFI-10: Fixed checkstyle violation |
|
Java | apache-2.0 | 6bffc0a2a4e1038388d56613f6b75c8d48d9ba4f | 0 | dslomov/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ryano144/intellij-community,asedunov/intellij-community,slisson/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,jagguli/intellij-community,da1z/intellij-community,vladmm/intellij-community,FHannes/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,kool79/intellij-community,slisson/intellij-community,supersven/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,signed/intellij-community,supersven/intellij-community,samthor/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,jexp/idea2,TangHao1987/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ryano144/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,fnouama/intellij-community,retomerz/intellij-community,kool79/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,diorcety/intellij-community,apixandru/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,diorcety/intellij-community,robovm/robovm-studio,asedunov/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,signed/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,signed/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,allotria/intellij-community,clumsy/intellij-community,kdwink/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,samthor/intellij-community,samthor/intellij-community,akosyakov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,dslomov/intellij-community,da1z/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,kool79/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,signed/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,izonder/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,jexp/idea2,SerCeMan/intellij-community,robovm/robovm-studio,fnouama/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,apixandru/intellij-community,consulo/consulo,fnouama/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,caot/intellij-community,wreckJ/intellij-community,signed/intellij-community,supersven/intellij-community,signed/intellij-community,amith01994/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,blademainer/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,jexp/idea2,orekyuu/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,xfournet/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,kool79/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,dslomov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,petteyg/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,vladmm/intellij-community,fitermay/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,signed/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,da1z/intellij-community,holmes/intellij-community,da1z/intellij-community,fnouama/intellij-community,holmes/intellij-community,fnouama/intellij-community,jagguli/intellij-community,allotria/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,slisson/intellij-community,amith01994/intellij-community,ryano144/intellij-community,caot/intellij-community,ryano144/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,diorcety/intellij-community,consulo/consulo,amith01994/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,adedayo/intellij-community,dslomov/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,signed/intellij-community,holmes/intellij-community,vladmm/intellij-community,allotria/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,jexp/idea2,TangHao1987/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,hurricup/intellij-community,apixandru/intellij-community,jagguli/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,izonder/intellij-community,dslomov/intellij-community,jagguli/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,jexp/idea2,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,joewalnes/idea-community,petteyg/intellij-community,fitermay/intellij-community,signed/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,supersven/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,vladmm/intellij-community,izonder/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,jexp/idea2,da1z/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,adedayo/intellij-community,retomerz/intellij-community,apixandru/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,kool79/intellij-community,consulo/consulo,fnouama/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,retomerz/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,dslomov/intellij-community,joewalnes/idea-community,fnouama/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,hurricup/intellij-community,petteyg/intellij-community,slisson/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,kool79/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,izonder/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,holmes/intellij-community,samthor/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ernestp/consulo,salguarnieri/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,izonder/intellij-community,semonte/intellij-community,wreckJ/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,jexp/idea2,gnuhub/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,ol-loginov/intellij-community,vladmm/intellij-community,diorcety/intellij-community,dslomov/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,kdwink/intellij-community,semonte/intellij-community,amith01994/intellij-community,allotria/intellij-community,youdonghai/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,diorcety/intellij-community,petteyg/intellij-community,kool79/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,caot/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,adedayo/intellij-community,izonder/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,consulo/consulo,asedunov/intellij-community,ernestp/consulo,caot/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,signed/intellij-community,adedayo/intellij-community,xfournet/intellij-community,petteyg/intellij-community,blademainer/intellij-community,consulo/consulo,lucafavatella/intellij-community,vladmm/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,hurricup/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,izonder/intellij-community,samthor/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,semonte/intellij-community,amith01994/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,xfournet/intellij-community,joewalnes/idea-community,caot/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,caot/intellij-community,ibinti/intellij-community,adedayo/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,ibinti/intellij-community,joewalnes/idea-community,holmes/intellij-community,petteyg/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,jexp/idea2,hurricup/intellij-community,fnouama/intellij-community,ryano144/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,supersven/intellij-community,fnouama/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,samthor/intellij-community,apixandru/intellij-community,diorcety/intellij-community,jagguli/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,slisson/intellij-community,fnouama/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,blademainer/intellij-community,supersven/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ryano144/intellij-community,samthor/intellij-community,da1z/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,caot/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ernestp/consulo,robovm/robovm-studio,nicolargo/intellij-community,diorcety/intellij-community,semonte/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,caot/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,holmes/intellij-community,caot/intellij-community,hurricup/intellij-community,semonte/intellij-community,blademainer/intellij-community,ryano144/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community | /*
* Copyright 2008 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.bugs;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Query;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.TypeUtils;
import com.siyeh.ig.psiutils.ClassUtils;
import com.siyeh.InspectionGadgetsBundle;
import org.jetbrains.annotations.NotNull;
public class ThrowableResultOfMethodCallIgnoredInspection extends BaseInspection {
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message(
"throwable.result.of.method.call.ignored.display.name");
}
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"throwable.result.of.method.call.ignored.problem.descriptor");
}
@Override
public boolean isEnabledByDefault() {
return true;
}
public BaseInspectionVisitor buildVisitor() {
return new ThrowableResultOfMethodCallIgnoredVisitor();
}
private static class ThrowableResultOfMethodCallIgnoredVisitor
extends BaseInspectionVisitor {
@Override
public void visitMethodCallExpression(
PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
PsiElement parent = expression.getParent();
while (parent instanceof PsiParenthesizedExpression) {
parent = parent.getParent();
}
if (parent instanceof PsiReturnStatement ||
parent instanceof PsiThrowStatement) {
return;
}
if (!TypeUtils.expressionHasTypeOrSubtype(expression,
"java.lang.Throwable")) {
return;
}
final PsiMethod method = expression.resolveMethod();
if (method == null) {
return;
}
if (!method.hasModifierProperty(PsiModifier.STATIC)) {
final PsiClass containingClass = method.getContainingClass();
if (ClassUtils.isSubclass(containingClass,
"java.lang.Throwable")) {
return;
}
}
final PsiLocalVariable variable;
if (parent instanceof PsiAssignmentExpression) {
final PsiAssignmentExpression assignmentExpression =
(PsiAssignmentExpression)parent;
final PsiExpression rhs = assignmentExpression.getRExpression();
if (!PsiTreeUtil.isAncestor(rhs, expression, false)) {
return;
}
final PsiExpression lhs = assignmentExpression.getLExpression();
if (!(lhs instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression referenceExpression =
(PsiReferenceExpression) lhs;
final PsiElement target = referenceExpression.resolve();
if (!(target instanceof PsiLocalVariable)) {
return;
}
variable = (PsiLocalVariable)target;
} else if (parent instanceof PsiVariable) {
if (!(parent instanceof PsiLocalVariable)) {
return;
}
variable = (PsiLocalVariable)parent;
} else {
variable = null;
}
if (variable != null) {
final Query<PsiReference> query =
ReferencesSearch.search(variable,
variable.getUseScope());
for (PsiReference reference : query) {
final PsiElement usage = reference.getElement();
PsiElement usageParent = usage.getParent();
while (usageParent instanceof PsiParenthesizedExpression) {
usageParent = usageParent.getParent();
}
if (usageParent instanceof PsiThrowStatement) {
return;
} else if (usageParent instanceof PsiReturnStatement) {
return;
}
}
}
registerMethodCallError(expression);
}
}
}
| plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableResultOfMethodCallIgnoredInspection.java | /*
* Copyright 2008 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.bugs;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Query;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.TypeUtils;import com.siyeh.InspectionGadgetsBundle;
import org.jetbrains.annotations.NotNull;
public class ThrowableResultOfMethodCallIgnoredInspection extends BaseInspection {
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message(
"throwable.result.of.method.call.ignored.display.name");
}
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"throwable.result.of.method.call.ignored.problem.descriptor");
}
@Override
public boolean isEnabledByDefault() {
return true;
}
public BaseInspectionVisitor buildVisitor() {
return new ThrowableResultOfMethodCallIgnoredVisitor();
}
private class ThrowableResultOfMethodCallIgnoredVisitor
extends BaseInspectionVisitor {
@Override
public void visitMethodCallExpression(
PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
PsiElement parent = expression.getParent();
while (parent instanceof PsiParenthesizedExpression) {
parent = parent.getParent();
}
if (parent instanceof PsiReturnStatement ||
parent instanceof PsiThrowStatement) {
return;
}
final PsiType type = expression.getType();
if (!TypeUtils.expressionHasTypeOrSubtype(expression,
"java.lang.Throwable")) {
return;
}
final PsiLocalVariable variable;
if (parent instanceof PsiAssignmentExpression) {
final PsiAssignmentExpression assignmentExpression =
(PsiAssignmentExpression)parent;
final PsiExpression rhs = assignmentExpression.getRExpression();
if (!PsiTreeUtil.isAncestor(rhs, expression, false)) {
return;
}
final PsiExpression lhs = assignmentExpression.getLExpression();
if (!(lhs instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression referenceExpression =
(PsiReferenceExpression) lhs;
final PsiElement target = referenceExpression.resolve();
if (!(target instanceof PsiLocalVariable)) {
return;
}
variable = (PsiLocalVariable)target;
} else if (parent instanceof PsiVariable) {
if (!(parent instanceof PsiLocalVariable)) {
return;
}
variable = (PsiLocalVariable)parent;
} else {
variable = null;
}
if (variable != null) {
final Query<PsiReference> query =
ReferencesSearch.search(variable,
variable.getUseScope());
for (PsiReference reference : query) {
final PsiElement usage = reference.getElement();
PsiElement usageParent = usage.getParent();
while (usageParent instanceof PsiParenthesizedExpression) {
usageParent = usageParent.getParent();
}
if (usageParent instanceof PsiThrowStatement) {
return;
} else if (usageParent instanceof PsiReturnStatement) {
return;
}
}
}
registerMethodCallError(expression);
}
}
}
| IDEADEV-25823 | plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableResultOfMethodCallIgnoredInspection.java | IDEADEV-25823 |
|
Java | apache-2.0 | 7368588ee9c420943d49b7fe408e5daa8adfbfca | 0 | estatio/isis,apache/isis,oscarbou/isis,sanderginn/isis,niv0/isis,sanderginn/isis,niv0/isis,niv0/isis,incodehq/isis,sanderginn/isis,estatio/isis,incodehq/isis,apache/isis,apache/isis,apache/isis,apache/isis,estatio/isis,sanderginn/isis,incodehq/isis,oscarbou/isis,niv0/isis,estatio/isis,incodehq/isis,apache/isis,oscarbou/isis,oscarbou/isis | /**
* 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.isis.schema.services.jaxb;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.apache.isis.applib.services.jaxb.JaxbService;
/**
* An implementation of {@link SchemaOutputResolver} that keeps track of all the schemas for which it has
* {@link #createOutput(String, String) created} an output {@link StreamResult} containing the content of the schema.
*/
class CatalogingSchemaOutputResolver extends SchemaOutputResolver {
private static final String SCHEMA_LOCATION_INCORRECT = "http://isis.apache.org/schema/common";
private static final String SCHEMA_LOCATION_CORRECT = "http://isis.apache.org/schema/common/common.xsd";
private final JaxbService.IsisSchemas isisSchemas;
private final List<String> namespaceUris = Lists.newArrayList();
public CatalogingSchemaOutputResolver(final JaxbService.IsisSchemas isisSchemas) {
this.isisSchemas = isisSchemas;
}
public List<String> getNamespaceUris() {
return namespaceUris;
}
private Map<String, StreamResultWithWriter> schemaResultByNamespaceUri = Maps.newLinkedHashMap();
public String getSchemaTextFor(final String namespaceUri) {
final StreamResultWithWriter streamResult = schemaResultByNamespaceUri.get(namespaceUri);
if (streamResult == null) {
return null;
}
String xsd = streamResult.asString();
// HACK if it appears,
// replace <xs:import namespace="http://isis.apache.org/schema/common" schemaLocation="http://isis.apache.org/schema/common"/>
// with <xs:import namespace="http://isis.apache.org/schema/common" schemaLocation="http://isis.apache.org/schema/common/common.xsd"/>
try {
final DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder parser = docBuildFactory.newDocumentBuilder();
final Document document = parser.parse(new InputSource(new StringReader(xsd)));
final Element el = document.getDocumentElement();
replaceCommonSchemaLocationIfAny(el);
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
final StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
xsd = writer.toString();
} catch(Exception ex) {
// ignore
}
return xsd;
}
private static void replaceCommonSchemaLocationIfAny(final Node node) {
if(schemaLocationReplacedIn(node)) {
return;
}
final NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
final Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
replaceCommonSchemaLocationIfAny(currentNode);
}
}
}
private static boolean schemaLocationReplacedIn(final Node node) {
if(node instanceof Element) {
final Element importEl = (Element) node;
final Attr schemaLocationAttr = importEl.getAttributeNode("schemaLocation");
if(schemaLocationAttr != null) {
final String value = schemaLocationAttr.getValue();
if(SCHEMA_LOCATION_INCORRECT.endsWith(value)) {
schemaLocationAttr.setValue(SCHEMA_LOCATION_CORRECT);
return true;
}
}
}
return false;
}
@Override
public Result createOutput(
final String namespaceUri, final String suggestedFileName) throws IOException {
final StreamResultWithWriter result = new StreamResultWithWriter();
result.setSystemId(namespaceUri);
if (isisSchemas.shouldIgnore(namespaceUri)) {
// skip
} else {
namespaceUris.add(namespaceUri);
schemaResultByNamespaceUri.put(namespaceUri, result);
}
return result;
}
public Map<String, String> asMap() {
final Map<String,String> map = Maps.newLinkedHashMap();
final List<String> namespaceUris = getNamespaceUris();
for (String namespaceUri : namespaceUris) {
map.put(namespaceUri, getSchemaTextFor(namespaceUri));
}
return Collections.unmodifiableMap(map);
}
}
| core/schema/src/main/java/org/apache/isis/schema/services/jaxb/CatalogingSchemaOutputResolver.java | /**
* 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.isis.schema.services.jaxb;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.isis.applib.services.jaxb.JaxbService;
/**
* An implementation of {@link SchemaOutputResolver} that keeps track of all the schemas for which it has
* {@link #createOutput(String, String) created} an output {@link StreamResult} containing the content of the schema.
*/
class CatalogingSchemaOutputResolver extends SchemaOutputResolver
{
private final JaxbService.IsisSchemas isisSchemas;
private List<String> namespaceUris = Lists.newArrayList();
public CatalogingSchemaOutputResolver(final JaxbService.IsisSchemas isisSchemas) {
this.isisSchemas = isisSchemas;
}
public List<String> getNamespaceUris() {
return namespaceUris;
}
private Map<String, StreamResultWithWriter> schemaResultByNamespaceUri = Maps.newLinkedHashMap();
public String getSchemaTextFor(final String namespaceUri) {
final StreamResultWithWriter streamResult = schemaResultByNamespaceUri.get(namespaceUri);
return streamResult != null? streamResult.asString(): null;
}
@Override
public Result createOutput(
final String namespaceUri, final String suggestedFileName) throws IOException {
final StreamResultWithWriter result = new StreamResultWithWriter();
result.setSystemId(namespaceUri);
if (isisSchemas.shouldIgnore(namespaceUri)) {
// skip
} else {
namespaceUris.add(namespaceUri);
schemaResultByNamespaceUri.put(namespaceUri, result);
}
return result;
}
public Map<String, String> asMap() {
final Map<String,String> map = Maps.newLinkedHashMap();
final List<String> namespaceUris = getNamespaceUris();
for (String namespaceUri : namespaceUris) {
map.put(namespaceUri, getSchemaTextFor(namespaceUri));
}
return Collections.unmodifiableMap(map);
}
}
| ISIS-1312: fix up the generated common schema.
| core/schema/src/main/java/org/apache/isis/schema/services/jaxb/CatalogingSchemaOutputResolver.java | ISIS-1312: fix up the generated common schema. |
|
Java | apache-2.0 | 3c652f0656210343dd5ed99af132e48f436b7bab | 0 | pax95/camel,pax95/camel,tdiesler/camel,apache/camel,cunningt/camel,christophd/camel,christophd/camel,apache/camel,pax95/camel,adessaigne/camel,cunningt/camel,tadayosi/camel,cunningt/camel,tadayosi/camel,cunningt/camel,christophd/camel,adessaigne/camel,pax95/camel,adessaigne/camel,apache/camel,tdiesler/camel,pax95/camel,tadayosi/camel,tadayosi/camel,tadayosi/camel,christophd/camel,adessaigne/camel,cunningt/camel,apache/camel,tdiesler/camel,cunningt/camel,tdiesler/camel,adessaigne/camel,apache/camel,christophd/camel,tadayosi/camel,pax95/camel,adessaigne/camel,tdiesler/camel,christophd/camel,apache/camel,tdiesler/camel | ///usr/bin/env jbang "$0" "$@" ; exit $?
/*
* 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.
*/
//REPOS mavencentral,apache=https://repository.apache.org/snapshots
//DEPS org.apache.camel:camel-bom:3.12.0-SNAPSHOT@pom
//DEPS org.apache.camel:camel-core
//DEPS org.apache.camel:camel-core-model
//DEPS org.apache.camel:camel-api
//DEPS org.apache.camel:camel-main
//DEPS org.apache.camel:camel-kamelet-main
//DEPS org.apache.camel:camel-file-watch
//DEPS org.apache.camel:camel-resourceresolver-github
//DEPS org.apache.camel:camel-jbang-core:3.12.0-SNAPSHOT
//DEPS org.apache.logging.log4j:log4j-api:2.13.3
//DEPS org.apache.logging.log4j:log4j-core:2.13.3
//DEPS org.apache.logging.log4j:log4j-slf4j-impl:2.13.3
//DEPS org.apache.velocity:velocity-engine-core:2.3
//DEPS info.picocli:picocli:4.6.1
package main;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dsl.jbang.core.commands.AbstractInitKamelet;
import org.apache.camel.dsl.jbang.core.commands.AbstractSearch;
import org.apache.camel.dsl.jbang.core.common.MatchExtractor;
import org.apache.camel.dsl.jbang.core.common.exceptions.ResourceAlreadyExists;
import org.apache.camel.dsl.jbang.core.common.exceptions.ResourceDoesNotExist;
import org.apache.camel.dsl.jbang.core.components.ComponentConverter;
import org.apache.camel.dsl.jbang.core.components.ComponentDescriptionMatching;
import org.apache.camel.dsl.jbang.core.components.ComponentPrinter;
import org.apache.camel.dsl.jbang.core.kamelets.KameletConverter;
import org.apache.camel.dsl.jbang.core.kamelets.KameletDescriptionMatching;
import org.apache.camel.dsl.jbang.core.kamelets.KameletPrinter;
import org.apache.camel.dsl.jbang.core.languages.LanguageConverter;
import org.apache.camel.dsl.jbang.core.languages.LanguageDescriptionMatching;
import org.apache.camel.dsl.jbang.core.languages.LanguagePrinter;
import org.apache.camel.dsl.jbang.core.others.OtherConverter;
import org.apache.camel.dsl.jbang.core.others.OtherDescriptionMatching;
import org.apache.camel.dsl.jbang.core.others.OtherPrinter;
import org.apache.camel.dsl.jbang.core.templates.VelocityTemplateParser;
import org.apache.camel.dsl.jbang.core.types.Component;
import org.apache.camel.dsl.jbang.core.types.Kamelet;
import org.apache.camel.dsl.jbang.core.types.Language;
import org.apache.camel.dsl.jbang.core.types.Other;
import org.apache.camel.main.KameletMain;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
@Command(name = "run", description = "Run a Kamelet")
class Run implements Callable<Integer> {
private CamelContext context;
@Parameters(description = "The path to the kamelet binding", arity = "0..1")
private String binding;
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--debug-level" }, defaultValue = "info", description = "Default debug level")
private String debugLevel;
@Option(names = { "--stop" }, description = "Stop all running instances of Camel JBang")
private boolean stopRequested;
@Option(names = { "--max-messages" }, defaultValue = "0", description = "Max number of messages to process before stopping")
private int maxMessages;
class ShutdownRoute extends RouteBuilder {
private File lockFile;
public ShutdownRoute(File lockFile) {
this.lockFile = lockFile;
}
public void configure() {
fromF("file-watch://%s?events=DELETE&antInclude=%s", lockFile.getParent(), lockFile.getName())
.process(p -> context.shutdown());
}
}
@Override
public Integer call() throws Exception {
System.setProperty("camel.main.name", "CamelJBang");
if (stopRequested) {
stop();
} else {
run();
}
return 0;
}
private int stop() {
File currentDir = new File(".");
File[] lockFiles = currentDir.listFiles(f -> f.getName().endsWith(".camel.lock"));
for (File lockFile : lockFiles) {
System.out.println("Removing file " + lockFile);
if (!lockFile.delete()) {
System.err.println("Failed to remove lock file " + lockFile);
}
}
return 0;
}
private int run() throws Exception {
if (maxMessages > 0) {
System.setProperty("camel.main.durationMaxMessages", String.valueOf(maxMessages));
}
System.setProperty("camel.main.routes-include-pattern", "file:" + binding);
switch (debugLevel) {
case "trace":
Configurator.setRootLevel(Level.TRACE);
break;
case "debug":
Configurator.setRootLevel(Level.DEBUG);
break;
case "info":
Configurator.setRootLevel(Level.INFO);
break;
case "warn":
Configurator.setRootLevel(Level.WARN);
break;
case "fatal":
Configurator.setRootLevel(Level.FATAL);
break;
default: {
System.err.println("Invalid debug level " + debugLevel);
return 1;
}
}
File bindingFile = new File(binding);
if (!bindingFile.exists()) {
System.err.println("The binding file does not exist");
return 1;
}
System.out.println("Starting Camel JBang!");
KameletMain main = new KameletMain();
main.configure().addRoutesBuilder(new ShutdownRoute(createLockFile()));
main.start();
context = main.getCamelContext();
main.run();
return 0;
}
public File createLockFile() throws IOException {
File lockFile = File.createTempFile(".run", ".camel.lock", new File("."));
System.out.printf("A new lock file was created on %s. Delete this file to stop running%n",
lockFile.getAbsolutePath());
lockFile.deleteOnExit();
return lockFile;
}
}
@Command(name = "search", description = "Search for kameletes, components and patterns (use --help)")
class Search extends AbstractSearch implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
public Search() {
super(null, null);
}
public void printHeader() {
// NO-OP
}
@Override
public Integer call() throws Exception {
new CommandLine(this).execute("--help");
return 0;
}
}
@Command(name = "kamelets", description = "Search for a Kamelet in the Kamelet catalog")
class SearchKamelets extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* xref:ROOT:mariadb-sink.adoc[image:kamelets/mariadb-sink.svg[] MariaDB Sink]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*):(.*)\\[(.*)\\[\\] (.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "main", hidden = true,
description = "The branch to use when downloading resources from (used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "KAMELET", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel-kamelets:docs/modules/ROOT/nav.adoc");
setBranch(branch);
MatchExtractor<Kamelet> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new KameletConverter(), new KameletPrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new KameletConverter(),
new KameletDescriptionMatching(searchTerm));
}
search(matchExtractor);
return 0;
}
}
@Command(name = "components", description = "Search for Camel Core components")
class SearchComponents extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* * xref:ROOT:index.adoc[Components]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*)\\[(.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "camel-3.12.0-SNAPSHOT", hidden = true,
description = "The branch to use when downloading or searching resources (mostly used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "COMPONENT", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel:docs/components/modules/ROOT/nav.adoc");
setBranch(branch);
MatchExtractor<Component> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new ComponentConverter(), new ComponentPrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new ComponentConverter(),
new ComponentDescriptionMatching(searchTerm));
}
try {
search(matchExtractor);
return 0;
} catch (ResourceDoesNotExist e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "languages", description = "Search for Camel expression languages")
class SearchLanguages extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* * xref:ROOT:index.adoc[Components]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*)\\[(.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "camel-3.12.0-SNAPSHOT", hidden = true,
description = "The branch to use when downloading or searching resources (mostly used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "LANGUAGE", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel:docs/components/modules/languages/nav.adoc");
setBranch(branch);
MatchExtractor<Language> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new LanguageConverter(), new LanguagePrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new LanguageConverter(),
new LanguageDescriptionMatching(searchTerm));
}
try {
search(matchExtractor);
return 0;
} catch (ResourceDoesNotExist e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "others", description = "Search for Camel miscellaneous components")
class SearchOthers extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* * xref:ROOT:index.adoc[Components]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*)\\[(.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "camel-3.12.0-SNAPSHOT", hidden = true,
description = "The branch to use when downloading or searching resources (mostly used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "COMPONENT", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel:docs/components/modules/others/nav.adoc");
setBranch(branch);
MatchExtractor<Other> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new OtherConverter(), new OtherPrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new OtherConverter(),
new OtherDescriptionMatching(searchTerm));
}
try {
search(matchExtractor);
return 0;
} catch (ResourceDoesNotExist e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "init", description = "Provide init templates for kamelets and bindings")
class Init implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Override
public Integer call() throws Exception {
new CommandLine(this).execute("--help");
return 0;
}
}
@Command(name = "kamelet", description = "Provide init templates for kamelets")
class InitKamelet extends AbstractInitKamelet implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@CommandLine.ArgGroup(exclusive = true, multiplicity = "1")
private ProcessOptions processOptions;
static class ProcessOptions {
@Option(names = { "--bootstrap" },
description = "Bootstrap the Kamelet template generator - download the properties file for editing")
private boolean bootstrap = false;
@Option(names = { "--properties-path" }, defaultValue = "", description = "Kamelet name")
private String propertiesPath;
}
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from (used for development/testing)")
private String baseResourceLocation;
@Option(names = { "--branch" }, defaultValue = "main", hidden = true,
description = "The branch to use when downloading resources from (used for development/testing)")
private String branch;
@Option(names = { "--destination" }, defaultValue = "work",
description = "The destination directory where to download the files")
private String destination;
@Override
public Integer call() throws Exception {
if (processOptions.bootstrap) {
bootstrap();
} else {
generateTemplate();
}
return 0;
}
private int generateTemplate() throws IOException, CamelException {
setBranch(branch);
setResourceLocation(baseResourceLocation, "camel-kamelets:templates/init-template.kamelet.yaml.vm");
File workDirectory = new File(destination);
File localTemplateFile;
try {
localTemplateFile = resolveResource(workDirectory);
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
localTemplateFile.deleteOnExit();
VelocityTemplateParser templateParser = new VelocityTemplateParser(
localTemplateFile.getParentFile(),
processOptions.propertiesPath);
File outputFile;
try {
outputFile = templateParser.getOutputFile(workDirectory);
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
try (FileWriter fw = new FileWriter(outputFile)) {
templateParser.parse(localTemplateFile.getName(), fw);
System.out.println("Template file was written to " + outputFile);
}
return 0;
}
private int bootstrap() throws IOException, CamelException {
try {
super.bootstrap(branch, baseResourceLocation, destination);
return 0;
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "binding", description = "Provide init templates for kamelet bindings")
class InitBinding extends AbstractInitKamelet implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from (used for development/testing)")
private String baseResourceLocation;
@Option(names = { "--branch" }, defaultValue = "main", hidden = true,
description = "The branch to use when downloading resources from (used for development/testing)")
private String branch;
@Option(names = { "--destination" }, defaultValue = "work",
description = "The destination directory where to download the files")
private String destination;
@Option(names = { "--kamelet" }, defaultValue = "",
description = "The kamelet to create a binding for")
private String kamelet;
@Option(names = { "--project" }, defaultValue = "camel-k",
description = "The project to create a binding for (either camel-k or core)")
private String project;
private int downloadSample() throws IOException, CamelException {
setBranch(branch);
String resourcePath = String.format("camel-kamelets:templates/bindings/%s/%s-binding.yaml", project, kamelet);
setResourceLocation(baseResourceLocation, resourcePath);
try {
resolveResource(new File(destination));
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
return 0;
}
@Override
public Integer call() throws Exception {
return downloadSample();
}
}
@Command(name = "CamelJBang", mixinStandardHelpOptions = true, version = "CamelJBang 3.12.0-SNAPSHOT",
description = "A JBang-based Camel app for running Kamelets")
public class CamelJBang implements Callable<Integer> {
private static CommandLine commandLine;
static {
Configurator.initialize(new DefaultConfiguration());
}
public static void main(String... args) {
commandLine = new CommandLine(new CamelJBang())
.addSubcommand("run", new Run())
.addSubcommand("search", new CommandLine(new Search())
.addSubcommand("kamelets", new SearchKamelets())
.addSubcommand("components", new SearchComponents())
.addSubcommand("languages", new SearchLanguages())
.addSubcommand("others", new SearchOthers()))
.addSubcommand("init", new CommandLine(new Init())
.addSubcommand("kamelet", new InitKamelet())
.addSubcommand("binding", new InitBinding()));
int exitCode = commandLine.execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception {
commandLine.execute("--help");
return 0;
}
}
| dsl/camel-jbang/camel-jbang-main/dist/CamelJBang.java | ///usr/bin/env jbang "$0" "$@" ; exit $?
/*
* 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.
*/
//REPOS mavencentral,apache=https://repository.apache.org/snapshots
//DEPS org.apache.camel:camel-bom:3.12.0-SNAPSHOT@pom
//DEPS org.apache.camel:camel-core
//DEPS org.apache.camel:camel-core-model
//DEPS org.apache.camel:camel-api
//DEPS org.apache.camel:camel-main
//DEPS org.apache.camel:camel-kamelet-main
//DEPS org.apache.camel:camel-file-watch
//DEPS org.apache.camel:camel-resourceresolver-github
//DEPS org.apache.camel:camel-jbang-core:3.12.0-SNAPSHOT
//DEPS org.apache.logging.log4j:log4j-api:2.13.3
//DEPS org.apache.logging.log4j:log4j-core:2.13.3
//DEPS org.apache.logging.log4j:log4j-slf4j-impl:2.13.3
//DEPS org.apache.velocity:velocity-engine-core:2.3
//DEPS info.picocli:picocli:4.5.0
package main;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dsl.jbang.core.commands.AbstractInitKamelet;
import org.apache.camel.dsl.jbang.core.commands.AbstractSearch;
import org.apache.camel.dsl.jbang.core.common.MatchExtractor;
import org.apache.camel.dsl.jbang.core.common.exceptions.ResourceAlreadyExists;
import org.apache.camel.dsl.jbang.core.common.exceptions.ResourceDoesNotExist;
import org.apache.camel.dsl.jbang.core.components.ComponentConverter;
import org.apache.camel.dsl.jbang.core.components.ComponentDescriptionMatching;
import org.apache.camel.dsl.jbang.core.components.ComponentPrinter;
import org.apache.camel.dsl.jbang.core.kamelets.KameletConverter;
import org.apache.camel.dsl.jbang.core.kamelets.KameletDescriptionMatching;
import org.apache.camel.dsl.jbang.core.kamelets.KameletPrinter;
import org.apache.camel.dsl.jbang.core.languages.LanguageConverter;
import org.apache.camel.dsl.jbang.core.languages.LanguageDescriptionMatching;
import org.apache.camel.dsl.jbang.core.languages.LanguagePrinter;
import org.apache.camel.dsl.jbang.core.others.OtherConverter;
import org.apache.camel.dsl.jbang.core.others.OtherDescriptionMatching;
import org.apache.camel.dsl.jbang.core.others.OtherPrinter;
import org.apache.camel.dsl.jbang.core.templates.VelocityTemplateParser;
import org.apache.camel.dsl.jbang.core.types.Component;
import org.apache.camel.dsl.jbang.core.types.Kamelet;
import org.apache.camel.dsl.jbang.core.types.Language;
import org.apache.camel.dsl.jbang.core.types.Other;
import org.apache.camel.main.KameletMain;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
@Command(name = "run", description = "Run a Kamelet")
class Run implements Callable<Integer> {
private CamelContext context;
@Parameters(description = "The path to the kamelet binding", arity = "0..1")
private String binding;
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--debug-level" }, defaultValue = "info", description = "Default debug level")
private String debugLevel;
@Option(names = { "--stop" }, description = "Stop all running instances of Camel JBang")
private boolean stopRequested;
@Option(names = { "--max-messages" }, defaultValue = "0", description = "Max number of messages to process before stopping")
private int maxMessages;
class ShutdownRoute extends RouteBuilder {
private File lockFile;
public ShutdownRoute(File lockFile) {
this.lockFile = lockFile;
}
public void configure() {
fromF("file-watch://%s?events=DELETE&antInclude=%s", lockFile.getParent(), lockFile.getName())
.process(p -> context.shutdown());
}
}
@Override
public Integer call() throws Exception {
System.setProperty("camel.main.name", "CamelJBang");
if (stopRequested) {
stop();
} else {
run();
}
return 0;
}
private int stop() {
File currentDir = new File(".");
File[] lockFiles = currentDir.listFiles(f -> f.getName().endsWith(".camel.lock"));
for (File lockFile : lockFiles) {
System.out.println("Removing file " + lockFile);
if (!lockFile.delete()) {
System.err.println("Failed to remove lock file " + lockFile);
}
}
return 0;
}
private int run() throws Exception {
if (maxMessages > 0) {
System.setProperty("camel.main.durationMaxMessages", String.valueOf(maxMessages));
}
System.setProperty("camel.main.routes-include-pattern", "file:" + binding);
switch (debugLevel) {
case "trace":
Configurator.setRootLevel(Level.TRACE);
break;
case "debug":
Configurator.setRootLevel(Level.DEBUG);
break;
case "info":
Configurator.setRootLevel(Level.INFO);
break;
case "warn":
Configurator.setRootLevel(Level.WARN);
break;
case "fatal":
Configurator.setRootLevel(Level.FATAL);
break;
default: {
System.err.println("Invalid debug level " + debugLevel);
return 1;
}
}
File bindingFile = new File(binding);
if (!bindingFile.exists()) {
System.err.println("The binding file does not exist");
return 1;
}
System.out.println("Starting Camel JBang!");
KameletMain main = new KameletMain();
main.configure().addRoutesBuilder(new ShutdownRoute(createLockFile()));
main.start();
context = main.getCamelContext();
main.run();
return 0;
}
public File createLockFile() throws IOException {
File lockFile = File.createTempFile(".run", ".camel.lock", new File("."));
System.out.printf("A new lock file was created on %s. Delete this file to stop running%n",
lockFile.getAbsolutePath());
lockFile.deleteOnExit();
return lockFile;
}
}
@Command(name = "search", description = "Search for kameletes, components and patterns (use --help)")
class Search extends AbstractSearch implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
public Search() {
super(null, null);
}
public void printHeader() {
// NO-OP
}
@Override
public Integer call() throws Exception {
new CommandLine(this).execute("--help");
return 0;
}
}
@Command(name = "kamelets", description = "Search for a Kamelet in the Kamelet catalog")
class SearchKamelets extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* xref:ROOT:mariadb-sink.adoc[image:kamelets/mariadb-sink.svg[] MariaDB Sink]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*):(.*)\\[(.*)\\[\\] (.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "main", hidden = true,
description = "The branch to use when downloading resources from (used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "KAMELET", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel-kamelets:docs/modules/ROOT/nav.adoc");
setBranch(branch);
MatchExtractor<Kamelet> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new KameletConverter(), new KameletPrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new KameletConverter(),
new KameletDescriptionMatching(searchTerm));
}
search(matchExtractor);
return 0;
}
}
@Command(name = "components", description = "Search for Camel Core components")
class SearchComponents extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* * xref:ROOT:index.adoc[Components]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*)\\[(.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "camel-3.12.0-SNAPSHOT", hidden = true,
description = "The branch to use when downloading or searching resources (mostly used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "COMPONENT", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel:docs/components/modules/ROOT/nav.adoc");
setBranch(branch);
MatchExtractor<Component> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new ComponentConverter(), new ComponentPrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new ComponentConverter(),
new ComponentDescriptionMatching(searchTerm));
}
try {
search(matchExtractor);
return 0;
} catch (ResourceDoesNotExist e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "languages", description = "Search for Camel expression languages")
class SearchLanguages extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* * xref:ROOT:index.adoc[Components]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*)\\[(.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "camel-3.12.0-SNAPSHOT", hidden = true,
description = "The branch to use when downloading or searching resources (mostly used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "LANGUAGE", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel:docs/components/modules/languages/nav.adoc");
setBranch(branch);
MatchExtractor<Language> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new LanguageConverter(), new LanguagePrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new LanguageConverter(),
new LanguageDescriptionMatching(searchTerm));
}
try {
search(matchExtractor);
return 0;
} catch (ResourceDoesNotExist e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "others", description = "Search for Camel miscellaneous components")
class SearchOthers extends AbstractSearch implements Callable<Integer> {
/*
* Matches the following line. Separate them into groups and pick the last
* which contains the description:
*
* * xref:ROOT:index.adoc[Components]
*/
private static final Pattern PATTERN = Pattern.compile("(.*):(.*)\\[(.*)\\]");
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--search-term" }, defaultValue = "", description = "Default debug level")
private String searchTerm;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from")
private String resourceLocation;
@Option(names = { "--branch" }, defaultValue = "camel-3.12.0-SNAPSHOT", hidden = true,
description = "The branch to use when downloading or searching resources (mostly used for development/testing)")
private String branch;
@Override
public void printHeader() {
System.out.printf("%-35s %-45s %s%n", "COMPONENT", "DESCRIPTION", "LINK");
System.out.printf("%-35s %-45s %s%n", "-------", "-----------", "-----");
}
@Override
public Integer call() throws Exception {
setResourceLocation(resourceLocation, "camel:docs/components/modules/others/nav.adoc");
setBranch(branch);
MatchExtractor<Other> matchExtractor;
if (searchTerm.isEmpty()) {
matchExtractor = new MatchExtractor<>(PATTERN, new OtherConverter(), new OtherPrinter());
} else {
matchExtractor = new MatchExtractor<>(
PATTERN, new OtherConverter(),
new OtherDescriptionMatching(searchTerm));
}
try {
search(matchExtractor);
return 0;
} catch (ResourceDoesNotExist e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "init", description = "Provide init templates for kamelets and bindings")
class Init implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Override
public Integer call() throws Exception {
new CommandLine(this).execute("--help");
return 0;
}
}
@Command(name = "kamelet", description = "Provide init templates for kamelets")
class InitKamelet extends AbstractInitKamelet implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@CommandLine.ArgGroup(exclusive = true, multiplicity = "1")
private ProcessOptions processOptions;
static class ProcessOptions {
@Option(names = { "--bootstrap" },
description = "Bootstrap the Kamelet template generator - download the properties file for editing")
private boolean bootstrap = false;
@Option(names = { "--properties-path" }, defaultValue = "", description = "Kamelet name")
private String propertiesPath;
}
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from (used for development/testing)")
private String baseResourceLocation;
@Option(names = { "--branch" }, defaultValue = "main", hidden = true,
description = "The branch to use when downloading resources from (used for development/testing)")
private String branch;
@Option(names = { "--destination" }, defaultValue = "work",
description = "The destination directory where to download the files")
private String destination;
@Override
public Integer call() throws Exception {
if (processOptions.bootstrap) {
bootstrap();
} else {
generateTemplate();
}
return 0;
}
private int generateTemplate() throws IOException, CamelException {
setBranch(branch);
setResourceLocation(baseResourceLocation, "camel-kamelets:templates/init-template.kamelet.yaml.vm");
File workDirectory = new File(destination);
File localTemplateFile;
try {
localTemplateFile = resolveResource(workDirectory);
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
localTemplateFile.deleteOnExit();
VelocityTemplateParser templateParser = new VelocityTemplateParser(
localTemplateFile.getParentFile(),
processOptions.propertiesPath);
File outputFile;
try {
outputFile = templateParser.getOutputFile(workDirectory);
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
try (FileWriter fw = new FileWriter(outputFile)) {
templateParser.parse(localTemplateFile.getName(), fw);
System.out.println("Template file was written to " + outputFile);
}
return 0;
}
private int bootstrap() throws IOException, CamelException {
try {
super.bootstrap(branch, baseResourceLocation, destination);
return 0;
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
}
}
@Command(name = "binding", description = "Provide init templates for kamelet bindings")
class InitBinding extends AbstractInitKamelet implements Callable<Integer> {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display the help and sub-commands")
private boolean helpRequested = false;
@Option(names = { "--base-resource-location" }, defaultValue = "github:apache", hidden = true,
description = "Where to download the resources from (used for development/testing)")
private String baseResourceLocation;
@Option(names = { "--branch" }, defaultValue = "main", hidden = true,
description = "The branch to use when downloading resources from (used for development/testing)")
private String branch;
@Option(names = { "--destination" }, defaultValue = "work",
description = "The destination directory where to download the files")
private String destination;
@Option(names = { "--kamelet" }, defaultValue = "",
description = "The kamelet to create a binding for")
private String kamelet;
@Option(names = { "--project" }, defaultValue = "camel-k",
description = "The project to create a binding for (either camel-k or core)")
private String project;
private int downloadSample() throws IOException, CamelException {
setBranch(branch);
String resourcePath = String.format("camel-kamelets:templates/bindings/%s/%s-binding.yaml", project, kamelet);
setResourceLocation(baseResourceLocation, resourcePath);
try {
resolveResource(new File(destination));
} catch (ResourceAlreadyExists e) {
System.err.println(e.getMessage());
return 1;
}
return 0;
}
@Override
public Integer call() throws Exception {
return downloadSample();
}
}
@Command(name = "CamelJBang", mixinStandardHelpOptions = true, version = "CamelJBang 3.12.0-SNAPSHOT",
description = "A JBang-based Camel app for running Kamelets")
public class CamelJBang implements Callable<Integer> {
private static CommandLine commandLine;
static {
Configurator.initialize(new DefaultConfiguration());
}
public static void main(String... args) {
commandLine = new CommandLine(new CamelJBang())
.addSubcommand("run", new Run())
.addSubcommand("search", new CommandLine(new Search())
.addSubcommand("kamelets", new SearchKamelets())
.addSubcommand("components", new SearchComponents())
.addSubcommand("languages", new SearchLanguages())
.addSubcommand("others", new SearchOthers()))
.addSubcommand("init", new CommandLine(new Init())
.addSubcommand("kamelet", new InitKamelet())
.addSubcommand("binding", new InitBinding()));
int exitCode = commandLine.execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception {
commandLine.execute("--help");
return 0;
}
}
| Regen for commit 24b9c39da5abd8b8488adf8b37ed03a93c302c84
Signed-off-by: GitHub <[email protected]>
| dsl/camel-jbang/camel-jbang-main/dist/CamelJBang.java | Regen for commit 24b9c39da5abd8b8488adf8b37ed03a93c302c84 |
|
Java | apache-2.0 | 7d034e2693c95dea344db00045d8a6a5db1eb48d | 0 | Valkryst/VTerminal | package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.builder.component.TextAreaBuilder;
import lombok.*;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ToString
public class TextArea extends Component {
/** The foreground color of the caret. */
@Getter @Setter private Color caretForegroundColor;
/** The background color of the caret. */
@Getter @Setter private Color caretBackgroundColor;
/** The foreground color of non-caret characters. */
@Getter @Setter private Color foregroundColor;
/** The background color of non-caret characters. */
@Getter @Setter private Color backgroundColor;
/** Whether or not the HOME key can be used to move the caret to the first index of the current line. */
@Getter @Setter private boolean homeKeyEnabled;
/** Whether or not the END key can be used to move the caret to the last index of the current line. */
@Getter @Setter private boolean endKeyEnabled;
/** Whether or not the PAGE UP key can be used to move the caret to the first row. */
@Getter @Setter private boolean pageUpKeyEnabled;
/** Whether or nor the PAGE DOWN key can be used to move the caret to the last row. */
@Getter @Setter private boolean pageDownKeyEnabled;
/** Whether or not the DELETE key can be used to erase the character that the caret is on. */
@Getter @Setter private boolean deleteKeyEnabled;
/** Whether or not the LEFT ARROW key can be used to move the caret one index to the left. */
@Getter @Setter private boolean leftArrowKeyEnabled;
/** Whether or not the RIGHT ARROW key can be used to move the caret one index to the right. */
@Getter @Setter private boolean rightArrowKeyEnabled;
/** Whether or not the UP ARROW key can be used to move the caret one index up. */
@Getter @Setter private boolean upArrowKeyEnabled;
/** Whether or not the DOWN ARROW key can be used to move the caret one index up. */
@Getter @Setter private boolean downArrowKeyEnabled;
/** Whether or not the ENTER key can be used to advance the caret to the first position of the next line. */
@Getter @Setter private boolean enterKeyEnabled;
/** Whether or not the BACK SPACE key can be used to erase the character before the caret and move the caret backwards. */
@Getter @Setter private boolean backSpaceKeyEnabled;
/** Whether or not the TAB key can be used to indent by some number of spaces. */
@Getter @Setter private boolean tabKeyEnabled;
/** The current position of the visual caret on the x-axis. */
@Getter private int x_index_caret_visual = 0;
/** The current position of the visual caret on the y-axis. */
@Getter private int y_index_caret_visual = 0;
/** The current position of the caret, on the x-axis, in the enteredText array. */
@Getter private int x_index_caret_actual = 0;
/** The current position of the caret, on the y-axis, in the enteredText array. */
@Getter private int y_index_caret_actual = 0;
/** The maximum number of characters that the field can contain along the x-axis. */
@Getter private int maxHorizontalCharacters;
/** The maximum number of characters that the field can contain along the y-axis. */
@Getter private int maxVerticalCharacters;
/** The amount of spaces to insert when the TAB key is pressed. */
@Getter private int tabSize;
/** The text entered by the user. */
@Getter private char[][] enteredText;
/** The pattern used to determine which typed characters can be entered into the field. */
@Getter @Setter private Pattern allowedCharacterPattern;
/**
* Constructs a new AsciiTextField.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public TextArea(final @NonNull TextAreaBuilder builder) {
super(builder.getColumnIndex(), builder.getRowIndex(), builder.getWidth(), builder.getHeight());
super.setRadio(builder.getRadio());
caretForegroundColor = builder.getCaretForegroundColor();
caretBackgroundColor = builder.getCaretBackgroundColor();
foregroundColor = builder.getForegroundColor();
backgroundColor = builder.getBackgroundColor();
homeKeyEnabled = builder.isHomeKeyEnabled();
endKeyEnabled = builder.isEndKeyEnabled();
pageUpKeyEnabled = builder.isPageUpKeyEnabled();
pageDownKeyEnabled = builder.isPageDownKeyEnabled();
deleteKeyEnabled = builder.isDeleteKeyEnabled();
leftArrowKeyEnabled = builder.isLeftArrowKeyEnabled();
rightArrowKeyEnabled = builder.isRightArrowKeyEnabled();
upArrowKeyEnabled = builder.isUpArrowKeyEnabled();
downArrowKeyEnabled = builder.isDownArrowKeyEnabled();
enterKeyEnabled = builder.isEnterKeyEnabled();
backSpaceKeyEnabled = builder.isBackSpaceKeyEnabled();
tabKeyEnabled = builder.isTabKeyEnabled();
maxHorizontalCharacters = builder.getMaxHorizontalCharacters();
maxVerticalCharacters = builder.getMaxVerticalCharacters();
tabSize = builder.getTabSize();
enteredText = new char[maxVerticalCharacters][maxHorizontalCharacters];
clearText();
allowedCharacterPattern = builder.getAllowedCharacterPattern();
// Set the area's initial colors:
for (final AsciiString string : super.getStrings()) {
string.setBackgroundColor(backgroundColor);
string.setForegroundColor(foregroundColor);
}
// Set initial caret position:
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual);
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual);
}
@Override
public void createEventListeners(final @NonNull Panel panel) {
super.createEventListeners(panel);
final KeyListener keyListener = new KeyListener() {
@Override
public void keyTyped(final KeyEvent e) {
if (isFocused()) {
final char character = e.getKeyChar();
final Matcher matcher = allowedCharacterPattern.matcher(character + "");
if (matcher.matches()) {
changeVisualCharacter(x_index_caret_visual, y_index_caret_visual, character);
changeActualCharacter(x_index_caret_actual, y_index_caret_actual, character);
final boolean caretAtEndOfLine = x_index_caret_actual == maxHorizontalCharacters - 1;
if (caretAtEndOfLine) {
if (y_index_caret_actual < maxVerticalCharacters - 1) {
moveCaretDown();
moveCaretToStartOfLine();
}
} else {
moveCaretRight();
}
updateDisplayedCharacters();
transmitDraw();
}
}
}
@Override
public void keyPressed(final KeyEvent e) {
}
@Override
public void keyReleased(final KeyEvent e) {
if (isFocused()) {
int keyCode = e.getKeyCode();
switch (keyCode) {
// Move the caret to the first position on the left:
case KeyEvent.VK_HOME: {
if (homeKeyEnabled) {
moveCaretToStartOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the last position on the right:
case KeyEvent.VK_END: {
if (endKeyEnabled) {
moveCaretToEndOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the first row:
case KeyEvent.VK_PAGE_UP: {
if (pageUpKeyEnabled) {
moveCaretToFirstLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the last row:
case KeyEvent.VK_PAGE_DOWN: {
if (pageDownKeyEnabled) {
moveCaretToLastLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Erase the current character:
case KeyEvent.VK_DELETE: {
if (deleteKeyEnabled) {
clearCurrentCell();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position to the left:
case KeyEvent.VK_LEFT: {
if (leftArrowKeyEnabled) {
boolean moveToPreviousLine = x_index_caret_actual == 0;
moveToPreviousLine &= y_index_caret_actual > 0;
if (moveToPreviousLine) {
moveCaretUp();
moveCaretToEndOfLine();
} else {
moveCaretLeft();
}
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position to the right:
case KeyEvent.VK_RIGHT: {
if (isRightArrowKeyEnabled()) {
boolean moveToNextLine = x_index_caret_actual == maxHorizontalCharacters - 1;
moveToNextLine &= y_index_caret_actual < maxVerticalCharacters - 1;
if (moveToNextLine) {
moveCaretDown();
moveCaretToStartOfLine();
} else {
moveCaretRight();
}
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position up:
case KeyEvent.VK_UP: {
if (upArrowKeyEnabled) {
moveCaretUp();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position down:
case KeyEvent.VK_DOWN: {
if (downArrowKeyEnabled) {
moveCaretDown();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the first position of the next row:
case KeyEvent.VK_ENTER: {
boolean canWork = enterKeyEnabled;
canWork &= y_index_caret_actual < maxVerticalCharacters - 1;
if (canWork) {
moveCaretDown();
moveCaretToStartOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Delete the character to the left of the caret, then move the caret one position left:
case KeyEvent.VK_BACK_SPACE: {
if (! backSpaceKeyEnabled) {
break;
}
final boolean caretAtStartOfLine = x_index_caret_actual == 0;
final boolean caretAtEndOfLine = x_index_caret_actual == maxHorizontalCharacters - 1;
if (caretAtStartOfLine) {
if (y_index_caret_actual > 0) {
moveCaretUp();
moveCaretToEndOfLine();
}
} else if (caretAtEndOfLine) {
final AsciiCharacter currentChar = TextArea.super.getStrings()[y_index_caret_visual].getCharacters()[x_index_caret_visual];
if (currentChar.getCharacter() == ' ') {
moveCaretLeft();
}
} else {
moveCaretLeft();
}
clearCurrentCell();
updateDisplayedCharacters();
transmitDraw();
break;
}
case KeyEvent.VK_TAB: {
if (tabKeyEnabled) {
for (int i = 0 ; i < tabSize ; i++) {
if (i < maxHorizontalCharacters - 1) {
moveCaretRight();
}
}
}
updateDisplayedCharacters();
transmitDraw();
break;
}
}
}
}
};
super.getEventListeners().add(keyListener);
}
/** Moves the caret one cell up. */
public void moveCaretUp() {
if (y_index_caret_visual > 0) {
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual - 1);
}
if (y_index_caret_actual > 0) {
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual - 1);
}
}
/** Moves the caret one cell down. */
public void moveCaretDown() {
if (y_index_caret_visual < super.getHeight() - 1) {
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual + 1);
}
if (y_index_caret_actual < maxVerticalCharacters - 1) {
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual + 1);
}
}
/** Moves the caret one cell left. */
public void moveCaretLeft() {
if (x_index_caret_visual > 0) {
changeVisualCaretPosition(x_index_caret_visual - 1, y_index_caret_visual);
}
if (x_index_caret_actual > 0) {
changeActualCaretPosition(x_index_caret_actual - 1, y_index_caret_actual);
}
}
/** Moves the caret one cell right. */
public void moveCaretRight() {
if (x_index_caret_visual < super.getWidth() - 1) {
changeVisualCaretPosition(x_index_caret_visual + 1, y_index_caret_visual);
}
if (x_index_caret_actual < maxHorizontalCharacters - 1) {
changeActualCaretPosition(x_index_caret_actual + 1, y_index_caret_actual);
}
}
/** Moves the caret to the first line. Does not change the x-axis position of the caret. */
public void moveCaretToFirstLine() {
changeVisualCaretPosition(x_index_caret_visual, 0);
changeActualCaretPosition(x_index_caret_actual, 0);
}
/** Moves the caret to the last line. Does not change the x-axis position of the caret. */
public void moveCaretToLastLine() {
changeVisualCaretPosition(x_index_caret_visual, super.getHeight() - 1);
changeActualCaretPosition(x_index_caret_actual, maxVerticalCharacters - 1);
}
/** Moves the caret to the beginning of the current line. */
public void moveCaretToStartOfLine() {
changeVisualCaretPosition(0, y_index_caret_visual);
changeActualCaretPosition(0, y_index_caret_actual);
}
/** Moves the caret to the end of the current line. */
public void moveCaretToEndOfLine() {
changeVisualCaretPosition(super.getWidth() - 1, y_index_caret_visual);
changeActualCaretPosition(maxHorizontalCharacters - 1, y_index_caret_actual);
}
/** Deletes the character in the current cell. */
public void clearCurrentCell() {
changeVisualCharacter(x_index_caret_visual, y_index_caret_visual, ' ');
changeActualCharacter(x_index_caret_actual, y_index_caret_actual, ' ');
}
/**
* Moves the visual caret to the specified location.
*
* @param newColumnIndex
* The new column index for the caret.
*
* @param newRowIndex
* The new row index for the caret.
*/
private void changeVisualCaretPosition(final int newColumnIndex, final int newRowIndex) {
final Radio<String> radio = super.getRadio();
// Reset current position's fore/background:
AsciiCharacter[] characters = super.getString(y_index_caret_visual).getCharacters();
characters[x_index_caret_visual].setForegroundColor(foregroundColor);
characters[x_index_caret_visual].setBackgroundColor(backgroundColor);
if (radio != null) {
// Reset current position's blink/hidden state:
characters[x_index_caret_visual].disableBlinkEffect();
characters[x_index_caret_visual].setHidden(false);
}
// Set new position's fore/background:
characters = super.getString(newRowIndex).getCharacters();
characters[newColumnIndex].setForegroundColor(caretForegroundColor);
characters[newColumnIndex].setBackgroundColor(caretBackgroundColor);
if (radio != null) {
// Set new position's blink state:
characters[newColumnIndex].enableBlinkEffect((short) 1000, radio);
}
x_index_caret_visual = newColumnIndex;
y_index_caret_visual = newRowIndex;
}
/**
* Moves the actual caret to the specified location.
*
* @param newColumnIndex
* The new column index for the caret.
*
* @param newRowIndex
* The new row index for the caret.
*/
private void changeActualCaretPosition(final int newColumnIndex, final int newRowIndex) {
x_index_caret_actual = newColumnIndex;
y_index_caret_actual = newRowIndex;
}
/**
* Changes the visual character at the specified location.
*
* @param columnIndex
* The column index.
*
* @param rowIndex
* The row index.
*
* @param character
* The new character.
*/
private void changeVisualCharacter(final int columnIndex, final int rowIndex, final char character) {
final AsciiCharacter[] characters = super.getString(rowIndex).getCharacters();
characters[columnIndex].setCharacter(character);
}
/**
* Changes the actual character at the specified index.
*
* @param columnIndex
* The column index.
*
* @param rowIndex
* The row index.
*
* @param character
* The new character.
*/
private void changeActualCharacter(final int columnIndex, final int rowIndex, final char character) {
if (columnIndex < 0 || columnIndex > maxHorizontalCharacters) {
return;
}
if (rowIndex < 0 || rowIndex > maxVerticalCharacters) {
return;
}
enteredText[rowIndex][columnIndex] = character;
}
private void updateDisplayedCharacters() {
final int xDifference = x_index_caret_actual - x_index_caret_visual;
final int yDifference = y_index_caret_actual - y_index_caret_visual;
for (int y = yDifference ; y < super.getHeight() + yDifference ; y++) {
final AsciiString string = super.getString(y - yDifference);
final AsciiCharacter[] characters = string.getCharacters();
for (int x = xDifference ; x < super.getWidth() + xDifference ; x++) {
characters[x - xDifference].setCharacter(enteredText[y][x]);
}
}
}
/**
* Sets the text contained within a row of the area.
*
* @param rowIndex
* The row index.
*
* @param text
* The text.
*
* @throws NullPointerException
* If the text is null.
*/
public void setText(final int rowIndex, @NonNull String text) {
if (text.length() > maxHorizontalCharacters) {
text = text.substring(0, maxHorizontalCharacters);
}
System.arraycopy(text.toCharArray(), 0, enteredText[rowIndex], 0, text.length());
}
/**
* Sets the text contained within the area.
*
* Clears the field before setting.
*
* @param text
* The list of text.
*
* @throws NullPointerException
* If the text is null.
*/
public void setText(final @NonNull List<String> text) {
clearText();
for (int i = 0 ; i < text.size() && i < maxVerticalCharacters ; i++) {
setText(i, text.get(i));
}
}
/** @return The text contained within the area. */
public String[] getText() {
final String[] strings = new String[super.getHeight()];
String temp = "";
for (int i = 0 ; i < super.getHeight() ; i++) {
for (final char c : enteredText[i]) {
temp += c;
}
strings[i] = temp;
temp = "";
}
return strings;
}
/**
* Clears text from a row.
*
* @param rowIndex
* The row index,
*
* @throws java.lang.IllegalArgumentException
* If the row index is below zero.
* If the row index exceeds the TextArea's height.
*/
public void clearText(final int rowIndex) {
if (rowIndex < 0) {
throw new IllegalArgumentException("The row index cannot be below 0.");
}
if (rowIndex > super.getHeight()) {
throw new IllegalArgumentException("The row index cannot be above " + super.getHeight() +".");
}
Arrays.fill(enteredText[rowIndex], ' ');
if (y_index_caret_actual == y_index_caret_visual && y_index_caret_actual == rowIndex) {
for (final AsciiCharacter character : super.getString(rowIndex).getCharacters()) {
character.setCharacter(' ');
}
}
}
/** Clears all text from the field. */
public void clearText() {
for (int i = 0 ; i < enteredText.length ; i++) {
Arrays.fill(enteredText[i], ' ');
}
for (final AsciiString string : super.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
character.setCharacter(' ');
}
}
}
}
| src/com/valkryst/VTerminal/component/TextArea.java | package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.builder.component.TextAreaBuilder;
import lombok.*;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ToString
public class TextArea extends Component {
/** The foreground color of the caret. */
@Getter @Setter private Color caretForegroundColor;
/** The background color of the caret. */
@Getter @Setter private Color caretBackgroundColor;
/** The foreground color of non-caret characters. */
@Getter @Setter private Color foregroundColor;
/** The background color of non-caret characters. */
@Getter @Setter private Color backgroundColor;
/** Whether or not the HOME key can be used to move the caret to the first index of the current line. */
@Getter @Setter private boolean homeKeyEnabled;
/** Whether or not the END key can be used to move the caret to the last index of the current line. */
@Getter @Setter private boolean endKeyEnabled;
/** Whether or not the PAGE UP key can be used to move the caret to the first row. */
@Getter @Setter private boolean pageUpKeyEnabled;
/** Whether or nor the PAGE DOWN key can be used to move the caret to the last row. */
@Getter @Setter private boolean pageDownKeyEnabled;
/** Whether or not the DELETE key can be used to erase the character that the caret is on. */
@Getter @Setter private boolean deleteKeyEnabled;
/** Whether or not the LEFT ARROW key can be used to move the caret one index to the left. */
@Getter @Setter private boolean leftArrowKeyEnabled;
/** Whether or not the RIGHT ARROW key can be used to move the caret one index to the right. */
@Getter @Setter private boolean rightArrowKeyEnabled;
/** Whether or not the UP ARROW key can be used to move the caret one index up. */
@Getter @Setter private boolean upArrowKeyEnabled;
/** Whether or not the DOWN ARROW key can be used to move the caret one index up. */
@Getter @Setter private boolean downArrowKeyEnabled;
/** Whether or not the ENTER key can be used to advance the caret to the first position of the next line. */
@Getter @Setter private boolean enterKeyEnabled;
/** Whether or not the BACK SPACE key can be used to erase the character before the caret and move the caret backwards. */
@Getter @Setter private boolean backSpaceKeyEnabled;
/** Whether or not the TAB key can be used to indent by some number of spaces. */
@Getter @Setter private boolean tabKeyEnabled;
/** The current position of the visual caret on the x-axis. */
@Getter private int x_index_caret_visual = 0;
/** The current position of the visual caret on the y-axis. */
@Getter private int y_index_caret_visual = 0;
/** The current position of the caret, on the x-axis, in the enteredText array. */
@Getter private int x_index_caret_actual = 0;
/** The current position of the caret, on the y-axis, in the enteredText array. */
@Getter private int y_index_caret_actual = 0;
/** The maximum number of characters that the field can contain along the x-axis. */
@Getter private int maxHorizontalCharacters;
/** The maximum number of characters that the field can contain along the y-axis. */
@Getter private int maxVerticalCharacters;
/** The amount of spaces to insert when the TAB key is pressed. */
@Getter private int tabSize;
/** The text entered by the user. */
@Getter private char[][] enteredText;
/** The pattern used to determine which typed characters can be entered into the field. */
@Getter @Setter private Pattern allowedCharacterPattern;
/**
* Constructs a new AsciiTextField.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public TextArea(final @NonNull TextAreaBuilder builder) {
super(builder.getColumnIndex(), builder.getRowIndex(), builder.getWidth(), builder.getHeight());
super.setRadio(builder.getRadio());
caretForegroundColor = builder.getCaretForegroundColor();
caretBackgroundColor = builder.getCaretBackgroundColor();
foregroundColor = builder.getForegroundColor();
backgroundColor = builder.getBackgroundColor();
homeKeyEnabled = builder.isHomeKeyEnabled();
endKeyEnabled = builder.isEndKeyEnabled();
pageUpKeyEnabled = builder.isPageUpKeyEnabled();
pageDownKeyEnabled = builder.isPageDownKeyEnabled();
deleteKeyEnabled = builder.isDeleteKeyEnabled();
leftArrowKeyEnabled = builder.isLeftArrowKeyEnabled();
rightArrowKeyEnabled = builder.isRightArrowKeyEnabled();
upArrowKeyEnabled = builder.isUpArrowKeyEnabled();
downArrowKeyEnabled = builder.isDownArrowKeyEnabled();
enterKeyEnabled = builder.isEnterKeyEnabled();
backSpaceKeyEnabled = builder.isBackSpaceKeyEnabled();
tabKeyEnabled = builder.isTabKeyEnabled();
maxHorizontalCharacters = builder.getMaxHorizontalCharacters();
maxVerticalCharacters = builder.getMaxVerticalCharacters();
tabSize = builder.getTabSize();
enteredText = new char[maxVerticalCharacters][maxHorizontalCharacters];
clearText();
allowedCharacterPattern = builder.getAllowedCharacterPattern();
// Set the area's initial colors:
for (final AsciiString string : super.getStrings()) {
string.setBackgroundColor(backgroundColor);
string.setForegroundColor(foregroundColor);
}
// Set initial caret position:
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual);
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual);
}
@Override
public void createEventListeners(final @NonNull Panel panel) {
super.createEventListeners(panel);
final KeyListener keyListener = new KeyListener() {
@Override
public void keyTyped(final KeyEvent e) {
if (isFocused()) {
final char character = e.getKeyChar();
final Matcher matcher = allowedCharacterPattern.matcher(character + "");
if (matcher.matches()) {
changeVisualCharacter(x_index_caret_visual, y_index_caret_visual, character);
changeActualCharacter(x_index_caret_actual, y_index_caret_actual, character);
final boolean caretAtEndOfLine = x_index_caret_actual == maxHorizontalCharacters - 1;
if (caretAtEndOfLine) {
if (y_index_caret_actual < maxVerticalCharacters - 1) {
moveCaretDown();
moveCaretToStartOfLine();
}
} else {
moveCaretRight();
}
updateDisplayedCharacters();
transmitDraw();
}
}
}
@Override
public void keyPressed(final KeyEvent e) {
}
@Override
public void keyReleased(final KeyEvent e) {
if (isFocused()) {
int keyCode = e.getKeyCode();
switch (keyCode) {
// Move the caret to the first position on the left:
case KeyEvent.VK_HOME: {
if (homeKeyEnabled) {
moveCaretToStartOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the last position on the right:
case KeyEvent.VK_END: {
if (endKeyEnabled) {
moveCaretToEndOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the first row:
case KeyEvent.VK_PAGE_UP: {
if (pageUpKeyEnabled) {
moveCaretToFirstLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the last row:
case KeyEvent.VK_PAGE_DOWN: {
if (pageDownKeyEnabled) {
moveCaretToLastLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Erase the current character:
case KeyEvent.VK_DELETE: {
if (deleteKeyEnabled) {
clearCurrentCell();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position to the left:
case KeyEvent.VK_LEFT: {
if (leftArrowKeyEnabled) {
boolean moveToPreviousLine = x_index_caret_actual == 0;
moveToPreviousLine &= y_index_caret_actual > 0;
if (moveToPreviousLine) {
moveCaretUp();
moveCaretToEndOfLine();
} else {
moveCaretLeft();
}
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position to the right:
case KeyEvent.VK_RIGHT: {
if (isRightArrowKeyEnabled()) {
boolean moveToNextLine = x_index_caret_actual == maxHorizontalCharacters - 1;
moveToNextLine &= y_index_caret_actual < maxVerticalCharacters - 1;
if (moveToNextLine) {
moveCaretDown();
moveCaretToStartOfLine();
} else {
moveCaretRight();
}
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position up:
case KeyEvent.VK_UP: {
if (upArrowKeyEnabled) {
moveCaretUp();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret one position down:
case KeyEvent.VK_DOWN: {
if (downArrowKeyEnabled) {
moveCaretDown();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Move the caret to the first position of the next row:
case KeyEvent.VK_ENTER: {
boolean canWork = enterKeyEnabled;
canWork &= y_index_caret_actual < maxVerticalCharacters - 1;
if (canWork) {
moveCaretDown();
moveCaretToStartOfLine();
updateDisplayedCharacters();
transmitDraw();
}
break;
}
// Delete the character to the left of the caret, then move the caret one position left:
case KeyEvent.VK_BACK_SPACE: {
if (! backSpaceKeyEnabled) {
break;
}
final boolean caretAtStartOfLine = x_index_caret_actual == 0;
final boolean caretAtEndOfLine = x_index_caret_actual == maxHorizontalCharacters - 1;
if (caretAtStartOfLine) {
if (y_index_caret_actual > 0) {
moveCaretUp();
moveCaretToEndOfLine();
}
} else if (caretAtEndOfLine) {
final AsciiCharacter currentChar = TextArea.super.getStrings()[y_index_caret_visual].getCharacters()[x_index_caret_visual];
if (currentChar.getCharacter() == ' ') {
moveCaretLeft();
}
} else {
moveCaretLeft();
}
clearCurrentCell();
updateDisplayedCharacters();
transmitDraw();
break;
}
case KeyEvent.VK_TAB: {
if (tabKeyEnabled) {
for (int i = 0 ; i < tabSize ; i++) {
if (i < maxHorizontalCharacters - 1) {
moveCaretRight();
}
}
}
updateDisplayedCharacters();
transmitDraw();
break;
}
}
}
}
};
super.getEventListeners().add(keyListener);
}
/** Moves the caret one cell up. */
public void moveCaretUp() {
if (y_index_caret_visual > 0) {
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual - 1);
}
if (y_index_caret_actual > 0) {
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual - 1);
}
}
/** Moves the caret one cell down. */
public void moveCaretDown() {
if (y_index_caret_visual < super.getHeight() - 1) {
changeVisualCaretPosition(x_index_caret_visual, y_index_caret_visual + 1);
}
if (y_index_caret_actual < maxVerticalCharacters - 1) {
changeActualCaretPosition(x_index_caret_actual, y_index_caret_actual + 1);
}
}
/** Moves the caret one cell left. */
public void moveCaretLeft() {
if (x_index_caret_visual > 0) {
changeVisualCaretPosition(x_index_caret_visual - 1, y_index_caret_visual);
}
if (x_index_caret_actual > 0) {
changeActualCaretPosition(x_index_caret_actual - 1, y_index_caret_actual);
}
}
/** Moves the caret one cell right. */
public void moveCaretRight() {
if (x_index_caret_visual < super.getWidth() - 1) {
changeVisualCaretPosition(x_index_caret_visual + 1, y_index_caret_visual);
}
if (x_index_caret_actual < maxHorizontalCharacters - 1) {
changeActualCaretPosition(x_index_caret_actual + 1, y_index_caret_actual);
}
}
/** Moves the caret to the first line. Does not change the x-axis position of the caret. */
public void moveCaretToFirstLine() {
changeVisualCaretPosition(x_index_caret_visual, 0);
changeActualCaretPosition(x_index_caret_visual, 0);
}
/** Moves the caret to the last line. Does not change the x-axis position of the caret. */
public void moveCaretToLastLine() {
changeVisualCaretPosition(x_index_caret_visual, super.getHeight() - 1);
changeActualCaretPosition(x_index_caret_visual, super.getHeight() - 1);
}
/** Moves the caret to the beginning of the current line. */
public void moveCaretToStartOfLine() {
changeVisualCaretPosition(0, y_index_caret_visual);
changeActualCaretPosition(0, y_index_caret_actual);
}
/** Moves the caret to the end of the current line. */
public void moveCaretToEndOfLine() {
changeVisualCaretPosition(super.getWidth() - 1, y_index_caret_visual);
changeActualCaretPosition(maxHorizontalCharacters - 1, y_index_caret_actual);
}
/** Deletes the character in the current cell. */
public void clearCurrentCell() {
changeVisualCharacter(x_index_caret_visual, y_index_caret_visual, ' ');
changeActualCharacter(x_index_caret_actual, y_index_caret_actual, ' ');
}
/**
* Moves the visual caret to the specified location.
*
* @param newColumnIndex
* The new column index for the caret.
*
* @param newRowIndex
* The new row index for the caret.
*/
private void changeVisualCaretPosition(final int newColumnIndex, final int newRowIndex) {
final Radio<String> radio = super.getRadio();
// Reset current position's fore/background:
AsciiCharacter[] characters = super.getString(y_index_caret_visual).getCharacters();
characters[x_index_caret_visual].setForegroundColor(foregroundColor);
characters[x_index_caret_visual].setBackgroundColor(backgroundColor);
if (radio != null) {
// Reset current position's blink/hidden state:
characters[x_index_caret_visual].disableBlinkEffect();
characters[x_index_caret_visual].setHidden(false);
}
// Set new position's fore/background:
characters = super.getString(newRowIndex).getCharacters();
characters[newColumnIndex].setForegroundColor(caretForegroundColor);
characters[newColumnIndex].setBackgroundColor(caretBackgroundColor);
if (radio != null) {
// Set new position's blink state:
characters[newColumnIndex].enableBlinkEffect((short) 1000, radio);
}
x_index_caret_visual = newColumnIndex;
y_index_caret_visual = newRowIndex;
}
/**
* Moves the actual caret to the specified location.
*
* @param newColumnIndex
* The new column index for the caret.
*
* @param newRowIndex
* The new row index for the caret.
*/
private void changeActualCaretPosition(final int newColumnIndex, final int newRowIndex) {
x_index_caret_actual = newColumnIndex;
y_index_caret_actual = newRowIndex;
}
/**
* Changes the visual character at the specified location.
*
* @param columnIndex
* The column index.
*
* @param rowIndex
* The row index.
*
* @param character
* The new character.
*/
private void changeVisualCharacter(final int columnIndex, final int rowIndex, final char character) {
final AsciiCharacter[] characters = super.getString(rowIndex).getCharacters();
characters[columnIndex].setCharacter(character);
}
/**
* Changes the actual character at the specified index.
*
* @param columnIndex
* The column index.
*
* @param rowIndex
* The row index.
*
* @param character
* The new character.
*/
private void changeActualCharacter(final int columnIndex, final int rowIndex, final char character) {
if (columnIndex < 0 || columnIndex > maxHorizontalCharacters) {
return;
}
if (rowIndex < 0 || rowIndex > maxVerticalCharacters) {
return;
}
enteredText[rowIndex][columnIndex] = character;
}
private void updateDisplayedCharacters() {
final int xDifference = x_index_caret_actual - x_index_caret_visual;
final int yDifference = y_index_caret_actual - y_index_caret_visual;
for (int y = yDifference ; y < super.getHeight() + yDifference ; y++) {
final AsciiString string = super.getString(y - yDifference);
final AsciiCharacter[] characters = string.getCharacters();
for (int x = xDifference ; x < super.getWidth() + xDifference ; x++) {
characters[x - xDifference].setCharacter(enteredText[y][x]);
}
}
}
/**
* Sets the text contained within a row of the area.
*
* @param rowIndex
* The row index.
*
* @param text
* The text.
*
* @throws NullPointerException
* If the text is null.
*/
public void setText(final int rowIndex, @NonNull String text) {
if (text.length() > maxHorizontalCharacters) {
text = text.substring(0, maxHorizontalCharacters);
}
System.arraycopy(text.toCharArray(), 0, enteredText[rowIndex], 0, text.length());
}
/**
* Sets the text contained within the area.
*
* Clears the field before setting.
*
* @param text
* The list of text.
*
* @throws NullPointerException
* If the text is null.
*/
public void setText(final @NonNull List<String> text) {
clearText();
for (int i = 0 ; i < text.size() && i < maxVerticalCharacters ; i++) {
setText(i, text.get(i));
}
}
/** @return The text contained within the area. */
public String[] getText() {
final String[] strings = new String[super.getHeight()];
String temp = "";
for (int i = 0 ; i < super.getHeight() ; i++) {
for (final char c : enteredText[i]) {
temp += c;
}
strings[i] = temp;
temp = "";
}
return strings;
}
/**
* Clears text from a row.
*
* @param rowIndex
* The row index,
*
* @throws java.lang.IllegalArgumentException
* If the row index is below zero.
* If the row index exceeds the TextArea's height.
*/
public void clearText(final int rowIndex) {
if (rowIndex < 0) {
throw new IllegalArgumentException("The row index cannot be below 0.");
}
if (rowIndex > super.getHeight()) {
throw new IllegalArgumentException("The row index cannot be above " + super.getHeight() +".");
}
Arrays.fill(enteredText[rowIndex], ' ');
if (y_index_caret_actual == y_index_caret_visual && y_index_caret_actual == rowIndex) {
for (final AsciiCharacter character : super.getString(rowIndex).getCharacters()) {
character.setCharacter(' ');
}
}
}
/** Clears all text from the field. */
public void clearText() {
for (int i = 0 ; i < enteredText.length ; i++) {
Arrays.fill(enteredText[i], ' ');
}
for (final AsciiString string : super.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
character.setCharacter(' ');
}
}
}
}
| Fixes logic errors in the move to first/last line functions.
| src/com/valkryst/VTerminal/component/TextArea.java | Fixes logic errors in the move to first/last line functions. |
|
Java | apache-2.0 | 2435d8e9abae79ae75a50f835ad051868055b60e | 0 | santhosh-tekuri/jlibs,santhosh-tekuri/jlibs | /**
* JLibs: Common Utilities for Java
* Copyright (C) 2009 Santhosh Kumar T <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*/
package jlibs.core.nio.channels;
import jlibs.core.nio.AttachmentSupport;
import jlibs.core.nio.ClientChannel;
import jlibs.core.nio.SelectableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.WritableByteChannel;
/**
* @author Santhosh Kumar T
*/
public abstract class OutputChannel extends AttachmentSupport implements WritableByteChannel{
protected final SelectableByteChannel client;
protected final NIOSupport nioSupport;
protected OutputChannel(SelectableByteChannel client, NIOSupport nioSupport){
this.client = client;
this.nioSupport = nioSupport;
if(!(client.attachment() instanceof IOChannelHandler))
client.attach(nioSupport.createHandler());
clientHandler().output = this;
}
public final ClientChannel client(){
return (ClientChannel)client;
}
protected IOChannelHandler clientHandler(){
return (IOChannelHandler)client.attachment();
}
private boolean statusInterested;
public final void addStatusInterest(){
statusInterested = true;
}
public final void removeStatusInterest(){
statusInterested = false;
}
private boolean writeInterested;
public final void addWriteInterest(){
if(status()!=Status.NEEDS_OUTPUT){
if(handler!=null){
handler.onWrite(this);
}
}else
writeInterested = true;
}
protected abstract boolean activateInterest();
public void removeWriteInterest() throws IOException{
writeInterested = false;
if(status()!=Status.NEEDS_OUTPUT)
client.removeInterest(SelectionKey.OP_WRITE);
}
protected OutputHandler handler;
public void setHandler(OutputHandler handler){
this.handler = handler;
}
@Override
public final int write(ByteBuffer src) throws IOException{
if(src.remaining()==0 || status()==Status.NEEDS_OUTPUT)
return 0;
try{
int wrote = onWrite(src);
if(wrote>0)
onWrite();
return wrote;
}catch(IOException ex){
onIOException();
throw ex;
}
}
protected abstract int onWrite(ByteBuffer src) throws IOException;
protected void onIOException(){}
private boolean closed;
@Override
public final boolean isOpen(){
return !closed;
}
@Override
public final void close() throws IOException{
closed = true;
writeInterested = false;
doClose();
onWrite();
}
protected void doClose() throws IOException{}
protected final void onWrite() throws IOException{
Status earlierStatus = status();
if(earlierStatus==Status.NEEDS_OUTPUT)
writePending();
Status curStatus = status();
if(curStatus==Status.NEEDS_OUTPUT)
client.addInterest(SelectionKey.OP_WRITE);
else
notifyCompleted(earlierStatus, curStatus);
}
protected abstract void writePending() throws IOException;
public abstract Status status();
protected void notifyCompleted(Status earlierStatus, Status curStatus){
if(clientHandler().output==this && !isOpen() && curStatus==Status.COMPLETED) // favor GC
clientHandler().output = null;
if(statusInterested){
statusInterested = false;
if(earlierStatus!=curStatus && handler!=null)
handler.onStatus(this);
}
if(writeInterested){
writeInterested = false;
if(handler!=null && isOpen())
handler.onWrite(this);
}
}
@Override
public String toString(){
return getClass().getSimpleName()+'('+client+')';
}
public enum Status{ NEEDS_INPUT, NEEDS_OUTPUT, COMPLETED }
}
| core/src/main/java/jlibs/core/nio/channels/OutputChannel.java | /**
* JLibs: Common Utilities for Java
* Copyright (C) 2009 Santhosh Kumar T <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*/
package jlibs.core.nio.channels;
import jlibs.core.nio.AttachmentSupport;
import jlibs.core.nio.ClientChannel;
import jlibs.core.nio.SelectableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.WritableByteChannel;
/**
* @author Santhosh Kumar T
*/
public abstract class OutputChannel extends AttachmentSupport implements WritableByteChannel{
protected final SelectableByteChannel client;
protected final NIOSupport nioSupport;
protected OutputChannel(SelectableByteChannel client, NIOSupport nioSupport){
this.client = client;
this.nioSupport = nioSupport;
if(!(client.attachment() instanceof IOChannelHandler))
client.attach(nioSupport.createHandler());
clientHandler().output = this;
}
public final ClientChannel client(){
return (ClientChannel)client;
}
protected IOChannelHandler clientHandler(){
return (IOChannelHandler)client.attachment();
}
private boolean statusInterested;
public final void addStatusInterest(){
statusInterested = true;
}
public final void removeStatusInterest(){
statusInterested = false;
}
private boolean writeInterested;
public final void addWriteInterest(){
if(status()!=Status.NEEDS_OUTPUT){
if(handler!=null){
handler.onWrite(this);
}
}else
writeInterested = true;
}
protected abstract boolean activateInterest();
public void removeWriteInterest() throws IOException{
writeInterested = false;
if(status()!=Status.NEEDS_OUTPUT)
client.removeInterest(SelectionKey.OP_WRITE);
}
protected OutputHandler handler;
public void setHandler(OutputHandler handler){
this.handler = handler;
}
@Override
public final int write(ByteBuffer src) throws IOException{
if(src.remaining()==0 || status()==Status.NEEDS_OUTPUT)
return 0;
try{
int wrote = onWrite(src);
if(wrote>0)
onWrite();
return wrote;
}catch(IOException ex){
onIOException();
throw ex;
}
}
protected abstract int onWrite(ByteBuffer src) throws IOException;
protected void onIOException(){}
private boolean closed;
@Override
public final boolean isOpen(){
return !closed;
}
@Override
public final void close() throws IOException{
closed = true;
writeInterested = false;
doClose();
onWrite();
}
protected void doClose() throws IOException{}
protected final void onWrite() throws IOException{
Status earlierStatus = status();
if(earlierStatus==Status.NEEDS_OUTPUT)
writePending();
Status curStatus = status();
if(curStatus==Status.NEEDS_OUTPUT)
client.addInterest(SelectionKey.OP_WRITE);
else
notifyCompleted(earlierStatus, curStatus);
}
protected abstract void writePending() throws IOException;
public abstract Status status();
protected void notifyCompleted(Status earlierStatus, Status curStatus){
OutputChannel output = clientHandler().output;
if(output==this && !isOpen() && curStatus==Status.COMPLETED) // favor GC
clientHandler().output = null;
if(output.statusInterested){
output.statusInterested = false;
if(earlierStatus!=curStatus && output.handler!=null)
output.handler.onStatus(output);
}
if(output.writeInterested){
output.writeInterested = false;
if(output.handler!=null)
output.handler.onWrite(output);
}
}
@Override
public String toString(){
return getClass().getSimpleName()+'('+client+')';
}
public enum Status{ NEEDS_INPUT, NEEDS_OUTPUT, COMPLETED }
}
| notify only the handler that is registered to this | core/src/main/java/jlibs/core/nio/channels/OutputChannel.java | notify only the handler that is registered to this |
|
Java | apache-2.0 | 6f9416a61c6dc66fcb6c31d2815fc2f27ec7a7ce | 0 | magi42/vaadin,carrchang/vaadin,travisfw/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,kironapublic/vaadin,travisfw/vaadin,kironapublic/vaadin,mittop/vaadin,synes/vaadin,travisfw/vaadin,fireflyc/vaadin,asashour/framework,carrchang/vaadin,Darsstar/framework,jdahlstrom/vaadin.react,peterl1084/framework,carrchang/vaadin,Peppe/vaadin,sitexa/vaadin,synes/vaadin,Scarlethue/vaadin,udayinfy/vaadin,Flamenco/vaadin,bmitc/vaadin,Flamenco/vaadin,udayinfy/vaadin,shahrzadmn/vaadin,Peppe/vaadin,shahrzadmn/vaadin,sitexa/vaadin,mstahv/framework,mittop/vaadin,udayinfy/vaadin,magi42/vaadin,Flamenco/vaadin,fireflyc/vaadin,synes/vaadin,Flamenco/vaadin,jdahlstrom/vaadin.react,jdahlstrom/vaadin.react,peterl1084/framework,asashour/framework,kironapublic/vaadin,synes/vaadin,Peppe/vaadin,sitexa/vaadin,cbmeeks/vaadin,magi42/vaadin,udayinfy/vaadin,Peppe/vaadin,Darsstar/framework,oalles/vaadin,fireflyc/vaadin,bmitc/vaadin,cbmeeks/vaadin,Darsstar/framework,mstahv/framework,magi42/vaadin,Scarlethue/vaadin,oalles/vaadin,bmitc/vaadin,oalles/vaadin,fireflyc/vaadin,peterl1084/framework,Scarlethue/vaadin,jdahlstrom/vaadin.react,Legioth/vaadin,Legioth/vaadin,travisfw/vaadin,mstahv/framework,asashour/framework,sitexa/vaadin,shahrzadmn/vaadin,shahrzadmn/vaadin,asashour/framework,peterl1084/framework,udayinfy/vaadin,Peppe/vaadin,oalles/vaadin,Legioth/vaadin,Darsstar/framework,Legioth/vaadin,oalles/vaadin,asashour/framework,Darsstar/framework,synes/vaadin,bmitc/vaadin,sitexa/vaadin,jdahlstrom/vaadin.react,mittop/vaadin,peterl1084/framework,travisfw/vaadin,cbmeeks/vaadin,kironapublic/vaadin,cbmeeks/vaadin,carrchang/vaadin,Scarlethue/vaadin,magi42/vaadin,kironapublic/vaadin,Legioth/vaadin,fireflyc/vaadin,mittop/vaadin,mstahv/framework,mstahv/framework | package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.Vector;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.KeyboardListenerCollection;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollListener;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
/**
* "Sub window" component.
*
* TODO update position / scrollposition / size to client
*
* @author IT Mill Ltd
*/
public class IWindow extends PopupPanel implements Paintable, ScrollListener {
private static final int DEFAULT_HEIGHT = 300;
private static final int DEFAULT_WIDTH = 400;
private static Vector windowOrder = new Vector();
public static final String CLASSNAME = "i-window";
/** pixels used by inner borders and paddings horizontally */
protected static final int BORDER_WIDTH_HORIZONTAL = 41;
/** pixels used by headers, footers, inner borders and paddings vertically */
protected static final int BORDER_WIDTH_VERTICAL = 58;
private static final int STACKING_OFFSET_PIXELS = 15;
private static final int Z_INDEX_BASE = 10000;
private Paintable layout;
private Element contents;
private Element header;
private Element footer;
private Element resizeBox;
private ScrollPanel contentPanel = new ScrollPanel();
private boolean dragging;
private int startX;
private int startY;
private int origX;
private int origY;
private boolean resizing;
private int origW;
private int origH;
private Element closeBox;
protected ApplicationConnection client;
private String id;
ShortcutActionHandler shortcutHandler;
/** Last known width read from UIDL or updated to application connection */
private int uidlWidth = -1;
/** Last known height read from UIDL or updated to application connection */
private int uidlHeight = -1;
/** Last known positionx read from UIDL or updated to application connection */
private int uidlPositionX = -1;
/** Last known positiony read from UIDL or updated to application connection */
private int uidlPositionY = -1;
public IWindow() {
super();
int order = windowOrder.size();
setWindowOrder(order);
windowOrder.add(this);
setStyleName(CLASSNAME);
constructDOM();
setPopupPosition(order * STACKING_OFFSET_PIXELS, order
* STACKING_OFFSET_PIXELS);
contentPanel.addScrollListener(this);
}
private void bringToFront() {
int curIndex = windowOrder.indexOf(this);
if (curIndex + 1 < windowOrder.size()) {
windowOrder.remove(this);
windowOrder.add(this);
for (; curIndex < windowOrder.size(); curIndex++) {
((IWindow) windowOrder.get(curIndex)).setWindowOrder(curIndex);
}
}
}
/**
* Returns true if window is the topmost window
*
* @return
*/
private boolean isActive() {
return windowOrder.lastElement().equals(this);
}
public void setWindowOrder(int order) {
DOM.setStyleAttribute(getElement(), "zIndex", ""
+ (order + Z_INDEX_BASE));
}
protected void constructDOM() {
header = DOM.createDiv();
DOM.setElementProperty(header, "className", CLASSNAME + "-header");
contents = DOM.createDiv();
DOM.setElementProperty(contents, "className", CLASSNAME + "-contents");
footer = DOM.createDiv();
DOM.setElementProperty(footer, "className", CLASSNAME + "-footer");
resizeBox = DOM.createDiv();
DOM
.setElementProperty(resizeBox, "className", CLASSNAME
+ "-resizebox");
closeBox = DOM.createDiv();
DOM.setElementProperty(closeBox, "className", CLASSNAME + "-closebox");
DOM.appendChild(footer, resizeBox);
DOM.sinkEvents(header, Event.MOUSEEVENTS);
DOM.sinkEvents(resizeBox, Event.MOUSEEVENTS);
DOM.sinkEvents(closeBox, Event.ONCLICK);
DOM.sinkEvents(contents, Event.ONCLICK);
Element wrapper = DOM.createDiv();
DOM.setElementProperty(wrapper, "className", CLASSNAME + "-wrap");
Element wrapper2 = DOM.createDiv();
DOM.setElementProperty(wrapper2, "className", CLASSNAME + "-wrap2");
DOM.sinkEvents(wrapper, Event.ONKEYDOWN);
DOM.appendChild(wrapper2, closeBox);
DOM.appendChild(wrapper2, header);
DOM.appendChild(wrapper2, contents);
DOM.appendChild(wrapper2, footer);
DOM.appendChild(wrapper, wrapper2);
DOM.appendChild(getElement(), wrapper);
setWidget(contentPanel);
// set default size
setWidth(DEFAULT_WIDTH + "px");
setHeight(DEFAULT_HEIGHT + "px");
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.id = uidl.getId();
this.client = client;
if (uidl.hasAttribute("invisible")) {
this.hide();
return;
}
if (client.updateComponent(this, uidl, false))
return;
// Initialize the width from UIDL
if (uidl.hasVariable("width")) {
String width = uidl.getStringVariable("width");
setWidth(width);
}
if (uidl.hasVariable("height")) {
String height = uidl.getStringVariable("height");
setHeight(height);
}
contentPanel.setScrollPosition(uidl.getIntVariable("scrolltop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollleft"));
// Initialize the position form UIDL
try {
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 && positiony >= 0) {
setPopupPosition(positionx, positiony);
}
} catch (IllegalArgumentException e) {
// Silently ignored as positionx and positiony are not required
// parameters
}
if (!isAttached()) {
show();
}
UIDL childUidl = uidl.getChildUIDL(0);
Paintable lo = (Paintable) client.getWidget(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
contentPanel.setWidget((Widget) lo);
layout = lo;
}
} else {
contentPanel.setWidget((Widget) lo);
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"));
}
lo.updateFromUIDL(childUidl, client);
// we may have actions
if (uidl.getChidlCount() > 1) {
childUidl = uidl.getChildUIDL(1);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null)
shortcutHandler = new ShortcutActionHandler(id, client);
shortcutHandler.updateActionMap(childUidl);
}
}
}
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (left != uidlPositionX && client != null) {
client.updateVariable(id, "positionx", left, false);
uidlPositionX = left;
}
if (top != uidlPositionY && client != null) {
client.updateVariable(id, "positiony", top, false);
uidlPositionY = top;
}
}
public void setCaption(String c) {
DOM.setInnerText(header, c);
}
protected Element getContainerElement() {
return contents;
}
public void onBrowserEvent(Event event) {
int type = DOM.eventGetType(event);
if (type == Event.ONKEYDOWN && shortcutHandler != null) {
int modifiers = KeyboardListenerCollection
.getKeyboardModifiers(event);
shortcutHandler.handleKeyboardEvent((char) DOM
.eventGetKeyCode(event), modifiers);
return;
}
if (!isActive()) {
bringToFront();
}
Element target = DOM.eventGetTarget(event);
if (dragging || DOM.compare(header, target)) {
onHeaderEvent(event);
DOM.eventCancelBubble(event, true);
} else if (resizing || DOM.compare(resizeBox, target)) {
onResizeEvent(event);
DOM.eventCancelBubble(event, true);
} else if (DOM.compare(target, closeBox) && type == Event.ONCLICK) {
onCloseClick();
DOM.eventCancelBubble(event, true);
}
}
private void onCloseClick() {
client.updateVariable(id, "close", true, true);
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
resizing = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origW = DOM.getIntStyleAttribute(getElement(), "width")
- BORDER_WIDTH_HORIZONTAL;
origH = getWidget().getOffsetHeight();
DOM.addEventPreview(this);
break;
case Event.ONMOUSEUP:
resizing = false;
DOM.removeEventPreview(this);
setSize(event, true);
break;
case Event.ONMOUSEMOVE:
if (resizing) {
setSize(event, false);
DOM.eventPreventDefault(event);
}
break;
default:
DOM.eventPreventDefault(event);
break;
}
}
public void setSize(Event event, boolean updateVariables) {
int w = DOM.eventGetScreenX(event) - startX + origW;
if (w < 60)
w = 60;
int h = DOM.eventGetScreenY(event) - startY + origH;
if (h < 60)
h = 60;
setWidth(w + "px");
setHeight(h + "px");
if (updateVariables) {
// sending width back always as pixels, no need for unit
client.updateVariable(id, "width", w, false);
client.updateVariable(id, "height", h, false);
}
// Update child widget dimensions
Util.runAncestorsLayout(this);
}
public void setWidth(String width) {
DOM.setStyleAttribute(getElement(), "width", (Integer.parseInt(width
.substring(0, width.length() - 2)) + BORDER_WIDTH_HORIZONTAL)
+ "px");
}
private void onHeaderEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
dragging = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origX = DOM.getAbsoluteLeft(getElement());
origY = DOM.getAbsoluteTop(getElement());
DOM.eventPreventDefault(event);
DOM.addEventPreview(this);
break;
case Event.ONMOUSEUP:
dragging = false;
DOM.removeEventPreview(this);
break;
case Event.ONMOUSEMOVE:
if (dragging) {
int x = DOM.eventGetScreenX(event) - startX + origX;
int y = DOM.eventGetScreenY(event) - startY + origY;
this.setPopupPosition(x, y);
DOM.eventPreventDefault(event);
}
break;
default:
break;
}
}
public boolean onEventPreview(Event event) {
if (dragging) {
onHeaderEvent(event);
return false;
} else if (resizing) {
onResizeEvent(event);
return false;
}
// TODO return false when modal
return true;
}
public void onScroll(Widget widget, int scrollLeft, int scrollTop) {
client.updateVariable(id, "scrolltop", scrollTop, false);
client.updateVariable(id, "scrollleft", scrollLeft, false);
}
}
| src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java | package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.Vector;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.KeyboardListenerCollection;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollListener;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
/**
* "Sub window" component.
*
* TODO update position / scrollposition / size to client
*
* @author IT Mill Ltd
*/
public class IWindow extends PopupPanel implements Paintable, ScrollListener {
private static final int DEFAULT_HEIGHT = 300;
private static final int DEFAULT_WIDTH = 400;
private static Vector windowOrder = new Vector();
public static final String CLASSNAME = "i-window";
/** pixels used by inner borders and paddings horizontally */
protected static final int BORDER_WIDTH_HORIZONTAL = 41;
/** pixels used by headers, footers, inner borders and paddings vertically */
protected static final int BORDER_WIDTH_VERTICAL = 58;
private static final int STACKING_OFFSET_PIXELS = 15;
private static final int Z_INDEX_BASE = 10000;
private Paintable layout;
private Element contents;
private Element header;
private Element footer;
private Element resizeBox;
private ScrollPanel contentPanel = new ScrollPanel();
private boolean dragging;
private int startX;
private int startY;
private int origX;
private int origY;
private boolean resizing;
private int origW;
private int origH;
private Element closeBox;
protected ApplicationConnection client;
private String id;
ShortcutActionHandler shortcutHandler;
/** Last known width read from UIDL or updated to application connection */
private int uidlWidth = -1;
/** Last known height read from UIDL or updated to application connection */
private int uidlHeight = -1;
/** Last known positionx read from UIDL or updated to application connection */
private int uidlPositionX = -1;
/** Last known positiony read from UIDL or updated to application connection */
private int uidlPositionY = -1;
public IWindow() {
super();
int order = windowOrder.size();
setWindowOrder(order);
windowOrder.add(this);
setStyleName(CLASSNAME);
constructDOM();
setPopupPosition(order * STACKING_OFFSET_PIXELS, order
* STACKING_OFFSET_PIXELS);
contentPanel.addScrollListener(this);
}
private void bringToFront() {
int curIndex = windowOrder.indexOf(this);
if (curIndex + 1 < windowOrder.size()) {
windowOrder.remove(this);
windowOrder.add(this);
for (; curIndex < windowOrder.size(); curIndex++) {
((IWindow) windowOrder.get(curIndex)).setWindowOrder(curIndex);
}
}
}
/**
* Returns true if window is the topmost window
*
* @return
*/
private boolean isActive() {
return windowOrder.lastElement().equals(this);
}
public void setWindowOrder(int order) {
DOM.setStyleAttribute(getElement(), "zIndex", ""
+ (order + Z_INDEX_BASE));
}
protected void constructDOM() {
header = DOM.createDiv();
DOM.setElementProperty(header, "className", CLASSNAME + "-header");
contents = DOM.createDiv();
DOM.setElementProperty(contents, "className", CLASSNAME + "-contents");
footer = DOM.createDiv();
DOM.setElementProperty(footer, "className", CLASSNAME + "-footer");
resizeBox = DOM.createDiv();
DOM
.setElementProperty(resizeBox, "className", CLASSNAME
+ "-resizebox");
closeBox = DOM.createDiv();
DOM.setElementProperty(closeBox, "className", CLASSNAME + "-closebox");
DOM.appendChild(footer, resizeBox);
DOM.sinkEvents(header, Event.MOUSEEVENTS);
DOM.sinkEvents(resizeBox, Event.MOUSEEVENTS);
DOM.sinkEvents(closeBox, Event.ONCLICK);
DOM.sinkEvents(contents, Event.ONCLICK);
Element wrapper = DOM.createDiv();
DOM.setElementProperty(wrapper, "className", CLASSNAME + "-wrap");
Element wrapper2 = DOM.createDiv();
DOM.setElementProperty(wrapper2, "className", CLASSNAME + "-wrap2");
DOM.sinkEvents(wrapper, Event.ONKEYDOWN);
DOM.appendChild(wrapper2, closeBox);
DOM.appendChild(wrapper2, header);
DOM.appendChild(wrapper2, contents);
DOM.appendChild(wrapper2, footer);
DOM.appendChild(wrapper, wrapper2);
DOM.appendChild(getElement(), wrapper);
setWidget(contentPanel);
// set default size
setWidth(DEFAULT_WIDTH + "px");
setHeight(DEFAULT_HEIGHT + "px");
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.id = uidl.getId();
this.client = client;
if (uidl.hasAttribute("invisible")) {
this.hide();
return;
}
if (client.updateComponent(this, uidl, false))
return;
// Initialize the width from UIDL
if (uidl.hasVariable("width")) {
String width = uidl.getStringVariable("width");
setWidth(width);
}
if (uidl.hasVariable("height")) {
String height = uidl.getStringVariable("height");
setHeight(height);
}
contentPanel.setScrollPosition(uidl.getIntVariable("scrolltop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollleft"));
// Initialize the position form UIDL
try {
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 && positiony >= 0) {
setPopupPosition(positionx, positiony);
}
} catch (IllegalArgumentException e) {
// Silently ignored as positionx and positiony are not required
// parameters
}
if (!isAttached()) {
show();
}
UIDL childUidl = uidl.getChildUIDL(0);
Paintable lo = (Paintable) client.getWidget(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
contentPanel.setWidget((Widget) lo);
layout = lo;
}
} else {
contentPanel.setWidget((Widget) lo);
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"));
}
lo.updateFromUIDL(childUidl, client);
// we may have actions
if (uidl.getChidlCount() > 1) {
childUidl = uidl.getChildUIDL(1);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null)
shortcutHandler = new ShortcutActionHandler(id, client);
shortcutHandler.updateActionMap(childUidl);
}
}
}
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (left != uidlPositionX && client != null) {
client.updateVariable(id, "positionx", left, false);
uidlPositionX = left;
}
if (top != uidlPositionY && client != null) {
client.updateVariable(id, "positiony", top, false);
uidlPositionY = top;
}
}
public void setCaption(String c) {
DOM.setInnerText(header, c);
}
protected Element getContainerElement() {
return contents;
}
public void onBrowserEvent(Event event) {
int type = DOM.eventGetType(event);
if (type == Event.ONKEYDOWN && shortcutHandler != null) {
int modifiers = KeyboardListenerCollection
.getKeyboardModifiers(event);
shortcutHandler.handleKeyboardEvent((char) DOM
.eventGetKeyCode(event), modifiers);
return;
}
if (!isActive()) {
bringToFront();
}
Element target = DOM.eventGetTarget(event);
if (dragging || DOM.compare(header, target)) {
onHeaderEvent(event);
DOM.eventCancelBubble(event, true);
} else if (resizing || DOM.compare(resizeBox, target)) {
onResizeEvent(event);
DOM.eventCancelBubble(event, true);
} else if (DOM.compare(target, closeBox) && type == Event.ONCLICK) {
onCloseClick();
DOM.eventCancelBubble(event, true);
}
}
private void onCloseClick() {
client.updateVariable(id, "close", true, true);
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
resizing = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origW = DOM.getIntStyleAttribute(getElement(), "width")
- BORDER_WIDTH_HORIZONTAL;
origH = getWidget().getOffsetHeight();
DOM.addEventPreview(this);
break;
case Event.ONMOUSEUP:
resizing = false;
DOM.removeEventPreview(this);
setSize(event, true);
break;
case Event.ONMOUSEMOVE:
if (resizing) {
setSize(event, false);
DOM.eventPreventDefault(event);
}
break;
default:
DOM.eventPreventDefault(event);
break;
}
}
public void setSize(Event event, boolean updateVariables) {
int w = DOM.eventGetScreenX(event) - startX + origW;
if (w < 60)
w = 60;
int h = DOM.eventGetScreenY(event) - startY + origH;
if (h < 60)
h = 60;
setWidth(w + "px");
setHeight(h + "px");
if (updateVariables) {
// sending width back always as pixels, no need for unit
client.updateVariable(id, "width", w, false);
client.updateVariable(id, "height", h, false);
}
// Update child widget dimensions
Util.runAncestorsLayout(this);
}
public void setWidth(String width) {
DOM.setStyleAttribute(getElement(), "width", (Integer.parseInt(width
.substring(0, width.length() - 2)) + BORDER_WIDTH_HORIZONTAL)
+ "px");
}
private void onHeaderEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
dragging = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origX = DOM.getAbsoluteLeft(getElement());
origY = DOM.getAbsoluteTop(getElement());
DOM.addEventPreview(this);
break;
case Event.ONMOUSEUP:
dragging = false;
DOM.removeEventPreview(this);
break;
case Event.ONMOUSEMOVE:
if (dragging) {
int x = DOM.eventGetScreenX(event) - startX + origX;
int y = DOM.eventGetScreenY(event) - startY + origY;
this.setPopupPosition(x, y);
DOM.eventPreventDefault(event);
}
break;
default:
break;
}
}
public boolean onEventPreview(Event event) {
if (dragging) {
onHeaderEvent(event);
return false;
} else if (resizing) {
onResizeEvent(event);
return false;
}
// TODO return false when modal
return true;
}
public void onScroll(Widget widget, int scrollLeft, int scrollTop) {
client.updateVariable(id, "scrolltop", scrollTop, false);
client.updateVariable(id, "scrollleft", scrollLeft, false);
}
}
| fixes #1007
svn changeset:2613/svn branch:trunk
| src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java | fixes #1007 |
|
Java | apache-2.0 | 18725a993906c8b394773a7938450d2c618a848c | 0 | PkayJava/pluggable,PkayJava/pluggable | package com.itrustcambodia.pluggable.quartz;
import java.util.Date;
import org.springframework.jdbc.core.JdbcTemplate;
import com.itrustcambodia.pluggable.core.AbstractPlugin;
import com.itrustcambodia.pluggable.core.AbstractWebApplication;
import com.itrustcambodia.pluggable.database.EntityRowMapper;
import com.itrustcambodia.pluggable.utilities.TableUtilities;
/**
* @author Socheat KHAUV
*/
public abstract class Job {
// private static final Logger LOGGER = LoggerFactory.getLogger(Job.class);
private AbstractWebApplication application;
public final void execute() {
if (!application.isMigrated()) {
return;
}
AbstractPlugin plugin = application.getPlugin(application
.getPluginMapping(this.getClass().getName()));
if (plugin != null) {
if (!plugin.isMigrated() || !plugin.isActivated()) {
return;
}
}
JdbcTemplate jdbcTemplate = application.getJdbcTemplate();
com.itrustcambodia.pluggable.entity.Job job = jdbcTemplate
.queryForObject(
"select * from "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
new EntityRowMapper<com.itrustcambodia.pluggable.entity.Job>(
com.itrustcambodia.pluggable.entity.Job.class),
this.getClass().getName());
if (job.isDisable()
|| job.isPause()
|| com.itrustcambodia.pluggable.entity.Job.Status.BUSY
.equals(job.getStatus())) {
return;
}
// LOGGER.info("job {}", this.getClass().getName());
jdbcTemplate
.update("update "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " set "
+ com.itrustcambodia.pluggable.entity.Job.STATUS
+ " = ? where "
+ com.itrustcambodia.pluggable.entity.Job.ID + " = ?",
com.itrustcambodia.pluggable.entity.Job.Status.BUSY,
this.getClass().getName());
try {
process(application);
jdbcTemplate
.update("update "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " set "
+ com.itrustcambodia.pluggable.entity.Job.STATUS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_PROCESS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_ERROR
+ " = ? where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
com.itrustcambodia.pluggable.entity.Job.Status.IDLE,
new Date(), "", this.getClass().getName());
job = jdbcTemplate
.queryForObject(
"select * from "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
new EntityRowMapper<com.itrustcambodia.pluggable.entity.Job>(
com.itrustcambodia.pluggable.entity.Job.class),
this.getClass().getName());
} catch (Throwable e) {
jdbcTemplate
.update("update "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " set "
+ com.itrustcambodia.pluggable.entity.Job.STATUS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_PROCESS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_ERROR
+ " = ? ,"
+ com.itrustcambodia.pluggable.entity.Job.PAUSE
+ " = ? where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
com.itrustcambodia.pluggable.entity.Job.Status.IDLE,
new Date(), e.getMessage(), true, this.getClass()
.getName());
}
}
public abstract void process(AbstractWebApplication application);
public AbstractWebApplication getApplication() {
return application;
}
public void setApplication(AbstractWebApplication application) {
this.application = application;
}
}
| src/main/java/com/itrustcambodia/pluggable/quartz/Job.java | package com.itrustcambodia.pluggable.quartz;
import java.util.Date;
import org.springframework.jdbc.core.JdbcTemplate;
import com.itrustcambodia.pluggable.core.AbstractPlugin;
import com.itrustcambodia.pluggable.core.AbstractWebApplication;
import com.itrustcambodia.pluggable.database.EntityRowMapper;
import com.itrustcambodia.pluggable.utilities.TableUtilities;
/**
* @author Socheat KHAUV
*/
public abstract class Job {
// private static final Logger LOGGER = LoggerFactory.getLogger(Job.class);
private AbstractWebApplication application;
public final void execute() {
if (!application.isMigrated()) {
return;
}
AbstractPlugin plugin = application.getPlugin(application
.getPluginMapping(this.getClass().getName()));
if (plugin != null) {
if (!plugin.isMigrated() || !plugin.isActivated()) {
return;
}
}
JdbcTemplate jdbcTemplate = application.getJdbcTemplate();
com.itrustcambodia.pluggable.entity.Job job = jdbcTemplate
.queryForObject(
"select * from "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
new EntityRowMapper<com.itrustcambodia.pluggable.entity.Job>(
com.itrustcambodia.pluggable.entity.Job.class),
this.getClass().getName());
if (job.isDisable() || job.isPause()) {
return;
}
// LOGGER.info("job {}", this.getClass().getName());
jdbcTemplate
.update("update "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " set "
+ com.itrustcambodia.pluggable.entity.Job.STATUS
+ " = ? where "
+ com.itrustcambodia.pluggable.entity.Job.ID + " = ?",
com.itrustcambodia.pluggable.entity.Job.Status.BUSY,
this.getClass().getName());
try {
process(application);
jdbcTemplate
.update("update "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " set "
+ com.itrustcambodia.pluggable.entity.Job.STATUS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_PROCESS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_ERROR
+ " = ? where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
com.itrustcambodia.pluggable.entity.Job.Status.IDLE,
new Date(), "", this.getClass().getName());
job = jdbcTemplate
.queryForObject(
"select * from "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
new EntityRowMapper<com.itrustcambodia.pluggable.entity.Job>(
com.itrustcambodia.pluggable.entity.Job.class),
this.getClass().getName());
} catch (Throwable e) {
jdbcTemplate
.update("update "
+ TableUtilities
.getTableName(com.itrustcambodia.pluggable.entity.Job.class)
+ " set "
+ com.itrustcambodia.pluggable.entity.Job.STATUS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_PROCESS
+ " = ?, "
+ com.itrustcambodia.pluggable.entity.Job.LAST_ERROR
+ " = ? ,"
+ com.itrustcambodia.pluggable.entity.Job.PAUSE
+ " = ? where "
+ com.itrustcambodia.pluggable.entity.Job.ID
+ " = ?",
com.itrustcambodia.pluggable.entity.Job.Status.IDLE,
new Date(), e.getMessage(), true, this.getClass()
.getName());
}
}
public abstract void process(AbstractWebApplication application);
public AbstractWebApplication getApplication() {
return application;
}
public void setApplication(AbstractWebApplication application) {
this.application = application;
}
}
| job which are busy is not allow to execute | src/main/java/com/itrustcambodia/pluggable/quartz/Job.java | job which are busy is not allow to execute |
|
Java | apache-2.0 | a3cf0cd8fcfa28c737e83f9cfd38e7bf32c96b68 | 0 | haku/Onosendai,haku/Onosendai | package com.vaguehope.onosendai.ui;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Toast;
import com.vaguehope.onosendai.C;
import com.vaguehope.onosendai.R;
import com.vaguehope.onosendai.config.Column;
import com.vaguehope.onosendai.config.Config;
import com.vaguehope.onosendai.config.InternalColumnType;
import com.vaguehope.onosendai.images.HybridBitmapCache;
import com.vaguehope.onosendai.images.ImageLoadRequest;
import com.vaguehope.onosendai.images.ImageLoader;
import com.vaguehope.onosendai.images.ImageLoaderUtils;
import com.vaguehope.onosendai.update.AlarmReceiver;
public class MainActivity extends FragmentActivity implements ImageLoader {
private HybridBitmapCache imageCache;
@Override
protected void onCreate (final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Config conf = null;
try {
conf = new Config();
}
catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
finish();
return;
}
final float columnWidth = Float.parseFloat(getResources().getString(R.string.column_width));
this.imageCache = new HybridBitmapCache(this, C.MAX_MEMORY_IMAGE_CACHE);
// If this becomes too memory intensive, switch to android.support.v4.app.FragmentStatePagerAdapter.
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), conf, columnWidth);
((ViewPager) findViewById(R.id.pager)).setAdapter(sectionsPagerAdapter);
AlarmReceiver.configureAlarm(this); // FIXME be more smart about this?
}
@Override
protected void onDestroy () {
if (this.imageCache != null) this.imageCache.clean();
super.onDestroy();
}
@Override
public void loadImage (final ImageLoadRequest req) {
ImageLoaderUtils.loadImage(this.imageCache, req);
}
private static class SectionsPagerAdapter extends FragmentPagerAdapter {
private final Config conf;
private final float pageWidth;
public SectionsPagerAdapter (final FragmentManager fm, final Config conf, final float pageWidth) {
super(fm);
this.conf = conf;
this.pageWidth = pageWidth;
}
@Override
public Fragment getItem (final int position) {
final Column col = this.conf.getColumns().get(position);
// getItem is called to instantiate the fragment for the given page.
Fragment fragment = new TweetListFragment();
Bundle args = new Bundle();
args.putInt(TweetListFragment.ARG_COLUMN_ID, col.id);
args.putString(TweetListFragment.ARG_COLUMN_TITLE, col.title);
args.putBoolean(TweetListFragment.ARG_COLUMN_IS_LATER, InternalColumnType.LATER.matchesColumn(col));
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount () {
return this.conf.getColumns().size();
}
@Override
public CharSequence getPageTitle (final int position) {
return this.conf.getColumn(position).title;
}
@Override
public float getPageWidth (final int position) {
return this.pageWidth;
}
}
}
| src/main/java/com/vaguehope/onosendai/ui/MainActivity.java | package com.vaguehope.onosendai.ui;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Toast;
import com.vaguehope.onosendai.C;
import com.vaguehope.onosendai.R;
import com.vaguehope.onosendai.config.Column;
import com.vaguehope.onosendai.config.Config;
import com.vaguehope.onosendai.config.InternalColumnType;
import com.vaguehope.onosendai.images.HybridBitmapCache;
import com.vaguehope.onosendai.images.ImageLoadRequest;
import com.vaguehope.onosendai.images.ImageLoader;
import com.vaguehope.onosendai.images.ImageLoaderUtils;
import com.vaguehope.onosendai.update.AlarmReceiver;
public class MainActivity extends FragmentActivity implements ImageLoader {
private HybridBitmapCache imageCache;
@Override
protected void onCreate (final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Config conf = null;
try {
conf = new Config();
}
catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
finish();
return;
}
final float columnWidth = Float.parseFloat(getResources().getString(R.string.column_width));
this.imageCache = new HybridBitmapCache(this, C.MAX_MEMORY_IMAGE_CACHE);
// If this becomes too memory intensive, switch to android.support.v4.app.FragmentStatePagerAdapter.
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), conf, columnWidth);
((ViewPager) findViewById(R.id.pager)).setAdapter(sectionsPagerAdapter);
AlarmReceiver.configureAlarm(this); // FIXME be more smart about this?
}
@Override
protected void onDestroy () {
this.imageCache.clean();
super.onDestroy();
}
@Override
public void loadImage (final ImageLoadRequest req) {
ImageLoaderUtils.loadImage(this.imageCache, req);
}
private static class SectionsPagerAdapter extends FragmentPagerAdapter {
private final Config conf;
private final float pageWidth;
public SectionsPagerAdapter (final FragmentManager fm, final Config conf, final float pageWidth) {
super(fm);
this.conf = conf;
this.pageWidth = pageWidth;
}
@Override
public Fragment getItem (final int position) {
final Column col = this.conf.getColumns().get(position);
// getItem is called to instantiate the fragment for the given page.
Fragment fragment = new TweetListFragment();
Bundle args = new Bundle();
args.putInt(TweetListFragment.ARG_COLUMN_ID, col.id);
args.putString(TweetListFragment.ARG_COLUMN_TITLE, col.title);
args.putBoolean(TweetListFragment.ARG_COLUMN_IS_LATER, InternalColumnType.LATER.matchesColumn(col));
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount () {
return this.conf.getColumns().size();
}
@Override
public CharSequence getPageTitle (final int position) {
return this.conf.getColumn(position).title;
}
@Override
public float getPageWidth (final int position) {
return this.pageWidth;
}
}
}
| Fix NPE. | src/main/java/com/vaguehope/onosendai/ui/MainActivity.java | Fix NPE. |
|
Java | apache-2.0 | cd82155f8c16cab4f1a2625a7066f34c9eef8919 | 0 | MER-GROUP/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,ernestp/consulo,ryano144/intellij-community,hurricup/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ryano144/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,kool79/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,slisson/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,retomerz/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,holmes/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,vladmm/intellij-community,fitermay/intellij-community,allotria/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,signed/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,izonder/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,semonte/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,dslomov/intellij-community,holmes/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,semonte/intellij-community,kdwink/intellij-community,vladmm/intellij-community,vladmm/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,allotria/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,da1z/intellij-community,allotria/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,holmes/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,fnouama/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,slisson/intellij-community,gnuhub/intellij-community,holmes/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,ryano144/intellij-community,petteyg/intellij-community,kool79/intellij-community,ernestp/consulo,pwoodworth/intellij-community,FHannes/intellij-community,da1z/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,adedayo/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,caot/intellij-community,vladmm/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,holmes/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,hurricup/intellij-community,signed/intellij-community,asedunov/intellij-community,fitermay/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,samthor/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ernestp/consulo,akosyakov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,da1z/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ryano144/intellij-community,asedunov/intellij-community,slisson/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,caot/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,diorcety/intellij-community,samthor/intellij-community,hurricup/intellij-community,samthor/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,kool79/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,signed/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,da1z/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,caot/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,holmes/intellij-community,da1z/intellij-community,semonte/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,consulo/consulo,izonder/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,izonder/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,retomerz/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,fitermay/intellij-community,dslomov/intellij-community,fnouama/intellij-community,blademainer/intellij-community,retomerz/intellij-community,robovm/robovm-studio,allotria/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,samthor/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,robovm/robovm-studio,supersven/intellij-community,apixandru/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,asedunov/intellij-community,blademainer/intellij-community,amith01994/intellij-community,adedayo/intellij-community,jagguli/intellij-community,fnouama/intellij-community,vladmm/intellij-community,da1z/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,caot/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,da1z/intellij-community,ibinti/intellij-community,asedunov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,hurricup/intellij-community,consulo/consulo,semonte/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,caot/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,adedayo/intellij-community,amith01994/intellij-community,caot/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,consulo/consulo,SerCeMan/intellij-community,slisson/intellij-community,signed/intellij-community,supersven/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,ryano144/intellij-community,semonte/intellij-community,youdonghai/intellij-community,izonder/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ibinti/intellij-community,slisson/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,adedayo/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,fnouama/intellij-community,supersven/intellij-community,diorcety/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,blademainer/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,slisson/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,caot/intellij-community,robovm/robovm-studio,semonte/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,fitermay/intellij-community,kdwink/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,diorcety/intellij-community,jagguli/intellij-community,clumsy/intellij-community,FHannes/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,signed/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,supersven/intellij-community,blademainer/intellij-community,apixandru/intellij-community,hurricup/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ernestp/consulo,clumsy/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,semonte/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,clumsy/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,samthor/intellij-community,robovm/robovm-studio,caot/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,asedunov/intellij-community,adedayo/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ernestp/consulo,pwoodworth/intellij-community,petteyg/intellij-community,petteyg/intellij-community,kool79/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,apixandru/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,caot/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,consulo/consulo,vladmm/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,clumsy/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,consulo/consulo,supersven/intellij-community,wreckJ/intellij-community,signed/intellij-community,blademainer/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,asedunov/intellij-community,kdwink/intellij-community,signed/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,slisson/intellij-community,allotria/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,allotria/intellij-community,kool79/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,izonder/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,consulo/consulo,TangHao1987/intellij-community,samthor/intellij-community,Lekanich/intellij-community | /*
* 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.psi.impl.search;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.search.TextOccurenceProcessor;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.text.StringSearcher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class LowLevelSearchUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.LowLevelSearchUtil");
private LowLevelSearchUtil() {
}
// TRUE/FALSE -> injected psi has been discovered and processor returned true/false;
// null -> there were nothing injected found
private static Boolean processInjectedFile(PsiElement element,
final TextOccurenceProcessor processor,
final StringSearcher searcher,
ProgressIndicator progress) {
if (!(element instanceof PsiLanguageInjectionHost)) return null;
List<Pair<PsiElement,TextRange>> list = ((PsiLanguageInjectionHost)element).getInjectedPsi();
if (list == null) return null;
for (Pair<PsiElement, TextRange> pair : list) {
final PsiElement injected = pair.getFirst();
if (!processElementsContainingWordInElement(processor, injected, searcher, false, progress)) return Boolean.FALSE;
}
return Boolean.TRUE;
}
private static boolean processTreeUp(final TextOccurenceProcessor processor,
final PsiElement scope,
final StringSearcher searcher,
final int offset,
final boolean ignoreInjectedPsi, ProgressIndicator progress) {
final int scopeStartOffset = scope.getTextRange().getStartOffset();
final int patternLength = searcher.getPatternLength();
PsiElement leafElement = null;
TreeElement leafNode = null;
ASTNode scopeNode = scope.getNode();
boolean useTree = scopeNode != null;
int start;
if (useTree) {
leafNode = (LeafElement)scopeNode.findLeafElementAt(offset);
if (leafNode == null) return true;
start = offset - leafNode.getStartOffset() + scopeStartOffset;
}
else {
if (scope instanceof PsiFile) {
leafElement = ((PsiFile)scope).getViewProvider().findElementAt(offset, scope.getLanguage());
}
else {
leafElement = scope.findElementAt(offset);
}
if (leafElement == null) return true;
start = offset - leafElement.getTextRange().getStartOffset() + scopeStartOffset;
}
if (start < 0) {
LOG.error("offset=" + offset + " scopeStartOffset=" + scopeStartOffset + " leafElement=" + leafElement + " " +
" scope=" + scope.toString());
}
boolean contains = false;
PsiElement prev = null;
TreeElement prevNode = null;
PsiElement run = null;
while (run != scope) {
if (progress != null) progress.checkCanceled();
if (useTree) {
start += prevNode == null ? 0 : prevNode.getStartOffsetInParent();
prevNode = leafNode;
run = leafNode.getPsi();
}
else {
start += prev == null ? 0 : prev.getStartOffsetInParent();
prev = run;
run = leafElement;
}
contains |= run.getTextLength() - start >= patternLength; //do not compute if already contains
if (contains) {
if (!ignoreInjectedPsi) {
Boolean result = processInjectedFile(run, processor, searcher, progress);
if (result != null) {
return result.booleanValue();
}
}
if (!processor.execute(run, start)) {
return false;
}
}
if (useTree) {
leafNode = leafNode.getTreeParent();
if (leafNode == null) break;
}
else {
leafElement = leafElement.getParent();
if (leafElement == null) break;
}
}
assert run == scope: "Malbuilt PSI: scopeNode="+scope+"; leafNode="+run+"; isAncestor="+ PsiTreeUtil.isAncestor(scope, run, false);
return true;
}
//@RequiresReadAction
public static boolean processElementsContainingWordInElement(@NotNull TextOccurenceProcessor processor,
@NotNull PsiElement scope,
@NotNull StringSearcher searcher,
final boolean ignoreInjectedPsi,
ProgressIndicator progress) {
if (progress != null) progress.checkCanceled();
PsiFile file = scope.getContainingFile();
final CharSequence buffer = file.getViewProvider().getContents();
TextRange range = scope.getTextRange();
if (range == null) {
throw new AssertionError("Element " + scope + " of class " + scope.getClass() + " has null range");
}
int scopeStart = range.getStartOffset();
int startOffset = scopeStart;
int endOffset = range.getEndOffset();
if (endOffset > buffer.length()) {
LOG.error("Range for element: '"+scope+"' = "+range+" is out of file '" + file + "' range: " + file.getTextLength());
}
do {
if (progress != null) progress.checkCanceled();
startOffset = searchWord(buffer, startOffset, endOffset, searcher, progress);
if (startOffset < 0) {
return true;
}
if (!processTreeUp(processor, scope, searcher, startOffset - scopeStart, ignoreInjectedPsi, progress)) return false;
startOffset++;
}
while (startOffset < endOffset);
return true;
}
public static int searchWord(@NotNull CharSequence text, int startOffset, int endOffset, @NotNull StringSearcher searcher, @Nullable ProgressIndicator progress) {
LOG.assertTrue(endOffset <= text.length());
for (int index = startOffset; index < endOffset; index++) {
if (progress != null) progress.checkCanceled();
//noinspection AssignmentToForLoopParameter
index = searcher.scan(text, index, endOffset);
if (index < 0) return -1;
if (!searcher.isJavaIdentifier()) {
return index;
}
if (index > startOffset) {
char c = text.charAt(index - 1);
if (Character.isJavaIdentifierPart(c) && c != '$') {
if (index < 2 || text.charAt(index - 2) != '\\') { //escape sequence
continue;
}
}
}
String pattern = searcher.getPattern();
if (index + pattern.length() < endOffset) {
char c = text.charAt(index + pattern.length());
if (Character.isJavaIdentifierPart(c) && c != '$') {
continue;
}
}
return index;
}
return -1;
}
}
| platform/lang-impl/src/com/intellij/psi/impl/search/LowLevelSearchUtil.java | /*
* 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.psi.impl.search;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.search.TextOccurenceProcessor;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.text.StringSearcher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class LowLevelSearchUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.LowLevelSearchUtil");
private LowLevelSearchUtil() {
}
// TRUE/FALSE -> injected psi has been discovered and processor returned true/false;
// null -> there were nothing injected found
private static Boolean processInjectedFile(PsiElement element,
final TextOccurenceProcessor processor,
final StringSearcher searcher,
ProgressIndicator progress) {
if (!(element instanceof PsiLanguageInjectionHost)) return null;
List<Pair<PsiElement,TextRange>> list = ((PsiLanguageInjectionHost)element).getInjectedPsi();
if (list == null) return null;
for (Pair<PsiElement, TextRange> pair : list) {
final PsiElement injected = pair.getFirst();
if (!processElementsContainingWordInElement(processor, injected, searcher, false, progress)) return Boolean.FALSE;
}
return Boolean.TRUE;
}
private static boolean processTreeUp(final TextOccurenceProcessor processor,
final PsiElement scope,
final StringSearcher searcher,
final int offset,
final boolean ignoreInjectedPsi, ProgressIndicator progress) {
final int scopeStartOffset = scope.getTextRange().getStartOffset();
final int patternLength = searcher.getPatternLength();
PsiElement leafElement = null;
TreeElement leafNode = null;
ASTNode scopeNode = scope.getNode();
boolean useTree = scopeNode != null;
int start;
if (useTree) {
leafNode = (LeafElement)scopeNode.findLeafElementAt(offset);
if (leafNode == null) return true;
start = offset - leafNode.getStartOffset() + scopeStartOffset;
}
else {
if (scope instanceof PsiFile) {
leafElement = ((PsiFile)scope).getViewProvider().findElementAt(offset, scope.getLanguage());
}
else {
leafElement = scope.findElementAt(offset);
}
if (leafElement == null) return true;
start = offset - leafElement.getTextRange().getStartOffset() + scopeStartOffset;
}
if (start < 0) {
LOG.error("offset=" + offset + " scopeStartOffset=" + scopeStartOffset + " leafElement=" + leafElement + " " +
" scope=" + scope.toString());
}
boolean contains = false;
PsiElement prev = null;
TreeElement prevNode = null;
PsiElement run = null;
while (run != scope) {
if (progress != null) progress.checkCanceled();
if (useTree) {
start += prevNode == null ? 0 : prevNode.getStartOffsetInParent();
prevNode = leafNode;
run = leafNode.getPsi();
}
else {
start += prev == null ? 0 : prev.getStartOffsetInParent();
prev = run;
run = leafElement;
}
contains |= run.getTextLength() - start >= patternLength; //do not compute if already contains
if (contains) {
if (!ignoreInjectedPsi) {
Boolean result = processInjectedFile(run, processor, searcher, progress);
if (result != null) {
return result.booleanValue();
}
}
if (!processor.execute(run, start)) {
return false;
}
}
if (useTree) {
leafNode = leafNode.getTreeParent();
if (leafNode == null) break;
}
else {
leafElement = leafElement.getParent();
if (leafElement == null) break;
}
}
assert run == scope: "Malbuilt PSI: scopeNode="+scope+"; leafNode="+run+"; isAncestor="+ PsiTreeUtil.isAncestor(scope, run, false);
return true;
}
//@RequiresReadAction
public static boolean processElementsContainingWordInElement(@NotNull TextOccurenceProcessor processor,
@NotNull PsiElement scope,
@NotNull StringSearcher searcher,
final boolean ignoreInjectedPsi,
ProgressIndicator progress) {
if (progress != null) progress.checkCanceled();
PsiFile file = scope.getContainingFile();
final CharSequence buffer = file.getViewProvider().getContents();
TextRange range = scope.getTextRange();
int scopeStart = range.getStartOffset();
int startOffset = scopeStart;
int endOffset = range.getEndOffset();
if (endOffset > buffer.length()) {
LOG.error("Range for element: '"+scope+"' = "+range+" is out of file '" + file + "' range: " + file.getTextLength());
}
do {
if (progress != null) progress.checkCanceled();
startOffset = searchWord(buffer, startOffset, endOffset, searcher, progress);
if (startOffset < 0) {
return true;
}
if (!processTreeUp(processor, scope, searcher, startOffset - scopeStart, ignoreInjectedPsi, progress)) return false;
startOffset++;
}
while (startOffset < endOffset);
return true;
}
public static int searchWord(@NotNull CharSequence text, int startOffset, int endOffset, @NotNull StringSearcher searcher, @Nullable ProgressIndicator progress) {
LOG.assertTrue(endOffset <= text.length());
for (int index = startOffset; index < endOffset; index++) {
if (progress != null) progress.checkCanceled();
//noinspection AssignmentToForLoopParameter
index = searcher.scan(text, index, endOffset);
if (index < 0) return -1;
if (!searcher.isJavaIdentifier()) {
return index;
}
if (index > startOffset) {
char c = text.charAt(index - 1);
if (Character.isJavaIdentifierPart(c) && c != '$') {
if (index < 2 || text.charAt(index - 2) != '\\') { //escape sequence
continue;
}
}
}
String pattern = searcher.getPattern();
if (index + pattern.length() < endOffset) {
char c = text.charAt(index + pattern.length());
if (Character.isJavaIdentifierPart(c) && c != '$') {
continue;
}
}
return index;
}
return -1;
}
}
| diagnostics for EA-25474
| platform/lang-impl/src/com/intellij/psi/impl/search/LowLevelSearchUtil.java | diagnostics for EA-25474 |
|
Java | apache-2.0 | 1aede707a044ba048abd5bbdce6601629eec536e | 0 | codeaudit/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics | /**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.sesame;
import static com.opengamma.util.result.FailureStatus.ERROR;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.threeten.bp.LocalDate;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.LinkedListMultimap;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.curve.interestrate.generator.GeneratorCurveYieldInterpolated;
import com.opengamma.analytics.financial.curve.interestrate.generator.GeneratorCurveYieldInterpolatedAnchorNode;
import com.opengamma.analytics.financial.curve.interestrate.generator.GeneratorYDCurve;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.instrument.index.IndexON;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.legalentity.LegalEntity;
import com.opengamma.analytics.financial.legalentity.LegalEntityFilter;
import com.opengamma.analytics.financial.provider.calculator.generic.LastTimeCalculator;
import com.opengamma.analytics.financial.provider.calculator.issuer.ParSpreadMarketQuoteCurveSensitivityIssuerDiscountingCalculator;
import com.opengamma.analytics.financial.provider.calculator.issuer.ParSpreadMarketQuoteIssuerDiscountingCalculator;
import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlockBundle;
import com.opengamma.analytics.financial.provider.curve.MultiCurveBundle;
import com.opengamma.analytics.financial.provider.curve.SingleCurveBundle;
import com.opengamma.analytics.financial.provider.curve.issuer.IssuerDiscountBuildingRepository;
import com.opengamma.analytics.financial.provider.description.interestrate.IssuerProviderDiscount;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.core.link.ConventionLink;
import com.opengamma.core.link.SecurityLink;
import com.opengamma.core.marketdatasnapshot.SnapshotDataBundle;
import com.opengamma.financial.analytics.curve.AbstractCurveDefinition;
import com.opengamma.financial.analytics.curve.AbstractCurveSpecification;
import com.opengamma.financial.analytics.curve.ConverterUtils;
import com.opengamma.financial.analytics.curve.CurveConstructionConfiguration;
import com.opengamma.financial.analytics.curve.CurveGroupConfiguration;
import com.opengamma.financial.analytics.curve.CurveSpecification;
import com.opengamma.financial.analytics.curve.CurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.DiscountingCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.FixedDateInterpolatedCurveDefinition;
import com.opengamma.financial.analytics.curve.IborCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.InterpolatedCurveDefinition;
import com.opengamma.financial.analytics.curve.IssuerCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.OvernightCurveTypeConfiguration;
import com.opengamma.financial.analytics.ircurve.strips.CurveNodeWithIdentifier;
import com.opengamma.financial.convention.IborIndexConvention;
import com.opengamma.financial.convention.OvernightIndexConvention;
import com.opengamma.financial.security.index.OvernightIndex;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.result.Result;
import com.opengamma.util.tuple.Pair;
import com.opengamma.util.tuple.Pairs;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
/**
* Utility class for building elements of curve bundles
*/
//TODO SSM-164 this provider is currently only working for Issue Provider curves, not Multicurve
public final class CurveBundleProvider {
private final CurveNodeConverterFn _curveNodeConverter;
private final CurveSpecificationFn _curveSpecificationProvider;
private final CurveSpecificationMarketDataFn _curveSpecMarketDataProvider;
private final CurveNodeInstrumentDefinitionFactory _curveNodeInstrumentDefinitionFactory;
private static final ParSpreadMarketQuoteIssuerDiscountingCalculator DISCOUNTING_CALCULATOR =
ParSpreadMarketQuoteIssuerDiscountingCalculator.getInstance();
private static final ParSpreadMarketQuoteCurveSensitivityIssuerDiscountingCalculator CURVE_SENSITIVITY_CALCULATOR =
ParSpreadMarketQuoteCurveSensitivityIssuerDiscountingCalculator.getInstance();
/**
* Creates the curve bundle provider.
*
* @param curveNodeConverter converter for curve nodes, not null.
* @param curveSpecificationProvider provides the curve spec, not null.
* @param curveSpecMarketDataProvider market data required for a curve specification, not null.
* @param curveNodeInstrumentDefinitionFactory factory to build node definitions, not null.
*
*/
public CurveBundleProvider(CurveNodeConverterFn curveNodeConverter,
CurveSpecificationFn curveSpecificationProvider,
CurveSpecificationMarketDataFn curveSpecMarketDataProvider,
CurveNodeInstrumentDefinitionFactory curveNodeInstrumentDefinitionFactory) {
_curveNodeConverter = ArgumentChecker.notNull(curveNodeConverter, "curveNodeConverter");
_curveSpecificationProvider = ArgumentChecker.notNull(curveSpecificationProvider, "curveSpecificationProvider");
_curveSpecMarketDataProvider = ArgumentChecker.notNull(curveSpecMarketDataProvider, "curveSpecMarketDataProvider");
_curveNodeInstrumentDefinitionFactory =
ArgumentChecker.notNull(curveNodeInstrumentDefinitionFactory, "curveNodeInstrumentDefinitionFactory");
}
private SnapshotDataBundle createSnapshotDataBundle(Map<ExternalIdBundle, Double> marketData) {
SnapshotDataBundle snapshotDataBundle = new SnapshotDataBundle();
for (Map.Entry<ExternalIdBundle, Double> entry : marketData.entrySet()) {
snapshotDataBundle.setDataPoint(entry.getKey(), entry.getValue());
}
return snapshotDataBundle;
}
private GeneratorYDCurve getGenerator(final AbstractCurveDefinition definition, LocalDate valuationDate) {
if (definition instanceof InterpolatedCurveDefinition) {
InterpolatedCurveDefinition interpolatedDefinition = (InterpolatedCurveDefinition) definition;
String interpolatorName = interpolatedDefinition.getInterpolatorName();
String leftExtrapolatorName = interpolatedDefinition.getLeftExtrapolatorName();
String rightExtrapolatorName = interpolatedDefinition.getRightExtrapolatorName();
Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName,
leftExtrapolatorName,
rightExtrapolatorName);
if (definition instanceof FixedDateInterpolatedCurveDefinition) {
FixedDateInterpolatedCurveDefinition fixedDateDefinition = (FixedDateInterpolatedCurveDefinition) definition;
List<LocalDate> fixedDates = fixedDateDefinition.getFixedDates();
DoubleArrayList nodePoints = new DoubleArrayList(fixedDates.size()); //TODO what about equal node points?
for (final LocalDate fixedDate : fixedDates) {
//TODO what to do if the fixed date is before the valuation date?
nodePoints.add(TimeCalculator.getTimeBetween(valuationDate, fixedDate));
}
final double anchor = nodePoints.get(0); //TODO should the anchor go into the definition?
return new GeneratorCurveYieldInterpolatedAnchorNode(nodePoints.toDoubleArray(), anchor, interpolator);
}
return new GeneratorCurveYieldInterpolated(LastTimeCalculator.getInstance(), interpolator);
}
throw new OpenGammaRuntimeException("Cannot handle curves of type " + definition.getClass());
}
private IndexON createOvernightIndex(OvernightCurveTypeConfiguration type) {
OvernightIndex index = SecurityLink.resolvable(type.getConvention().toBundle(), OvernightIndex.class).resolve();
OvernightIndexConvention indexConvention =
ConventionLink.resolvable(index.getConventionId(), OvernightIndexConvention.class).resolve();
return ConverterUtils.indexON(index.getName(), indexConvention);
}
private IborIndex createIborIndex(IborCurveTypeConfiguration type) {
com.opengamma.financial.security.index.IborIndex indexSecurity =
SecurityLink.resolvable(type.getConvention(), com.opengamma.financial.security.index.IborIndex.class).resolve();
IborIndexConvention indexConvention =
ConventionLink.resolvable(indexSecurity.getConventionId(), IborIndexConvention.class).resolve();
return ConverterUtils.indexIbor(indexSecurity.getName(), indexConvention, indexSecurity.getTenor());
}
public Result<Pair<IssuerProviderDiscount, CurveBuildingBlockBundle>> getCurves(
Environment env,
CurveConstructionConfiguration config,
Result<IssuerProviderDiscount> exogenousBundle,
Result<FXMatrix> fxMatrixResult,
Set<String> impliedCurveNames,
IssuerDiscountBuildingRepository builder) {
final int nGroups = config.getCurveGroups().size();
@SuppressWarnings("unchecked")
MultiCurveBundle<GeneratorYDCurve>[] curveBundles = new MultiCurveBundle[nGroups];
LinkedHashMap<String, Currency> discountingMap = new LinkedHashMap<>();
LinkedHashMap<String, IborIndex[]> forwardIborMap = new LinkedHashMap<>();
LinkedHashMap<String, IndexON[]> forwardONMap = new LinkedHashMap<>();
LinkedListMultimap<String, Pair<Object, LegalEntityFilter<LegalEntity>>> issuerMap = LinkedListMultimap.create();
//TODO comparator to sort groups by order
int i = 0; // Implementation Note: loop on the groups
// Result to allow us to capture any failures in all these loops, the
// actual value if a success is of no consequence
Result<Boolean> curveBundleResult = Result.success(true);
for (final CurveGroupConfiguration group : config.getCurveGroups()) { // Group - start
final int nCurves = group.getTypesForCurves().size();
@SuppressWarnings("unchecked")
final SingleCurveBundle<GeneratorYDCurve>[] singleCurves = new SingleCurveBundle[nCurves];
int j = 0;
for (final Map.Entry<AbstractCurveDefinition, List<? extends CurveTypeConfiguration>> entry :
group.resolveTypesForCurves().entrySet()) {
AbstractCurveDefinition curve = entry.getKey();
String curveName = curve.getName();
//TODO PLAT-6800 check implied curves first
Result<AbstractCurveSpecification> curveSpecResult =
_curveSpecificationProvider.getCurveSpecification(env, curve);
if (curveSpecResult.isSuccess()) {
final CurveSpecification specification = (CurveSpecification) curveSpecResult.getValue();
Result<Map<ExternalIdBundle, Double>> marketDataResult =
_curveSpecMarketDataProvider.requestData(env, specification);
// Only proceed if we have all market data values available to us
if (Result.allSuccessful(fxMatrixResult, marketDataResult)) {
FXMatrix fxMatrix = fxMatrixResult.getValue();
// todo this is temporary to allow us to get up and running fast
SnapshotDataBundle snapshot = createSnapshotDataBundle(marketDataResult.getValue());
int nNodes = specification.getNodes().size();
double[] parameterGuessForCurves = new double[nNodes];
// For FX forward, the FX rate is not a good initial guess. // TODO: change this // marketData
Arrays.fill(parameterGuessForCurves, 0.02);
Result<InstrumentDerivative[]> derivativesForCurve =
extractInstrumentDerivatives(env, specification, snapshot, fxMatrix, env.getValuationTime());
List<IborIndex> iborIndex = new ArrayList<>();
List<IndexON> overnightIndex = new ArrayList<>();
for (final CurveTypeConfiguration type : entry.getValue()) {
if (type instanceof DiscountingCurveTypeConfiguration) {
final String reference = ((DiscountingCurveTypeConfiguration) type).getReference();
try {
Currency currency = Currency.of(reference);
//should this map check that the curve name has not already been entered?
discountingMap.put(curveName, currency);
} catch (final IllegalArgumentException e) {
throw new OpenGammaRuntimeException("Cannot handle reference type " + reference
+ " for discounting curves");
}
} else if (type instanceof IborCurveTypeConfiguration) {
iborIndex.add(createIborIndex((IborCurveTypeConfiguration) type));
} else if (type instanceof OvernightCurveTypeConfiguration) {
overnightIndex.add(createOvernightIndex((OvernightCurveTypeConfiguration) type));
} else if (type instanceof IssuerCurveTypeConfiguration) {
final IssuerCurveTypeConfiguration issuer = (IssuerCurveTypeConfiguration) type;
issuerMap.put(curveName, Pairs.<Object, LegalEntityFilter<LegalEntity>>of(issuer.getKeys(),
issuer.getFilters()));
} else {
Result<?> typeFailure =
Result.failure(ERROR, "Cannot handle curveTypeConfiguration with type {} whilst building curve: {}",
type.getClass(), curveName);
curveBundleResult = Result.failure(curveBundleResult, typeFailure);
}
}
if (!iborIndex.isEmpty()) {
forwardIborMap.put(curveName, iborIndex.toArray(new IborIndex[iborIndex.size()]));
}
if (!overnightIndex.isEmpty()) {
forwardONMap.put(curveName, overnightIndex.toArray(new IndexON[overnightIndex.size()]));
}
if (derivativesForCurve.isSuccess()) {
GeneratorYDCurve generator = getGenerator(curve, env.getValuationDate());
singleCurves[j] = new SingleCurveBundle<>(curveName,
derivativesForCurve.getValue(),
generator.initialGuess(parameterGuessForCurves),
generator);
} else {
curveBundleResult = Result.failure(curveBundleResult, derivativesForCurve);
}
} else {
curveBundleResult = Result.failure(curveBundleResult, fxMatrixResult, marketDataResult);
}
} else {
curveBundleResult = Result.failure(curveBundleResult, curveSpecResult);
}
j++;
}
if (curveBundleResult.isSuccess()) {
curveBundles[i++] = new MultiCurveBundle<>(singleCurves);
}
} // Group - end
if (Result.allSuccessful(exogenousBundle, curveBundleResult)) {
//TODO PLAT-6800 remove implied curves
IssuerProviderDiscount knownData = exogenousBundle.getValue();
Pair<IssuerProviderDiscount, CurveBuildingBlockBundle> calibratedCurves =
builder.makeCurvesFromDerivatives(curveBundles,
knownData.getIssuerProvider(),
discountingMap,
forwardIborMap,
forwardONMap,
issuerMap,
DISCOUNTING_CALCULATOR,
CURVE_SENSITIVITY_CALCULATOR);
return Result.success(calibratedCurves);
} else {
return Result.failure(exogenousBundle, curveBundleResult);
}
}
private Result<InstrumentDerivative[]> extractInstrumentDerivatives(Environment env,
CurveSpecification specification,
SnapshotDataBundle snapshot,
FXMatrix fxMatrix,
ZonedDateTime valuationTime) {
Set<CurveNodeWithIdentifier> nodes = specification.getNodes();
List<InstrumentDerivative> derivativesForCurve = new ArrayList<>(nodes.size());
List<Result<?>> failures = new ArrayList<>();
for (CurveNodeWithIdentifier node : nodes) {
InstrumentDefinition<?> definitionForNode =
_curveNodeInstrumentDefinitionFactory.createInstrumentDefinition(node, snapshot, valuationTime, fxMatrix);
Result<InstrumentDerivative> derivativeResult =
_curveNodeConverter.getDerivative(env, node, definitionForNode, valuationTime);
if (derivativeResult.isSuccess()) {
derivativesForCurve.add(derivativeResult.getValue());
} else {
failures.add(derivativeResult);
}
}
if (failures.isEmpty()) {
return Result.success(derivativesForCurve.toArray(new InstrumentDerivative[derivativesForCurve.size()]));
} else {
return Result.failure(failures);
}
}
}
| sesame-function/src/main/java/com/opengamma/sesame/CurveBundleProvider.java | /**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.sesame;
import static com.opengamma.util.result.FailureStatus.ERROR;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.threeten.bp.LocalDate;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.LinkedListMultimap;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.curve.interestrate.generator.GeneratorCurveYieldInterpolated;
import com.opengamma.analytics.financial.curve.interestrate.generator.GeneratorCurveYieldInterpolatedAnchorNode;
import com.opengamma.analytics.financial.curve.interestrate.generator.GeneratorYDCurve;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.instrument.index.IndexON;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.legalentity.LegalEntity;
import com.opengamma.analytics.financial.legalentity.LegalEntityFilter;
import com.opengamma.analytics.financial.provider.calculator.generic.LastTimeCalculator;
import com.opengamma.analytics.financial.provider.calculator.issuer.ParSpreadMarketQuoteCurveSensitivityIssuerDiscountingCalculator;
import com.opengamma.analytics.financial.provider.calculator.issuer.ParSpreadMarketQuoteIssuerDiscountingCalculator;
import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlockBundle;
import com.opengamma.analytics.financial.provider.curve.MultiCurveBundle;
import com.opengamma.analytics.financial.provider.curve.SingleCurveBundle;
import com.opengamma.analytics.financial.provider.curve.issuer.IssuerDiscountBuildingRepository;
import com.opengamma.analytics.financial.provider.description.interestrate.IssuerProviderDiscount;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.core.link.ConventionLink;
import com.opengamma.core.link.SecurityLink;
import com.opengamma.core.marketdatasnapshot.SnapshotDataBundle;
import com.opengamma.financial.analytics.curve.AbstractCurveDefinition;
import com.opengamma.financial.analytics.curve.AbstractCurveSpecification;
import com.opengamma.financial.analytics.curve.ConverterUtils;
import com.opengamma.financial.analytics.curve.CurveConstructionConfiguration;
import com.opengamma.financial.analytics.curve.CurveGroupConfiguration;
import com.opengamma.financial.analytics.curve.CurveSpecification;
import com.opengamma.financial.analytics.curve.CurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.DiscountingCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.FixedDateInterpolatedCurveDefinition;
import com.opengamma.financial.analytics.curve.IborCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.InterpolatedCurveDefinition;
import com.opengamma.financial.analytics.curve.IssuerCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.OvernightCurveTypeConfiguration;
import com.opengamma.financial.analytics.ircurve.strips.CurveNodeWithIdentifier;
import com.opengamma.financial.convention.IborIndexConvention;
import com.opengamma.financial.convention.OvernightIndexConvention;
import com.opengamma.financial.security.index.OvernightIndex;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.result.Result;
import com.opengamma.util.tuple.Pair;
import com.opengamma.util.tuple.Pairs;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
/**
* Utility class for building elements of curve bundles
*/
//TODO SSM-164 this provider is currently only working for Issue Provider curves, not Multicurve
public final class CurveBundleProvider {
private final CurveNodeConverterFn _curveNodeConverter;
private final CurveSpecificationFn _curveSpecificationProvider;
private final CurveSpecificationMarketDataFn _curveSpecMarketDataProvider;
private final CurveNodeInstrumentDefinitionFactory _curveNodeInstrumentDefinitionFactory;
private static final ParSpreadMarketQuoteIssuerDiscountingCalculator DISCOUNTING_CALCULATOR =
ParSpreadMarketQuoteIssuerDiscountingCalculator.getInstance();
private static final ParSpreadMarketQuoteCurveSensitivityIssuerDiscountingCalculator CURVE_SENSITIVITY_CALCULATOR =
ParSpreadMarketQuoteCurveSensitivityIssuerDiscountingCalculator.getInstance();
/**
* Creates the curve bundle provider.
*
* @param curveNodeConverter converter bor curve nodes, not null.
* @param curveSpecificationProvider provides the curve spec, not null.
* @param curveSpecMarketDataProvider market data required for a curve specification, not null.
* @param curveNodeInstrumentDefinitionFactory factory to build node definitions, not null.
*
*/
public CurveBundleProvider(CurveNodeConverterFn curveNodeConverter,
CurveSpecificationFn curveSpecificationProvider,
CurveSpecificationMarketDataFn curveSpecMarketDataProvider,
CurveNodeInstrumentDefinitionFactory curveNodeInstrumentDefinitionFactory) {
_curveNodeConverter = ArgumentChecker.notNull(curveNodeConverter, "curveNodeConverter");
_curveSpecificationProvider = ArgumentChecker.notNull(curveSpecificationProvider, "curveSpecificationProvider");
_curveSpecMarketDataProvider = ArgumentChecker.notNull(curveSpecMarketDataProvider, "curveSpecMarketDataProvider");
_curveNodeInstrumentDefinitionFactory =
ArgumentChecker.notNull(curveNodeInstrumentDefinitionFactory, "curveNodeInstrumentDefinitionFactory");
}
private SnapshotDataBundle createSnapshotDataBundle(Map<ExternalIdBundle, Double> marketData) {
SnapshotDataBundle snapshotDataBundle = new SnapshotDataBundle();
for (Map.Entry<ExternalIdBundle, Double> entry : marketData.entrySet()) {
snapshotDataBundle.setDataPoint(entry.getKey(), entry.getValue());
}
return snapshotDataBundle;
}
private GeneratorYDCurve getGenerator(final AbstractCurveDefinition definition, LocalDate valuationDate) {
if (definition instanceof InterpolatedCurveDefinition) {
InterpolatedCurveDefinition interpolatedDefinition = (InterpolatedCurveDefinition) definition;
String interpolatorName = interpolatedDefinition.getInterpolatorName();
String leftExtrapolatorName = interpolatedDefinition.getLeftExtrapolatorName();
String rightExtrapolatorName = interpolatedDefinition.getRightExtrapolatorName();
Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName,
leftExtrapolatorName,
rightExtrapolatorName);
if (definition instanceof FixedDateInterpolatedCurveDefinition) {
FixedDateInterpolatedCurveDefinition fixedDateDefinition = (FixedDateInterpolatedCurveDefinition) definition;
List<LocalDate> fixedDates = fixedDateDefinition.getFixedDates();
DoubleArrayList nodePoints = new DoubleArrayList(fixedDates.size()); //TODO what about equal node points?
for (final LocalDate fixedDate : fixedDates) {
//TODO what to do if the fixed date is before the valuation date?
nodePoints.add(TimeCalculator.getTimeBetween(valuationDate, fixedDate));
}
final double anchor = nodePoints.get(0); //TODO should the anchor go into the definition?
return new GeneratorCurveYieldInterpolatedAnchorNode(nodePoints.toDoubleArray(), anchor, interpolator);
}
return new GeneratorCurveYieldInterpolated(LastTimeCalculator.getInstance(), interpolator);
}
throw new OpenGammaRuntimeException("Cannot handle curves of type " + definition.getClass());
}
private IndexON createOvernightIndex(OvernightCurveTypeConfiguration type) {
OvernightIndex index = SecurityLink.resolvable(type.getConvention().toBundle(), OvernightIndex.class).resolve();
OvernightIndexConvention indexConvention =
ConventionLink.resolvable(index.getConventionId(), OvernightIndexConvention.class).resolve();
return ConverterUtils.indexON(index.getName(), indexConvention);
}
private IborIndex createIborIndex(IborCurveTypeConfiguration type) {
com.opengamma.financial.security.index.IborIndex indexSecurity =
SecurityLink.resolvable(type.getConvention(), com.opengamma.financial.security.index.IborIndex.class).resolve();
IborIndexConvention indexConvention =
ConventionLink.resolvable(indexSecurity.getConventionId(), IborIndexConvention.class).resolve();
return ConverterUtils.indexIbor(indexSecurity.getName(), indexConvention, indexSecurity.getTenor());
}
// TODO sort this out [SSM-164]
public Result<Pair<IssuerProviderDiscount, CurveBuildingBlockBundle>> getCurves(
Environment env,
CurveConstructionConfiguration config,
Result<IssuerProviderDiscount> exogenousBundle,
Result<FXMatrix> fxMatrixResult,
Set<String> impliedCurveNames,
IssuerDiscountBuildingRepository builder) {
final int nGroups = config.getCurveGroups().size();
@SuppressWarnings("unchecked")
MultiCurveBundle<GeneratorYDCurve>[] curveBundles = new MultiCurveBundle[nGroups];
LinkedHashMap<String, Currency> discountingMap = new LinkedHashMap<>();
LinkedHashMap<String, IborIndex[]> forwardIborMap = new LinkedHashMap<>();
LinkedHashMap<String, IndexON[]> forwardONMap = new LinkedHashMap<>();
LinkedListMultimap<String, Pair<Object, LegalEntityFilter<LegalEntity>>> issuerMap = LinkedListMultimap.create();
//TODO comparator to sort groups by order
int i = 0; // Implementation Note: loop on the groups
// Result to allow us to capture any failures in all these loops, the
// actual value if a success is of no consequence
Result<Boolean> curveBundleResult = Result.success(true);
for (final CurveGroupConfiguration group : config.getCurveGroups()) { // Group - start
final int nCurves = group.getTypesForCurves().size();
@SuppressWarnings("unchecked")
final SingleCurveBundle<GeneratorYDCurve>[] singleCurves = new SingleCurveBundle[nCurves];
int j = 0;
for (final Map.Entry<AbstractCurveDefinition, List<? extends CurveTypeConfiguration>> entry : group.resolveTypesForCurves().entrySet()) {
AbstractCurveDefinition curve = entry.getKey();
String curveName = curve.getName();
//TODO PLAT-6800 check implied curves first
Result<AbstractCurveSpecification> curveSpecResult =
_curveSpecificationProvider.getCurveSpecification(env, curve);
if (curveSpecResult.isSuccess()) {
final CurveSpecification specification = (CurveSpecification) curveSpecResult.getValue();
Result<Map<ExternalIdBundle, Double>> marketDataResult =
_curveSpecMarketDataProvider.requestData(env, specification);
// Only proceed if we have all market data values available to us
if (Result.allSuccessful(fxMatrixResult, marketDataResult)) {
FXMatrix fxMatrix = fxMatrixResult.getValue();
// todo this is temporary to allow us to get up and running fast
SnapshotDataBundle snapshot = createSnapshotDataBundle(marketDataResult.getValue());
int nNodes = specification.getNodes().size();
double[] parameterGuessForCurves = new double[nNodes];
// For FX forward, the FX rate is not a good initial guess. // TODO: change this // marketData
Arrays.fill(parameterGuessForCurves, 0.02);
Result<InstrumentDerivative[]> derivativesForCurve =
extractInstrumentDerivatives(env, specification, snapshot, fxMatrix, env.getValuationTime());
List<IborIndex> iborIndex = new ArrayList<>();
List<IndexON> overnightIndex = new ArrayList<>();
for (final CurveTypeConfiguration type : entry.getValue()) {
if (type instanceof DiscountingCurveTypeConfiguration) {
final String reference = ((DiscountingCurveTypeConfiguration) type).getReference();
try {
Currency currency = Currency.of(reference);
//should this map check that the curve name has not already been entered?
discountingMap.put(curveName, currency);
} catch (final IllegalArgumentException e) {
throw new OpenGammaRuntimeException("Cannot handle reference type " + reference + " for discounting curves");
}
} else if (type instanceof IborCurveTypeConfiguration) {
iborIndex.add(createIborIndex((IborCurveTypeConfiguration) type));
} else if (type instanceof OvernightCurveTypeConfiguration) {
overnightIndex.add(createOvernightIndex((OvernightCurveTypeConfiguration) type));
} else if (type instanceof IssuerCurveTypeConfiguration) {
final IssuerCurveTypeConfiguration issuer = (IssuerCurveTypeConfiguration) type;
issuerMap.put(curveName, Pairs.<Object, LegalEntityFilter<LegalEntity>>of(issuer.getKeys(),
issuer.getFilters()));
} else {
Result<?> typeFailure =
Result.failure(ERROR, "Cannot handle curveTypeConfiguration with type {} whilst building curve: {}",
type.getClass(), curveName);
curveBundleResult = Result.failure(curveBundleResult, typeFailure);
}
}
if (!iborIndex.isEmpty()) {
forwardIborMap.put(curveName, iborIndex.toArray(new IborIndex[iborIndex.size()]));
}
if (!overnightIndex.isEmpty()) {
forwardONMap.put(curveName, overnightIndex.toArray(new IndexON[overnightIndex.size()]));
}
if (derivativesForCurve.isSuccess()) {
GeneratorYDCurve generator = getGenerator(curve, env.getValuationDate());
singleCurves[j] = new SingleCurveBundle<>(curveName,
derivativesForCurve.getValue(),
generator.initialGuess(parameterGuessForCurves),
generator);
} else {
curveBundleResult = Result.failure(curveBundleResult, derivativesForCurve);
}
} else {
curveBundleResult = Result.failure(curveBundleResult, fxMatrixResult, marketDataResult);
}
} else {
curveBundleResult = Result.failure(curveBundleResult, curveSpecResult);
}
j++;
}
if (curveBundleResult.isSuccess()) {
curveBundles[i++] = new MultiCurveBundle<>(singleCurves);
}
} // Group - end
if (Result.allSuccessful(exogenousBundle, curveBundleResult)) {
//TODO PLAT-6800 remove implied curves
IssuerProviderDiscount knownData = exogenousBundle.getValue();
Pair<IssuerProviderDiscount, CurveBuildingBlockBundle> calibratedCurves =
builder.makeCurvesFromDerivatives(curveBundles,
knownData.getIssuerProvider(),
discountingMap,
forwardIborMap,
forwardONMap,
issuerMap,
DISCOUNTING_CALCULATOR,
CURVE_SENSITIVITY_CALCULATOR);
return Result.success(calibratedCurves);
} else {
return Result.failure(exogenousBundle, curveBundleResult);
}
}
private Result<InstrumentDerivative[]> extractInstrumentDerivatives(Environment env,
CurveSpecification specification,
SnapshotDataBundle snapshot,
FXMatrix fxMatrix,
ZonedDateTime valuationTime) {
Set<CurveNodeWithIdentifier> nodes = specification.getNodes();
List<InstrumentDerivative> derivativesForCurve = new ArrayList<>(nodes.size());
List<Result<?>> failures = new ArrayList<>();
for (CurveNodeWithIdentifier node : nodes) {
InstrumentDefinition<?> definitionForNode =
_curveNodeInstrumentDefinitionFactory.createInstrumentDefinition(node, snapshot, valuationTime, fxMatrix);
Result<InstrumentDerivative> derivativeResult =
_curveNodeConverter.getDerivative(env, node, definitionForNode, valuationTime);
if (derivativeResult.isSuccess()) {
derivativesForCurve.add(derivativeResult.getValue());
} else {
failures.add(derivativeResult);
}
}
if (failures.isEmpty()) {
return Result.success(derivativesForCurve.toArray(new InstrumentDerivative[derivativesForCurve.size()]));
} else {
return Result.failure(failures);
}
}
}
| REQS-537 pr comments - formatting/typos
| sesame-function/src/main/java/com/opengamma/sesame/CurveBundleProvider.java | REQS-537 pr comments - formatting/typos |
|
Java | apache-2.0 | 03ad7d40ca67b6e8d3f8365f3dc38219c983396d | 0 | nagyistoce/camunda-bpm-assert,remibantos/activiti-assert | package org.camunda.bdd.examples.simple.steps;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import javax.inject.Inject;
import org.camunda.bdd.examples.simple.SimpleProcess.Elements;
import org.camunda.bdd.examples.simple.SimpleProcess.Events;
import org.camunda.bdd.examples.simple.SimpleProcess.Variables;
import org.camunda.bdd.examples.simple.SimpleProcessAdapter;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.test.mock.Mocks;
import org.camunda.bpm.engine.test.mock.RegisterMock;
import org.camunda.bpm.test.CamundaSupport;
import org.jbehave.core.annotations.AfterScenario;
import org.jbehave.core.annotations.BeforeScenario;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.mockito.Mockito;
/**
* Specific process steps.
*
* @author Simon Zambrovski, Holisticon AG.
*/
public class SimpleProcessSteps {
@Inject
private SimpleProcessAdapter simpleProcessAdapter;
@Inject
private CamundaSupport support;
@BeforeScenario
public void initMocks() {
RegisterMock.registerMocksForFields(this);
}
@AfterScenario
public void resetMocks() {
Mockito.reset(simpleProcessAdapter);
}
@Given("the contract $verb automatically processible")
public void loadContractDataAutomatically(final String verb) {
final boolean processingPossible = support.parseStatement("not", verb, false);
when(simpleProcessAdapter.loadContractData()).thenReturn(processingPossible);
}
@Given("the contract processing $verb")
public void processingAutomatically(final String verb) {
final boolean withErrors = support.parseStatement("succeeds", verb, false);
if (withErrors) {
doThrow(new BpmnError(Events.ERROR_PROCESS_AUTOMATICALLY_FAILED)).when(simpleProcessAdapter).processContract();
}
}
@Then("the contract is loaded")
public void contractIsLoaded() {
support.assertActivityVisitedOnce(Elements.SERVICE_LOAD_CONTRACT_DATA);
}
@Then("the contract is processed automatically")
public void contractIsProcessed() {
support.assertActivityVisitedOnce(Elements.SERVICE_PROCESS_CONTRACT_AUTOMATICALLY);
}
@Then("the contract processing is cancelled")
public void cancelledProcessing() {
support.assertActivityVisitedOnce(Elements.SERVICE_CANCEL_PROCESSING);
}
@When("the contract is processed $withoutErrors")
public void processManuallys(final String withoutErrors) {
final boolean hasErrors = !support.parseStatement("with errors", withoutErrors, false);
support.completeTask(Variables.ARE_PROCESSING_ERRORS_PRESENT, Boolean.valueOf(hasErrors));
}
}
| src/test/java/org/camunda/bdd/examples/simple/steps/SimpleProcessSteps.java | package org.camunda.bdd.examples.simple.steps;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import javax.inject.Inject;
import org.camunda.bdd.examples.simple.SimpleProcess.Elements;
import org.camunda.bdd.examples.simple.SimpleProcess.Events;
import org.camunda.bdd.examples.simple.SimpleProcess.Variables;
import org.camunda.bdd.examples.simple.SimpleProcessAdapter;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.test.mock.Mocks;
import org.camunda.bpm.test.CamundaSupport;
import org.jbehave.core.annotations.AfterScenario;
import org.jbehave.core.annotations.BeforeScenario;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.mockito.Mockito;
/**
* Specific process steps.
*
* @author Simon Zambrovski, Holisticon AG.
*/
public class SimpleProcessSteps {
@Inject
private SimpleProcessAdapter simpleProcessAdapter;
@Inject
private CamundaSupport support;
@BeforeScenario
public void initMocks() {
Mocks.register(SimpleProcessAdapter.NAME, simpleProcessAdapter);
}
@AfterScenario
public void resetMocks() {
Mockito.reset(simpleProcessAdapter);
}
@Given("the contract $verb automatically processible")
public void loadContractDataAutomatically(final String verb) {
final boolean processingPossible = support.parseStatement("not", verb, false);
when(simpleProcessAdapter.loadContractData()).thenReturn(processingPossible);
}
@Given("the contract processing $verb")
public void processingAutomatically(final String verb) {
final boolean withErrors = support.parseStatement("succeeds", verb, false);
if (withErrors) {
doThrow(new BpmnError(Events.ERROR_PROCESS_AUTOMATICALLY_FAILED)).when(simpleProcessAdapter).processContract();
}
}
@Then("the contract is loaded")
public void contractIsLoaded() {
support.assertActivityVisitedOnce(Elements.SERVICE_LOAD_CONTRACT_DATA);
}
@Then("the contract is processed automatically")
public void contractIsProcessed() {
support.assertActivityVisitedOnce(Elements.SERVICE_PROCESS_CONTRACT_AUTOMATICALLY);
}
@Then("the contract processing is cancelled")
public void cancelledProcessing() {
support.assertActivityVisitedOnce(Elements.SERVICE_CANCEL_PROCESSING);
}
@When("the contract is processed $withoutErrors")
public void processManuallys(final String withoutErrors) {
final boolean hasErrors = !support.parseStatement("with errors", withoutErrors, false);
support.completeTask(Variables.ARE_PROCESSING_ERRORS_PRESENT, Boolean.valueOf(hasErrors));
}
}
| register mocks without explicit mention
| src/test/java/org/camunda/bdd/examples/simple/steps/SimpleProcessSteps.java | register mocks without explicit mention |
|
Java | bsd-2-clause | 40d4a4d21d73877d45e7d8d9d88d3883a5a929b6 | 0 | Ucombinator/jaam,Ucombinator/jaam | package org.ucombinator.jaam.visualizer.layout;
import java.util.*;
public class LayoutAlgorithm
{
// This works on a graph whose vertices have been assigned a bounding box
private static final double MARGIN_PADDING = 10;
private static final double NODES_PADDING = 10;
private static final double ROOT_V_OFFSET = 10;
public static void layout(AbstractLayoutVertex parentVertex) {
initializeSizes(parentVertex);
bfsLayout(parentVertex);
parentVertex.setY(parentVertex.getY() + ROOT_V_OFFSET);
}
private static void initializeSizes(AbstractLayoutVertex parentVertex) {
parentVertex.setWidth(AbstractLayoutVertex.DEFAULT_WIDTH);
parentVertex.setHeight(AbstractLayoutVertex.DEFAULT_HEIGHT);
parentVertex.setX(0);
parentVertex.setY(0);
for(AbstractLayoutVertex v : parentVertex.getInnerGraph().getVisibleVertices()) {
initializeSizes(v);
}
}
private static void expandSubGraphs(AbstractLayoutVertex parentVertex) {
for(AbstractLayoutVertex v: parentVertex.getInnerGraph().getVisibleVertices()) {
HierarchicalGraph innerGraph = v.getInnerGraph();
if (innerGraph.getVisibleVertices().size() != 0)
{
// Layout the inner graphs of each node and assign width W and height H to each node
// X and Y coordinates are RELATIVE to the parent
if (v.isExpanded()) {
dfsLayout(v);
} else {
System.out.println("Collapsed node: " + v.getId());
}
}
}
}
private static void dfsLayout(AbstractLayoutVertex parentVertex) {
HierarchicalGraph graph = parentVertex.getInnerGraph();
expandSubGraphs(parentVertex);
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap = new HashMap<>();
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
childrenMap.put(v, new ArrayList<>());
childrenMap.get(v).addAll(graph.getVisibleOutNeighbors(v));
}
doLayout(parentVertex, childrenMap);
}
private static void bfsLayout(AbstractLayoutVertex parentVertex) {
HierarchicalGraph graph = parentVertex.getInnerGraph();
// Interior graphs use the DFS Layout
expandSubGraphs(parentVertex);
// Initialize all the nodes to be WHITE
for(AbstractLayoutVertex v: graph.getVisibleVertices()) {
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
// Do the BFS Pass
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap = maxDepthChildren(graph);
// Reset all the nodes to be white AND check that we visited everybody...
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
if (v.getVertexStatus() != AbstractLayoutVertex.VertexStatus.BLACK) {
System.out.println("ERROR in Max Depth Drawings. Does your graph have a cycle?");
System.out.println("BFS ERROR Didn't process " + v.getId()
+ " in BFS Children Pass " + v.getVertexStatus());
}
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
doLayout(parentVertex, childrenMap, classComp);
}
private static Comparator<AbstractLayoutVertex> classComp = new Comparator<AbstractLayoutVertex>() {
@Override
public int compare(AbstractLayoutVertex o1, AbstractLayoutVertex o2) {
if(o1 instanceof LayoutSccVertex)
{
if(o2 instanceof LayoutSccVertex)
return o1.getId() < o2.getId() ? -1 : o1.getId() == o2.getId() ? 0 : 1;
else
return -1;
}
else if(o2 instanceof LayoutSccVertex)
{
return 1;
}
if(o1 instanceof CodeEntity && o2 instanceof CodeEntity)
{
CodeEntity c1 = (CodeEntity)o1;
CodeEntity c2 = (CodeEntity)o2;
int shortClassComp = c1.getShortClassName().compareTo(c2.getShortClassName());
if(shortClassComp != 0)
return shortClassComp;
int fullClassComp = c1.getClassName().compareTo(c2.getClassName());
if(fullClassComp != 0)
return fullClassComp;
int methodComp = c1.getMethodName().compareTo(c2.getMethodName());
if(methodComp != 0)
return methodComp;
}
return o1.getId() < o2.getId() ? -1 : o1.getId() == o2.getId() ? 0 : 1;
}
};
private static void doLayout(AbstractLayoutVertex parentVertex,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap)
{
doLayout(parentVertex, childrenMap, null);
}
private static void doLayout(AbstractLayoutVertex parentVertex,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap,
Comparator<AbstractLayoutVertex> childrenSortOrder)
{
if(childrenSortOrder != null) {
for (ArrayList<AbstractLayoutVertex> l : childrenMap.values()) {
l.sort(childrenSortOrder);
}
}
HierarchicalGraph graph = parentVertex.getInnerGraph();
ArrayList<AbstractLayoutVertex> roots = graph.getVisibleRoots();
double parentWidth = AbstractLayoutVertex.DEFAULT_WIDTH;
double parentHeight = AbstractLayoutVertex.DEFAULT_HEIGHT;
if(roots.size() > 0) {
parentWidth += (roots.size() + 1) * MARGIN_PADDING;
parentHeight += 2 * MARGIN_PADDING;
}
double currentWidth = MARGIN_PADDING;
for(AbstractLayoutVertex root : roots) {
storeBBoxWidthAndHeight(root, childrenMap);
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
assignInnerCoordinates(root, currentWidth, MARGIN_PADDING, childrenMap);
currentWidth += root.getBboxWidth() + MARGIN_PADDING;
parentWidth += root.getBboxWidth();
parentHeight = Math.max(parentHeight, root.getBboxHeight() + 2 * MARGIN_PADDING);
}
parentVertex.setWidth(parentWidth);
parentVertex.setHeight(parentHeight);
}
/**
* Preconditions: Graph has no Cycles
* We generate the children map for the layout, where every node is added to the map twice, once as a key
* and once in the children list of some other node. The root doesn't appear in any children list, and
* cannot be hidden.
* Every node appears as a child as deep as possible in the tree (ties, broken arbitrarily)
*/
private static HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> maxDepthChildren(
HierarchicalGraph graph)
{
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap = new HashMap<>();
HashMap<AbstractLayoutVertex, Integer> vertexCounters = new HashMap<>();
Queue<AbstractLayoutVertex> vertexQueue = new ArrayDeque<>();
HashSet<AbstractLayoutVertex> seen = new HashSet<>();
ArrayList<AbstractLayoutVertex> roots = graph.getVisibleRoots();
for(AbstractLayoutVertex root : roots) {
vertexQueue.add(root);
seen.add(root);
}
while(!vertexQueue.isEmpty())
{
AbstractLayoutVertex v = vertexQueue.remove();
childrenMap.put(v, new ArrayList<>());
for(AbstractLayoutVertex child : graph.getVisibleOutNeighbors(v))
{
if(child.equals(v)) {
continue; // Skip recursive edge
}
if (!seen.contains(child)) {
seen.add(child);
child.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
// Subtract v's incoming edge (v --> child)
int numberOfIncomingEdges = graph.getVisibleInNeighbors(child).size() - 1;
if (graph.getVisibleInNeighbors(child).contains(child)) {
numberOfIncomingEdges -= 1; // Ignore recursive call in edge count
}
if (numberOfIncomingEdges > 0) {
vertexCounters.put(child, numberOfIncomingEdges);
} else if (numberOfIncomingEdges == 0) {
childrenMap.get(v).add(child);
vertexQueue.add(child);
}
else {
for(AbstractLayoutVertex inNeighbor : graph.getVisibleInNeighbors(child)) {
System.out.print(inNeighbor.getId() + " ");
}
System.out.println();
}
} else if (child.getVertexStatus() == AbstractLayoutVertex.VertexStatus.GRAY) {
Integer numberOfIncomingEdges = vertexCounters.get(child);
if (numberOfIncomingEdges == null) {
System.out.println("Error Map\n\t " + vertexCounters);
}
else {
numberOfIncomingEdges -= 1; // v --> child
vertexCounters.put(child, numberOfIncomingEdges);
if (numberOfIncomingEdges == 0) {
childrenMap.get(v).add(child);
vertexQueue.add(child);
vertexCounters.remove(child);
}
}
}
}
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.BLACK);
}
if(vertexCounters.size() > 0) {
System.out.println("BFS uncounted vertices, what happened to the incoming?!!! " + vertexCounters);
for (Map.Entry<AbstractLayoutVertex, Integer> entry : vertexCounters.entrySet()) {
System.out.println("\t\t" + entry + " --> " + entry.getKey().getId() + " "
+ entry.getKey().getVertexStatus() + " " + entry.getKey().getMethodVertices());
for(AbstractLayoutVertex n : graph.getVisibleInNeighbors(entry.getKey()))
{
System.out.println("\t\t\t" + n + " --> " + n.getId() + " " + n.getVertexStatus());
}
}
}
return childrenMap;
}
/**
* Preconditions: Height and Width of the inner nodes of the graph is (recursively known)
* input: graph and left/top offset
* Changes of Status: assigns X and Y to the inner vertices of the graph
* Output: returns the W and H to be assign to the parent node
* */
private static void storeBBoxWidthAndHeight(
AbstractLayoutVertex root,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap)
{
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
ArrayList<AbstractLayoutVertex> grayChildren = new ArrayList<AbstractLayoutVertex>();
for(AbstractLayoutVertex child: childrenMap.get(root)) {
if (child.getVertexStatus() == AbstractLayoutVertex.VertexStatus.WHITE) {
child.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
grayChildren.add(child);
}
}
double currentWidth = 0;
double currentHeight = 0;
for(AbstractLayoutVertex curVer: grayChildren)
{
storeBBoxWidthAndHeight(curVer, childrenMap);
currentWidth += curVer.getBboxWidth();
currentHeight = Math.max(currentHeight, curVer.getBboxHeight());
}
currentWidth += (grayChildren.size() - 1) * NODES_PADDING;
double currBboxWidth, currBboxHeight;
currBboxWidth = Math.max(root.getWidth(), currentWidth);
if(grayChildren.size() == 0) {
currBboxHeight = root.getHeight();
}
else {
currBboxHeight = NODES_PADDING + root.getHeight() + currentHeight;
}
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.BLACK);
root.setBboxWidth(currBboxWidth);
root.setBboxHeight(currBboxHeight);
}
/**
* Preconditions: Height and width of the inner nodes of the graph is known (recursively)
* Input: graph and left/top offset
* State changes: assigns X and Y coordinates to the inner vertices of the graph
* */
private static void assignInnerCoordinates (AbstractLayoutVertex root, double left, double top,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap)
{
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
ArrayList<AbstractLayoutVertex> grayChildren = new ArrayList<>();
for(AbstractLayoutVertex child: childrenMap.get(root))
{
if (child.getVertexStatus() == AbstractLayoutVertex.VertexStatus.WHITE)
{
child.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
grayChildren.add(child);
}
}
double currentWidth = 0;
double currentHeight = 0;
for(AbstractLayoutVertex curVer: grayChildren) {
currentWidth += curVer.getBboxWidth();
}
currentWidth += NODES_PADDING * (grayChildren.size() - 1);
// Check if the root is wider than the total width of its children.
double rootOverlap;
if(root.getWidth() >= currentWidth) {
rootOverlap = (root.getWidth() - currentWidth)/2;
} else {
rootOverlap = 0;
}
currentWidth = 0;
for(AbstractLayoutVertex curVer: grayChildren)
{
assignInnerCoordinates(curVer,currentWidth + left + rootOverlap,
NODES_PADDING + top + root.getHeight(), childrenMap);
currentWidth += curVer.getBboxWidth() + NODES_PADDING;
currentHeight = Math.max(currentHeight, curVer.getBboxHeight());
}
root.setX(left + ((root.getBboxWidth() - root.getWidth()) / 2.0)); //left-most corner x
root.setY(top); //top-most corner y
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.BLACK);
}
}
| src/main/java/org/ucombinator/jaam/visualizer/layout/LayoutAlgorithm.java | package org.ucombinator.jaam.visualizer.layout;
import java.util.*;
public class LayoutAlgorithm
{
// This works on a graph whose vertices have been assigned a bounding box
private static final double MARGIN_PADDING = 10;
private static final double NODES_PADDING = 10;
private static final double ROOT_V_OFFSET = 10;
public static void layout(AbstractLayoutVertex parentVertex) {
initializeSizes(parentVertex);
bfsLayout(parentVertex);
parentVertex.setY(parentVertex.getY() + ROOT_V_OFFSET);
}
private static void initializeSizes(AbstractLayoutVertex parentVertex) {
parentVertex.setWidth(AbstractLayoutVertex.DEFAULT_WIDTH);
parentVertex.setHeight(AbstractLayoutVertex.DEFAULT_HEIGHT);
parentVertex.setX(0);
parentVertex.setY(0);
for(AbstractLayoutVertex v : parentVertex.getInnerGraph().getVisibleVertices()) {
initializeSizes(v);
}
}
private static void expandSubGraphs(AbstractLayoutVertex parentVertex) {
for(AbstractLayoutVertex v: parentVertex.getInnerGraph().getVisibleVertices()) {
HierarchicalGraph innerGraph = v.getInnerGraph();
if (innerGraph.getVisibleVertices().size() != 0)
{
// Layout the inner graphs of each node and assign width W and height H to each node
// X and Y coordinates are RELATIVE to the parent
if (v.isExpanded()) {
dfsLayout(v);
} else {
System.out.println("Collapsed node: " + v.getId());
}
}
}
}
private static void dfsLayout(AbstractLayoutVertex parentVertex) {
HierarchicalGraph graph = parentVertex.getInnerGraph();
expandSubGraphs(parentVertex);
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap = new HashMap<>();
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
childrenMap.put(v, new ArrayList<>());
childrenMap.get(v).addAll(graph.getVisibleOutNeighbors(v));
}
doLayout(parentVertex, childrenMap);
}
private static void bfsLayout(AbstractLayoutVertex parentVertex) {
HierarchicalGraph graph = parentVertex.getInnerGraph();
// Interior graphs use the DFS Layout
expandSubGraphs(parentVertex);
// Initialize all the nodes to be WHITE
for(AbstractLayoutVertex v: graph.getVisibleVertices()) {
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
// Do the BFS Pass
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap = maxDepthChildren(graph);
// Reset all the nodes to be white AND check that we visited everybody...
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
if (v.getVertexStatus() != AbstractLayoutVertex.VertexStatus.BLACK) {
System.out.println("ERROR in Max Depth Drawings. Does your graph have a cycle?");
System.out.println("BFS ERROR Didn't process " + v.getId()
+ " in BFS Children Pass " + v.getVertexStatus());
}
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
doLayout(parentVertex, childrenMap, classComp);
}
private static Comparator<AbstractLayoutVertex> classComp = new Comparator<AbstractLayoutVertex>() {
@Override
public int compare(AbstractLayoutVertex o1, AbstractLayoutVertex o2) {
if(o1 instanceof LayoutSccVertex)
{
if(o2 instanceof LayoutSccVertex)
return o1.getId() < o2.getId() ? -1 : o1.getId() == o2.getId() ? 0 : 1;
else
return -1;
}
else if(o2 instanceof LayoutSccVertex)
{
return 1;
}
if(o1 instanceof CodeEntity && o2 instanceof CodeEntity)
{
CodeEntity c1 = (CodeEntity)o1;
CodeEntity c2 = (CodeEntity)o2;
int shortClassComp = c1.getShortClassName().compareTo(c2.getShortClassName());
if(shortClassComp != 0)
return shortClassComp;
int fullClassComp = c1.getClassName().compareTo(c2.getClassName());
if(fullClassComp != 0)
return fullClassComp;
int methodComp = c1.getMethodName().compareTo(c2.getMethodName());
if(methodComp != 0)
return methodComp;
}
return o1.getId() < o2.getId() ? -1 : o1.getId() == o2.getId() ? 0 : 1;
}
};
private static void doLayout(AbstractLayoutVertex parentVertex,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap)
{
doLayout(parentVertex, childrenMap, null);
}
private static void doLayout(AbstractLayoutVertex parentVertex,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap,
Comparator<AbstractLayoutVertex> childrenSortOrder)
{
if(childrenSortOrder != null) {
for (ArrayList<AbstractLayoutVertex> l : childrenMap.values()) {
l.sort(childrenSortOrder);
}
}
HierarchicalGraph graph = parentVertex.getInnerGraph();
ArrayList<AbstractLayoutVertex> roots = graph.getVisibleRoots();
double parentWidth = AbstractLayoutVertex.DEFAULT_WIDTH;
double parentHeight = AbstractLayoutVertex.DEFAULT_HEIGHT;
if(roots.size() > 0) {
parentWidth += (roots.size() + 1) * MARGIN_PADDING;
parentHeight += 2 * MARGIN_PADDING;
}
double currentWidth = MARGIN_PADDING;
for(AbstractLayoutVertex root : roots) {
storeBBoxWidthAndHeight(root, childrenMap);
for (AbstractLayoutVertex v : graph.getVisibleVertices()) {
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.WHITE);
}
assignInnerCoordinates(root, currentWidth, MARGIN_PADDING, childrenMap);
currentWidth += root.getBboxWidth() + MARGIN_PADDING;
parentWidth += root.getBboxWidth();
parentHeight = Math.max(parentHeight, root.getBboxHeight() + 2 * MARGIN_PADDING);
}
parentVertex.setWidth(parentWidth);
parentVertex.setHeight(parentHeight);
}
/**
* Preconditions: Graph has no Cycles
* We generate the children map for the layout, where every node is added to the map twice, once as a key
* and once in the children list of some other node. The root doesn't appear in any children list, and
* cannot be hidden.
* Every node appears as a child as deep as possible in the tree (ties, broken arbitrarily)
*/
private static HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> maxDepthChildren(
HierarchicalGraph graph)
{
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap = new HashMap<>();
HashMap<AbstractLayoutVertex, Integer> vertexCounters = new HashMap<>();
Queue<AbstractLayoutVertex> vertexQueue = new ArrayDeque<>();
HashSet<AbstractLayoutVertex> seen = new HashSet<>();
ArrayList<AbstractLayoutVertex> roots = graph.getVisibleRoots();
for(AbstractLayoutVertex root : roots) {
vertexQueue.add(root);
seen.add(root);
}
while(!vertexQueue.isEmpty())
{
AbstractLayoutVertex v = vertexQueue.remove();
childrenMap.put(v, new ArrayList<>());
for(AbstractLayoutVertex child : graph.getVisibleOutNeighbors(v))
{
if(child.equals(v)) {
continue; // Skip recursive edge
}
if (!seen.contains(child)) {
seen.add(child);
child.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
// Subtract v's incoming edge (v --> child)
int numberOfIncomingEdges = graph.getVisibleInNeighbors(child).size() - 1;
if (graph.getVisibleInNeighbors(child).contains(child)) {
numberOfIncomingEdges -= 1; // Ignore recursive call in edge count
}
if (numberOfIncomingEdges > 0) {
vertexCounters.put(child, numberOfIncomingEdges);
} else if (numberOfIncomingEdges == 0) {
childrenMap.get(v).add(child);
vertexQueue.add(child);
}
else {
for(AbstractLayoutVertex inNeighbor : graph.getVisibleInNeighbors(child)) {
System.out.print(inNeighbor.getId() + " ");
}
System.out.println();
}
} else if (child.getVertexStatus() == AbstractLayoutVertex.VertexStatus.GRAY) {
Integer numberOfIncomingEdges = vertexCounters.get(child);
if (numberOfIncomingEdges == null) {
System.out.println("Error Map\n\t " + vertexCounters);
}
else {
numberOfIncomingEdges -= 1; // v --> child
vertexCounters.put(child, numberOfIncomingEdges);
if (numberOfIncomingEdges == 0) {
childrenMap.get(v).add(child);
vertexQueue.add(child);
vertexCounters.remove(child);
}
}
}
}
v.setVertexStatus(AbstractLayoutVertex.VertexStatus.BLACK);
}
if(vertexCounters.size() > 0) {
System.out.println("BFS uncounted vertices, what happened to the incoming?!!! " + vertexCounters);
for (Map.Entry<AbstractLayoutVertex, Integer> entry : vertexCounters.entrySet()) {
System.out.println("\t\t" + entry + " --> " + entry.getKey().getId() + " "
+ entry.getKey().getVertexStatus() + " " + entry.getKey().getMethodVertices());
for(AbstractLayoutVertex n : graph.getVisibleInNeighbors(entry.getKey()))
{
System.out.println("\t\t\t" + n + " --> " + n.getId() + " " + n.getVertexStatus());
}
}
}
return childrenMap;
}
/**
* Preconditions: Height and Width of the inner nodes of the graph is (recursively known)
* input: graph and left/top offset
* Changes of Status: assigns X and Y to the inner vertices of the graph
* Output: returns the W and H to be assign to the parent node
* */
private static void storeBBoxWidthAndHeight(
AbstractLayoutVertex root,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap)
{
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
ArrayList<AbstractLayoutVertex> grayChildren = new ArrayList<AbstractLayoutVertex>();
for(AbstractLayoutVertex child: childrenMap.get(root)) {
if (child.getVertexStatus() == AbstractLayoutVertex.VertexStatus.WHITE) {
child.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
grayChildren.add(child);
}
}
double currentWidth = 0;
double currentHeight = 0;
for(AbstractLayoutVertex curVer: grayChildren)
{
storeBBoxWidthAndHeight(curVer, childrenMap);
currentWidth += curVer.getBboxWidth() + NODES_PADDING;
currentHeight = Math.max(currentHeight, curVer.getBboxHeight());
}
double currBboxWidth, currBboxHeight;
currBboxWidth = Math.max(root.getWidth(), currentWidth - NODES_PADDING);
if(grayChildren.size() == 0) {
currBboxHeight = root.getHeight();
}
else {
currBboxHeight = NODES_PADDING + root.getHeight() + currentHeight;
}
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.BLACK);
root.setBboxWidth(currBboxWidth);
root.setBboxHeight(currBboxHeight);
}
/**
* Preconditions: Height and width of the inner nodes of the graph is known (recursively)
* Input: graph and left/top offset
* State changes: assigns X and Y coordinates to the inner vertices of the graph
* */
private static void assignInnerCoordinates (AbstractLayoutVertex root, double left, double top,
HashMap<AbstractLayoutVertex, ArrayList<AbstractLayoutVertex>> childrenMap)
{
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
ArrayList<AbstractLayoutVertex> grayChildren = new ArrayList<>();
for(AbstractLayoutVertex child: childrenMap.get(root))
{
if (child.getVertexStatus() == AbstractLayoutVertex.VertexStatus.WHITE)
{
child.setVertexStatus(AbstractLayoutVertex.VertexStatus.GRAY);
grayChildren.add(child);
}
}
double currentWidth = 0;
double currentHeight = 0;
for(AbstractLayoutVertex curVer: grayChildren) {
currentWidth += curVer.getBboxWidth();
}
currentWidth += NODES_PADDING * (grayChildren.size() - 1);
// Check if the root is wider than the total width of its children.
double rootOverlap;
if(root.getWidth() >= currentWidth) {
rootOverlap = (root.getWidth() - currentWidth)/2;
} else {
rootOverlap = 0;
}
currentWidth = 0;
for(AbstractLayoutVertex curVer: grayChildren)
{
assignInnerCoordinates(curVer,currentWidth + left + rootOverlap,
NODES_PADDING + top + root.getHeight(), childrenMap);
currentWidth += curVer.getBboxWidth() + NODES_PADDING;
currentHeight = Math.max(currentHeight, curVer.getBboxHeight());
}
root.setX(left + ((root.getBboxWidth() - root.getWidth()) / 2.0)); //left-most corner x
root.setY(top); //top-most corner y
root.setVertexStatus(AbstractLayoutVertex.VertexStatus.BLACK);
}
}
| Minor refactor
| src/main/java/org/ucombinator/jaam/visualizer/layout/LayoutAlgorithm.java | Minor refactor |
|
Java | bsd-3-clause | 518cc3e2b53928c69ac1e4d3f585ec71f04b6d71 | 0 | interdroid/interdroid-vdb,kastur/interdroid-vdb,interdroid/interdroid-vdb,kastur/interdroid-vdb,interdroid/interdroid-vdb,kastur/interdroid-vdb | /*
* Copyright (c) 2008-2012 Vrije Universiteit, The Netherlands 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 Vrije Universiteit 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 interdroid.vdb.content.avro;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import interdroid.vdb.Authority;
import interdroid.vdb.content.EntityUriBuilder;
import interdroid.vdb.content.VdbConfig.RepositoryConf;
import interdroid.vdb.content.VdbProviderRegistry;
import interdroid.vdb.content.metadata.DatabaseFieldType;
import interdroid.vdb.content.orm.DbEntity;
import interdroid.vdb.content.orm.DbField;
import interdroid.vdb.content.orm.ORMGenericContentProvider;
import interdroid.vdb.persistence.api.VdbRepository;
import interdroid.vdb.persistence.api.VdbRepositoryRegistry;
import org.apache.avro.Schema;
import org.eclipse.jgit.lib.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.Uri;
/**
* This class holds a registry for avro content providers
* holding the namespace, name and schema for each avro provider.
*
* It is a content provider itself, constructed using the ORM
* system within VDB. Nothing like bootstrapping the system using
* your own dog food. ;)
*
* @author nick <[email protected]>
*
*/
public class AvroProviderRegistry extends ORMGenericContentProvider {
/**
* Access to logger.
*/
private static final Logger LOG = LoggerFactory
.getLogger(AvroProviderRegistry.class);
/**
* The registry configuration.
* @author nick <[email protected]>
*
*/
@DbEntity(name = AvroSchemaRegistrationHandler.NAME,
itemContentType = "vnd.android.cursor.item/"
+ AvroSchemaRegistrationHandler.FULL_NAME,
contentType = "vnd.android.cursor.dir/"
+ AvroSchemaRegistrationHandler.FULL_NAME)
public static final class RegistryConf {
/**
* No construction.
*/
private RegistryConf() { }
/**
* The default sort order for this table.
*/
public static final String DEFAULT_SORT_ORDER = "modified DESC";
/**
* The content URI for this type.
*/
public static final Uri CONTENT_URI =
Uri.withAppendedPath(EntityUriBuilder.branchUri(
Authority.VDB, AvroSchemaRegistrationHandler.NAMESPACE,
"master"), AvroSchemaRegistrationHandler.NAME);
/**
* The ID field.
*/
@DbField(isID = true, dbType = DatabaseFieldType.INTEGER)
public static final String ID = "_id";
/**
* The key field.
*/
@DbField(dbType = DatabaseFieldType.TEXT)
public static final String NAME =
AvroSchemaRegistrationHandler.KEY_NAME;
/**
* The namespace field.
*/
@DbField(dbType = DatabaseFieldType.TEXT)
public static final String NAMESPACE =
AvroSchemaRegistrationHandler.KEY_NAMESPACE;
/**
* The schema field.
*/
@DbField(dbType = DatabaseFieldType.TEXT)
public static final String SCHEMA =
AvroSchemaRegistrationHandler.KEY_SCHEMA;
}
/**
* The context we are working in.
*/
private Context mContext;
/**
* Construct a provider registry.
*/
public AvroProviderRegistry() {
super(AvroSchemaRegistrationHandler.NAMESPACE, RegistryConf.class);
}
/**
* Returns all repositories registered with the system.
* @return the list of repository configurations.
*/
public final List<RepositoryConf> getAllRepositories() {
Cursor c = null;
ArrayList<RepositoryConf> result = new ArrayList<RepositoryConf>();
try {
c = query(AvroSchemaRegistrationHandler.URI,
new String[]{AvroSchemaRegistrationHandler.KEY_NAMESPACE,
AvroSchemaRegistrationHandler.KEY_SCHEMA},
null, null, null);
if (c != null) {
while (c.moveToNext()) {
result.add(new RepositoryConf(
c.getString(0),
c.getString(1)));
}
}
} finally {
if (c != null) {
try {
c.close();
} catch (Exception e) {
LOG.warn("Exception while closing cursor: ", e);
}
}
}
return result;
}
@Override
public final void onAttach(final Context context, final ProviderInfo info) {
super.attachInfo(context, info);
mContext = context;
}
@Override
public final void onPostUpdate(final Uri uri, final ContentValues values,
final String where, final String[] whereArgs) {
try {
LOG.debug("Migrating DB: {} {}", values, whereArgs);
migrateDb(
whereArgs[0],
values.getAsString(AvroSchemaRegistrationHandler.KEY_SCHEMA));
} catch (IOException e) {
throw new RuntimeException("Error updating database.");
}
}
@Override
public final void onPostInsert(final Uri uri,
final ContentValues userValues) {
LOG.debug("On post insert: {}", userValues);
String name = userValues.getAsString(
AvroSchemaRegistrationHandler.KEY_NAMESPACE);
String schema = userValues.getAsString(
AvroSchemaRegistrationHandler.KEY_SCHEMA);
LOG.debug("Registering: {} {}", name, schema);
registerRepository(name, schema);
}
@Override
public final void onPostDelete(final Uri uri,
final String where, final String[] whereArgs) {
LOG.debug("Deleted avro repo: {}", whereArgs[0]);
VdbRepositoryRegistry.getInstance().deleteRepository(getContext(),
whereArgs[0]);
try {
new VdbProviderRegistry(getContext()).unregister(whereArgs[0]);
} catch (IOException e) {
// TODO: Auto-generated catch block
e.printStackTrace();
}
}
private void registerRepository(final String namespace, final String schema) {
VdbProviderRegistry registry;
try {
LOG.debug("Registering avro repo: {} {}", namespace, schema);
registry = new VdbProviderRegistry(mContext);
registry.registerRepository(
new RepositoryConf(namespace, schema));
} catch (IOException e) {
throw new RuntimeException("Unable to build registry: ", e);
}
}
/**
* Migrates a database from one schema to the new schema.
* @param namespace the namespace for the repository
* @param schemaString the new schema as a string.
* @throws IOException
*/
private void migrateDb(final String namespace, final String schemaString)
throws IOException {
// Make sure the repo is registered.
registerRepository(namespace, schemaString);
// Parse the schema
Schema newSchema = Schema.parse(schemaString);
VdbRepository repo = VdbRepositoryRegistry.getInstance()
.getRepository(getContext(), namespace);
repo.updateDatabase(Constants.MASTER, newSchema);
}
/**
* Queries for the schema for the given URI.
*
* @param context the context to query in
* @param uri the uri to retrieve the schema for
* @return the schema for the given uri
*/
public static Schema getSchema(final Context context, final Uri uri) {
Cursor c = null;
Schema schema = null;
Uri dbUri = uri;
try {
// We expect to deal with internal paths
if (!Authority.VDB.equals(uri.getAuthority())) {
LOG.debug("Mapping to native: {}", uri);
dbUri = EntityUriBuilder.toInternal(uri);
}
LOG.debug("Querying for schema for: {} {}", dbUri,
dbUri.getPathSegments().get(0));
c = context.getContentResolver().query(
AvroSchemaRegistrationHandler.URI,
new String[]{AvroSchemaRegistrationHandler.KEY_SCHEMA},
AvroSchemaRegistrationHandler.KEY_NAMESPACE + "=?",
new String[] {dbUri.getPathSegments().get(0)}, null);
if (c != null && c.moveToFirst()) {
String schemaString = c.getString(0);
LOG.debug("Got schema: {}", schemaString);
schema = Schema.parse(schemaString);
} else {
LOG.error("Schema not found.");
}
} finally {
if (c != null) {
try {
c.close();
} catch (Exception e) {
LOG.warn("Exception while closing cursor: ", e);
}
}
}
return schema;
}
}
| src/interdroid/vdb/content/avro/AvroProviderRegistry.java | /*
* Copyright (c) 2008-2012 Vrije Universiteit, The Netherlands 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 Vrije Universiteit 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 interdroid.vdb.content.avro;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import interdroid.vdb.Authority;
import interdroid.vdb.content.EntityUriBuilder;
import interdroid.vdb.content.VdbConfig.RepositoryConf;
import interdroid.vdb.content.VdbProviderRegistry;
import interdroid.vdb.content.metadata.DatabaseFieldType;
import interdroid.vdb.content.orm.DbEntity;
import interdroid.vdb.content.orm.DbField;
import interdroid.vdb.content.orm.ORMGenericContentProvider;
import interdroid.vdb.persistence.api.VdbRepository;
import interdroid.vdb.persistence.api.VdbRepositoryRegistry;
import org.apache.avro.Schema;
import org.eclipse.jgit.lib.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.Uri;
/**
* This class holds a registry for avro content providers
* holding the namespace, name and schema for each avro provider.
*
* It is a content provider itself, constructed using the ORM
* system within VDB. Nothing like bootstrapping the system using
* your own dog food. ;)
*
* @author nick <[email protected]>
*
*/
public class AvroProviderRegistry extends ORMGenericContentProvider {
/**
* Access to logger.
*/
private static final Logger LOG = LoggerFactory
.getLogger(AvroProviderRegistry.class);
/**
* The registry configuration.
* @author nick <[email protected]>
*
*/
@DbEntity(name = AvroSchemaRegistrationHandler.NAME,
itemContentType = "vnd.android.cursor.item/"
+ AvroSchemaRegistrationHandler.FULL_NAME,
contentType = "vnd.android.cursor.dir/"
+ AvroSchemaRegistrationHandler.FULL_NAME)
public static final class RegistryConf {
/**
* No construction.
*/
private RegistryConf() { }
/**
* The default sort order for this table.
*/
public static final String DEFAULT_SORT_ORDER = "modified DESC";
/**
* The content URI for this type.
*/
public static final Uri CONTENT_URI =
Uri.withAppendedPath(EntityUriBuilder.branchUri(
Authority.VDB, AvroSchemaRegistrationHandler.NAMESPACE,
"master"), AvroSchemaRegistrationHandler.NAME);
/**
* The ID field.
*/
@DbField(isID = true, dbType = DatabaseFieldType.INTEGER)
public static final String ID = "_id";
/**
* The key field.
*/
@DbField(dbType = DatabaseFieldType.TEXT)
public static final String NAME =
AvroSchemaRegistrationHandler.KEY_NAME;
/**
* The namespace field.
*/
@DbField(dbType = DatabaseFieldType.TEXT)
public static final String NAMESPACE =
AvroSchemaRegistrationHandler.KEY_NAMESPACE;
/**
* The schema field.
*/
@DbField(dbType = DatabaseFieldType.TEXT)
public static final String SCHEMA =
AvroSchemaRegistrationHandler.KEY_SCHEMA;
}
/**
* The context we are working in.
*/
private Context mContext;
/**
* Construct a provider registry.
*/
public AvroProviderRegistry() {
super(AvroSchemaRegistrationHandler.NAMESPACE, RegistryConf.class);
}
/**
* Returns all repositories registered with the system.
* @return the list of repository configurations.
*/
public final List<RepositoryConf> getAllRepositories() {
Cursor c = null;
ArrayList<RepositoryConf> result = new ArrayList<RepositoryConf>();
try {
c = query(AvroSchemaRegistrationHandler.URI,
new String[]{AvroSchemaRegistrationHandler.KEY_NAMESPACE,
AvroSchemaRegistrationHandler.KEY_SCHEMA},
null, null, null);
if (c != null) {
int namespaceIndex = c.getColumnIndex(
AvroSchemaRegistrationHandler.KEY_NAMESPACE);
int schemaIndex = c.getColumnIndex(
AvroSchemaRegistrationHandler.KEY_SCHEMA);
while (c.moveToNext()) {
result.add(new RepositoryConf(
c.getString(namespaceIndex),
c.getString(schemaIndex)));
}
}
} finally {
if (c != null) {
try {
c.close();
} catch (Exception e) {
LOG.warn("Exception while closing cursor: ", e);
}
}
}
return result;
}
@Override
public final void onAttach(final Context context, final ProviderInfo info) {
super.attachInfo(context, info);
mContext = context;
}
@Override
public final void onPostUpdate(final Uri uri, final ContentValues values,
final String where, final String[] whereArgs) {
try {
LOG.debug("Migrating DB: {} {}", values, whereArgs);
migrateDb(
whereArgs[0],
values.getAsString(AvroSchemaRegistrationHandler.KEY_SCHEMA));
} catch (IOException e) {
throw new RuntimeException("Error updating database.");
}
}
@Override
public final void onPostInsert(final Uri uri,
final ContentValues userValues) {
LOG.debug("On post insert: {}", userValues);
String name = userValues.getAsString(
AvroSchemaRegistrationHandler.KEY_NAMESPACE);
String schema = userValues.getAsString(
AvroSchemaRegistrationHandler.KEY_SCHEMA);
LOG.debug("Registering: {} {}", name, schema);
registerRepository(name, schema);
}
@Override
public final void onPostDelete(final Uri uri,
final String where, final String[] whereArgs) {
LOG.debug("Deleted avro repo: {}", whereArgs[0]);
VdbRepositoryRegistry.getInstance().deleteRepository(getContext(),
whereArgs[0]);
try {
new VdbProviderRegistry(getContext()).unregister(whereArgs[0]);
} catch (IOException e) {
// TODO: Auto-generated catch block
e.printStackTrace();
}
}
private void registerRepository(final String namespace, final String schema) {
VdbProviderRegistry registry;
try {
LOG.debug("Registering avro repo: {} {}", namespace, schema);
registry = new VdbProviderRegistry(mContext);
registry.registerRepository(
new RepositoryConf(namespace, schema));
} catch (IOException e) {
throw new RuntimeException("Unable to build registry: ", e);
}
}
/**
* Migrates a database from one schema to the new schema.
* @param namespace the namespace for the repository
* @param schemaString the new schema as a string.
* @throws IOException
*/
private void migrateDb(final String namespace, final String schemaString)
throws IOException {
// Make sure the repo is registered.
registerRepository(namespace, schemaString);
// Parse the schema
Schema newSchema = Schema.parse(schemaString);
VdbRepository repo = VdbRepositoryRegistry.getInstance()
.getRepository(getContext(), namespace);
repo.updateDatabase(Constants.MASTER, newSchema);
}
/**
* Queries for the schema for the given URI.
*
* @param context the context to query in
* @param uri the uri to retrieve the schema for
* @return the schema for the given uri
*/
public static Schema getSchema(final Context context, final Uri uri) {
Cursor c = null;
Schema schema = null;
Uri dbUri = uri;
try {
// We expect to deal with internal paths
if (!Authority.VDB.equals(uri.getAuthority())) {
LOG.debug("Mapping to native: {}", uri);
dbUri = EntityUriBuilder.toInternal(uri);
}
LOG.debug("Querying for schema for: {} {}", dbUri,
dbUri.getPathSegments().get(0));
c = context.getContentResolver().query(
AvroSchemaRegistrationHandler.URI,
new String[]{AvroSchemaRegistrationHandler.KEY_SCHEMA},
AvroSchemaRegistrationHandler.KEY_NAMESPACE + "=?",
new String[] {dbUri.getPathSegments().get(0)}, null);
if (c != null && c.moveToFirst()) {
int schemaIndex = c.getColumnIndex(
AvroSchemaRegistrationHandler.KEY_SCHEMA);
String schemaString = c.getString(schemaIndex);
LOG.debug("Got schema: {}", schemaString);
schema = Schema.parse(schemaString);
} else {
LOG.error("Schema not found.");
}
} finally {
if (c != null) {
try {
c.close();
} catch (Exception e) {
LOG.warn("Exception while closing cursor: ", e);
}
}
}
return schema;
}
}
| Use direct column constants.
| src/interdroid/vdb/content/avro/AvroProviderRegistry.java | Use direct column constants. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.