answer
stringlengths 17
10.2M
|
|---|
package de.fau.amos.virtualledger.android.views.calendar;
import android.widget.Toast;
import com.roomorama.caldroid.CaldroidFragment;
import com.roomorama.caldroid.CaldroidGridAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import javax.inject.Inject;
import de.fau.amos.virtualledger.android.dagger.App;
import de.fau.amos.virtualledger.android.data.BankingDataManager;
import de.fau.amos.virtualledger.android.data.BankingSyncFailedException;
import de.fau.amos.virtualledger.android.views.transactionOverview.Transaction;
import de.fau.amos.virtualledger.android.views.transactionOverview.TransactionsComparator;
import de.fau.amos.virtualledger.dtos.BankAccountBookings;
import de.fau.amos.virtualledger.dtos.Booking;
import hirondelle.date4j.DateTime;
public class CaldroidBankingFragment extends CaldroidFragment {
@Inject
BankingDataManager bankingDataManager;
private HashMap<DateTime, BankingDateInformation> bankingDateInformationMap;
@Override
public CaldroidGridAdapter getNewDatesGridAdapter(int month, int year) {
((App) getActivity().getApplication()).getNetComponent().inject(this);
init();
return new CaldroidBankingCellAdapter(getContext(), month, year, getCaldroidData(), getExtraData(), bankingDateInformationMap );
}
private void init() {
bankingDateInformationMap = new HashMap<>();
// TODO get from Fragment instantiation
List<Transaction> transactionList = new ArrayList<>();
double totalAmount = 1000.000;
Collections.sort(transactionList, new TransactionsComparator());
for(int i = 0; i < transactionList.size(); ++i) {
Booking booking = transactionList.get(i).booking();
Date date = booking.getDate();
DateTime dateTime = DateTime.forInstantNanos(date.getTime(), TimeZone.getDefault());
BankingDateInformation bankingDateInformation = bankingDateInformationMap.get(dateTime);
if(bankingDateInformation == null) {
bankingDateInformation = new BankingDateInformation(dateTime, totalAmount, new ArrayList<Booking>());
bankingDateInformationMap.put(dateTime, bankingDateInformation);
}
bankingDateInformation.getBookingList().add(booking);
bankingDateInformation.setAmount(totalAmount - booking.getAmount());
totalAmount -= booking.getAmount();
}
}
}
|
package com.sample.demo;
import java.util.stream.IntStream;
public class Java8FizzBuzz {
/*
* Java 8
* */
public static void main(String[] args) {
IntStream.range(1,100).forEach(i -> {
String s = "";
s = i % 3 == 0 ? "Fizz " : "";
s += i % 5 == 0 ? "Buzz " : "";
if(!s.isEmpty()) System.out.println(s);
});
}
}
|
package org.csstudio.swt.xygraph.figures;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.csstudio.swt.xygraph.linearscale.AbstractScale.LabelSide;
import org.csstudio.swt.xygraph.linearscale.LinearScale.Orientation;
import org.csstudio.swt.xygraph.undo.OperationsManager;
import org.csstudio.swt.xygraph.undo.ZoomCommand;
import org.csstudio.swt.xygraph.undo.ZoomType;
import org.csstudio.swt.xygraph.util.XYGraphMediaFactory;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.SWTGraphics;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
/**
* XY-Graph Figure.
* @author Xihui Chen
*
*/
public class XYGraph extends Figure{
private static final int GAP = 2;
public final static Color WHITE_COLOR = ColorConstants.white;
public final static Color BLACK_COLOR = ColorConstants.black;
public final static Color[] DEFAULT_TRACES_COLOR = new Color[]{
ColorConstants.red,
ColorConstants.blue,
ColorConstants.darkGreen,
ColorConstants.orange,
ColorConstants.darkBlue,
ColorConstants.cyan,
ColorConstants.green,
ColorConstants.yellow,
ColorConstants.black
};
private int traceNum = 0;
private boolean transparent = true;
private boolean showLegend = true;
private Map<Axis, Legend> legendMap;
private String title;
private Color titleColor;
private Label titleLabel;
private List<Axis> xAxisList;
private List<Axis> yAxisList;
private PlotArea plotArea;
public Axis primaryXAxis;
public Axis primaryYAxis;
private OperationsManager operationsManager;
private ZoomType zoomType;
/**
* Constructor.
*/
public XYGraph() {
setOpaque(!transparent);
legendMap = new LinkedHashMap<Axis, Legend>();
titleLabel = new Label();
setTitleFont(XYGraphMediaFactory.getInstance().getFont(
new FontData("Arial", 12, SWT.BOLD)));
//titleLabel.setVisible(false);
xAxisList = new ArrayList<Axis>();
yAxisList = new ArrayList<Axis>();
plotArea = new PlotArea(this);
add(titleLabel);
add(plotArea);
primaryYAxis = new Axis("Y-Axis", true);
primaryYAxis.setOrientation(Orientation.VERTICAL);
primaryYAxis.setTickLableSide(LabelSide.Primary);
primaryYAxis.setAutoScaleThreshold(0.1);
addAxis(primaryYAxis);
primaryXAxis = new Axis("X-Axis", false);
primaryXAxis.setOrientation(Orientation.HORIZONTAL);
primaryXAxis.setTickLableSide(LabelSide.Primary);
addAxis(primaryXAxis);
operationsManager = new OperationsManager();
}
@Override
public boolean isOpaque() {
return false;
}
@Override
protected void layout() {
Rectangle clientArea = getClientArea().getCopy();
boolean hasRightYAxis = false;
boolean hasTopXAxis = false;
if(titleLabel != null && titleLabel.isVisible() && !titleLabel.getText().equals("")){
Dimension titleSize = titleLabel.getPreferredSize();
titleLabel.setBounds(new Rectangle(clientArea.x + clientArea.width/2 - titleSize.width/2,
clientArea.y, titleSize.width, titleSize.height));
clientArea.y += titleSize.height + GAP;
clientArea.height -= titleSize.height + GAP;
}
if(showLegend){
List<Integer> rowHPosList = new ArrayList<Integer>();
List<Dimension> legendSizeList = new ArrayList<Dimension>();
List<Integer> rowLegendNumList = new ArrayList<Integer>();
List<Legend> legendList = new ArrayList<Legend>();
Object[] yAxes = legendMap.keySet().toArray();
int hPos = 0;
int rowLegendNum = 0;
for(int i = 0; i< yAxes.length; i++){
Legend legend = legendMap.get(yAxes[i]);
if(legend != null && legend.isVisible()){
legendList.add(legend);
Dimension legendSize = legend.getPreferredSize(clientArea.width, clientArea.height);
legendSizeList.add(legendSize);
if((hPos+legendSize.width + GAP) > clientArea.width){
if(rowLegendNum ==0)
break;
rowHPosList.add(clientArea.x + (clientArea.width-hPos)/2);
rowLegendNumList.add(rowLegendNum);
rowLegendNum = 1;
hPos = legendSize.width + GAP;
clientArea.height -=legendSize.height +GAP;
if(i==yAxes.length-1){
hPos =legendSize.width + GAP;
rowLegendNum = 1;
rowHPosList.add(clientArea.x + (clientArea.width-hPos)/2);
rowLegendNumList.add(rowLegendNum);
clientArea.height -=legendSize.height +GAP;
}
}else{
hPos+=legendSize.width + GAP;
rowLegendNum++;
if(i==yAxes.length-1){
rowHPosList.add(clientArea.x + (clientArea.width-hPos)/2);
rowLegendNumList.add(rowLegendNum);
clientArea.height -=legendSize.height +GAP;
}
}
}
}
int lm = 0;
int vPos = clientArea.y + clientArea.height + GAP;
for(int i=0; i<rowLegendNumList.size(); i++){
hPos = rowHPosList.get(i);
for(int j=0; j<rowLegendNumList.get(i); j++){
legendList.get(lm).setBounds(new Rectangle(
hPos, vPos, legendSizeList.get(lm).width, legendSizeList.get(lm).height));
hPos += legendSizeList.get(lm).width + GAP;
lm++;
}
vPos += legendSizeList.get(lm-1).height + GAP;
}
}
for(int i=xAxisList.size()-1; i>=0; i
Axis xAxis = xAxisList.get(i);
Dimension xAxisSize = xAxis.getPreferredSize(clientArea.width, clientArea.height);
if(xAxis.getTickLablesSide() == LabelSide.Primary){
xAxis.setBounds(new Rectangle(clientArea.x,
clientArea.y + clientArea.height - xAxisSize.height,
xAxisSize.width, xAxisSize.height));
clientArea.height -= xAxisSize.height;
}else{
hasTopXAxis = true;
xAxis.setBounds(new Rectangle(clientArea.x,
clientArea.y+1,
xAxisSize.width, xAxisSize.height));
clientArea.y += xAxisSize.height ;
clientArea.height -= xAxisSize.height;
}
}
for(int i=yAxisList.size()-1; i>=0; i
Axis yAxis = yAxisList.get(i);
Dimension yAxisSize = yAxis.getPreferredSize(clientArea.width,
clientArea.height + (hasTopXAxis? 2:1) *yAxis.getMargin());
if(yAxis.getTickLablesSide() == LabelSide.Primary){ // on the left
yAxis.setBounds(new Rectangle(clientArea.x,
clientArea.y - (hasTopXAxis? yAxis.getMargin():0),
yAxisSize.width, yAxisSize.height));
clientArea.x += yAxisSize.width;
clientArea.width -= yAxisSize.width;
}else{ // on the right
hasRightYAxis = true;
yAxis.setBounds(new Rectangle(clientArea.x + clientArea.width - yAxisSize.width -1,
clientArea.y- (hasTopXAxis? yAxis.getMargin():0),
yAxisSize.width, yAxisSize.height));
clientArea.width -= yAxisSize.width;
}
}
//re-adjust xAxis boundss
for(int i=xAxisList.size()-1; i>=0; i
Axis xAxis = xAxisList.get(i);
xAxis.getBounds().x = clientArea.x - xAxis.getMargin()-1;
if(hasRightYAxis)
xAxis.getBounds().width = clientArea.width + 2*xAxis.getMargin();
else
xAxis.getBounds().width = clientArea.width + xAxis.getMargin();
}
if(plotArea != null && plotArea.isVisible()){
Rectangle plotAreaBound = new Rectangle(
primaryXAxis.getBounds().x + primaryXAxis.getMargin(),
primaryYAxis.getBounds().y + primaryYAxis.getMargin(),
primaryXAxis.getBounds().width - 2*primaryXAxis.getMargin(),
primaryYAxis.getBounds().height - 2*primaryYAxis.getMargin()
);
plotArea.setBounds(plotAreaBound);
}
super.layout();
}
/**
* @param zoomType the zoomType to set
*/
public void setZoomType(ZoomType zoomType) {
this.zoomType = zoomType;
plotArea.setZoomType(zoomType);
for(Axis axis : xAxisList)
axis.setZoomType(zoomType);
for(Axis axis : yAxisList)
axis.setZoomType(zoomType);
}
/**
* @return the zoomType
*/
public ZoomType getZoomType() {
return zoomType;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
titleLabel.setText(title);
}
/**
* @param showTitle true if title should be shown; false otherwise.
*/
public void setShowTitle(boolean showTitle){
titleLabel.setVisible(showTitle);
revalidate();
}
/**
* @return true if title should be shown; false otherwise.
*/
public boolean isShowTitle(){
return titleLabel.isVisible();
}
/**
* @param showLegend true if legend should be shown; false otherwise.
*/
public void setShowLegend(boolean showLegend){
this.showLegend = showLegend;
for(Axis yAxis : legendMap.keySet()){
Legend legend = legendMap.get(yAxis);
legend.setVisible(showLegend);
}
revalidate();
}
/**
* @return the showLegend
*/
public boolean isShowLegend() {
return showLegend;
}
/**Add an axis to the graph
* @param axis
*/
public void addAxis(Axis axis){
if(axis.isHorizontal())
xAxisList.add(axis);
else
yAxisList.add(axis);
plotArea.addGrid(new Grid(axis));
add(axis);
axis.setXyGraph(this);
revalidate();
}
/**Remove an axis from the graph
* @param axis
* @return true if this axis exists.
*/
public boolean removeAxis(Axis axis){
remove(axis);
plotArea.removeGrid(axis.getGrid());
revalidate();
if(axis.isHorizontal())
return xAxisList.remove(axis);
else
return yAxisList.remove(axis);
}
/**Add a trace
* @param trace
*/
public void addTrace(Trace trace){
if (trace.getTraceColor() == null)
{ // Cycle through default colors
trace.setTraceColor(DEFAULT_TRACES_COLOR[traceNum % DEFAULT_TRACES_COLOR.length]);
++traceNum;
}
if(legendMap.containsKey(trace.getYAxis()))
legendMap.get(trace.getYAxis()).addTrace(trace);
else{
legendMap.put(trace.getYAxis(), new Legend());
legendMap.get(trace.getYAxis()).addTrace(trace);
add(legendMap.get(trace.getYAxis()));
}
plotArea.addTrace(trace);
trace.setXYGraph(this);
trace.dataChanged(null);
revalidate();
}
/**Remove a trace.
* @param trace
*/
public void removeTrace(Trace trace){
if(legendMap.containsKey(trace.getYAxis())){
legendMap.get(trace.getYAxis()).removeTrace(trace);
if(legendMap.get(trace.getYAxis()).getTraceList().size() <=0){
remove(legendMap.remove(trace.getYAxis()));
}
}
plotArea.removeTrace(trace);
revalidate();
}
/**Add an annotation
* @param annotation
*/
public void addAnnotation(Annotation annotation){
plotArea.addAnnotation(annotation);
}
/**Remove an annotation
* @param annotation
*/
public void removeAnnotation(Annotation annotation){
plotArea.removeAnnotation(annotation);
}
/**
* @param titleFont the titleFont to set
*/
public void setTitleFont(Font titleFont) {
titleLabel.setFont(titleFont);
}
/**
* @return the title font.
*/
public Font getTitleFont(){
return titleLabel.getFont();
}
/**
* @param titleColor the titleColor to set
*/
public void setTitleColor(Color titleColor) {
this.titleColor = titleColor;
titleLabel.setForegroundColor(titleColor);
}
/**
* {@inheritDoc}
*/
public void paintFigure(final Graphics graphics) {
if (!transparent) {
graphics.fillRectangle(getClientArea());
}
super.paintFigure(graphics);
}
/**
* @param transparent the transparent to set
*/
public void setTransparent(boolean transparent) {
this.transparent = transparent;
repaint();
}
/**
* @return the transparent
*/
public boolean isTransparent() {
return transparent;
}
/**
* @return the plotArea, which contains all the elements drawn inside it.
*/
public PlotArea getPlotArea() {
return plotArea;
}
/**
* @return the image of the XYFigure
*/
public Image getImage(){
Image image = new Image(null, bounds.width + 6, bounds.height + 6);
GC gc = new GC(image);
SWTGraphics graphics = new SWTGraphics(gc);
graphics.translate(-bounds.x + 3, -bounds.y + 3);
graphics.setForegroundColor(getForegroundColor());
graphics.setBackgroundColor(getBackgroundColor());
paint(graphics);
gc.dispose();
return image;
}
/**
* @return the titleColor
*/
public Color getTitleColor() {
if(titleColor == null)
return getForegroundColor();
return titleColor;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @return the operationsManager
*/
public OperationsManager getOperationsManager() {
return operationsManager;
}
/**
* @return the xAxisList
*/
public List<Axis> getXAxisList() {
return xAxisList;
}
/**
* @return the yAxisList
*/
public List<Axis> getYAxisList() {
return yAxisList;
}
/**
* @return the all the axis include xAxes and yAxes.
* yAxisList is appended to xAxisList in the returned list.
*/
public List<Axis> getAxisList(){
List<Axis> list = new ArrayList<Axis>();
list.addAll(xAxisList);
list.addAll(yAxisList);
return list;
}
/**
* @return the legendMap
*/
public Map<Axis, Legend> getLegendMap() {
return legendMap;
}
/**
* Perform forced autoscale to all axes.
*/
public void performAutoScale(){
ZoomCommand command = new ZoomCommand("Auto Scale", xAxisList, yAxisList);
command.savePreviousStates();
for(Axis axis : xAxisList){
axis.performAutoScale(true);
}
for(Axis axis : yAxisList){
axis.performAutoScale(true);
}
command.saveAfterStates();
operationsManager.addCommand(command);
}
}
|
// $Id: CommonTest.java,v 1.2 2004/03/01 15:38:21 belaban Exp $
package org.jgroups.tests;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import junit.framework.*;
import org.jgroups.log.Trace;
public class CommonTest extends TestCase {
protected static final int TEST_SOCKET_PORT=12345;
protected static final String TMP_OUTPUT_FILE="Common_test.out";
protected static final String TMP_ROOT=System.getProperty("tests.tmp.dir") != null ?
System.getProperty("tests.tmp.dir") :
(System.getProperty("java.io.tmpdir") != null ? System.getProperty("java.io.tmpdir") : "/tmp");
protected static final String GENERATED_TMP_OUTPUT_FILE=
TMP_ROOT + "/Module_DEBUG";
protected static final String GENERATED_METHOD_TMP_OUTPUT_FILE=
TMP_ROOT + "/Module.method_FATAL";
protected File tmpOutput;
protected File generatedTmpOutput;
protected File generatedMethodTmpOutput;
protected String[] expectedDebugResults={
"] [DEBUG] Module: module debug",
"] [FATAL] Module: module fatal",
"] [DEBUG] Module.method(): module with method name",
"] [DEBUG] Module.method(arg): module with method name and arg"
};
protected String[] expectedFatalResults={
"] [FATAL] Module: module fatal",
};
protected String[] expectedDefaultResults={
"] [DEBUG] Module2: output to default",
};
// Lets JUnit use reflection to find all test* methods and add them to the
// test suite.
// Actually, as of JUnit version 2.1 even this method is no
// longer necessary. Junit's TestRunner will automatically find and run
// all public void methods that start with "test".
public static Test suite() {
return new TestSuite(CommonTest.class);
}
public void setUp() {
tmpOutput=new File(TMP_OUTPUT_FILE);
generatedTmpOutput=new File(GENERATED_TMP_OUTPUT_FILE);
generatedMethodTmpOutput=new File(GENERATED_METHOD_TMP_OUTPUT_FILE);
Trace.closeAllOutputs();
Trace.restoreDefaultOutput();
Trace.setDefaultOutput(Trace.DEBUG, System.out);
deleteTempFiles();
}
public void tearDown() {
Trace.closeAllOutputs();
deleteTempFiles();
}
protected void deleteTempFiles() {
if(tmpOutput.exists()) tmpOutput.delete();
if(generatedTmpOutput.exists()) generatedTmpOutput.delete();
if(generatedMethodTmpOutput.exists()) generatedMethodTmpOutput.delete();
}
public CommonTest(String name) {
super(name);
}
// Test a bug reported by Bela.
public void testInnerClasses() {
try {
Trace.setOutput("FD", Trace.DEBUG, TMP_OUTPUT_FILE);
Trace.println("FD.PingThread.run()", Trace.WARN, "thread terminated");
Trace.println("FD.setProperties()", Trace.FATAL,
"property timeout not recognized");
Trace.closeAllOutputs();
String[] expectedResults={
"] [WARN] FD.PingThread.run(): thread terminated",
"] [FATAL] FD.setProperties(): property timeout not recognized",
};
compareOutputs(TMP_OUTPUT_FILE, expectedResults);
}
catch(IOException e) {
fail("testInnerClasses: exception " + e + " thrown");
}
}
public void testBogusModuleName() {
try {
Trace.setOutput("method()", Trace.DEBUG, TMP_OUTPUT_FILE);
// Trace.setDefaultOutput("/dev/null");
Trace.closeDefaultOutput();
// Messages should go to default output (/dev/null)
sendTestMessages();
Trace.closeOutput("method()");
// Make sure file was never created.
File f=new File(TMP_OUTPUT_FILE);
assertTrue("testBogusModuleName: file should never be created",
!f.exists());
}
catch(IOException e) {
fail("testBogusModuleName: exception " + e + " thrown");
}
}
public void testNullDefaultOutputOK() {
//try {
Trace.closeDefaultOutput();
Trace.println("Module", Trace.DEBUG, "nowhere to go");
//catch (Exception e) {
//fail("testNullDefaultOutputOK: exception " + e + " thrown");
}
// Change default output to TMP_OUTPUT_FILE and make sure we see output
// not destined for any other place.
public void testChangeDefaultOutput() {
try {
Trace.setDefaultOutput(TMP_OUTPUT_FILE);
// Trace.setOutput() has not been called; all output should go
// to default output.
sendTestMessages();
Trace.restoreDefaultOutput(); // Closes TMP_OUTPUT_FILE
compareOutputs(TMP_OUTPUT_FILE, expectedDebugResults);
}
catch(Exception e) {
Thread.dumpStack();
fail("testChangeDefaultOutput: exception " + e + " thrown");
}
}
// Send messages to default default output (STDOUT).
public void testDefaultOutput() {
try {
// Reset system out to known file. This doesn't use Trace code;
// we are telling the System class to redirect stdout.
PrintStream origSystemOut=System.out;
PrintStream newSystemOut=
new PrintStream(new FileOutputStream(TMP_OUTPUT_FILE));
System.setOut(newSystemOut);
// Since no output assigned for Module2, should go to stdout
Trace.println("Module2", Trace.DEBUG, "output to default");
// Restore system out
System.setOut(origSystemOut);
newSystemOut.flush();
newSystemOut.close();
// Compare contents of log file to array of expected results strings
compareOutputs(TMP_OUTPUT_FILE, expectedDefaultResults);
}
catch(Exception e) {
fail("testDefaultOutput: exception " + e + " thrown");
}
}
public void testDefaultWithLevel() {
try {
Trace.setDefaultOutput(Trace.FATAL, TMP_OUTPUT_FILE);
sendTestMessages();
Trace.closeDefaultOutput();
// Compare contents of log file to array of expected results strings
compareOutputs(TMP_OUTPUT_FILE, expectedFatalResults);
}
catch(IOException e) {
fail("testDefaultWithLevel: exception " + e + " thrown");
}
}
public void testDebugFileOutput() {
_testFileOutput(Trace.DEBUG, expectedDebugResults);
}
public void testFatalFileOutput() {
_testFileOutput(Trace.FATAL, expectedFatalResults);
}
// Also tests "inheritance" because we set output for "Module" but print to
// "Module", "Module.method()", "Module.method(arg)". We don't have to test
// here for unassigned modules because that is tested in
// <code>testStdoutDefault</code>.
protected void _testFileOutput(int level, String[] expectedResults) {
try {
// Set output to temp file.
Trace.setOutput("Module", level, TMP_OUTPUT_FILE);
sendTestMessages();
// Close output so temp file is flushed and closed.
Trace.closeOutput("Module");
// Compare contents of log file to array of expected results strings
compareOutputs(TMP_OUTPUT_FILE, expectedResults);
}
catch(Exception e) {
fail("exception " + e + " thrown");
}
}
// Test call to setOutput with System.err as argument.
public void testStreamOutput() {
try {
// Reset system err to known file
PrintStream origSystemErr=System.err;
System.setErr(new PrintStream(new FileOutputStream(TMP_OUTPUT_FILE)));
// Set output to stderr.
Trace.setOutput("Module", Trace.DEBUG, System.err);
sendTestMessages();
// Restore system err
System.setErr(origSystemErr);
// Close output so temp file is flushed and closed.
Trace.closeOutput("Module");
// Compare contents of log file to array of expected results strings
compareOutputs(TMP_OUTPUT_FILE, expectedDebugResults);
}
catch(Exception e) {
fail("exception " + e + " thrown");
}
}
public void testSocketOutput() {
try {
final ServerSocket serverSocket=new ServerSocket(0); // Any free port
int port=serverSocket.getLocalPort();
// Create separate thread to act as server and listen for input
new Thread(new Runnable() {
public void run() {
try {
// Open socket
Socket listener=serverSocket.accept();
byte[] buf=new byte[1024];
StringBuffer lineBuffer=new StringBuffer();
// Read one line
int numBytesRead;
while(true) {
numBytesRead=listener.getInputStream().read(buf);
lineBuffer.append(new String(buf, 0, numBytesRead));
if(buf[numBytesRead - 1] == (byte)'\n')
break;
}
// Close socket
listener.close();
serverSocket.close();
// Compare expected string to what we received
String line=lineBuffer.toString();
int endOfDate=line.indexOf(']');
assertEquals("] [DEBUG] Module: socket message\n",
line.substring(endOfDate));
}
catch(Exception e) {
fail("exception " + e + " thrown");
}
}
}).start();
// Send string to server
Trace.setOutput("Module", Trace.DEBUG, InetAddress.getLocalHost(),
port);
Trace.println("Module", Trace.DEBUG, "socket message");
}
catch(Exception e) {
fail("exception " + e + " thrown");
}
}
// Send messages common to many tests.
protected void sendTestMessages() {
Trace.println("Module", Trace.DEBUG, "module debug");
Trace.println("Module", Trace.FATAL, "module fatal");
Trace.println("Module.method()", Trace.DEBUG,
"module with method name");
Trace.println("Module.method(arg)", Trace.DEBUG,
"module with method name and arg");
}
// Compare output file with array of expected result strings.
protected void compareOutputs(String outputFileName, String[] expectedResults)
throws FileNotFoundException, IOException {
BufferedReader in=
new BufferedReader(new FileReader(outputFileName));
String input=null;
for(int i=0; i < expectedResults.length; ++i) {
input=in.readLine();
assertNotNull("unexpected EOF in module output; expected to see <"
+ expectedResults[i] + ">", input);
int endOfDate=input.indexOf(']');
assertTrue("compareOutputs: malformed output string (no brackets): '"
+ input + "'", endOfDate != -1);
assertEquals(expectedResults[i], input.substring(endOfDate));
}
// Look for extra, unexpected output.
input=in.readLine();
assertNull("trace output has too much output; saw <" + input + ">",
input);
}
public void testFileNameGeneration() {
try {
Trace.setOutput("Module", Trace.DEBUG, TMP_ROOT);
Trace.setOutput("Module.method()", Trace.FATAL, TMP_ROOT);
assertTrue(generatedTmpOutput.exists());
assertTrue(generatedMethodTmpOutput.exists());
Trace.closeOutput("Module");
Trace.closeOutput("Module.method()");
assertTrue(generatedTmpOutput.exists());
assertTrue(generatedMethodTmpOutput.exists());
}
catch(IOException e) {
fail("testFileNameGeneration threw exception " + e);
}
}
// Make sure that writing to a file, then closing it, then using it again
// appends to the file.
public void testAppend() {
try {
Trace.setOutput("Module", Trace.DEBUG, TMP_OUTPUT_FILE);
Trace.println("Module", Trace.DEBUG, "double the fun");
sendTestMessages();
Trace.closeOutput("Module");
Trace.setOutput("Module", Trace.DEBUG, TMP_OUTPUT_FILE);
sendTestMessages();
Trace.closeOutput("Module");
// Set up expected results: double the pleasure, double the fun
String[] doubleExpected=
new String[expectedDebugResults.length * 2 + 1];
doubleExpected[0]="] [DEBUG] Module: double the fun";
System.arraycopy(expectedDebugResults, 0,
doubleExpected, 1,
expectedDebugResults.length);
System.arraycopy(expectedDebugResults, 0,
doubleExpected, expectedDebugResults.length,
expectedDebugResults.length);
for(int i=0; i < expectedDebugResults.length; ++i)
doubleExpected[i + 1]=
doubleExpected[i + expectedDebugResults.length + 1]=
expectedDebugResults[i];
compareOutputs(TMP_OUTPUT_FILE, doubleExpected);
}
catch(IOException e) {
fail("testAppend threw exception " + e);
}
}
// This test deleted by jimm because (a) the default date format was changed
// by bela and (b) it was a rather simplistic, unnecessary test anyway.
// public void testDateFormatting() {
// Date d = new Date();
// String nullFormat = Format.formatTimestamp(d, null);
// String iso = Format.formatTimestamp(d, "yyyy-MM-dd'T'hh:mm:ss,S");
// assertEquals(nullFormat, iso);
// // System.out.println(Format.formatTimestamp(d, "MM/dd/yy"));
// Open two modules on the same file. Write output. Close one. Make sure
// output is what we expect. Write some more via the second module. Check
// the output again.
public void testOpenTwoCloseOne() {
try {
// Send output from two different modules to the same file.
Trace.setOutput("Module", Trace.DEBUG, TMP_OUTPUT_FILE);
Trace.setOutput("AnotherModule", Trace.DEBUG, TMP_OUTPUT_FILE);
sendTestMessages();
Trace.closeOutput("Module");
// Compare contents of log file to array of expected results strings
compareOutputs(TMP_OUTPUT_FILE, expectedDebugResults);
// What happens when we continue writing via AnotherModule?
Trace.println("AnotherModule", Trace.DEBUG, "more output");
Trace.closeOutput("AnotherModule");
// Set up expected results.
String[] expected=new String[expectedDebugResults.length + 1];
System.arraycopy(expectedDebugResults, 0, expected, 0,
expectedDebugResults.length);
expected[expectedDebugResults.length]=
"] [DEBUG] AnotherModule: more output";
// Compare contents of log file to array of expected results strings
compareOutputs(TMP_OUTPUT_FILE, expected);
}
catch(IOException e) {
fail("testOpenTwoCloseOne threw exception " + e);
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
|
package com.netflix.astyanax.entitystore;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.persistence.PersistenceException;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.model.CqlResult;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;
import com.netflix.astyanax.partitioner.BigInteger127Partitioner;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.query.ColumnFamilyQuery;
import com.netflix.astyanax.recipes.reader.AllRowsReader;
import com.netflix.astyanax.retry.RetryPolicy;
import com.netflix.astyanax.serializers.StringSerializer;
/**
* Manager entities in a column famliy with any key type but columns that are
* encoded as strings.
*/
public class DefaultEntityManager<T, K> implements EntityManager<T, K> {
// Builder pattern
public static class Builder<T, K> {
private Class<T> clazz = null;
private EntityMapper<T,K> entityMapper = null;
private Keyspace keyspace = null;
private ColumnFamily<K, String> columnFamily = null;
private ConsistencyLevel readConsitency = null;
private ConsistencyLevel writeConsistency = null;
private Integer ttl = null;
private RetryPolicy retryPolicy = null;
private LifecycleEvents<T> lifecycleHandler = null;
private String columnFamilyName = null;
private boolean autoCommit = true;
private Partitioner partitioner = DEFAULT_ENTITY_MANAGER_PARTITIONER;
public Builder() {
}
/**
* mandatory
* @param clazz entity class type
*/
public Builder<T, K> withEntityType(Class<T> clazz) {
Preconditions.checkNotNull(clazz);
this.clazz = clazz;
return this;
}
/**
* mandatory
* @param keyspace
*/
public Builder<T, K> withKeyspace(Keyspace keyspace) {
Preconditions.checkNotNull(keyspace);
this.keyspace = keyspace;
return this;
}
/**
* optional
* @param columnFamily column name type is fixed to String/UTF8
*/
public Builder<T, K> withColumnFamily(ColumnFamily<K, String> columnFamily) {
Preconditions.checkState(this.columnFamilyName == null && this.columnFamily == null , "withColumnFamily called multiple times");
Preconditions.checkNotNull(columnFamily);
this.columnFamily = columnFamily;
return this;
}
/**
* optional
* @param columnFamilyName Name of column family to use.
*/
public Builder<T, K> withColumnFamily(String columnFamilyName) {
Preconditions.checkState(this.columnFamilyName == null && columnFamily == null , "withColumnFamily called multiple times");
Preconditions.checkNotNull(columnFamilyName);
this.columnFamilyName = columnFamilyName;
return this;
}
/**
* optional
* @param level
*/
public Builder<T, K> withReadConsistency(ConsistencyLevel level) {
Preconditions.checkNotNull(level);
this.readConsitency = level;
return this;
}
/**
* optional
* @param level
*/
public Builder<T, K> withWriteConsistency(ConsistencyLevel level) {
Preconditions.checkNotNull(level);
this.writeConsistency = level;
return this;
}
/**
* set both read and write consistency
* optional
* @param level
*/
public Builder<T, K> withConsistency(ConsistencyLevel level) {
Preconditions.checkNotNull(level);
this.readConsitency = level;
this.writeConsistency = level;
return this;
}
/**
* default TTL for all columns written to cassandra
* optional
* @return
*/
public Builder<T, K> withTTL(Integer ttl) {
this.ttl = ttl;
return this;
}
/**
* optional
* @param level
*/
public Builder<T, K> withRetryPolicy(RetryPolicy policy) {
Preconditions.checkNotNull(policy);
this.retryPolicy = policy;
return this;
}
public Builder<T, K> withAutoCommit(boolean autoCommit) {
this.autoCommit = autoCommit;
return this;
}
/**
* Partitioner used to determine token ranges and how to break token
* ranges into sub parts. The default is BigInteger127Partitioner in
* pre-cassandra 1.2.
*
* @param partitioner
* @return
*/
public Builder<T, K> withPartitioner(Partitioner partitioner) {
this.partitioner = partitioner;
return this;
}
@SuppressWarnings("unchecked")
public DefaultEntityManager<T, K> build() {
// check mandatory fields
Preconditions.checkNotNull(clazz, "withEntityType(...) is not set");
Preconditions
.checkNotNull(keyspace, "withKeyspace(...) is not set");
// TODO: check @Id type compatibility
// TODO: do we need to require @Entity annotation
this.entityMapper = new EntityMapper<T, K>(clazz, ttl);
this.lifecycleHandler = new LifecycleEvents<T>(clazz);
if (columnFamily == null) {
if (columnFamilyName == null)
columnFamilyName = entityMapper.getEntityName();
columnFamily = new ColumnFamily<K, String>(columnFamilyName,
(com.netflix.astyanax.Serializer<K>) MappingUtils
.getSerializerForField(this.entityMapper
.getId()), StringSerializer.get());
}
// build object
return new DefaultEntityManager<T, K>(this);
}
}
public static <T,K> Builder<T,K> builder() {
return new Builder<T,K>();
}
// private members
private final EntityMapper<T, K> entityMapper;
private final Keyspace keyspace;
private final ColumnFamily<K, String> columnFamily;
private final ConsistencyLevel readConsitency;
private final ConsistencyLevel writeConsistency;
private final RetryPolicy retryPolicy;
private final LifecycleEvents<T> lifecycleHandler;
private final boolean autoCommit;
private final ThreadLocal<MutationBatch> tlMutation = new ThreadLocal<MutationBatch>();
private static final Partitioner DEFAULT_ENTITY_MANAGER_PARTITIONER = BigInteger127Partitioner
.get();
private final Partitioner partitioner;
private DefaultEntityManager(Builder<T, K> builder) {
entityMapper = builder.entityMapper;
keyspace = builder.keyspace;
columnFamily = builder.columnFamily;
readConsitency = builder.readConsitency;
writeConsistency = builder.writeConsistency;
retryPolicy = builder.retryPolicy;
lifecycleHandler = builder.lifecycleHandler;
autoCommit = builder.autoCommit;
partitioner = builder.partitioner;
}
// public APIs
/**
* @inheritDoc
*/
public void put(T entity) throws PersistenceException {
try {
lifecycleHandler.onPrePersist(entity);
MutationBatch mb = newMutationBatch();
entityMapper.fillMutationBatch(mb, columnFamily, entity);
if (autoCommit)
mb.execute();
lifecycleHandler.onPostPersist(entity);
} catch(Exception e) {
throw new PersistenceException("failed to put entity ", e);
}
}
/**
* @inheritDoc
*/
public T get(K id) throws PersistenceException {
try {
ColumnFamilyQuery<K, String> cfq = newQuery();
ColumnList<String> cl = cfq.getKey(id).execute().getResult();
// when a row is deleted in cassandra,
// the row key remains (without any columns) until the next compaction.
// simply return null (as non exist)
if(cl.isEmpty())
return null;
T entity = entityMapper.constructEntity(id, cl);
lifecycleHandler.onPostLoad(entity);
return entity;
} catch(Exception e) {
throw new PersistenceException("failed to get entity " + id, e);
}
}
/**
* @inheritDoc
*/
@Override
public void delete(K id) throws PersistenceException {
try {
MutationBatch mb = getMutationBatch();
mb.withRow(columnFamily, id).delete();
if (autoCommit)
mb.execute();
} catch(Exception e) {
throw new PersistenceException("failed to delete entity " + id, e);
}
}
@Override
public void remove(T entity) throws PersistenceException {
K id = null;
try {
lifecycleHandler.onPreRemove(entity);
id = entityMapper.getEntityId(entity);
MutationBatch mb = newMutationBatch();
mb.withRow(columnFamily, id).delete();
if (autoCommit)
mb.execute();
lifecycleHandler.onPostRemove(entity);
} catch(Exception e) {
throw new PersistenceException("failed to delete entity " + id, e);
}
}
/**
* @inheritDoc
*/
@Override
public List<T> getAll() throws PersistenceException {
final List<T> entities = Lists.newArrayList();
visitAll(new Function<T, Boolean>() {
@Override
public synchronized Boolean apply(T entity) {
entities.add(entity);
return true;
}
});
return entities;
}
/**
* @inheritDoc
*/
@Override
public List<T> get(Collection<K> ids) throws PersistenceException {
try {
ColumnFamilyQuery<K, String> cfq = newQuery();
Rows<K, String> rows = cfq.getRowSlice(ids).execute().getResult();
List<T> entities = Lists.newArrayListWithExpectedSize(rows.size());
for (Row<K, String> row : rows) {
if (!row.getColumns().isEmpty()) {
T entity = entityMapper.constructEntity(row.getKey(), row.getColumns());
lifecycleHandler.onPostLoad(entity);
entities.add(entity);
}
}
return entities;
} catch(Exception e) {
throw new PersistenceException("failed to get entities " + ids, e);
}
}
/**
* @inheritDoc
*/
@Override
public void delete(Collection<K> ids) throws PersistenceException {
MutationBatch mb = getMutationBatch();
try {
for (K id : ids) {
mb.withRow(columnFamily, id).delete();
}
if (autoCommit)
mb.execute();
} catch(Exception e) {
throw new PersistenceException("failed to delete entities " + ids, e);
}
}
@Override
public void remove(Collection<T> entities) throws PersistenceException {
MutationBatch mb = getMutationBatch();
try {
for (T entity : entities) {
lifecycleHandler.onPreRemove(entity);
K id = entityMapper.getEntityId(entity);
mb.withRow(columnFamily, id).delete();
}
mb.execute();
for (T entity : entities) {
lifecycleHandler.onPostRemove(entity);
}
} catch(Exception e) {
throw new PersistenceException("failed to delete entities ", e);
}
}
/**
* @inheritDoc
*/
@Override
public void put(Collection<T> entities) throws PersistenceException {
MutationBatch mb = getMutationBatch();
try {
for (T entity : entities) {
lifecycleHandler.onPrePersist(entity);
entityMapper.fillMutationBatch(mb, columnFamily, entity);
}
if (autoCommit)
mb.execute();
for (T entity : entities) {
lifecycleHandler.onPostPersist(entity);
}
} catch(Exception e) {
throw new PersistenceException("failed to put entities ", e);
}
}
/**
* @inheritDoc
*/
@Override
public void visitAll(final Function<T, Boolean> callback) throws PersistenceException {
try {
new AllRowsReader.Builder<K, String>(keyspace, columnFamily)
.withIncludeEmptyRows(false)
.withPartitioner(partitioner)
.forEachRow(new Function<Row<K,String>, Boolean>() {
@Override
public Boolean apply(Row<K, String> row) {
if (row.getColumns().isEmpty())
return true;
T entity = entityMapper.constructEntity(row.getKey(), row.getColumns());
try {
lifecycleHandler.onPostLoad(entity);
} catch (Exception e) {
// TODO:
}
return callback.apply(entity);
}
})
.build()
.call();
} catch (Exception e) {
throw new PersistenceException("Failed to fetch all entites", e);
}
}
@Override
public List<T> find(String cql) throws PersistenceException {
Preconditions.checkArgument(StringUtils.left(cql, 6).equalsIgnoreCase("SELECT"), "CQL must be SELECT statement");
try {
CqlResult<K, String> results = newQuery().withCql(cql).execute().getResult();
List<T> entities = Lists.newArrayListWithExpectedSize(results.getRows().size());
for (Row<K, String> row : results.getRows()) {
if (!row.getColumns().isEmpty()) {
T entity = entityMapper.constructEntity(row.getKey(), row.getColumns());
lifecycleHandler.onPostLoad(entity);
entities.add(entity);
}
}
return entities;
} catch (Exception e) {
throw new PersistenceException("Failed to execute cql query", e);
}
}
private MutationBatch newMutationBatch() {
MutationBatch mb = keyspace.prepareMutationBatch();
if(writeConsistency != null)
mb.withConsistencyLevel(writeConsistency);
if(retryPolicy != null)
mb.withRetryPolicy(retryPolicy);
return mb;
}
private MutationBatch getMutationBatch() {
if (autoCommit) {
return newMutationBatch();
}
else {
MutationBatch mb = tlMutation.get();
if (mb == null) {
mb = newMutationBatch();
tlMutation.set(mb);
}
return mb;
}
}
private ColumnFamilyQuery<K, String> newQuery() {
ColumnFamilyQuery<K, String> cfq = keyspace.prepareQuery(columnFamily);
if(readConsitency != null)
cfq.setConsistencyLevel(readConsitency);
if(retryPolicy != null)
cfq.withRetryPolicy(retryPolicy);
return cfq;
}
@Override
public void createStorage(Map<String, Object> options) throws PersistenceException {
try {
keyspace.createColumnFamily(this.columnFamily, options);
} catch (ConnectionException e) {
if (e.getMessage().contains("already exist"))
return;
throw new PersistenceException("Unable to create column family " + this.columnFamily.getName(), e);
}
}
@Override
public void deleteStorage() throws PersistenceException {
try {
keyspace.dropColumnFamily(this.columnFamily);
} catch (ConnectionException e) {
throw new PersistenceException("Unable to drop column family " + this.columnFamily.getName(), e);
}
}
@Override
public void truncate() throws PersistenceException {
try {
keyspace.truncateColumnFamily(this.columnFamily);
} catch (ConnectionException e) {
throw new PersistenceException("Unable to drop column family " + this.columnFamily.getName(), e);
}
}
@Override
public void commit() throws PersistenceException {
MutationBatch mb = tlMutation.get();
if (mb != null) {
try {
mb.execute();
} catch (ConnectionException e) {
throw new PersistenceException("Failed to commit mutation batch", e);
}
}
}
@Override
public NativeQuery<T, K> createNativeQuery() {
throw new UnsupportedOperationException("Not implemented yet");
}
}
|
package org.ovirt.engine.core.vdsbroker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.SELinuxMode;
import org.ovirt.engine.core.common.businessentities.V2VJobInfo;
import org.ovirt.engine.core.common.businessentities.V2VJobInfo.JobStatus;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSDomainsData;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VdsNumaNode;
import org.ovirt.engine.core.common.businessentities.VdsSpmStatus;
import org.ovirt.engine.core.common.businessentities.VdsStatistics;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.DestroyVmVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.SetVdsStatusVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.SetVmStatusVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsIdAndVdsVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.dao.SupportedHostFeatureDao;
import org.ovirt.engine.core.di.Injector;
import org.ovirt.engine.core.utils.NumaUtils;
import org.ovirt.engine.core.utils.crypt.EngineEncryptionUtils;
import org.ovirt.engine.core.utils.lock.EngineLock;
import org.ovirt.engine.core.utils.lock.LockManagerFactory;
import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil;
import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation;
import org.ovirt.engine.core.utils.timer.SchedulerUtil;
import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
import org.ovirt.engine.core.vdsbroker.irsbroker.IRSErrorException;
import org.ovirt.engine.core.vdsbroker.irsbroker.IrsBrokerCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.HostNetworkTopologyPersister;
import org.ovirt.engine.core.vdsbroker.vdsbroker.IVdsServer;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSNetworkException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSRecoveringException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VdsManager {
private static Logger log = LoggerFactory.getLogger(VdsManager.class);
private static Map<Guid, String> recoveringJobIdMap = new ConcurrentHashMap<>();
private final Object lockObj = new Object();
private final AtomicInteger failedToRunVmAttempts;
private final AtomicInteger unrespondedAttempts;
private final Guid vdsId;
private final VdsMonitor vdsMonitor = new VdsMonitor();
private VDS cachedVds;
private final AuditLogDirector auditLogDirector;
private long lastUpdate;
private long updateStartTime;
private long nextMaintenanceAttemptTime;
private List<String> registeredJobs;
private boolean isSetNonOperationalExecuted;
private MonitoringStrategy monitoringStrategy;
private EngineLock monitoringLock;
private boolean initialized;
private IVdsServer vdsProxy;
private boolean beforeFirstRefresh = true;
private HostMonitoring hostMonitoring;
private boolean monitoringNeeded;
private List<VM> lastVmsList = Collections.emptyList();
private final ResourceManager resourceManager;
private final DbFacade dbFacade;
private Map<Guid, V2VJobInfo> vmIdToV2VJob = new ConcurrentHashMap<>();
private VmStatsRefresher vmsRefresher;
protected int refreshIteration;
protected final int HOST_REFRESH_RATE;
protected final int NUMBER_HOST_REFRESHES_BEFORE_SAVE;
public VdsManager(VDS vds, AuditLogDirector auditLogDirector, ResourceManager resourceManager, DbFacade dbFacade) {
HOST_REFRESH_RATE = Config.<Integer> getValue(ConfigValues.VdsRefreshRate) * 1000;
NUMBER_HOST_REFRESHES_BEFORE_SAVE = Config.<Integer> getValue(ConfigValues.NumberVmRefreshesBeforeSave);
refreshIteration = NUMBER_HOST_REFRESHES_BEFORE_SAVE - 1;
this.resourceManager = resourceManager;
this.dbFacade = dbFacade;
this.auditLogDirector = auditLogDirector;
log.info("Entered VdsManager constructor");
cachedVds = vds;
vdsId = vds.getId();
monitoringStrategy = MonitoringStrategyFactory.getMonitoringStrategyForVds(vds);
unrespondedAttempts = new AtomicInteger();
failedToRunVmAttempts = new AtomicInteger();
monitoringLock = new EngineLock(Collections.singletonMap(vdsId.toString(),
new Pair<>(LockingGroup.VDS_INIT.name(), "")), null);
registeredJobs = new ArrayList<>();
handlePreviousStatus();
handleSecureSetup();
initVdsBroker();
}
public void handleSecureSetup() {
// if ssl is on and no certificate file
if (Config.<Boolean> getValue(ConfigValues.EncryptHostCommunication)
&& !EngineEncryptionUtils.haveKey()) {
if (cachedVds.getStatus() != VDSStatus.Maintenance && cachedVds.getStatus() != VDSStatus.InstallFailed) {
setStatus(VDSStatus.NonResponsive, cachedVds);
updateDynamicData(cachedVds.getDynamicData());
}
log.error("Could not find VDC Certificate file.");
AuditLogableBase logable = new AuditLogableBase(vdsId);
auditLogDirector.log(logable, AuditLogType.CERTIFICATE_FILE_NOT_FOUND);
}
}
public void handlePreviousStatus() {
if (cachedVds.getStatus() == VDSStatus.PreparingForMaintenance) {
cachedVds.setPreviousStatus(cachedVds.getStatus());
} else {
cachedVds.setPreviousStatus(VDSStatus.Up);
}
}
public void scheduleJobs() {
SchedulerUtil sched = getSchedulUtil();
int refreshRate = Config.<Integer> getValue(ConfigValues.VdsRefreshRate) * 1000;
registeredJobs.add(sched.scheduleAFixedDelayJob(
this,
"onTimer",
new Class[0],
new Object[0],
refreshRate,
refreshRate,
TimeUnit.MILLISECONDS));
double availableUpdatesRefreshRate = Config.<Double> getValue(ConfigValues.HostPackagesUpdateTimeInHours);
final int HOURS_TO_MINUTES = 60;
long rateInMinutes = Math.round(availableUpdatesRefreshRate * HOURS_TO_MINUTES);
registeredJobs.add(sched.scheduleAFixedDelayJob(
this,
"availableUpdates",
new Class[0],
new Object[0],
rateInMinutes,
rateInMinutes,
TimeUnit.MINUTES));
vmsRefresher = getRefresherFactory().create(this);
vmsRefresher.startMonitoring();
}
private RefresherFactory getRefresherFactory() {
return Injector.get(RefresherFactory.class);
}
private SchedulerUtil getSchedulUtil() {
return Injector.get(SchedulerUtilQuartzImpl.class);
}
private void initVdsBroker() {
log.info("Initialize vdsBroker '{}:{}'", cachedVds.getHostName(), cachedVds.getPort());
// Get the values of the timeouts:
int clientTimeOut = Config.<Integer> getValue(ConfigValues.vdsTimeout) * 1000;
int connectionTimeOut = Config.<Integer> getValue(ConfigValues.vdsConnectionTimeout) * 1000;
int heartbeat = Config.<Integer> getValue(ConfigValues.vdsHeartbeatInSeconds) * 1000;
int clientRetries = Config.<Integer> getValue(ConfigValues.vdsRetries);
vdsProxy = TransportFactory.createVdsServer(
cachedVds.getProtocol(),
cachedVds.getVdsGroupCompatibilityVersion(),
cachedVds.getHostName(),
cachedVds.getPort(),
clientTimeOut,
connectionTimeOut,
clientRetries,
heartbeat);
}
@OnTimerMethodAnnotation("onTimer")
public void onTimer() {
if (LockManagerFactory.getLockManager().acquireLock(monitoringLock).getFirst()) {
try {
setIsSetNonOperationalExecuted(false);
Guid storagePoolId = null;
ArrayList<VDSDomainsData> domainsList = null;
synchronized (getLockObj()) {
refreshCachedVds();
if (cachedVds == null) {
log.error("VdsManager::refreshVdsRunTimeInfo - onTimer is NULL for '{}'",
getVdsId());
return;
}
try {
updateIteration();
if (isMonitoringNeeded()) {
setStartTime();
hostMonitoring =
new HostMonitoring(this,
cachedVds,
monitoringStrategy,
resourceManager,
dbFacade,
auditLogDirector);
hostMonitoring.refresh();
unrespondedAttempts.set(0);
setLastUpdate();
}
} catch (VDSNetworkException e) {
logNetworkException(e);
} catch (VDSRecoveringException ex) {
handleVdsRecoveringException(ex);
} catch (RuntimeException ex) {
logFailureMessage(ex);
}
try {
if (hostMonitoring != null) {
hostMonitoring.afterRefreshTreatment();
// Get cachedVds data for updating domains list, ignoring cachedVds which is down, since it's not
// connected
// the storage anymore (so there is no sense in updating the domains list in that case).
if (cachedVds != null && cachedVds.getStatus() != VDSStatus.Maintenance) {
storagePoolId = cachedVds.getStoragePoolId();
domainsList = cachedVds.getDomains();
}
}
hostMonitoring = null;
} catch (IRSErrorException ex) {
logAfterRefreshFailureMessage(ex);
if (log.isDebugEnabled()) {
logException(ex);
}
} catch (RuntimeException ex) {
logAfterRefreshFailureMessage(ex);
logException(ex);
}
}
// Now update the status of domains, this code should not be in
// synchronized part of code
if (domainsList != null) {
IrsBrokerCommand.updateVdsDomainsData(cachedVds, storagePoolId, domainsList);
}
} catch (Exception e) {
log.error("Timer update runtime info failed. Exception:", e);
} finally {
LockManagerFactory.getLockManager().releaseLock(monitoringLock);
}
}
}
private void refreshCachedVds() {
cachedVds = dbFacade.getVdsDao().get(getVdsId());
setMonitoringNeeded();
}
@OnTimerMethodAnnotation("availableUpdates")
public void availableUpdates() {
if (cachedVds.getStatus() != VDSStatus.Maintenance
&& cachedVds.getStatus() != VDSStatus.Up
&& cachedVds.getStatus() != VDSStatus.NonOperational) {
log.warn("Check for available updates is skipped for host '{}' due to unsupported host status '{}' ",
cachedVds.getName(),
cachedVds.getStatus());
return;
}
boolean updateAvailable;
try {
updateAvailable = resourceManager.isUpdateAvailable(cachedVds);
} catch (Exception e) {
log.error("Failed to check if updates are available for host '{}'", cachedVds.getName());
AuditLogableBase auditLog = new AuditLogableBase();
auditLog.setVds(cachedVds);
auditLog.addCustomValue("Message", StringUtils.defaultString(e.getMessage(), e.getCause().toString()));
auditLogDirector.log(auditLog, AuditLogType.HOST_AVAILABLE_UPDATES_FAILED);
return;
}
synchronized (getLockObj()) {
if (updateAvailable != cachedVds.isUpdateAvailable()) {
cachedVds.getDynamicData().setUpdateAvailable(updateAvailable);
dbFacade.getVdsDynamicDao().updateUpdateAvailable(cachedVds.getId(), updateAvailable);
}
}
}
/**
* @return a safe copy of the internal VDS. mutating it must not affect internal.
*/
public VDS getCopyVds() {
return cachedVds.clone();
}
public String getVdsName() {
return cachedVds.getName();
}
public Guid getVdsGroupId() {
return cachedVds.getVdsGroupId();
}
public Version getGroupCompatibilityVersion() {
return cachedVds.getVdsGroupCompatibilityVersion();
}
private void logFailureMessage(RuntimeException ex) {
log.warn(
"Failed to refresh VDS , vds = '{}' : '{}', error = '{}', continuing.",
cachedVds.getName(),
cachedVds.getId(),
ex.getMessage());
log.error("Exception", ex);
}
private void logException(final RuntimeException ex) {
log.error("ResourceManager::refreshVdsRunTimeInfo", ex);
}
private void logAfterRefreshFailureMessage(RuntimeException ex) {
log.warn(
"Failed to AfterRefreshTreatment VDS, continuing: {}",
ex.getMessage());
log.debug("Exception", ex);
}
private void setMonitoringNeeded() {
monitoringNeeded = (monitoringStrategy.isMonitoringNeeded(cachedVds) &&
cachedVds.getStatus() != VDSStatus.Installing &&
cachedVds.getStatus() != VDSStatus.InstallFailed &&
cachedVds.getStatus() != VDSStatus.Reboot &&
cachedVds.getStatus() != VDSStatus.Maintenance &&
cachedVds.getStatus() != VDSStatus.PendingApproval &&
cachedVds.getStatus() != VDSStatus.InstallingOS &&
cachedVds.getStatus() != VDSStatus.Down &&
cachedVds.getStatus() != VDSStatus.Kdumping);
}
public boolean isMonitoringNeeded() {
return monitoringNeeded;
}
private void handleVdsRecoveringException(VDSRecoveringException ex) {
if (cachedVds.getStatus() != VDSStatus.Initializing && cachedVds.getStatus() != VDSStatus.NonOperational) {
setStatus(VDSStatus.Initializing, cachedVds);
dbFacade.getVdsDynamicDao().updateStatus(cachedVds.getId(), VDSStatus.Initializing);
AuditLogableBase logable = new AuditLogableBase(cachedVds.getId());
logable.addCustomValue("ErrorMessage", ex.getMessage());
logable.updateCallStackFromThrowable(ex);
auditLogDirector.log(logable, AuditLogType.VDS_INITIALIZING);
log.warn(
"Failed to refresh VDS, continuing, vds='{}'({}): {}",
cachedVds.getName(),
cachedVds.getId(),
ex.getMessage());
log.debug("Exception", ex);
final int VDS_RECOVERY_TIMEOUT_IN_MINUTES = Config.<Integer> getValue(ConfigValues.VdsRecoveryTimeoutInMinutes);
String jobId = getSchedulUtil().scheduleAOneTimeJob(this, "onTimerHandleVdsRecovering", new Class[0],
new Object[0], VDS_RECOVERY_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
recoveringJobIdMap.put(cachedVds.getId(), jobId);
}
}
@OnTimerMethodAnnotation("onTimerHandleVdsRecovering")
public void onTimerHandleVdsRecovering() {
recoveringJobIdMap.remove(getVdsId());
VDS vds = dbFacade.getVdsDao().get(getVdsId());
if (vds.getStatus() == VDSStatus.Initializing) {
try {
resourceManager.getEventListener().vdsNonOperational(vds.getId(),
NonOperationalReason.TIMEOUT_RECOVERING_FROM_CRASH,
true,
Guid.Empty);
setIsSetNonOperationalExecuted(true);
} catch (RuntimeException exp) {
log.error(
"HandleVdsRecoveringException::Error in recovery timer treatment, vds='{}'({}): {}",
vds.getName(),
vds.getId(),
exp.getMessage());
log.debug("Exception", exp);
}
}
}
/**
* Save dynamic data to cache and DB.
*
* @param dynamicData
*/
public void updateDynamicData(VdsDynamic dynamicData) {
dbFacade.getVdsDynamicDao().updateIfNeeded(dynamicData);
cachedVds.setDynamicData(dynamicData);
}
public void updatePartialDynamicData(NonOperationalReason nonOperationalReason, String maintenanceReason) {
cachedVds.getDynamicData().setNonOperationalReason(nonOperationalReason);
cachedVds.getDynamicData().setMaintenanceReason(maintenanceReason);
dbFacade.getVdsDynamicDao().updateStatusAndReasons(cachedVds.getDynamicData());
}
/**
* Save statistics data to cache and DB.
*
* @param statisticsData
*/
public void updateStatisticsData(VdsStatistics statisticsData) {
dbFacade.getVdsStatisticsDao().update(statisticsData);
cachedVds.setStatisticsData(statisticsData);
}
/**
* Publish the current pending resource summary
*
* @param pendingMemory - scheduled memory in MiB
* @param pendingCpuCount - scheduled number of CPUs
*/
public void updatePendingData(int pendingMemory, int pendingCpuCount) {
synchronized (getLockObj()) {
cachedVds.setPendingVcpusCount(pendingCpuCount);
cachedVds.setPendingVmemSize(pendingMemory);
updateDynamicData(cachedVds.getDynamicData());
}
}
/**
* Save or update numa data to DB
*
* @param vds
*/
public void updateNumaData(final VDS vds) {
if (vds.getNumaNodeList() == null || vds.getNumaNodeList().isEmpty()) {
return;
}
final List<VdsNumaNode> numaNodesToSave = new ArrayList<>();
final List<VdsNumaNode> numaNodesToUpdate = new ArrayList<>();
final List<Guid> numaNodesToRemove = new ArrayList<>();
List<VdsNumaNode> dbVdsNumaNodes = dbFacade.getVdsNumaNodeDao().getAllVdsNumaNodeByVdsId(vds.getId());
for (VdsNumaNode node : vds.getNumaNodeList()) {
VdsNumaNode searchNode = NumaUtils.getVdsNumaNodeByIndex(dbVdsNumaNodes, node.getIndex());
if (searchNode != null) {
node.setId(searchNode.getId());
numaNodesToUpdate.add(node);
dbVdsNumaNodes.remove(searchNode);
}
else {
node.setId(Guid.newGuid());
numaNodesToSave.add(node);
}
}
for (VdsNumaNode node : dbVdsNumaNodes) {
numaNodesToRemove.add(node.getId());
}
//The database operation should be in one transaction
TransactionSupport.executeInScope(TransactionScopeOption.Required,
new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
if (!numaNodesToRemove.isEmpty()) {
dbFacade.getVdsNumaNodeDao().massRemoveNumaNodeByNumaNodeId(numaNodesToRemove);
}
if (!numaNodesToUpdate.isEmpty()) {
dbFacade.getVdsNumaNodeDao().massUpdateNumaNode(numaNodesToUpdate);
}
if (!numaNodesToSave.isEmpty()) {
dbFacade.getVdsNumaNodeDao().massSaveNumaNode(numaNodesToSave, vds.getId(), null);
}
return null;
}
});
}
public void refreshHost(VDS vds) {
try {
refreshCapabilities(new AtomicBoolean(), vds);
} finally {
if (vds != null) {
updateDynamicData(vds.getDynamicData());
updateNumaData(vds);
// Update VDS after testing special hardware capabilities
monitoringStrategy.processHardwareCapabilities(vds);
// Always check VdsVersion
resourceManager.getEventListener().handleVdsVersion(vds.getId());
}
}
}
public void setStatus(VDSStatus status, VDS vds) {
synchronized (getLockObj()) {
// non-responsive event during moving host to maintenance should be ignored
if (isNetworkExceptionDuringMaintenance(status)) {
return;
}
if (vds == null) {
vds = dbFacade.getVdsDao().get(getVdsId());
}
if (vds.getStatus() != status) {
if (status == VDSStatus.PreparingForMaintenance) {
calculateNextMaintenanceAttemptTime();
}
vds.setPreviousStatus(vds.getStatus());
if (this.cachedVds != null) {
this.cachedVds.setPreviousStatus(vds.getStatus());
}
}
// update to new status
vds.setStatus(status);
if (this.cachedVds != null) {
this.cachedVds.setStatus(status);
}
switch (status) {
case NonOperational:
if (this.cachedVds != null) {
this.cachedVds.setNonOperationalReason(vds.getNonOperationalReason());
}
if (vds.getVmCount() > 0) {
break;
}
case NonResponsive:
case Down:
case Maintenance:
vds.setCpuSys(Double.valueOf(0));
vds.setCpuUser(Double.valueOf(0));
vds.setCpuIdle(Double.valueOf(0));
vds.setCpuLoad(Double.valueOf(0));
vds.setUsageCpuPercent(0);
vds.setUsageMemPercent(0);
vds.setUsageNetworkPercent(0);
if (this.cachedVds != null) {
this.cachedVds.setCpuSys(Double.valueOf(0));
this.cachedVds.setCpuUser(Double.valueOf(0));
this.cachedVds.setCpuIdle(Double.valueOf(0));
this.cachedVds.setCpuLoad(Double.valueOf(0));
this.cachedVds.setUsageCpuPercent(0);
this.cachedVds.setUsageMemPercent(0);
this.cachedVds.setUsageNetworkPercent(0);
}
default:
break;
}
}
}
private boolean isNetworkExceptionDuringMaintenance(VDSStatus status) {
return status == VDSStatus.NonResponsive
&& this.cachedVds != null
&& this.cachedVds.getStatus() == VDSStatus.Maintenance;
}
/**
* This scheduled method allows this cachedVds to recover from
* Error status.
*/
@OnTimerMethodAnnotation("recoverFromError")
public void recoverFromError() {
VDS vds = dbFacade.getVdsDao().get(getVdsId());
/**
* Move cachedVds to Up status from error
*/
if (vds != null && vds.getStatus() == VDSStatus.Error) {
setStatus(VDSStatus.Up, vds);
dbFacade.getVdsDynamicDao().updateStatus(getVdsId(), VDSStatus.Up);
log.info("Settings host '{}' to up after {} failed attempts to run a VM",
vds.getName(),
failedToRunVmAttempts);
failedToRunVmAttempts.set(0);
}
}
/**
* This callback method notifies this cachedVds that an attempt to run a vm on it
* failed. above a certain threshold such hosts are marked as
* VDSStatus.Error.
*
* @param vds
*/
public void failedToRunVm(VDS vds) {
if (failedToRunVmAttempts.get() < Config.<Integer> getValue(ConfigValues.NumberOfFailedRunsOnVds)
&& failedToRunVmAttempts.incrementAndGet() >= Config
.<Integer> getValue(ConfigValues.NumberOfFailedRunsOnVds)) {
//Only one thread at a time can enter here
resourceManager.runVdsCommand(VDSCommandType.SetVdsStatus,
new SetVdsStatusVDSCommandParameters(vds.getId(), VDSStatus.Error));
SchedulerUtil sched = getSchedulUtil();
sched.scheduleAOneTimeJob(
this,
"recoverFromError",
new Class[0],
new Object[0],
Config.<Integer>getValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes),
TimeUnit.MINUTES);
auditLogDirector.log(
new AuditLogableBase(vds.getId()).addCustomValue(
"Time",
Config.<Integer> getValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes).toString()),
AuditLogType.VDS_FAILED_TO_RUN_VMS);
log.info("Vds '{}' moved to Error mode after {} attempts. Time: {}", vds.getName(),
failedToRunVmAttempts, new Date());
}
}
public void succeededToRunVm(Guid vmId) {
unrespondedAttempts.set(0);
resourceManager.succededToRunVm(vmId, getVdsId());
}
public VDSStatus refreshCapabilities(AtomicBoolean processHardwareCapsNeeded, VDS vds) {
log.debug("monitoring: refresh '{}' capabilities", vds);
VDS oldVDS = vds.clone();
VDSReturnValue caps =
resourceManager.runVdsCommand(VDSCommandType.GetCapabilities,
new VdsIdAndVdsVDSCommandParametersBase(vds));
if (caps.getSucceeded()) {
// Verify version capabilities
HashSet<Version> hostVersions = null;
Version clusterCompatibility = vds.getVdsGroupCompatibilityVersion();
if (FeatureSupported.hardwareInfo(clusterCompatibility) &&
// If the feature is enabled in cluster level, we continue by verifying that this VDS also
// supports the specific cluster level. Otherwise getHardwareInfo API won't exist for the
// host and an exception will be raised by VDSM.
(hostVersions = vds.getSupportedClusterVersionsSet()) != null &&
hostVersions.contains(clusterCompatibility)) {
VDSReturnValue ret = resourceManager.runVdsCommand(VDSCommandType.GetHardwareInfo,
new VdsIdAndVdsVDSCommandParametersBase(vds));
if (!ret.getSucceeded()) {
AuditLogableBase logable = new AuditLogableBase(vds.getId());
logable.updateCallStackFromThrowable(ret.getExceptionObject());
auditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_GET_HOST_HARDWARE_INFO);
}
}
// For gluster nodes, SELinux needs to be in enforcing mode,
// hence warning in case of permissive as well.
if (vds.getSELinuxEnforceMode() == null || vds.getSELinuxEnforceMode().equals(SELinuxMode.DISABLED)
|| (vds.getVdsGroupSupportsGlusterService()
&& vds.getSELinuxEnforceMode().equals(SELinuxMode.PERMISSIVE))) {
auditLogDirector.log(new AuditLogableBase(vds.getId()).addCustomValue("Mode",
vds.getSELinuxEnforceMode() == null ? "UNKNOWN" : vds.getSELinuxEnforceMode().name()),
AuditLogType.VDS_NO_SELINUX_ENFORCEMENT);
if (vds.getSELinuxEnforceMode() != null) {
log.warn("Host '{}' is running with SELinux in '{}' mode", vds.getName(), vds.getSELinuxEnforceMode());
} else {
log.warn("Host '{}' does not report SELinux enforcement information.", vds.getName());
}
}
VDSStatus returnStatus = vds.getStatus();
NonOperationalReason nonOperationalReason =
getHostNetworkTopologyPersister().persistAndEnforceNetworkCompliance(vds);
if (nonOperationalReason != NonOperationalReason.NONE) {
setIsSetNonOperationalExecuted(true);
if (returnStatus != VDSStatus.NonOperational) {
log.debug(
"monitoring: vds '{}' networks do not match its cluster networks, vds will be moved to NonOperational",
vds);
vds.setStatus(VDSStatus.NonOperational);
vds.setNonOperationalReason(nonOperationalReason);
}
}
// We process the software capabilities.
VDSStatus oldStatus = vds.getStatus();
if (oldStatus != VDSStatus.Up) {
// persist to db the host's cpu_flags.
// TODO this needs to be revisited - either all the logic is in-memory or based on db
dbFacade.getVdsDynamicDao().updateCpuFlags(vds.getId(), vds.getCpuFlags());
processHostFeaturesReported(vds);
monitoringStrategy.processHardwareCapabilities(vds);
}
monitoringStrategy.processSoftwareCapabilities(vds);
returnStatus = vds.getStatus();
if (returnStatus != oldStatus && returnStatus == VDSStatus.NonOperational) {
setIsSetNonOperationalExecuted(true);
}
processHardwareCapsNeeded.set(monitoringStrategy.processHardwareCapabilitiesNeeded(oldVDS, vds));
return returnStatus;
} else if (caps.getExceptionObject() != null) {
throw caps.getExceptionObject();
} else {
log.error("refreshCapabilities:GetCapabilitiesVDSCommand failed with no exception!");
throw new RuntimeException(caps.getExceptionString());
}
}
private void processHostFeaturesReported(VDS host) {
SupportedHostFeatureDao hostFeatureDao = DbFacade.getInstance().getSupportedHostFeatureDao();
Set<String> supportedHostFeatures = hostFeatureDao.getSupportedHostFeaturesByHostId(host.getId());
Set<String> featuresReturendByVdsCaps = new HashSet<String>(host.getAdditionalFeatures());
host.getAdditionalFeatures().removeAll(supportedHostFeatures);
if (!host.getAdditionalFeatures().isEmpty()) {
hostFeatureDao.addAllSupportedHostFeature(host.getId(), host.getAdditionalFeatures());
}
supportedHostFeatures.removeAll(featuresReturendByVdsCaps);
if (!supportedHostFeatures.isEmpty()) {
hostFeatureDao.removeAllSupportedHostFeature(host.getId(), supportedHostFeatures);
}
}
private HostNetworkTopologyPersister getHostNetworkTopologyPersister() {
return Injector.get(HostNetworkTopologyPersister.class);
}
private long calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) {
int spmIndicator = spmStatus == VdsSpmStatus.None ? 0 : 1;
int secToFence = (int) (
// delay time can be fracture number, casting it to int should be enough
Config.<Integer> getValue(ConfigValues.TimeoutToResetVdsInSeconds)
+ Config.<Double> getValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator
+ Config.<Double> getValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount);
return TimeUnit.SECONDS.toMillis(secToFence);
}
/**
* Handle network exception
*
* @param ex exception to handle
* @return
*/
public void handleNetworkException(VDSNetworkException ex) {
boolean saveToDb = true;
if (cachedVds.getStatus() != VDSStatus.Down) {
long timeoutToFence = calcTimeoutToFence(cachedVds.getVmCount(), cachedVds.getSpmStatus());
if (isHostInGracePeriod(false)) {
if (cachedVds.getStatus() != VDSStatus.Connecting
&& cachedVds.getStatus() != VDSStatus.PreparingForMaintenance
&& cachedVds.getStatus() != VDSStatus.NonResponsive) {
setStatus(VDSStatus.Connecting, cachedVds);
logChangeStatusToConnecting(timeoutToFence);
} else {
saveToDb = false;
}
unrespondedAttempts.incrementAndGet();
} else {
if (cachedVds.getStatus() == VDSStatus.Maintenance) {
saveToDb = false;
} else {
if (cachedVds.getStatus() != VDSStatus.NonResponsive) {
setStatus(VDSStatus.NonResponsive, cachedVds);
moveVMsToUnknown();
logHostFailToRespond(ex, timeoutToFence);
resourceManager.getEventListener().vdsNotResponding(cachedVds);
} else {
setStatus(VDSStatus.NonResponsive, cachedVds);
}
}
}
}
if (saveToDb) {
updateDynamicData(cachedVds.getDynamicData());
updateStatisticsData(cachedVds.getStatisticsData());
}
}
/**
* Checks if host is in grace period from last successful communication to fencing attempt
*
* @param sshSoftFencingExecuted
* if SSH Soft Fencing was already executed we need to raise default timeout to determine if SSH Soft
* Fencing was successful and host became Up
* @return <code>true</code> if host is still in grace period, otherwise <code>false</code>
*/
public boolean isHostInGracePeriod(boolean sshSoftFencingExecuted) {
long timeoutToFence = calcTimeoutToFence(cachedVds.getVmCount(), cachedVds.getSpmStatus());
int unrespondedAttemptsBarrier = Config.<Integer>getValue(ConfigValues.VDSAttemptsToResetCount);
if (sshSoftFencingExecuted) {
// SSH Soft Fencing has already been executed, increase timeout to see if host is OK
timeoutToFence = timeoutToFence * 2;
unrespondedAttemptsBarrier = unrespondedAttemptsBarrier * 2;
}
return unrespondedAttempts.get() < unrespondedAttemptsBarrier
|| (lastUpdate + timeoutToFence) > System.currentTimeMillis();
}
private void logHostFailToRespond(VDSNetworkException ex, long timeoutToFence) {
log.info(
"Server failed to respond, vds_id='{}', vds_name='{}', vm_count={}, " +
"spm_status='{}', non-responsive_timeout (seconds)={}, error: {}",
cachedVds.getId(), cachedVds.getName(), cachedVds.getVmCount(), cachedVds.getSpmStatus(),
TimeUnit.MILLISECONDS.toSeconds(timeoutToFence), ex.getMessage());
AuditLogableBase logable;
logable = new AuditLogableBase(cachedVds.getId());
logable.updateCallStackFromThrowable(ex);
if (ex.getCause() instanceof java.net.UnknownHostException){
auditLogDirector.log(logable, AuditLogType.VDS_UNKNOWN_HOST);
} else {
auditLogDirector.log(logable, AuditLogType.VDS_FAILURE);
}
}
private void logChangeStatusToConnecting(long timeoutToFence) {
String msg;
AuditLogType auditLogType;
if (cachedVds.isPmEnabled()) {
msg = "Host '{}' is not responding. It will stay in Connecting state for a grace period " +
"of {} seconds and after that an attempt to fence the host will be issued.";
auditLogType = AuditLogType.VDS_HOST_NOT_RESPONDING_CONNECTING;
log.warn(msg, cachedVds.getName(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence));
} else {
msg = "Host '{}' is not responding.";
auditLogType = AuditLogType.VDS_HOST_NOT_RESPONDING;
log.warn(msg, cachedVds.getName());
}
AuditLogableBase logable = new AuditLogableBase();
logable.setVdsId(cachedVds.getId());
logable.addCustomValue("Seconds", Long.toString(TimeUnit.MILLISECONDS.toSeconds(timeoutToFence)));
auditLogDirector.log(logable, auditLogType);
}
public void dispose() {
log.info("vdsManager::disposing");
for (String jobId : registeredJobs) {
getSchedulUtil().deleteJob(jobId);
}
vmsRefresher.stopMonitoring();
vdsProxy.close();
}
/**
* Log the network exception depending on the VDS status.
*
* @param e
* The exception to log.
*/
private void logNetworkException(VDSNetworkException e) {
switch (cachedVds.getStatus()) {
case Down:
break;
case NonResponsive:
log.debug(
"Failed to refresh VDS, network error, continuing, vds='{}'({}): {}",
cachedVds.getName(),
cachedVds.getId(),
e.getMessage());
break;
default:
log.warn(
"Failed to refresh VDS, network error, continuing, vds='{}'({}): {}",
cachedVds.getName(),
cachedVds.getId(),
e.getMessage());
}
log.debug("Exception", e);
}
public void setIsSetNonOperationalExecuted(boolean isExecuted) {
this.isSetNonOperationalExecuted = isExecuted;
}
public boolean isSetNonOperationalExecuted() {
return isSetNonOperationalExecuted;
}
private void setStartTime() {
updateStartTime = System.currentTimeMillis();
}
/**
* Return time of last successful host monitoring communication
*/
public long getLastUpdate() {
return lastUpdate;
}
private void setLastUpdate() {
lastUpdate = System.currentTimeMillis();
}
/**
* @return elapsed time in milliseconds it took to update the Host run-time info. 0 means the updater never ran.
*/
public long getLastUpdateElapsed() {
return lastUpdate - updateStartTime;
}
/**
* @return VdsMonitor a class with means for lock and conditions for signaling
*/
public VdsMonitor getVdsMonitor() {
return vdsMonitor;
}
public void calculateNextMaintenanceAttemptTime() {
this.nextMaintenanceAttemptTime = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(
Config.<Integer> getValue(ConfigValues.HostPreparingForMaintenanceIdleTime), TimeUnit.SECONDS);
}
public boolean isTimeToRetryMaintenance() {
return System.currentTimeMillis() > nextMaintenanceAttemptTime;
}
private void moveVMsToUnknown() {
List<VM> vmList = getVmsToMoveToUnknown();
for (VM vm :vmList) {
destroyVmOnDestination(vm);
resourceManager.runVdsCommand(VDSCommandType.SetVmStatus,
new SetVmStatusVDSCommandParameters(vm.getId(), VMStatus.Unknown));
// log VM transition to unknown status
AuditLogableBase logable = new AuditLogableBase();
logable.setVmId(vm.getId());
auditLogDirector.log(logable, AuditLogType.VM_SET_TO_UNKNOWN_STATUS);
}
}
private void destroyVmOnDestination(final VM vm) {
if (vm.getStatus() != VMStatus.MigratingFrom || vm.getMigratingToVds() == null) {
return;
}
// avoid nested locks by doing this in a separate thread
ThreadPoolUtil.execute(new Runnable() {
@Override
public void run() {
VDSReturnValue returnValue = null;
returnValue =
resourceManager.runVdsCommand(VDSCommandType.DestroyVm,
new DestroyVmVDSCommandParameters(vm.getMigratingToVds(), vm.getId(), true, false, 0));
if (returnValue != null && returnValue.getSucceeded()) {
log.info("Stopped migrating VM: '{}' on VDS: '{}'", vm.getName(), vm.getMigratingToVds());
}
else {
log.info("Could not stop migrating VM: '{}' on VDS: '{}'", vm.getName(),
vm.getMigratingToVds());
}
}
});
}
private List<VM> getVmsToMoveToUnknown() {
List<VM> vmList = dbFacade.getVmDao().getAllRunningForVds(getVdsId());
List<VM> migratingVms = dbFacade.getVmDao().getAllMigratingToHost(getVdsId());
for (VM incomingVm : migratingVms) {
if (incomingVm.getStatus() == VMStatus.MigratingTo) {
// this VM is finished the migration handover and is running on this host now
// and should be treated as well.
vmList.add(incomingVm);
}
}
return vmList;
}
public boolean isInitialized() {
return initialized;
}
public void setInitialized(boolean value) {
initialized = value;
}
public IVdsServer getVdsProxy() {
return vdsProxy;
}
public Guid getVdsId() {
return vdsId;
}
public void cancelRecoveryJob() {
String jobId = recoveringJobIdMap.remove(vdsId);
if (jobId != null) {
log.info("Cancelling the recovery from crash timer for VDS '{}' because vds started initializing", vdsId);
try {
Injector.get(SchedulerUtilQuartzImpl.class).deleteJob(jobId);
} catch (Exception e) {
log.warn("Failed deleting job '{}' at cancelRecoveryJob: {}", jobId, e.getMessage());
log.debug("Exception", e);
}
}
}
public Version getCompatibilityVersion() {
return cachedVds.getVdsGroupCompatibilityVersion();
}
public String getVdsHostname() {
return cachedVds.getHostName();
}
private void updateIteration() {
if (refreshIteration == NUMBER_HOST_REFRESHES_BEFORE_SAVE) {
refreshIteration = 1;
} else {
refreshIteration++;
}
}
boolean isTimeToRefreshStatistics() {
return refreshIteration == NUMBER_HOST_REFRESHES_BEFORE_SAVE;
}
public Object getLockObj() {
return lockObj;
}
public boolean getbeforeFirstRefresh() {
return beforeFirstRefresh;
}
public void setbeforeFirstRefresh(boolean value) {
beforeFirstRefresh = value;
}
public List<VM> getLastVmsList() {
return lastVmsList;
}
/**
*
* This method is not thread safe
* @param lastVmsList
*/
public void setLastVmsList(List<VM> lastVmsList) {
this.lastVmsList = lastVmsList;
}
public void vmsMonitoringInitFinished() {
if (!isInitialized()) {
log.info("VMs initialization finished for Host: '{}:{}'", cachedVds.getName(), cachedVds.getId());
resourceManager.handleVmsFinishedInitOnVds(cachedVds.getId());
setInitialized(true);
}
}
public V2VJobInfo getV2VJobInfoForVm(Guid vmId) {
return vmIdToV2VJob.get(vmId);
}
public V2VJobInfo removeV2VJobInfoForVm(Guid vmId) {
synchronized (vmIdToV2VJob) {
return vmIdToV2VJob.remove(vmId);
}
}
public void addV2VJobInfoForVm(Guid vmId, JobStatus jobStatus) {
vmIdToV2VJob.put(vmId, new V2VJobInfo(vmId, jobStatus));
}
/**
* Update the status for V2V jobs according to the latest reports from VDSM
* @param v2vJobInfos - jobs we got from VDSM
*/
void updateV2VJobInfos(List<V2VJobInfo> v2vJobInfos) {
// Set the status of jobs that we expect to get from VDSM but
// didn't arrive in the latest report to non-exist
for (V2VJobInfo existingJobInfo : vmIdToV2VJob.values()) {
if (existingJobInfo.isMonitored() && !v2vJobInfos.contains(existingJobInfo)) {
existingJobInfo.setStatus(JobStatus.NOT_EXIST);
}
}
if (v2vJobInfos.isEmpty()) {
return;
}
// We don't want that by mistake a job that we tried to remove
// will be added again in case VDSM reports it at the same time
synchronized (vmIdToV2VJob) {
for (V2VJobInfo jobInfo : v2vJobInfos) {
if (vmIdToV2VJob.containsKey(jobInfo.getId())) {
vmIdToV2VJob.put(jobInfo.getId(), jobInfo);
}
}
}
}
}
|
package org.intermine.bio.dataconversion;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.sql.Database;
import org.intermine.xml.full.Item;
/**
* Read Ensembl SNP data directly from MySQL variarion database.
* @author Richard Smith
*/
public class EnsemblSnpDbConverter extends BioDBConverter
{
private static final String DATASET_TITLE = "Ensembl SNP data";
private static final String DATA_SOURCE_NAME = "Ensembl";
private Map<String, String> sources = new HashMap<String, String>();
private Map<String, String> states = new HashMap<String, String>();
private Map<String, String> transcripts = new HashMap<String, String>();
private Map<String, String> noTranscriptConsequences = new HashMap<String, String>();
private static final Logger LOG = Logger.getLogger(EnsemblSnpDbConverter.class);
/**
* Construct a new EnsemblSnpDbConverter.
* @param database the database to read from
* @param model the Model used by the object store we will write to with the ItemWriter
* @param writer an ItemWriter used to handle Items created
*/
public EnsemblSnpDbConverter(Database database, Model model, ItemWriter writer) {
super(database, model, writer, DATA_SOURCE_NAME, DATASET_TITLE);
}
/**
* {@inheritDoc}
*/
public void process() throws Exception {
// a database has been initialised from properties starting with db.ensembl-snp-db
Connection connection = getDatabase().getConnection();
Set<String> chrNames = new HashSet<String>();
//int MIN_CHROMOSOME = 1;
int MIN_CHROMOSOME = 21;
for (int i = MIN_CHROMOSOME; i <= 22; i++) {
chrNames.add("" + i);
}
//chrNames.add("X");
//chrNames.add("Y");
for (String chrName : chrNames) {
processChromosome(connection, chrName);
}
connection.close();
}
/**
* {@inheritDoc}
*/
public void processChromosome(Connection connection, String chrName) throws Exception {
// a database has been initialised from properties starting with db.ensembl-snp-db
System.out.println("Starting to process chromosome " + chrName);
LOG.info("Starting to process chromosome " + chrName);
// TODO move this to a parser arguement
int taxonId = 9606;
int counter = 0;
int snpCounter = 0;
Item currentSnp = null;
String currentRsNumber = null;
Set<String> consequenceIdentifiers = new HashSet<String>();
ResultSet res = queryVariation(connection, chrName);
while (res.next()) {
counter++;
String rsNumber = res.getString("variation_name");
if (!rsNumber.equals(currentRsNumber)) {
if (currentSnp != null) {
storeSnp(currentSnp, consequenceIdentifiers);
}
currentRsNumber = rsNumber;
consequenceIdentifiers = new HashSet<String>();
//String chrName = res.getString("sr.name");
String alleles = res.getString("allele_string");
currentSnp = createItem("SNP");
currentSnp.setAttribute("primaryIdentifier", rsNumber);
currentSnp.setAttribute("alleles", alleles);
currentSnp.setReference("organism", getOrganismItem(taxonId));
Item chr = getChromosome(chrName, taxonId);
currentSnp.setReference("chromosome", chr);
// LOCATION
int chrStart = res.getInt("seq_region_start");
int chrEnd = res.getInt("seq_region_end");
String chrStrand = "" + res.getInt("seq_region_strand");
Item loc = createItem("Location");
loc.setAttribute("start", "" + Math.min(chrStart, chrEnd));
loc.setAttribute("end", "" + Math.max(chrStart, chrEnd));
loc.setAttribute("strand", chrStrand);
loc.setReference("locatedOn", chr);
loc.setReference("feature", currentSnp);
store(loc);
currentSnp.setReference("chromosomeLocation", loc);
// SOURCE
String source = res.getString("s.name");
currentSnp.setReference("source", getSourceIdentifier(source));
// VALIDATION STATES
String validationStatus = res.getString("validation_status");
List<String> validationStates = getValidationStateCollection(validationStatus);
if (!validationStates.isEmpty()) {
currentSnp.setCollection("validations", validationStates);
}
snpCounter++;
if (snpCounter % 1000 == 0) {
LOG.info("Read " + snpCounter + " SNPs, " + counter + " rows total.");
}
}
// CONSEQUENCE TYPES
String cdnaStart = res.getString("cdna_start");
if (StringUtils.isBlank(cdnaStart)) {
String typeStr = res.getString("vf.consequence_type");
for (String type : typeStr.split(",")) {
consequenceIdentifiers.add(getConsequenceIdentifier(type));
}
} else {
String type = res.getString("tv.consequence_type");
String peptideAlleles = res.getString("peptide_allele_string");
String transcriptStableId = res.getString("transcript_stable_id");
Item consequenceItem = createItem("Consequence");
consequenceItem.setAttribute("type", type);
if (!StringUtils.isBlank(peptideAlleles)) {
consequenceItem.setAttribute("peptideAlleles", peptideAlleles);
}
if (!StringUtils.isBlank(transcriptStableId)) {
consequenceItem.setReference("transcript",
getTranscriptIdentifier(transcriptStableId));
}
consequenceIdentifiers.add(consequenceItem.getIdentifier());
store(consequenceItem);
}
}
if (currentSnp != null) {
storeSnp(currentSnp, consequenceIdentifiers);
}
LOG.info("Finished chromosome " + chrName + " stored " + snpCounter + " SNPs.");
}
private void storeSnp(Item snp, Set<String> consequenceIdentifiers)
throws ObjectStoreException {
if (!consequenceIdentifiers.isEmpty()) {
snp.setCollection("consequences", new ArrayList<String>(consequenceIdentifiers));
}
store(snp);
}
private String getSourceIdentifier(String name) throws ObjectStoreException {
String sourceIdentifier = sources.get(name);
if (sourceIdentifier == null) {
Item source = createItem("Source");
source.setAttribute("name", name);
store(source);
sourceIdentifier = source.getIdentifier();
sources.put(name, sourceIdentifier);
}
return sourceIdentifier;
}
private String getTranscriptIdentifier(String transcriptStableId) throws ObjectStoreException {
String transcriptIdentifier = transcripts.get(transcriptStableId);
if (transcriptIdentifier == null) {
Item transcript = createItem("Transcript");
transcript.setAttribute("primaryIdentifier", transcriptStableId);
store(transcript);
transcriptIdentifier = transcript.getIdentifier();
transcripts.put(transcriptStableId, transcriptIdentifier);
}
return transcriptIdentifier;
}
private List<String> getValidationStateCollection(String input) throws ObjectStoreException {
List<String> stateIdentifiers = new ArrayList<String>();
if (!StringUtils.isBlank(input)) {
for (String state : input.split(",")) {
stateIdentifiers.add(getStateIdentifier(state));
}
}
return stateIdentifiers;
}
private String getStateIdentifier(String name) throws ObjectStoreException {
String stateIdentifier = states.get(name);
if (stateIdentifier == null) {
Item state = createItem("ValidationState");
state.setAttribute("name", name);
store(state);
stateIdentifier = state.getIdentifier();
states.put(name, stateIdentifier);
}
return stateIdentifier;
}
private String getConsequenceIdentifier(String type) throws ObjectStoreException {
String consequenceIdentifier = noTranscriptConsequences.get(type);
if (consequenceIdentifier == null) {
Item consequence = createItem("Consequence");
consequence.setAttribute("type", type);
store(consequence);
consequenceIdentifier = consequence.getIdentifier();
noTranscriptConsequences.put(type, consequenceIdentifier);
}
return consequenceIdentifier;
}
private ResultSet queryVariation(Connection connection, String chrName) throws SQLException {
String query = "SELECT vf.variation_name, vf.allele_string, "
+ " sr.name, vf.seq_region_start, vf.seq_region_end, vf.seq_region_strand, "
+ " s.name,"
+ " vf.validation_status,"
+ " vf.consequence_type,"
+ " tv.cdna_start, tv.consequence_type,tv.peptide_allele_string,tv.transcript_stable_id"
+ " FROM seq_region sr, source s, variation_feature vf "
+ " LEFT JOIN (transcript_variation tv)"
+ " ON (vf.variation_feature_id = tv.variation_feature_id"
+ " AND tv.cdna_start is not null)"
+ " WHERE vf.seq_region_id = sr.seq_region_id"
+ " AND vf.source_id = s.source_id"
+ " AND sr.name = '" + chrName + "'"
+ " ORDER BY vf.variation_name";
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* {@inheritDoc}
*/
@Override
public String getDataSetTitle(int taxonId) {
return DATASET_TITLE;
}
}
|
package dhbw.ka.mwi.businesshorizon2.methods.timeseries;
/**
* Klasse zur Berechnung der Trendgerade mit der Formel f(x) = m*x +b
* Annahme: Erster Wert ist das Ergebnis von f(1)
* @author Philipp Nagel, Jonathan Janke
*
*/
public class Trendgerade {
private double m;
private double b;
/**
* @author Philipp Nagel
*/
//method to get value from f(x) = m*x+b;
public double getValue(int x) {
return this.getM()*x + this.getB();
}
/**
* @author Philipp Nagel
*/
public Trendgerade (double[] zeitreihe) {
//trendgerade erzeugen
//m und b mit Startwerten belegen
this.m = zeitreihe[1] - zeitreihe[0];
this.b = zeitreihe[0] - this.m;
double autokovarianz;
double stepsize= this.b/10;
while(stepsize > 0.01){
autokovarianz = getAutoKoVarianz(this.m, this.b, zeitreihe);
//m+stepsize und b gleich
double autokovarianzNew = getAutoKoVarianz((this.m + stepsize), this.b, zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m += stepsize;
}
//m+stepsize und b-stepsize
autokovarianzNew = getAutoKoVarianz((this.m + stepsize), (this.b - stepsize), zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m += stepsize;
this.b -= stepsize;
}
//m+stepsize und b+stepsize
autokovarianzNew = getAutoKoVarianz((this.m + stepsize), (this.b + stepsize), zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m += stepsize;
this.b += stepsize;
}
//m-stepsize und b gleich
autokovarianzNew = getAutoKoVarianz((this.m - stepsize), (this.b), zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m -= stepsize;
}
//m-stepsize und b+stepsize
autokovarianzNew = getAutoKoVarianz((this.m - stepsize), (this.b + stepsize), zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m -= stepsize;
this.b += stepsize;
}
//m-stepsize und b-stepsize
autokovarianzNew = getAutoKoVarianz((this.m - stepsize), (this.b - stepsize), zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m -= stepsize;
this.b -= stepsize;
}
//m gleich und b-stepsize
autokovarianzNew = getAutoKoVarianz((this.m), (this.b - stepsize), zeitreihe);
if(autokovarianzNew<autokovarianz){
this.b -= stepsize;
}
//m gleich und b+stepsize
autokovarianzNew = getAutoKoVarianz((this.m ), (this.b + stepsize), zeitreihe);
if(autokovarianzNew<autokovarianz){
this.b += stepsize;
}
//mit m runden berechnen
double mRounded = Math.round(this.m);
double bRounded = Math.round(this.b);
autokovarianzNew = getAutoKoVarianz(mRounded, bRounded, zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m = mRounded;
this.b = bRounded;
}
//mit b runden berechnen
bRounded = Math.round(this.b);
autokovarianzNew = getAutoKoVarianz(mRounded, bRounded, zeitreihe);
if(autokovarianzNew<autokovarianz){
this.b = bRounded;
}
//mit m runden berechnen
mRounded = Math.round(this.m);
autokovarianzNew = getAutoKoVarianz(mRounded, bRounded, zeitreihe);
if(autokovarianzNew<autokovarianz){
this.m = mRounded;
}
stepsize = stepsize/2;
}
}
public static double getAutoKoVarianz(double m2, double b2, double[] urspruenglicheZeitreihe) {
double autoKovarianz = 0;
double[] ergebnisse = new double[urspruenglicheZeitreihe.length];
for(int i=0; i<ergebnisse.length;i++){
ergebnisse[i] = (m2* (i+1)) + b2;
}
for(int i=0; i<ergebnisse.length;i++){
autoKovarianz = autoKovarianz + ((ergebnisse[i] - urspruenglicheZeitreihe[i]) * (ergebnisse[i] - urspruenglicheZeitreihe[i]));
}
return autoKovarianz;
}
public double getM() {
// TODO Auto-generated method stub
return this.m;
}
public double getB(){
return this.b;
}
}
|
package org.jasig.cas.web.flow;
import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.CasProtocolConstants;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.AuthenticationContext;
import org.jasig.cas.authentication.AuthenticationContextBuilder;
import org.jasig.cas.authentication.AuthenticationSystemSupport;
import org.jasig.cas.authentication.AuthenticationTransaction;
import org.jasig.cas.authentication.DefaultAuthenticationContextBuilder;
import org.jasig.cas.authentication.DefaultAuthenticationSystemSupport;
import org.jasig.cas.authentication.AuthenticationException;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.HandlerResult;
import org.jasig.cas.authentication.MessageDescriptor;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.AbstractTicketException;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketCreationException;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.stereotype.Component;
import org.springframework.web.util.CookieGenerator;
import org.springframework.webflow.core.collection.LocalAttributeMap;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import javax.validation.constraints.NotNull;
import java.util.Map;
/**
* Action to authenticate credential and retrieve a TicketGrantingTicket for
* those credential. If there is a request for renew, then it also generates
* the Service Ticket required.
*
* @author Scott Battaglia
* @since 3.0.0
*/
@Component("authenticationViaFormAction")
public class AuthenticationViaFormAction {
/** Authentication succeeded with warnings from authn subsystem that should be displayed to user. */
public static final String SUCCESS_WITH_WARNINGS = "successWithWarnings";
/** Authentication failure result. */
public static final String AUTHENTICATION_FAILURE = "authenticationFailure";
/** Flow scope attribute that determines if authn is happening at a public workstation. */
public static final String PUBLIC_WORKSTATION_ATTRIBUTE = "publicWorkstation";
/** Logger instance. **/
protected final Logger logger = LoggerFactory.getLogger(getClass());
/** Core we delegate to for handling all ticket related tasks. */
@NotNull
@Autowired
@Qualifier("centralAuthenticationService")
private CentralAuthenticationService centralAuthenticationService;
@NotNull
@Autowired
@Qualifier("warnCookieGenerator")
private CookieGenerator warnCookieGenerator;
@NotNull
@Autowired(required=false)
@Qualifier("defaultAuthenticationSystemSupport")
private AuthenticationSystemSupport authenticationSystemSupport = new DefaultAuthenticationSystemSupport();
/**
* Handle the submission of credentials from the post.
*
* @param context the context
* @param credential the credential
* @param messageContext the message context
* @return the event
* @since 4.1.0
*/
public final Event submit(final RequestContext context, final Credential credential,
final MessageContext messageContext) {
if (!checkLoginTicketIfExists(context)) {
return returnInvalidLoginTicketEvent(context, messageContext);
}
if (isRequestAskingForServiceTicket(context)) {
return grantServiceTicket(context, credential);
}
return createTicketGrantingTicket(context, credential, messageContext);
}
/**
* Tries to to determine if the login ticket in the request flow scope
* matches the login ticket provided by the request. The comparison
* is case-sensitive.
*
* @param context the context
* @return true if valid
* @since 4.1.0
*/
protected boolean checkLoginTicketIfExists(final RequestContext context) {
final String loginTicketFromFlowScope = WebUtils.getLoginTicketFromFlowScope(context);
final String loginTicketFromRequest = WebUtils.getLoginTicketFromRequest(context);
logger.trace("Comparing login ticket in the flow scope [{}] with login ticket in the request [{}]",
loginTicketFromFlowScope, loginTicketFromRequest);
return StringUtils.equals(loginTicketFromFlowScope, loginTicketFromRequest);
}
/**
* Return invalid login ticket event.
*
* @param context the context
* @param messageContext the message context
* @return the error event
* @since 4.1.0
*/
protected Event returnInvalidLoginTicketEvent(final RequestContext context, final MessageContext messageContext) {
final String loginTicketFromRequest = WebUtils.getLoginTicketFromRequest(context);
logger.warn("Invalid login ticket [{}]", loginTicketFromRequest);
messageContext.addMessage(new MessageBuilder().error().code("error.invalid.loginticket").build());
return newEvent(AbstractCasWebflowConfigurer.TRANSITION_ID_ERROR);
}
/**
* Is request asking for service ticket?
*
* @param context the context
* @return true, if both service and tgt are found, and the request is not asking to renew.
* @since 4.1.0
*/
protected boolean isRequestAskingForServiceTicket(final RequestContext context) {
final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
final Service service = WebUtils.getService(context);
return (StringUtils.isNotBlank(context.getRequestParameters().get(CasProtocolConstants.PARAMETER_RENEW))
&& ticketGrantingTicketId != null
&& service != null);
}
/**
* Grant service ticket for the given credential based on the service and tgt
* that are found in the request context.
*
* @param context the context
* @param credential the credential
* @return the resulting event. Warning, authentication failure or error.
* @since 4.1.0
*/
protected Event grantServiceTicket(final RequestContext context, final Credential credential) {
final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
try {
final Service service = WebUtils.getService(context);
final AuthenticationContextBuilder builder = new DefaultAuthenticationContextBuilder(
this.authenticationSystemSupport.getPrincipalElectionStrategy());
final AuthenticationTransaction transaction =
AuthenticationTransaction.wrap(credential);
this.authenticationSystemSupport.getAuthenticationTransactionManager().handle(transaction, builder);
final AuthenticationContext authenticationContext = builder.build(service);
final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(
ticketGrantingTicketId, service, authenticationContext);
WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
WebUtils.putWarnCookieIfRequestParameterPresent(this.warnCookieGenerator, context);
return newEvent(AbstractCasWebflowConfigurer.TRANSITION_ID_WARN);
} catch (final AuthenticationException e) {
return newEvent(AUTHENTICATION_FAILURE, e);
} catch (final TicketCreationException e) {
logger.warn("Invalid attempt to access service using renew=true with different credential. Ending SSO session.");
this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);
} catch (final AbstractTicketException e) {
return newEvent(AbstractCasWebflowConfigurer.TRANSITION_ID_ERROR, e);
}
return newEvent(AbstractCasWebflowConfigurer.TRANSITION_ID_ERROR);
}
/**
* Create ticket granting ticket for the given credentials.
* Adds all warnings into the message context.
*
* @param context the context
* @param credential the credential
* @param messageContext the message context
* @return the resulting event.
* @since 4.1.0
*/
protected Event createTicketGrantingTicket(final RequestContext context, final Credential credential,
final MessageContext messageContext) {
try {
final Service service = WebUtils.getService(context);
final AuthenticationContextBuilder builder = new DefaultAuthenticationContextBuilder(
this.authenticationSystemSupport.getPrincipalElectionStrategy());
final AuthenticationTransaction transaction =
AuthenticationTransaction.wrap(credential);
this.authenticationSystemSupport.getAuthenticationTransactionManager().handle(transaction, builder);
final AuthenticationContext authenticationContext = builder.build(service);
final TicketGrantingTicket tgt = this.centralAuthenticationService.createTicketGrantingTicket(authenticationContext);
WebUtils.putTicketGrantingTicketInScopes(context, tgt);
WebUtils.putWarnCookieIfRequestParameterPresent(this.warnCookieGenerator, context);
putPublicWorkstationToFlowIfRequestParameterPresent(context);
if (addWarningMessagesToMessageContextIfNeeded(tgt, messageContext)) {
return newEvent(SUCCESS_WITH_WARNINGS);
}
return newEvent(AbstractCasWebflowConfigurer.TRANSITION_ID_SUCCESS);
} catch (final AuthenticationException e) {
logger.debug(e.getMessage(), e);
return newEvent(AUTHENTICATION_FAILURE, e);
} catch (final Exception e) {
logger.debug(e.getMessage(), e);
return newEvent(AbstractCasWebflowConfigurer.TRANSITION_ID_ERROR, e);
}
}
/**
* Add warning messages to message context if needed.
*
* @param tgtId the tgt id
* @param messageContext the message context
* @return true if warnings were found and added, false otherwise.
* @since 4.1.0
*/
protected boolean addWarningMessagesToMessageContextIfNeeded(final TicketGrantingTicket tgtId, final MessageContext messageContext) {
boolean foundAndAddedWarnings = false;
for (final Map.Entry<String, HandlerResult> entry : tgtId.getAuthentication().getSuccesses().entrySet()) {
for (final MessageDescriptor message : entry.getValue().getWarnings()) {
addWarningToContext(messageContext, message);
foundAndAddedWarnings = true;
}
}
return foundAndAddedWarnings;
}
/**
* Put public workstation into the flow if request parameter present.
*
* @param context the context
*/
private static void putPublicWorkstationToFlowIfRequestParameterPresent(final RequestContext context) {
if (StringUtils.isNotBlank(context.getExternalContext()
.getRequestParameterMap().get(PUBLIC_WORKSTATION_ATTRIBUTE))) {
context.getFlowScope().put(PUBLIC_WORKSTATION_ATTRIBUTE, Boolean.TRUE);
}
}
/**
* New event based on the given id.
*
* @param id the id
* @return the event
*/
private Event newEvent(final String id) {
return new Event(this, id);
}
/**
* New event based on the id, which contains an error attribute referring to the exception occurred.
*
* @param id the id
* @param error the error
* @return the event
*/
private Event newEvent(final String id, final Exception error) {
return new Event(this, id, new LocalAttributeMap("error", error));
}
/**
* Adds a warning message to the message context.
*
* @param context Message context.
* @param warning Warning message.
*/
private static void addWarningToContext(final MessageContext context, final MessageDescriptor warning) {
final MessageBuilder builder = new MessageBuilder()
.warning()
.code(warning.getCode())
.defaultText(warning.getDefaultMessage())
.args(warning.getParams());
context.addMessage(builder.build());
}
public void setCentralAuthenticationService(final CentralAuthenticationService centralAuthenticationService) {
this.centralAuthenticationService = centralAuthenticationService;
}
public void setWarnCookieGenerator(final CookieGenerator warnCookieGenerator) {
this.warnCookieGenerator = warnCookieGenerator;
}
public void setAuthenticationSystemSupport(final AuthenticationSystemSupport authenticationSystemSupport) {
this.authenticationSystemSupport = authenticationSystemSupport;
}
}
|
package org.realityforge.replicant.client.transport;
import arez.Arez;
import arez.Disposable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.replicant.client.Linkable;
import org.realityforge.replicant.client.Verifiable;
import replicant.Channel;
import replicant.ChannelAddress;
import replicant.Entity;
import replicant.FilterUtil;
import replicant.Replicant;
import replicant.Subscription;
import replicant.spy.DataLoadStatus;
import static org.realityforge.braincheck.Guards.*;
/**
* Class from which to extend to implement a service that loads data from a change set.
* Data is loaded incrementally and the load can be broken up into several
* steps to avoid locking a thread such as in GWT.
*/
@SuppressWarnings( { "WeakerAccess", "unused" } )
public abstract class AbstractDataLoaderService
extends AbstractDataLoaderService2
implements DataLoaderService
{
protected static final Logger LOG = Logger.getLogger( AbstractDataLoaderService.class.getName() );
private static final int DEFAULT_CHANGES_TO_PROCESS_PER_TICK = 100;
private static final int DEFAULT_LINKS_TO_PROCESS_PER_TICK = 100;
private final CacheService _cacheService;
private DataLoadAction _currentAction;
private List<AreaOfInterestEntry> _currentAoiActions = new ArrayList<>();
private int _changesToProcessPerTick = DEFAULT_CHANGES_TO_PROCESS_PER_TICK;
private int _linksToProcessPerTick = DEFAULT_LINKS_TO_PROCESS_PER_TICK;
private boolean _incrementalDataLoadInProgress;
/**
* Action invoked after current action completes to reset session state.
*/
private Runnable _resetAction;
private ClientSession _session;
private Disposable _schedulerLock;
protected AbstractDataLoaderService( @Nonnull final ReplicantClientSystem replicantClientSystem,
@Nonnull final CacheService cacheService )
{
super( replicantClientSystem );
_cacheService = Objects.requireNonNull( cacheService );
}
@Override
public final void requestSubscribe( @Nonnull final ChannelAddress address, @Nullable final Object filterParameter )
{
ensureSession().requestSubscribe( address, filterParameter );
}
@Override
public final void requestSubscriptionUpdate( @Nonnull final ChannelAddress address,
@Nullable final Object filterParameter )
{
ensureSession().requestSubscriptionUpdate( address, filterParameter );
}
@Override
public final void requestUnsubscribe( @Nonnull final ChannelAddress address )
{
ensureSession().requestUnsubscribe( address );
}
/**
* A symbolic key for describing system.
*/
@Nonnull
protected String getKey()
{
return getSessionContext().getKey();
}
@Nonnull
protected abstract SessionContext getSessionContext();
@Nonnull
protected abstract ChangeMapper getChangeMapper();
protected boolean shouldPurgeOnSessionChange()
{
return true;
}
protected void setSession( @Nullable final ClientSession session, @Nullable final Runnable postAction )
{
final Runnable runnable = () -> doSetSession( session, postAction );
if ( null == _currentAction )
{
runnable.run();
}
else
{
_resetAction = runnable;
}
}
protected void doSetSession( @Nullable final ClientSession session, @Nullable final Runnable postAction )
{
if ( session != _session )
{
_session = session;
// This should probably be moved elsewhere ... but where?
getSessionContext().setSession( session );
if ( shouldPurgeOnSessionChange() )
{
//TODO: else schedule action so that it runs in loop
// until it can disable broker. This will involve replacing _resetAction
// with something more like existing action setup.
context().safeAction( generateName( "purgeSubscriptions" ), this::purgeSubscriptions );
}
}
if ( null != postAction )
{
postAction.run();
}
}
@Nullable
protected final ClientSession getSession()
{
return _session;
}
@Nonnull
protected abstract ClientSession ensureSession();
protected void purgeSubscriptions()
{
Stream.concat( Replicant.context().getTypeSubscriptions().stream(),
Replicant.context().getInstanceSubscriptions().stream() )
// Only purge subscriptions for current system
.filter( s -> s.getChannel().getAddress().getSystem().equals( getSystemType() ) )
// Purge in reverse order. First instance subscriptions then type subscriptions
.sorted( Comparator.reverseOrder() )
.forEachOrdered( Disposable::dispose );
}
/**
* Schedule data loads using incremental scheduler.
*/
@Override
public void scheduleDataLoad()
{
if ( !_incrementalDataLoadInProgress )
{
_incrementalDataLoadInProgress = true;
doScheduleDataLoad();
}
}
/**
* Perform a single step in incremental data load process.
*
* @return true if more work is to be done.
*/
protected boolean stepDataLoad()
{
if ( null == _schedulerLock )
{
_schedulerLock = context().pauseScheduler();
}
try
{
final boolean aoiActionProgressed = progressAreaOfInterestActions();
final boolean dataActionProgressed = progressDataLoad();
_incrementalDataLoadInProgress = aoiActionProgressed || dataActionProgressed;
}
catch ( final Exception e )
{
onMessageProcessFailure( e );
_incrementalDataLoadInProgress = false;
return false;
}
finally
{
if ( !_incrementalDataLoadInProgress )
{
_schedulerLock.dispose();
_schedulerLock = null;
}
}
return _incrementalDataLoadInProgress;
}
/**
* Actually perform the scheduling of the data load action.
*/
protected abstract void doScheduleDataLoad();
@SuppressWarnings( "SameParameterValue" )
protected void setChangesToProcessPerTick( final int changesToProcessPerTick )
{
_changesToProcessPerTick = changesToProcessPerTick;
}
@SuppressWarnings( "SameParameterValue" )
protected void setLinksToProcessPerTick( final int linksToProcessPerTick )
{
_linksToProcessPerTick = linksToProcessPerTick;
}
@Nonnull
protected abstract ChangeSet parseChangeSet( @Nonnull String rawJsonData );
/**
* Perform a single step in sending one (or a batch) or requests to the server.
*
* @return true if more work is to be done.
*/
protected boolean progressAreaOfInterestActions()
{
if ( _currentAoiActions.isEmpty() )
{
final LinkedList<AreaOfInterestEntry> actions = ensureSession().getPendingAreaOfInterestActions();
if ( 0 == actions.size() )
{
return false;
}
final AreaOfInterestEntry first = actions.removeFirst();
_currentAoiActions.add( first );
while ( actions.size() > 0 && isCompatibleForBulkChange( first, actions.get( 0 ) ) )
{
_currentAoiActions.add( actions.removeFirst() );
}
}
if ( _currentAoiActions.get( 0 ).isInProgress() )
{
return false;
}
else
{
_currentAoiActions.forEach( AreaOfInterestEntry::markAsInProgress );
final AreaOfInterestAction action = _currentAoiActions.get( 0 ).getAction();
if ( action == AreaOfInterestAction.ADD )
{
return progressBulkAOIAddActions();
}
else if ( action == AreaOfInterestAction.REMOVE )
{
return progressBulkAOIRemoveActions();
}
else
{
return progressBulkAOIUpdateActions();
}
}
}
private String label( AreaOfInterestEntry entry )
{
final ChannelAddress descriptor = entry.getAddress();
final Object filterParameter = entry.getFilterParameter();
return getKey() + ":" + descriptor +
( null == filterParameter ? "" : "[" + filterToString( filterParameter ) + "]" );
}
private String label( List<AreaOfInterestEntry> entries )
{
if ( entries.size() == 0 )
{
return "";
}
final Object filterParameter = entries.get( 0 ).getFilterParameter();
return getKey() +
":" +
entries.stream().map( e -> e.getAddress().toString() ).collect( Collectors.joining( "/" ) ) +
( null == filterParameter ? "" : "[" + filterToString( filterParameter ) + "]" );
}
private boolean progressBulkAOIUpdateActions()
{
context().safeAction( generateName( "removeUnneededUpdateRequests" ), () -> {
_currentAoiActions.removeIf( a -> {
final Subscription subscription = Replicant.context().findSubscription( a.getAddress() );
if ( null == subscription )
{
LOG.warning( () -> "Subscription update of " + label( a ) + " requested but not subscribed." );
a.markAsComplete();
return true;
}
return false;
} );
} );
if ( 0 == _currentAoiActions.size() )
{
completeAoiAction();
return true;
}
final Consumer<Runnable> completionAction = a ->
{
LOG.warning( () -> "Subscription update of " + label( _currentAoiActions ) + " completed." );
completeAoiAction();
a.run();
};
final Consumer<Runnable> failAction = a ->
{
LOG.warning( () -> "Subscription update of " + label( _currentAoiActions ) + " failed." );
completeAoiAction();
a.run();
};
LOG.warning( () -> "Subscription update of " + label( _currentAoiActions ) + " requested." );
final AreaOfInterestEntry aoiEntry = _currentAoiActions.get( 0 );
assert null != aoiEntry.getFilterParameter();
if ( _currentAoiActions.size() > 1 )
{
final List<ChannelAddress> ids =
_currentAoiActions.stream().map( AreaOfInterestEntry::getAddress ).collect( Collectors.toList() );
requestBulkUpdateSubscription( ids, aoiEntry.getFilterParameter(), completionAction, failAction );
}
else
{
final ChannelAddress descriptor = aoiEntry.getAddress();
requestUpdateSubscription( descriptor, aoiEntry.getFilterParameter(), completionAction, failAction );
}
return true;
}
private boolean progressBulkAOIRemoveActions()
{
context().safeAction( generateName( "removeUnneededRemoveRequests" ), () -> {
_currentAoiActions.removeIf( a -> {
final Subscription subscription = Replicant.context().findSubscription( a.getAddress() );
if ( null == subscription )
{
LOG.warning( () -> "Unsubscribe from " + label( a ) + " requested but not subscribed." );
a.markAsComplete();
return true;
}
else if ( !subscription.isExplicitSubscription() )
{
LOG.warning( () -> "Unsubscribe from " + label( a ) + " requested but not explicitly subscribed." );
a.markAsComplete();
return true;
}
return false;
} );
} );
if ( 0 == _currentAoiActions.size() )
{
completeAoiAction();
return true;
}
LOG.info( () -> "Unsubscribe from " + label( _currentAoiActions ) + " requested." );
final Consumer<Runnable> completionAction = postAction ->
{
LOG.info( () -> "Unsubscribe from " + label( _currentAoiActions ) + " completed." );
context().safeAction( generateName( "setExplicitSubscription(false)" ), () -> _currentAoiActions.forEach( a -> {
final Subscription subscription = Replicant.context().findSubscription( a.getAddress() );
if ( null != subscription )
{
subscription.setExplicitSubscription( false );
}
} ) );
completeAoiAction();
postAction.run();
};
final Consumer<Runnable> failAction = postAction ->
{
LOG.info( "Unsubscribe from " + label( _currentAoiActions ) + " failed." );
context().safeAction( generateName( "setExplicitSubscription(false)" ), () -> _currentAoiActions.forEach( a -> {
final Subscription subscription = Replicant.context().findSubscription( a.getAddress() );
if ( null != subscription )
{
subscription.setExplicitSubscription( false );
}
} ) );
completeAoiAction();
postAction.run();
};
final AreaOfInterestEntry aoiEntry = _currentAoiActions.get( 0 );
if ( _currentAoiActions.size() > 1 )
{
final List<ChannelAddress> ids =
_currentAoiActions.stream().map( AreaOfInterestEntry::getAddress ).collect( Collectors.toList() );
requestBulkUnsubscribeFromChannel( ids, completionAction, failAction );
}
else
{
final ChannelAddress descriptor = aoiEntry.getAddress();
requestUnsubscribeFromChannel( descriptor, completionAction, failAction );
}
return true;
}
private boolean progressBulkAOIAddActions()
{
// Remove all Add Aoi actions that need no action as they are already present locally
context().safeAction( generateName( "removeUnneededAddRequests" ), () -> {
_currentAoiActions.removeIf( a -> {
final Subscription subscription = Replicant.context().findSubscription( a.getAddress() );
if ( null != subscription )
{
if ( subscription.isExplicitSubscription() )
{
LOG.warning( "Subscription to " + label( a ) + " requested but already subscribed." );
}
else
{
LOG.warning( () -> "Existing subscription to " + label( a ) + " converted to a explicit subscription." );
subscription.setExplicitSubscription( true );
}
a.markAsComplete();
return true;
}
return false;
} );
} );
if ( 0 == _currentAoiActions.size() )
{
completeAoiAction();
return true;
}
final Consumer<Runnable> completionAction = a ->
{
LOG.info( () -> "Subscription to " + label( _currentAoiActions ) + " completed." );
completeAoiAction();
a.run();
};
final Consumer<Runnable> failAction = a ->
{
LOG.info( () -> "Subscription to " + label( _currentAoiActions ) + " failed." );
completeAoiAction();
a.run();
};
final AreaOfInterestEntry aoiEntry = _currentAoiActions.get( 0 );
if ( _currentAoiActions.size() == 1 )
{
final String cacheKey = aoiEntry.getCacheKey();
final CacheEntry cacheEntry = _cacheService.lookup( cacheKey );
final String eTag;
final Consumer<Runnable> cacheAction;
if ( null != cacheEntry )
{
eTag = cacheEntry.getETag();
LOG.info( () -> "Found locally cached data for channel " + label( aoiEntry ) + " with etag " + eTag + "." );
cacheAction = a ->
{
LOG.info( () -> "Loading cached data for channel " + label( aoiEntry ) + " with etag " + eTag );
final Runnable completeAoiAction = () ->
{
LOG.info( () -> "Completed load of cached data for channel " +
label( aoiEntry ) +
" with etag " +
eTag +
"." );
completeAoiAction();
a.run();
};
ensureSession().enqueueOOB( cacheEntry.getContent(), completeAoiAction );
};
}
else
{
eTag = null;
cacheAction = null;
}
LOG.info( () -> "Subscription to " + label( aoiEntry ) + " with eTag " + cacheKey + "=" + eTag + " requested" );
requestSubscribeToChannel( aoiEntry.getAddress(),
aoiEntry.getFilterParameter(),
cacheKey,
eTag,
cacheAction,
completionAction,
failAction );
}
else
{
// don't support bulk loading of anything that is already cached
final List<ChannelAddress> ids =
_currentAoiActions.stream().map( AreaOfInterestEntry::getAddress ).collect( Collectors.toList() );
requestBulkSubscribeToChannel( ids, aoiEntry.getFilterParameter(), completionAction, failAction );
}
return true;
}
private boolean isCompatibleForBulkChange( final AreaOfInterestEntry template,
final AreaOfInterestEntry match )
{
final AreaOfInterestAction action = match.getAction();
return null == _cacheService.lookup( template.getCacheKey() ) &&
null == _cacheService.lookup( match.getCacheKey() ) &&
template.getAction().equals( action ) &&
template.getAddress().getChannelType().equals( match.getAddress().getChannelType() ) &&
( AreaOfInterestAction.REMOVE == action ||
FilterUtil.filtersEqual( match.getFilterParameter(), template.getFilterParameter() ) );
}
private void completeAoiAction()
{
scheduleDataLoad();
_currentAoiActions.forEach( AreaOfInterestEntry::markAsComplete );
_currentAoiActions.clear();
}
protected abstract void requestSubscribeToChannel( @Nonnull ChannelAddress descriptor,
@Nullable Object filterParameter,
@Nullable String cacheKey,
@Nullable String eTag,
@Nullable Consumer<Runnable> cacheAction,
@Nonnull Consumer<Runnable> completionAction,
@Nonnull Consumer<Runnable> failAction );
protected abstract void requestUnsubscribeFromChannel( @Nonnull ChannelAddress descriptor,
@Nonnull Consumer<Runnable> completionAction,
@Nonnull Consumer<Runnable> failAction );
protected abstract void requestUpdateSubscription( @Nonnull ChannelAddress descriptor,
@Nonnull Object filterParameter,
@Nonnull Consumer<Runnable> completionAction,
@Nonnull Consumer<Runnable> failAction );
protected abstract void requestBulkSubscribeToChannel( @Nonnull List<ChannelAddress> descriptor,
@Nullable Object filterParameter,
@Nonnull Consumer<Runnable> completionAction,
@Nonnull Consumer<Runnable> failAction );
protected abstract void requestBulkUnsubscribeFromChannel( @Nonnull List<ChannelAddress> descriptors,
@Nonnull Consumer<Runnable> completionAction,
@Nonnull Consumer<Runnable> failAction );
protected abstract void requestBulkUpdateSubscription( @Nonnull List<ChannelAddress> descriptors,
@Nonnull Object filterParameter,
@Nonnull Consumer<Runnable> completionAction,
@Nonnull Consumer<Runnable> failAction );
@Override
public boolean isAreaOfInterestActionPending( @Nonnull final AreaOfInterestAction action,
@Nonnull final ChannelAddress address,
@Nullable final Object filter )
{
final ClientSession session = getSession();
return
null != _currentAoiActions &&
_currentAoiActions.stream().anyMatch( a -> a.match( action, address, filter ) ) ||
(
null != session &&
session.getPendingAreaOfInterestActions().stream().
anyMatch( a -> a.match( action, address, filter ) )
);
}
@Override
public int indexOfPendingAreaOfInterestAction( @Nonnull final AreaOfInterestAction action,
@Nonnull final ChannelAddress address,
@Nullable final Object filter )
{
final ClientSession session = getSession();
if ( null != _currentAoiActions &&
_currentAoiActions.stream().anyMatch( a -> a.match( action, address, filter ) ) )
{
return 0;
}
else if ( null != session )
{
final LinkedList<AreaOfInterestEntry> actions = session.getPendingAreaOfInterestActions();
int index = actions.size();
final Iterator<AreaOfInterestEntry> iterator = actions.descendingIterator();
while ( iterator.hasNext() )
{
final AreaOfInterestEntry entry = iterator.next();
if ( entry.match( action, address, filter ) )
{
return index;
}
index -= 1;
}
}
return -1;
}
// Method only used in tests
DataLoadAction getCurrentAction()
{
return _currentAction;
}
// Method only used in tests
List<AreaOfInterestEntry> getCurrentAOIActions()
{
return _currentAoiActions;
}
protected boolean progressDataLoad()
{
final ClientSession session = ensureSession();
// Step: Retrieve any out of band actions
final LinkedList<DataLoadAction> oobActions = session.getOobActions();
if ( null == _currentAction && !oobActions.isEmpty() )
{
_currentAction = oobActions.removeFirst();
return true;
}
//Step: Retrieve the action from the parsed queue if it is the next in the sequence
final LinkedList<DataLoadAction> parsedActions = session.getParsedActions();
if ( null == _currentAction && !parsedActions.isEmpty() )
{
final DataLoadAction action = parsedActions.get( 0 );
final ChangeSet changeSet = action.getChangeSet();
assert null != changeSet;
if ( action.isOob() || session.getLastRxSequence() + 1 == changeSet.getSequence() )
{
_currentAction = parsedActions.remove();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Parsed Action Selected: " + _currentAction );
}
return true;
}
}
// Abort if there is no pending data load actions to take
final LinkedList<DataLoadAction> pendingActions = session.getPendingActions();
if ( null == _currentAction && pendingActions.isEmpty() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "No data to load. Terminating incremental load process." );
}
onTerminatingIncrementalDataLoadProcess();
return false;
}
//Step: Retrieve the action from the un-parsed queue
if ( null == _currentAction )
{
_currentAction = pendingActions.remove();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Un-parsed Action Selected: " + _currentAction );
}
return true;
}
//Step: Parse the json
final String rawJsonData = _currentAction.getRawJsonData();
if ( null != rawJsonData )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Parsing JSON: " + _currentAction );
}
final ChangeSet changeSet = parseChangeSet( _currentAction.getRawJsonData() );
// OOB messages are not in response to requests as such
final String requestID = _currentAction.isOob() ? null : changeSet.getRequestID();
// OOB messages have no etags as from local cache or generated locally
final String eTag = _currentAction.isOob() ? null : changeSet.getETag();
final int sequence = _currentAction.isOob() ? 0 : changeSet.getSequence();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(),
"Parsed ChangeSet:" +
" oob=" + _currentAction.isOob() +
" seq=" + sequence +
" requestID=" + requestID +
" eTag=" + eTag +
" changeCount=" + changeSet.getChangeCount()
);
}
final RequestEntry request;
if ( _currentAction.isOob() )
{
request = null;
}
else
{
request = null != requestID ? session.getRequest( requestID ) : null;
if ( null == request && null != requestID )
{
final String message =
"Unable to locate requestID '" + requestID + "' specified for ChangeSet: seq=" + sequence +
" Existing Requests: " + session.getRequests();
if ( LOG.isLoggable( Level.WARNING ) )
{
LOG.warning( message );
}
throw new IllegalStateException( message );
}
else if ( null != request )
{
final String cacheKey = request.getCacheKey();
if ( null != eTag && null != cacheKey )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Caching ChangeSet: seq=" + sequence + " cacheKey=" + cacheKey );
}
_cacheService.store( cacheKey, eTag, rawJsonData );
}
else
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Not caching ChangeSet: seq=" + sequence + " cacheKey=" + cacheKey );
}
}
}
}
_currentAction.setChangeSet( changeSet, request );
parsedActions.add( _currentAction );
Collections.sort( parsedActions );
_currentAction = null;
return true;
}
if ( _currentAction.needsChannelActionsProcessed() )
{
context().safeAction( generateName( "processChannelActions" ), this::processChannelActions );
return true;
}
//Step: Process a chunk of changes
if ( _currentAction.areChangesPending() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Processing ChangeSet: " + _currentAction );
}
final ChangeSet changeSet = _currentAction.getChangeSet();
assert null != changeSet;
context().safeAction( generateName( "applyChange" ), () -> {
Change change;
for ( int i = 0; i < _changesToProcessPerTick && null != ( change = _currentAction.nextChange() ); i++ )
{
final Object entity = getChangeMapper().applyChange( change );
if ( LOG.isLoggable( Level.INFO ) )
{
if ( change.isUpdate() )
{
_currentAction.incUpdateCount();
}
else
{
_currentAction.incRemoveCount();
}
}
_currentAction.changeProcessed( change.isUpdate(), entity );
}
}, changeSet.getSequence(), changeSet.getRequestID() );
return true;
}
//Step: Calculate the entities that need to be linked
if ( !_currentAction.areEntityLinksCalculated() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Calculating Link list: " + _currentAction );
}
_currentAction.calculateEntitiesToLink();
return true;
}
//Step: Process a chunk of links
if ( _currentAction.areEntityLinksPending() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Linking Entities: " + _currentAction );
}
final ChangeSet changeSet = _currentAction.getChangeSet();
assert null != changeSet;
context().safeAction( generateName( "link" ), () -> {
Linkable linkable;
for ( int i = 0; i < _linksToProcessPerTick && null != ( linkable = _currentAction.nextEntityToLink() ); i++ )
{
linkable.link();
if ( LOG.isLoggable( Level.INFO ) )
{
_currentAction.incLinkCount();
}
}
}, changeSet.getSequence(), changeSet.getRequestID() );
return true;
}
final ChangeSet set = _currentAction.getChangeSet();
assert null != set;
//Step: Finalize the change set
if ( !_currentAction.hasWorldBeenNotified() )
{
_currentAction.markWorldAsNotified();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Finalizing action: " + _currentAction );
}
// OOB messages are not sequenced
if ( !_currentAction.isOob() )
{
session.setLastRxSequence( set.getSequence() );
}
if ( Replicant.shouldValidateRepositoryOnLoad() )
{
// This should never need a transaction ... unless the repository is invalid and there is unlinked data.
context().safeAction( generateName( "validate" ), this::validateRepository );
}
return true;
}
final DataLoadStatus status = _currentAction.toStatus( getKey() );
if ( LOG.isLoggable( Level.INFO ) )
{
LOG.info( status.toString() );
}
//Step: Run the post actions
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Running post action and cleaning action: " + _currentAction );
}
final RequestEntry request = _currentAction.getRequest();
if ( null != request )
{
request.markResultsAsArrived();
}
final Runnable runnable = _currentAction.getRunnable();
if ( null != runnable )
{
runnable.run();
// OOB messages are not in response to requests as such
final String requestID = _currentAction.isOob() ? null : _currentAction.getChangeSet().getRequestID();
if ( null != requestID )
{
// We can remove the request because this side ran second and the
// RPC channel has already returned.
final boolean removed = session.removeRequest( requestID );
if ( !removed )
{
LOG.severe( "ChangeSet " + set.getSequence() + " expected to complete request '" +
requestID + "' but no request was registered with session." );
}
if ( requestDebugOutputEnabled() )
{
outputRequestDebug();
}
}
}
_currentAction = null;
onMessageProcessed( status );
if ( null != _resetAction )
{
_resetAction.run();
_resetAction = null;
}
return true;
}
private void processChannelActions()
{
_currentAction.markChannelActionsProcessed();
final ChangeSet changeSet = _currentAction.getChangeSet();
assert null != changeSet;
final int channelActionCount = changeSet.getChannelActionCount();
for ( int i = 0; i < channelActionCount; i++ )
{
final ChannelAction action = changeSet.getChannelAction( i );
final ChannelAddress address = toChannelDescriptor( action );
final Object filter = action.getChannelFilter();
final ChannelAction.Action actionType = action.getAction();
if ( LOG.isLoggable( getLogLevel() ) )
{
final String message = "ChannelAction:: " + actionType.name() + " " + address + " filter=" + filter;
LOG.log( getLogLevel(), message );
}
if ( ChannelAction.Action.ADD == actionType )
{
_currentAction.incChannelAddCount();
boolean explicitSubscribe = false;
if ( _currentAoiActions.stream().anyMatch( a -> a.isInProgress() && a.getAddress().equals( address ) ) )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Recording explicit subscription for " + address );
}
explicitSubscribe = true;
}
Replicant.context().createSubscription( address, filter, explicitSubscribe );
}
else if ( ChannelAction.Action.REMOVE == actionType )
{
final Subscription subscription = Replicant.context().findSubscription( address );
assert null != subscription;
Disposable.dispose( subscription );
_currentAction.incChannelRemoveCount();
}
else if ( ChannelAction.Action.UPDATE == actionType )
{
final Subscription subscription = Replicant.context().findSubscription( address );
assert null != subscription;
subscription.getChannel().setFilter( filter );
updateSubscriptionForFilteredEntities( subscription, filter );
_currentAction.incChannelUpdateCount();
}
else
{
throw new IllegalStateException();
}
}
}
protected abstract boolean requestDebugOutputEnabled();
@Nonnull
private ChannelAddress toChannelDescriptor( @Nonnull final ChannelAction action )
{
final int channelId = action.getChannelId();
final Integer subChannelId = action.getSubChannelId();
final Enum channelType = channelIdToType( channelId );
return new ChannelAddress( channelType, subChannelId );
}
@Nonnull
public abstract Class<? extends Enum> getSystemType();
/**
* Return the entity types processed by this loader.
*/
@Nonnull
public abstract Set<Class<?>> getEntityTypes();
protected abstract void updateSubscriptionForFilteredEntities( @Nonnull Subscription subscription,
@Nullable Object filter );
protected void updateSubscriptionForFilteredEntities( @Nonnull final Subscription subscription,
@Nullable final Object filter,
@Nonnull final Collection<Entity> entities )
{
if ( !entities.isEmpty() )
{
final Channel channel = subscription.getChannel();
for ( final Entity entity : new ArrayList<>( entities ) )
{
if ( !doesEntityMatchFilter( channel, entity ) )
{
entity.delinkFromSubscription( subscription );
}
}
}
}
protected abstract boolean doesEntityMatchFilter( @Nonnull Channel channel, @Nonnull Entity entity );
@Override
public void connect()
{
if ( null == getSession() && State.CONNECTING != getState() )
{
performConnect();
}
}
private void performConnect()
{
State state = State.ERROR;
try
{
doConnect( this::onConnected );
state = State.CONNECTING;
}
finally
{
setState( state );
}
}
protected abstract void doConnect( @Nullable Runnable runnable );
@Override
public void disconnect()
{
final ClientSession session = getSession();
if ( null != session && State.DISCONNECTING != getState() )
{
setState( State.DISCONNECTING );
doDisconnect( this::onDisconnected );
}
}
protected abstract void doDisconnect( @Nullable Runnable runnable );
@Nonnull
protected Enum channelIdToType( final int channel )
throws IllegalArgumentException
{
assert getSystemType().isEnum();
return getSystemType().getEnumConstants()[ channel ];
}
/**
* Template method invoked when progressDataLoad() is about to return false and terminate load process.
*/
protected void onTerminatingIncrementalDataLoadProcess()
{
}
@Nonnull
protected String filterToString( @Nullable final Object filterParameter )
{
if ( null == filterParameter )
{
return "";
}
else
{
return doFilterToString( filterParameter );
}
}
@Nonnull
protected abstract String doFilterToString( @Nonnull Object filterParameter );
@Nonnull
protected Level getLogLevel()
{
return Level.FINEST;
}
protected void validateRepository()
throws IllegalStateException
{
if ( Replicant.shouldCheckInvariants() )
{
for ( final Class<?> entityType : getEntityTypes() )
{
for ( final Object entity : Replicant.context().findAllEntitiesByType( entityType ) )
{
invariant( () -> !Disposable.isDisposed( entity ),
() -> "Invalid disposed entity found during validation. Entity: " + entity );
try
{
Verifiable.verify( entity );
}
catch ( final Exception e )
{
final String message = "Entity failed to verify. Entity = " + entity;
LOG.log( Level.WARNING, message, e );
throw new IllegalStateException( message, e );
}
}
}
}
}
protected void outputRequestDebug()
{
getRequestDebugger().outputRequests( getKey() + ":", ensureSession() );
}
@Nonnull
protected RequestDebugger getRequestDebugger()
{
return new RequestDebugger();
}
@Nullable
protected String generateName( @Nonnull final String name )
{
return Arez.areNamesEnabled() ? toString() + "." + name : null;
}
@Override
public String toString()
{
return Arez.areNamesEnabled() ? "DataLoader[" + getKey() + "]" : super.toString();
}
}
|
package com.example.e4.rcp.todo.ownannotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@javax.inject.Qualifier
@Documented
@Target({ ElementType.PARAMETER, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface UniqueTodo {
}
|
package org.jboss.as.connector.subsystems.resourceadapters;
import static org.jboss.as.connector.subsystems.common.pool.Constants.BACKGROUNDVALIDATION;
import static org.jboss.as.connector.subsystems.common.pool.Constants.BACKGROUNDVALIDATIONMILLIS;
import static org.jboss.as.connector.subsystems.common.pool.Constants.BLOCKING_TIMEOUT_WAIT_MILLIS;
import static org.jboss.as.connector.subsystems.common.pool.Constants.CAPACITY_DECREMENTER_CLASS;
import static org.jboss.as.connector.subsystems.common.pool.Constants.CAPACITY_DECREMENTER_PROPERTIES;
import static org.jboss.as.connector.subsystems.common.pool.Constants.CAPACITY_INCREMENTER_CLASS;
import static org.jboss.as.connector.subsystems.common.pool.Constants.CAPACITY_INCREMENTER_PROPERTIES;
import static org.jboss.as.connector.subsystems.common.pool.Constants.IDLETIMEOUTMINUTES;
import static org.jboss.as.connector.subsystems.common.pool.Constants.INITIAL_POOL_SIZE;
import static org.jboss.as.connector.subsystems.common.pool.Constants.MAX_POOL_SIZE;
import static org.jboss.as.connector.subsystems.common.pool.Constants.MIN_POOL_SIZE;
import static org.jboss.as.connector.subsystems.common.pool.Constants.POOL_FAIR;
import static org.jboss.as.connector.subsystems.common.pool.Constants.POOL_FLUSH_STRATEGY;
import static org.jboss.as.connector.subsystems.common.pool.Constants.POOL_PREFILL;
import static org.jboss.as.connector.subsystems.common.pool.Constants.POOL_USE_STRICT_MIN;
import static org.jboss.as.connector.subsystems.common.pool.Constants.USE_FAST_FAIL;
import static org.jboss.as.connector.subsystems.common.pool.Constants.VALIDATE_ON_MATCH;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.ALLOCATION_RETRY;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.ALLOCATION_RETRY_WAIT_MILLIS;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.APPLICATION;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.AUTHENTICATION_CONTEXT;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.AUTHENTICATION_CONTEXT_AND_APPLICATION;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.BEANVALIDATION_GROUPS;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.BOOTSTRAP_CONTEXT;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.CLASS_NAME;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.CONNECTABLE;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.ELYTRON_ENABLED;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.ENABLED;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.ENLISTMENT;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.ENLISTMENT_TRACE;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.INTERLEAVING;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.JNDINAME;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.MCP;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.NOTXSEPARATEPOOL;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.NO_RECOVERY;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.PAD_XID;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RECOVERLUGIN_CLASSNAME;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RECOVERLUGIN_PROPERTIES;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RECOVERY_AUTHENTICATION_CONTEXT;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RECOVERY_ELYTRON_ENABLED;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RECOVERY_PASSWORD;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RECOVERY_SECURITY_DOMAIN;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RECOVERY_USERNAME;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.SAME_RM_OVERRIDE;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.SECURITY_DOMAIN;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.SECURITY_DOMAIN_AND_APPLICATION;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.SHARABLE;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.TRACKING;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.TRANSACTION_SUPPORT;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.USE_CCM;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.USE_JAVA_CONTEXT;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_ELYTRON_ENABLED;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_DEFAULT_GROUPS;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_DEFAULT_PRINCIPAL;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_DOMAIN;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_MAPPING_FROM;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_MAPPING_GROUPS;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_MAPPING_REQUIRED;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_MAPPING_TO;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY_MAPPING_USERS;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WRAP_XA_RESOURCE;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.XA_RESOURCE_TIMEOUT;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jboss.as.connector.deployers.ra.processors.IronJacamarDeploymentParsingProcessor;
import org.jboss.as.connector.deployers.ra.processors.ParsedRaDeploymentProcessor;
import org.jboss.as.connector.deployers.ra.processors.RaDeploymentParsingProcessor;
import org.jboss.as.connector.deployers.ra.processors.RaNativeProcessor;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.metadata.api.common.Credential;
import org.jboss.as.connector.metadata.api.common.SecurityMetadata;
import org.jboss.as.connector.metadata.common.CredentialImpl;
import org.jboss.as.connector.metadata.common.SecurityImpl;
import org.jboss.as.connector.metadata.resourceadapter.WorkManagerSecurityImpl;
import org.jboss.as.connector.metadata.xmldescriptors.ConnectorXmlDescriptor;
import org.jboss.as.connector.metadata.xmldescriptors.IronJacamarXmlDescriptor;
import org.jboss.as.connector.services.resourceadapters.deployment.InactiveResourceAdapterDeploymentService;
import org.jboss.as.connector.services.resourceadapters.deployment.ResourceAdapterXmlDeploymentService;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.connector.util.CopyOnWriteArrayListMultiMap;
import org.jboss.as.connector.util.ModelNodeUtil;
import org.jboss.as.connector.util.RaServicesFactory;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.security.service.SecurityDomainService;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.annotation.ResourceRootIndexer;
import org.jboss.as.server.deployment.module.MountHandle;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.dmr.ModelNode;
import org.jboss.jandex.Index;
import org.jboss.jca.common.api.metadata.common.Capacity;
import org.jboss.jca.common.api.metadata.common.Extension;
import org.jboss.jca.common.api.metadata.common.FlushStrategy;
import org.jboss.jca.common.api.metadata.common.Pool;
import org.jboss.jca.common.api.metadata.common.Recovery;
import org.jboss.jca.common.api.metadata.common.Security;
import org.jboss.jca.common.api.metadata.common.TimeOut;
import org.jboss.jca.common.api.metadata.common.TransactionSupportEnum;
import org.jboss.jca.common.api.metadata.common.Validation;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.resourceadapter.AdminObject;
import org.jboss.jca.common.api.metadata.resourceadapter.ConnectionDefinition;
import org.jboss.jca.common.api.metadata.resourceadapter.WorkManager;
import org.jboss.jca.common.api.metadata.resourceadapter.WorkManagerSecurity;
import org.jboss.jca.common.api.validator.ValidateException;
import org.jboss.jca.common.metadata.common.PoolImpl;
import org.jboss.jca.common.metadata.common.TimeOutImpl;
import org.jboss.jca.common.metadata.common.ValidationImpl;
import org.jboss.jca.common.metadata.common.XaPoolImpl;
import org.jboss.jca.common.metadata.resourceadapter.WorkManagerImpl;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.msc.service.AbstractServiceListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.password.interfaces.ClearPassword;
public class RaOperationUtil {
public static final ServiceName RAR_MODULE = ServiceName.of("rarinsidemodule");
public static ModifiableResourceAdapter buildResourceAdaptersObject(final String id, final OperationContext context, ModelNode operation, String archiveOrModule) throws OperationFailedException {
Map<String, String> configProperties = new HashMap<>(0);
List<ConnectionDefinition> connectionDefinitions = new ArrayList<>(0);
List<AdminObject> adminObjects = new ArrayList<>(0);
TransactionSupportEnum transactionSupport = operation.hasDefined(TRANSACTION_SUPPORT.getName()) ? TransactionSupportEnum
.valueOf(operation.get(TRANSACTION_SUPPORT.getName()).asString()) : null;
String bootstrapContext = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, operation, BOOTSTRAP_CONTEXT);
List<String> beanValidationGroups = BEANVALIDATION_GROUPS.unwrap(context, operation);
boolean wmSecurity = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, operation, WM_SECURITY);
WorkManager workManager = null;
if (wmSecurity) {
final boolean mappingRequired = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, operation, WM_SECURITY_MAPPING_REQUIRED);
final String domain = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, operation, WM_SECURITY_DOMAIN);
final boolean elytronEnabled = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, operation, WM_ELYTRON_ENABLED);
final String defaultPrincipal = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, operation, WM_SECURITY_DEFAULT_PRINCIPAL);
final List<String> defaultGroups = WM_SECURITY_DEFAULT_GROUPS.unwrap(context, operation);
final Map<String, String> groups = ModelNodeUtil.extractMap(operation, WM_SECURITY_MAPPING_GROUPS, WM_SECURITY_MAPPING_FROM, WM_SECURITY_MAPPING_TO);
final Map<String, String> users = ModelNodeUtil.extractMap(operation, WM_SECURITY_MAPPING_USERS, WM_SECURITY_MAPPING_FROM, WM_SECURITY_MAPPING_TO);
workManager = new WorkManagerImpl(new WorkManagerSecurityImpl(mappingRequired, domain, elytronEnabled, defaultPrincipal, defaultGroups, users, groups));
}
ModifiableResourceAdapter ra;
ra = new ModifiableResourceAdapter(id, archiveOrModule, transactionSupport, connectionDefinitions,
adminObjects, configProperties, beanValidationGroups, bootstrapContext, workManager);
return ra;
}
public static ModifiableConnDef buildConnectionDefinitionObject(final OperationContext context, final ModelNode connDefModel, final String poolName,
final boolean isXa, ExceptionSupplier<CredentialSource, Exception> recoveryCredentialSourceSupplier) throws OperationFailedException, ValidateException {
Map<String, String> configProperties = new HashMap<String, String>(0);
String className = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, CLASS_NAME);
String jndiName = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, JNDINAME);
boolean enabled = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, ENABLED);
boolean connectable = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, CONNECTABLE);
Boolean tracking = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, TRACKING);
boolean useJavaContext = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, USE_JAVA_CONTEXT);
boolean useCcm = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, USE_CCM);
boolean sharable = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, SHARABLE);
boolean enlistment = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, ENLISTMENT);
final String mcp = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, MCP);
final Boolean enlistmentTrace = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, ENLISTMENT_TRACE);
int maxPoolSize = ModelNodeUtil.getIntIfSetOrGetDefault(context, connDefModel, MAX_POOL_SIZE);
int minPoolSize = ModelNodeUtil.getIntIfSetOrGetDefault(context, connDefModel, MIN_POOL_SIZE);
Integer initialPoolSize = ModelNodeUtil.getIntIfSetOrGetDefault(context, connDefModel, INITIAL_POOL_SIZE);
boolean prefill = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, POOL_PREFILL);
boolean fair = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, POOL_FAIR);
boolean useStrictMin = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, POOL_USE_STRICT_MIN);
String flushStrategyString = POOL_FLUSH_STRATEGY.resolveModelAttribute(context, connDefModel).asString();
final FlushStrategy flushStrategy = FlushStrategy.forName(flushStrategyString);
Boolean isSameRM = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, SAME_RM_OVERRIDE);
boolean interlivng = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, INTERLEAVING);
boolean padXid = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, PAD_XID);
boolean wrapXaResource = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, WRAP_XA_RESOURCE);
boolean noTxSeparatePool = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, NOTXSEPARATEPOOL);
Integer allocationRetry = ModelNodeUtil.getIntIfSetOrGetDefault(context, connDefModel, ALLOCATION_RETRY);
Long allocationRetryWaitMillis = ModelNodeUtil.getLongIfSetOrGetDefault(context, connDefModel, ALLOCATION_RETRY_WAIT_MILLIS);
Long blockingTimeoutMillis = ModelNodeUtil.getLongIfSetOrGetDefault(context, connDefModel, BLOCKING_TIMEOUT_WAIT_MILLIS);
Long idleTimeoutMinutes = ModelNodeUtil.getLongIfSetOrGetDefault(context, connDefModel, IDLETIMEOUTMINUTES);
Integer xaResourceTimeout = ModelNodeUtil.getIntIfSetOrGetDefault(context, connDefModel, XA_RESOURCE_TIMEOUT);
TimeOut timeOut = new TimeOutImpl(blockingTimeoutMillis, idleTimeoutMinutes, allocationRetry,
allocationRetryWaitMillis, xaResourceTimeout);
Extension incrementer = ModelNodeUtil.extractExtension(context, connDefModel, CAPACITY_INCREMENTER_CLASS, CAPACITY_INCREMENTER_PROPERTIES);
Extension decrementer = ModelNodeUtil.extractExtension(context, connDefModel, CAPACITY_DECREMENTER_CLASS, CAPACITY_DECREMENTER_PROPERTIES);
final Capacity capacity = new Capacity(incrementer, decrementer);
Pool pool;
if (isXa) {
pool = new XaPoolImpl(minPoolSize, initialPoolSize, maxPoolSize, prefill, useStrictMin, flushStrategy, capacity, fair, isSameRM, interlivng, padXid, wrapXaResource, noTxSeparatePool);
} else {
pool = new PoolImpl(minPoolSize, initialPoolSize, maxPoolSize, prefill, useStrictMin, flushStrategy, capacity, fair);
}
String securityDomain = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, SECURITY_DOMAIN);
String securityDomainAndApplication = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, SECURITY_DOMAIN_AND_APPLICATION);
boolean elytronEnabled = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, ELYTRON_ENABLED);
String authenticationContext = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, AUTHENTICATION_CONTEXT);
String authenticationContextAndApplication = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, AUTHENTICATION_CONTEXT_AND_APPLICATION);
boolean application = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, APPLICATION);
Security security = null;
if (securityDomain != null || securityDomainAndApplication != null || application) {
security = new SecurityImpl(elytronEnabled? authenticationContext: securityDomain,
elytronEnabled? authenticationContextAndApplication: securityDomainAndApplication, application,
elytronEnabled);
}
Long backgroundValidationMillis = ModelNodeUtil.getLongIfSetOrGetDefault(context, connDefModel, BACKGROUNDVALIDATIONMILLIS);
Boolean backgroundValidation = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, BACKGROUNDVALIDATION);
boolean useFastFail = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, USE_FAST_FAIL);
final Boolean validateOnMatch = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, VALIDATE_ON_MATCH );
Validation validation = new ValidationImpl(validateOnMatch, backgroundValidation, backgroundValidationMillis, useFastFail);
final String recoveryUsername = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, RECOVERY_USERNAME);
final String recoveryPassword;
try {
CredentialSource cs = null;
if (recoveryCredentialSourceSupplier != null) {
cs = recoveryCredentialSourceSupplier.get();
}
if (cs != null) {
recoveryPassword = new String(
cs.getCredential(PasswordCredential.class).getPassword(ClearPassword.class).getPassword());
} else {
recoveryPassword = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, RECOVERY_PASSWORD);
}
} catch (Exception e) {
throw new OperationFailedException(e);
}
final String recoverySecurityDomain = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, RECOVERY_SECURITY_DOMAIN);
final boolean recoveryElytronEnabled = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, RECOVERY_ELYTRON_ENABLED);
final String recoveryAuthenticationContext = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, connDefModel, RECOVERY_AUTHENTICATION_CONTEXT);
Boolean noRecovery = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, connDefModel, NO_RECOVERY);
Recovery recovery = null;
if ((recoveryUsername != null && recoveryPassword != null) || recoverySecurityDomain != null || noRecovery != null) {
Credential credential = null;
if ((recoveryUsername != null && recoveryPassword != null) || recoverySecurityDomain != null)
credential = new CredentialImpl(recoveryUsername, recoveryPassword,
recoveryElytronEnabled ? recoveryAuthenticationContext : recoverySecurityDomain, recoveryElytronEnabled);
Extension recoverPlugin = ModelNodeUtil.extractExtension(context, connDefModel, RECOVERLUGIN_CLASSNAME, RECOVERLUGIN_PROPERTIES);
if (noRecovery == null)
noRecovery = Boolean.FALSE;
recovery = new Recovery(credential, recoverPlugin, noRecovery);
}
ModifiableConnDef connectionDefinition = new ModifiableConnDef(configProperties, className, jndiName, poolName,
enabled, useJavaContext, useCcm, pool, timeOut, validation, security, recovery, sharable, enlistment, connectable, tracking, mcp, enlistmentTrace);
return connectionDefinition;
}
public static ModifiableAdminObject buildAdminObjects(final OperationContext context, ModelNode operation, final String poolName) throws OperationFailedException, ValidateException {
Map<String, String> configProperties = new HashMap<String, String>(0);
String className = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, operation, CLASS_NAME);
String jndiName = ModelNodeUtil.getResolvedStringIfSetOrGetDefault(context, operation, JNDINAME);
boolean enabled = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, operation, ENABLED);
boolean useJavaContext = ModelNodeUtil.getBooleanIfSetOrGetDefault(context, operation, USE_JAVA_CONTEXT);
ModifiableAdminObject adminObject = new ModifiableAdminObject(configProperties, className, jndiName, poolName,
enabled, useJavaContext);
return adminObject;
}
public static ServiceName restartIfPresent(OperationContext context, final String raName, final String id) throws OperationFailedException {
final ServiceName raDeploymentServiceName = ConnectorServices.getDeploymentServiceName(raName, id);
final ServiceRegistry registry = context.getServiceRegistry(true);
ServiceController raServiceController = registry.getService(raDeploymentServiceName);
if (raServiceController != null) {
final org.jboss.msc.service.ServiceController.Mode originalMode = raServiceController.getMode();
raServiceController.addListener(new AbstractServiceListener() {
@Override
public void transition(ServiceController controller, ServiceController.Transition transition) {
switch (transition) {
case STOPPING_to_DOWN:
try {
final ServiceController<?> RaxmlController = registry.getService(ServiceName.of(ConnectorServices.RA_SERVICE, id));
Activation raxml = (Activation) RaxmlController.getValue();
((ResourceAdapterXmlDeploymentService) controller.getService()).setRaxml(raxml);
controller.compareAndSetMode(ServiceController.Mode.NEVER, originalMode);
} finally {
controller.removeListener(this);
}
}
}
@Override
public void listenerAdded(ServiceController controller) {
controller.setMode(ServiceController.Mode.NEVER);
}
});
return raDeploymentServiceName;
} else {
return null;
}
}
public static boolean removeIfActive(OperationContext context, String raName, String id ) throws OperationFailedException {
boolean wasActive = false;
final ServiceName raDeploymentServiceName;
if (raName == null) {
raDeploymentServiceName = ConnectorServices.getDeploymentServiceName(id);
} else {
raDeploymentServiceName = ConnectorServices.getDeploymentServiceName(raName, id);
}
if(context.getServiceRegistry(true).getService(raDeploymentServiceName) != null){
context.removeService(raDeploymentServiceName);
wasActive = true;
}
return wasActive;
}
public static void activate(OperationContext context, String raName, String archiveName) throws OperationFailedException {
ServiceRegistry registry = context.getServiceRegistry(true);
ServiceController<?> inactiveRaController = registry.getService(ConnectorServices.INACTIVE_RESOURCE_ADAPTER_SERVICE.append(archiveName));
if (inactiveRaController == null) {
inactiveRaController = registry.getService(ConnectorServices.INACTIVE_RESOURCE_ADAPTER_SERVICE.append(raName));
if (inactiveRaController == null) {
throw ConnectorLogger.ROOT_LOGGER.RARNotYetDeployed(raName);
}
}
InactiveResourceAdapterDeploymentService.InactiveResourceAdapterDeployment inactive = (InactiveResourceAdapterDeploymentService.InactiveResourceAdapterDeployment) inactiveRaController.getValue();
final ServiceController<?> RaxmlController = registry.getService(ServiceName.of(ConnectorServices.RA_SERVICE, raName));
Activation raxml = (Activation) RaxmlController.getValue();
RaServicesFactory.createDeploymentService(inactive.getRegistration(), inactive.getConnectorXmlDescriptor(), inactive.getModule(), inactive.getServiceTarget(),
archiveName, inactive.getDeploymentUnitServiceName(), inactive.getDeployment(), raxml, inactive.getResource(), registry);
}
public static ServiceName installRaServices(OperationContext context, String name, ModifiableResourceAdapter resourceAdapter, final List<ServiceController<?>> newControllers) {
final ServiceTarget serviceTarget = context.getServiceTarget();
final ServiceController<?> resourceAdaptersService = context.getServiceRegistry(false).getService(
ConnectorServices.RESOURCEADAPTERS_SERVICE);
if (resourceAdaptersService == null) {
newControllers.add(serviceTarget.addService(ConnectorServices.RESOURCEADAPTERS_SERVICE,
new ResourceAdaptersService()).setInitialMode(ServiceController.Mode.ACTIVE).install());
}
ServiceName raServiceName = ServiceName.of(ConnectorServices.RA_SERVICE, name);
final ServiceController<?> service = context.getServiceRegistry(true).getService(raServiceName);
if (service == null) {
ResourceAdapterService raService = new ResourceAdapterService(resourceAdapter, name);
ServiceBuilder builder = serviceTarget.addService(raServiceName, raService).setInitialMode(ServiceController.Mode.ACTIVE)
.addDependency(ConnectorServices.RESOURCEADAPTERS_SERVICE, ResourceAdaptersService.ModifiableResourceAdaptors.class, raService.getResourceAdaptersInjector())
.addDependency(ConnectorServices.RESOURCEADAPTERS_SUBSYSTEM_SERVICE, CopyOnWriteArrayListMultiMap.class, raService.getResourceAdaptersMapInjector());
// add dependency on security domain service if applicable for recovery config
for (ConnectionDefinition cd : resourceAdapter.getConnectionDefinitions()) {
Security security = cd.getSecurity();
if (security != null) {
final boolean elytronEnabled = (security instanceof SecurityMetadata && ((SecurityMetadata) security).isElytronEnabled());
if (!elytronEnabled && security.getSecurityDomain() != null) {
builder.addDependency(SecurityDomainService.SERVICE_NAME.append(security.getSecurityDomain()));
}
if (!elytronEnabled && security.getSecurityDomainAndApplication() != null) {
builder.addDependency(SecurityDomainService.SERVICE_NAME.append(security.getSecurityDomainAndApplication()));
}
if (!elytronEnabled && cd.getRecovery() != null && cd.getRecovery().getCredential() != null && cd.getRecovery().getCredential().getSecurityDomain() != null) {
builder.addDependency(SecurityDomainService.SERVICE_NAME.append(cd.getRecovery().getCredential().getSecurityDomain()));
}
}
}
if (resourceAdapter.getWorkManager() != null) {
final WorkManagerSecurity workManagerSecurity = resourceAdapter.getWorkManager().getSecurity();
if (workManagerSecurity != null) {
final boolean elytronEnabled = (workManagerSecurity instanceof org.jboss.as.connector.metadata.api.resourceadapter.WorkManagerSecurity)
&& ((org.jboss.as.connector.metadata.api.resourceadapter.WorkManagerSecurity) workManagerSecurity).isElytronEnabled();
final String securityDomainName = workManagerSecurity.getDomain();
if (!elytronEnabled && securityDomainName != null) {
builder.addDependency(SecurityDomainService.SERVICE_NAME.append(securityDomainName));
}
}
}
newControllers.add(builder.install());
}
return raServiceName;
}
public static void installRaServicesAndDeployFromModule(OperationContext context, String name, ModifiableResourceAdapter resourceAdapter, String fullModuleName, final List<ServiceController<?>> newControllers) throws OperationFailedException{
ServiceName raServiceName = installRaServices(context, name, resourceAdapter, newControllers);
final boolean resolveProperties = true;
final ServiceTarget serviceTarget = context.getServiceTarget();
final String moduleName;
//load module
String slot = "main";
if (fullModuleName.contains(":")) {
slot = fullModuleName.substring(fullModuleName.indexOf(":") + 1);
moduleName = fullModuleName.substring(0, fullModuleName.indexOf(":"));
} else {
moduleName = fullModuleName;
}
Module module;
try {
ModuleIdentifier moduleId = ModuleIdentifier.create(moduleName, slot);
module = Module.getCallerModuleLoader().loadModule(moduleId);
} catch (ModuleLoadException e) {
throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.failedToLoadModuleRA(moduleName), e);
}
URL path = module.getExportedResource("META-INF/ra.xml");
Closeable closable = null;
try {
VirtualFile child;
if (path.getPath().contains("!")) {
throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.compressedRarNotSupportedInModuleRA(moduleName));
} else {
child = VFS.getChild(path.getPath().split("META-INF")[0]);
closable = VFS.mountReal(new File(path.getPath().split("META-INF")[0]), child);
}
//final Closeable closable = VFS.mountZip((InputStream) new JarInputStream(new FileInputStream(path.getPath().split("!")[0].split(":")[1])), path.getPath().split("!")[0].split(":")[1], child, TempFileProviderService.provider());
final MountHandle mountHandle = new MountHandle(closable);
final ResourceRoot resourceRoot = new ResourceRoot(child, mountHandle);
final VirtualFile deploymentRoot = resourceRoot.getRoot();
if (deploymentRoot == null || !deploymentRoot.exists())
return;
ConnectorXmlDescriptor connectorXmlDescriptor = RaDeploymentParsingProcessor.process(resolveProperties, deploymentRoot, null, name);
IronJacamarXmlDescriptor ironJacamarXmlDescriptor = IronJacamarDeploymentParsingProcessor.process(deploymentRoot, resolveProperties);
RaNativeProcessor.process(deploymentRoot);
Map<ResourceRoot, Index> annotationIndexes = new HashMap<ResourceRoot, Index>();
ResourceRootIndexer.indexResourceRoot(resourceRoot);
Index index = resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX);
if (index != null) {
annotationIndexes.put(resourceRoot, index);
}
if (ironJacamarXmlDescriptor != null) {
ConnectorLogger.SUBSYSTEM_RA_LOGGER.forceIJToNull();
ironJacamarXmlDescriptor = null;
}
final ServiceName deployerServiceName = ConnectorServices.RESOURCE_ADAPTER_DEPLOYER_SERVICE_PREFIX.append(connectorXmlDescriptor.getDeploymentName());
final ServiceController<?> deployerService = context.getServiceRegistry(true).getService(deployerServiceName);
if (deployerService == null) {
ServiceBuilder builder = ParsedRaDeploymentProcessor.process(connectorXmlDescriptor, ironJacamarXmlDescriptor, module.getClassLoader(), serviceTarget, annotationIndexes, RAR_MODULE.append(name), null, null);
newControllers.add(builder.addDependency(raServiceName).setInitialMode(ServiceController.Mode.ACTIVE).install());
}
String rarName = resourceAdapter.getArchive();
if (fullModuleName.equals(rarName)) {
ServiceName serviceName = ConnectorServices.INACTIVE_RESOURCE_ADAPTER_SERVICE.append(name);
InactiveResourceAdapterDeploymentService service = new InactiveResourceAdapterDeploymentService(connectorXmlDescriptor, module, name, name, RAR_MODULE.append(name), null, serviceTarget, null);
newControllers.add(serviceTarget
.addService(serviceName, service)
.setInitialMode(ServiceController.Mode.ACTIVE).install());
}
} catch (Exception e) {
throw new OperationFailedException(ConnectorLogger.ROOT_LOGGER.failedToLoadModuleRA(moduleName), e);
} finally {
if (closable != null) {
try {
closable.close();
} catch (IOException e) {
}
}
}
}
}
|
package com.streamsets.pipeline.runner.production;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.EvictingQueue;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.impl.ErrorMessage;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.config.DeliveryGuarantee;
import com.streamsets.pipeline.config.MemoryLimitConfiguration;
import com.streamsets.pipeline.config.MemoryLimitExceeded;
import com.streamsets.pipeline.config.StageType;
import com.streamsets.pipeline.main.RuntimeInfo;
import com.streamsets.pipeline.metrics.MetricsConfigurator;
import com.streamsets.pipeline.prodmanager.Constants;
import com.streamsets.pipeline.record.HeaderImpl;
import com.streamsets.pipeline.record.RecordImpl;
import com.streamsets.pipeline.runner.BatchListener;
import com.streamsets.pipeline.runner.ErrorSink;
import com.streamsets.pipeline.runner.FullPipeBatch;
import com.streamsets.pipeline.runner.Observer;
import com.streamsets.pipeline.runner.Pipe;
import com.streamsets.pipeline.runner.PipeBatch;
import com.streamsets.pipeline.runner.PipelineRunner;
import com.streamsets.pipeline.runner.PipelineRuntimeException;
import com.streamsets.pipeline.runner.SourceOffsetTracker;
import com.streamsets.pipeline.runner.StageContext;
import com.streamsets.pipeline.runner.StageOutput;
import com.streamsets.pipeline.snapshotstore.SnapshotStatus;
import com.streamsets.pipeline.snapshotstore.SnapshotStore;
import com.streamsets.pipeline.snapshotstore.impl.FileSnapshotStore;
import com.streamsets.pipeline.util.ContainerError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
public class ProductionPipelineRunner implements PipelineRunner {
private static final Logger LOG = LoggerFactory.getLogger(ProductionPipelineRunner.class);
private final RuntimeInfo runtimeInfo;
private final com.streamsets.pipeline.util.Configuration configuration;
private final MetricRegistry metrics;
private SourceOffsetTracker offsetTracker;
private final SnapshotStore snapshotStore;
private String sourceOffset;
private String newSourceOffset;
private DeliveryGuarantee deliveryGuarantee;
private final String pipelineName;
private final String revision;
private final Timer batchProcessingTimer;
private final Meter batchCountMeter;
private final Histogram batchInputRecordsHistogram;
private final Histogram batchOutputRecordsHistogram;
private final Histogram batchErrorRecordsHistogram;
private final Histogram batchErrorsHistogram;
private final Meter batchInputRecordsMeter;
private final Meter batchOutputRecordsMeter;
private final Meter batchErrorRecordsMeter;
private final Meter batchErrorMessagesMeter;
private final Counter memoryConsumedCounter;
/*indicates if the execution must be stopped after the current batch*/
private volatile boolean stop = false;
/*indicates if the next batch of data should be captured, only the next batch*/
private volatile boolean captureNextBatch = false;
/*indicates the snapshot name to be captured*/
private volatile String snapshotName;
/*indicates the batch size to be captured*/
private volatile int snapshotBatchSize;
/*Cache last N error records per stage in memory*/
private Map<String, EvictingQueue<Record>> stageToErrorRecordsMap;
/*Cache last N error messages in memory*/
private Map<String, EvictingQueue<ErrorMessage>> stageToErrorMessagesMap;
private BlockingQueue<Object> observeRequests;
private Observer observer;
private List<BatchListener> batchListenerList = new CopyOnWriteArrayList<BatchListener>();
private Object errorRecordsMutex;
private final MemoryLimitConfiguration memoryLimitConfiguration;
private long lastMemoryLimitNotification;
private ThreadHealthReporter threadHealthReporter;
public ProductionPipelineRunner(RuntimeInfo runtimeInfo, SnapshotStore snapshotStore,
DeliveryGuarantee deliveryGuarantee, String pipelineName, String revision,
BlockingQueue<Object> observeRequests,
com.streamsets.pipeline.util.Configuration configuration,
MemoryLimitConfiguration memoryLimitConfiguration) {
/*//retrieve pipeline properties from the pipeline configuration
int maxBatchSize = configuration.get(Configuration.MAX_BATCH_SIZE_KEY, Configuration.MAX_BATCH_SIZE_DEFAULT);
int maxErrorRecordsPerStage = configuration.get(Configuration.MAX_ERROR_RECORDS_PER_STAGE_KEY,
Configuration.MAX_ERROR_RECORDS_PER_STAGE_DEFAULT);
int maxPipelineErrors = configuration.get(Configuration.MAX_PIPELINE_ERRORS_KEY,
Configuration.MAX_PIPELINE_ERRORS_DEFAULT);*/
this.runtimeInfo = runtimeInfo;
this.configuration = configuration;
this.metrics = new MetricRegistry();
this.observeRequests = observeRequests;
this.memoryLimitConfiguration = memoryLimitConfiguration;
batchProcessingTimer = MetricsConfigurator.createTimer(metrics, "pipeline.batchProcessing");
batchCountMeter = MetricsConfigurator.createMeter(metrics, "pipeline.batchCount");
batchInputRecordsHistogram = MetricsConfigurator.createHistogram5Min(metrics, "pipeline.inputRecordsPerBatch");
batchOutputRecordsHistogram = MetricsConfigurator.createHistogram5Min(metrics, "pipeline.outputRecordsPerBatch");
batchErrorRecordsHistogram = MetricsConfigurator.createHistogram5Min(metrics, "pipeline.errorRecordsPerBatch");
batchErrorsHistogram = MetricsConfigurator.createHistogram5Min(metrics, "pipeline.errorsPerBatch");
batchInputRecordsMeter = MetricsConfigurator.createMeter(metrics, "pipeline.batchInputRecords");
batchOutputRecordsMeter = MetricsConfigurator.createMeter(metrics, "pipeline.batchOutputRecords");
batchErrorRecordsMeter = MetricsConfigurator.createMeter(metrics, "pipeline.batchErrorRecords");
batchErrorMessagesMeter = MetricsConfigurator.createMeter(metrics, "pipeline.batchErrorMessages");
memoryConsumedCounter = MetricsConfigurator.createCounter(metrics, "pipeline.memoryConsumed");
this.deliveryGuarantee = deliveryGuarantee;
this.snapshotStore = snapshotStore;
this.pipelineName = pipelineName;
this.revision = revision;
this.stageToErrorRecordsMap = new HashMap<>();
this.stageToErrorMessagesMap = new HashMap<>();
errorRecordsMutex = new Object();
}
@Override
public boolean isPreview() {
return false;
}
@Override
public MetricRegistry getMetrics() {
return metrics;
}
public void setOffsetTracker(SourceOffsetTracker offsetTracker) {
this.offsetTracker = offsetTracker;
}
public void setThreadHealthReporter(ThreadHealthReporter threadHealthReporter) {
this.threadHealthReporter = threadHealthReporter;
}
@Override
public void run(Pipe[] pipes, BadRecordsHandler badRecordsHandler) throws StageException, PipelineRuntimeException {
while(!offsetTracker.isFinished() && !stop) {
if(threadHealthReporter != null) {
threadHealthReporter.reportHealth(ProductionPipelineRunnable.RUNNABLE_NAME, -1, System.currentTimeMillis());
}
try {
for (BatchListener batchListener: batchListenerList) {
batchListener.preBatch();
}
runBatch(pipes, badRecordsHandler);
for (BatchListener batchListener : batchListenerList) {
batchListener.postBatch();
}
} catch (Throwable throwable) {
sendPipelineErrorNotificationRequest(throwable);
Throwables.propagateIfInstanceOf(throwable, StageException.class);
Throwables.propagateIfInstanceOf(throwable, PipelineRuntimeException.class);
Throwables.propagate(throwable);
}
}
}
@Override
public void run(Pipe[] pipes, BadRecordsHandler badRecordsHandler, List<StageOutput> stageOutputsToOverride)
throws StageException, PipelineRuntimeException {
throw new UnsupportedOperationException();
}
@Override
public List<List<StageOutput>> getBatchesOutput() {
List<List<StageOutput>> batchOutput = new ArrayList<>();
SnapshotStatus snapshotStatus = snapshotStore.getSnapshotStatus(pipelineName, revision, snapshotName);
if(snapshotStatus != null && snapshotStatus.isExists()) {
batchOutput.add(snapshotStore.retrieveSnapshot(pipelineName, revision, snapshotName));
}
return batchOutput;
}
@Override
public String getSourceOffset() {
return sourceOffset;
}
@Override
public String getNewSourceOffset() {
return newSourceOffset;
}
@Override
public void setObserver(Observer observer) {
this.observer = observer;
}
public String getCommittedOffset() {
return offsetTracker.getOffset();
}
/**
* Stops execution of the pipeline after the current batch completes
*/
public void stop() {
this.stop = true;
}
public boolean wasStopped() {
return stop;
}
public void captureNextBatch(String snapshotName, int batchSize) {
Preconditions.checkArgument(batchSize > 0);
this.snapshotName = snapshotName;
this.snapshotBatchSize = batchSize;
((FileSnapshotStore)snapshotStore).setInProgress(pipelineName, revision, snapshotName, true);
this.captureNextBatch = true;
}
private void runBatch(Pipe[] pipes, BadRecordsHandler badRecordsHandler) throws PipelineRuntimeException, StageException {
boolean committed = false;
/*value true indicates that this batch is captured */
boolean batchCaptured = false;
PipeBatch pipeBatch;
//pick up any recent changes done to the rule definitions
if(observer != null) {
observer.reconfigure();
}
if(captureNextBatch) {
batchCaptured = true;
pipeBatch = new FullPipeBatch(offsetTracker, snapshotBatchSize, true /*snapshot stage output*/);
} else {
pipeBatch = new FullPipeBatch(offsetTracker,
configuration.get(Constants.MAX_BATCH_SIZE_KEY, Constants.MAX_BATCH_SIZE_DEFAULT),
false /*snapshot stage output*/);
}
long start = System.currentTimeMillis();
sourceOffset = pipeBatch.getPreviousOffset();
long lastBatchTime = offsetTracker.getLastBatchTime();
Map<String, Long> memoryConsumedByStage = new HashMap<>();
for (Pipe pipe : pipes) {
//set the last batch time in the stage context of each pipe
((StageContext)pipe.getStage().getContext()).setLastBatchTime(lastBatchTime);
//TODO Define an interface to handle delivery guarantee
if (deliveryGuarantee == DeliveryGuarantee.AT_MOST_ONCE
&& pipe.getStage().getDefinition().getType() == StageType.TARGET && !committed) {
offsetTracker.commitOffset();
committed = true;
}
pipe.process(pipeBatch);
long memory = pipe.getMemoryConsumed();
memoryConsumedByStage.put(pipe.getStage().getInfo().getInstanceName(), memory);
}
enforceMemoryLimit(memoryConsumedByStage);
badRecordsHandler.handle(newSourceOffset, getBadRecords(pipeBatch.getErrorSink()));
if (deliveryGuarantee == DeliveryGuarantee.AT_LEAST_ONCE) {
offsetTracker.commitOffset();
}
batchProcessingTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
batchCountMeter.mark();
batchInputRecordsHistogram.update(pipeBatch.getInputRecords());
batchOutputRecordsHistogram.update(pipeBatch.getOutputRecords());
batchErrorRecordsHistogram.update(pipeBatch.getErrorRecords());
batchErrorsHistogram.update(pipeBatch.getErrorMessages());
batchInputRecordsMeter.mark(pipeBatch.getInputRecords());
batchOutputRecordsMeter.mark(pipeBatch.getOutputRecords());
batchErrorRecordsMeter.mark(pipeBatch.getErrorRecords());
batchErrorMessagesMeter.mark(pipeBatch.getErrorMessages());
newSourceOffset = offsetTracker.getOffset();
if(batchCaptured) {
List<StageOutput> snapshot = pipeBatch.getSnapshotsOfAllStagesOutput();
snapshotStore.storeSnapshot(pipelineName, revision, snapshotName, snapshot);
/*
* Reset the capture snapshot variable only after capturing the snapshot
* This guarantees that once captureSnapshot is called, the output is captured exactly once
* */
captureNextBatch = false;
snapshotBatchSize = 0;
}
//Retain X number of error records per stage
Map<String, List<Record>> errorRecords = pipeBatch.getErrorSink().getErrorRecords();
Map<String, List<ErrorMessage>> errorMessages = pipeBatch.getErrorSink().getStageErrors();
retainErrorsInMemory(errorRecords, errorMessages);
}
private RecordImpl getSourceRecord(Record record) {
return (RecordImpl) ((RecordImpl)record).getHeader().getSourceRecord();
}
private void injectErrorInfo(RecordImpl sourceRecord, Record record) {
HeaderImpl header = sourceRecord.getHeader();
header.copyErrorFrom(record);
header.setErrorContext(runtimeInfo.getId(), pipelineName);
}
private void enforceMemoryLimit(Map<String, Long> memoryConsumedByStage) throws PipelineRuntimeException {
long totalMemoryConsumed = 0;
for(Map.Entry<String, Long> entry : memoryConsumedByStage.entrySet()) {
totalMemoryConsumed += entry.getValue();
}
memoryConsumedCounter.inc(totalMemoryConsumed - memoryConsumedCounter.getCount());
long memoryLimit = memoryLimitConfiguration.getMemoryLimit() * 1000 * 1000;
if (memoryLimit > 0 && totalMemoryConsumed > memoryLimit) {
String largestConsumer = "unknown";
long largestConsumed = 0;
Map<String, String> humanReadbleMemoryConsumptionByStage = new HashMap<>();
for(Map.Entry<String, Long> entry : memoryConsumedByStage.entrySet()) {
if (entry.getValue() > largestConsumed) {
largestConsumed = entry.getValue();
largestConsumer = entry.getKey();
}
humanReadbleMemoryConsumptionByStage.put(entry.getKey(), Utils.humanReadableInt(entry.getValue()));
}
humanReadbleMemoryConsumptionByStage.remove(largestConsumer);
PipelineRuntimeException ex = new PipelineRuntimeException(ContainerError.CONTAINER_0011,
Utils.humanReadableInt(totalMemoryConsumed), Utils.humanReadableInt(memoryLimit),
largestConsumer, Utils.humanReadableInt(largestConsumed), humanReadbleMemoryConsumptionByStage);
String msg = "Pipeline memory limit exceeded: " + ex;
long elapsedTimeSinceLastTriggerMins = TimeUnit.MILLISECONDS.
toMinutes(System.currentTimeMillis() - lastMemoryLimitNotification);
lastMemoryLimitNotification = System.currentTimeMillis();
if (elapsedTimeSinceLastTriggerMins < 60 ) {
if (LOG.isDebugEnabled()) {
LOG.debug("Memory limit has been triggered, will take {} in {} mins",
memoryLimitConfiguration.getMemoryLimitExceeded(), (60 - elapsedTimeSinceLastTriggerMins));
}
} else if (memoryLimitConfiguration.getMemoryLimitExceeded() == MemoryLimitExceeded.LOG) {
LOG.error(msg, ex);
} else if (memoryLimitConfiguration.getMemoryLimitExceeded() == MemoryLimitExceeded.ALERT) {
LOG.error(msg, ex);
sendPipelineErrorNotificationRequest(ex);
} else if (memoryLimitConfiguration.getMemoryLimitExceeded() == MemoryLimitExceeded.STOP_PIPELINE) {
throw ex;
}
}
}
private void sendPipelineErrorNotificationRequest(Throwable throwable) {
boolean offered = false;
try {
observeRequests.put(new PipelineErrorNotificationRequest(throwable));
offered = true;
} catch (InterruptedException e) {
}
if(!offered) {
LOG.error("Could not submit alert request for pipeline ending error: " + throwable, throwable);
}
}
private List<Record> getBadRecords(ErrorSink errorSink) throws PipelineRuntimeException {
List<Record> badRecords = new ArrayList<>();
for (Map.Entry<String, List<Record>> entry : errorSink.getErrorRecords().entrySet()) {
for (Record record : entry.getValue()) {
RecordImpl sourceRecord = getSourceRecord(record);
injectErrorInfo(sourceRecord, record);
badRecords.add(sourceRecord);
}
}
return badRecords;
}
public SourceOffsetTracker getOffSetTracker() {
return this.offsetTracker;
}
private void retainErrorsInMemory(Map<String, List<Record>> errorRecords, Map<String,
List<ErrorMessage>> errorMessages) {
synchronized (errorRecordsMutex) {
for (Map.Entry<String, List<Record>> e : errorRecords.entrySet()) {
EvictingQueue<Record> errorRecordList = stageToErrorRecordsMap.get(e.getKey());
if (errorRecordList == null) {
//replace with a data structure with an upper cap
errorRecordList = EvictingQueue.create(configuration.get(Constants.MAX_ERROR_RECORDS_PER_STAGE_KEY,
Constants.MAX_ERROR_RECORDS_PER_STAGE_DEFAULT));
stageToErrorRecordsMap.put(e.getKey(), errorRecordList);
}
errorRecordList.addAll(errorRecords.get(e.getKey()));
}
for (Map.Entry<String, List<ErrorMessage>> e : errorMessages.entrySet()) {
EvictingQueue<ErrorMessage> errorMessageList = stageToErrorMessagesMap.get(e.getKey());
if (errorMessageList == null) {
//replace with a data structure with an upper cap
errorMessageList = EvictingQueue.create(configuration.get(Constants.MAX_PIPELINE_ERRORS_KEY,
Constants.MAX_PIPELINE_ERRORS_DEFAULT));
stageToErrorMessagesMap.put(e.getKey(), errorMessageList);
}
errorMessageList.addAll(errorMessages.get(e.getKey()));
}
}
}
@SuppressWarnings("unchecked")
public List<Record> getErrorRecords(String instanceName, int size) {
synchronized (errorRecordsMutex) {
if (stageToErrorRecordsMap == null || stageToErrorRecordsMap.isEmpty()
|| stageToErrorRecordsMap.get(instanceName) == null || stageToErrorRecordsMap.get(instanceName).isEmpty()) {
return Collections.emptyList();
}
}
if(stageToErrorRecordsMap.get(instanceName).size() > size) {
return new CopyOnWriteArrayList<>(stageToErrorRecordsMap.get(instanceName)).subList(0, size);
} else {
return new CopyOnWriteArrayList<>(stageToErrorRecordsMap.get(instanceName));
}
}
public List<ErrorMessage> getErrorMessages(String instanceName, int size) {
synchronized (errorRecordsMutex) {
if (stageToErrorMessagesMap == null || stageToErrorMessagesMap.isEmpty()
|| stageToErrorMessagesMap.get(instanceName) == null
|| stageToErrorMessagesMap.get(instanceName).isEmpty()) {
return Collections.emptyList();
}
}
if(stageToErrorMessagesMap.get(instanceName).size() > size) {
return new CopyOnWriteArrayList<>(stageToErrorMessagesMap.get(instanceName)).subList(0, size);
} else {
return new CopyOnWriteArrayList<>(stageToErrorMessagesMap.get(instanceName));
}
}
@Override
public void registerListener(BatchListener batchListener) {
batchListenerList.add(batchListener);
}
}
|
package org.talend.dataprep.dataset.service.analysis;
import java.io.StringWriter;
import java.util.Iterator;
import javax.jms.JMSException;
import javax.jms.Message;
import org.apache.spark.SparkContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import org.talend.dataprep.DistributedLock;
import org.talend.dataprep.api.dataset.ColumnMetadata;
import org.talend.dataprep.api.dataset.DataSetMetadata;
import org.talend.dataprep.api.dataset.json.DataSetMetadataModule;
import org.talend.dataprep.api.type.Type;
import org.talend.dataprep.dataset.exception.DataSetErrorCodes;
import org.talend.dataprep.dataset.service.Destinations;
import org.talend.dataprep.dataset.store.DataSetContentStore;
import org.talend.dataprep.dataset.store.DataSetMetadataRepository;
import org.talend.dataprep.exception.TDPException;
import org.talend.datascience.statistics.StatisticsClientJson;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ArrayNode;
@Component
public class SchemaAnalysis {
private static final Logger LOGGER = LoggerFactory.getLogger(SchemaAnalysis.class);
@Autowired
DataSetMetadataRepository repository;
@Autowired
DataSetContentStore store;
@Autowired
JmsTemplate jmsTemplate;
@Autowired
ApplicationContext applicationContext;
@Autowired
SparkContext sparkContext;
@JmsListener(destination = Destinations.SCHEMA_ANALYSIS)
public void analyzeSchema(Message message) {
try {
String dataSetId = message.getStringProperty("dataset.id"); //$NON-NLS-1$
DistributedLock datasetLock = repository.createDatasetMetadataLock(dataSetId);
DataSetMetadata metadata = repository.get(dataSetId);
try {
datasetLock.lock();
StatisticsClientJson statisticsClient = new StatisticsClientJson(true, sparkContext);
statisticsClient.setJsonRecordPath("records"); //$NON-NLS-1$
if (metadata != null) {
LOGGER.info("Analyzing schema in dataset #{}...", dataSetId);
// Create a content with the expected format for the StatisticsClientJson class
final SimpleModule module = DataSetMetadataModule.get(true, true, store.get(metadata), applicationContext);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
final StringWriter content = new StringWriter();
mapper.writer().writeValue(content, metadata);
// Determine schema for the content
String elasticDataSchema = statisticsClient.inferSchemaInMemory(content.toString());
LOGGER.debug("Analysis result: {}", elasticDataSchema);
// Set column types back in data set metadata
// Get record count at the same type as returned information contains occurrence count.
int recordCount = 0;
final Iterator<JsonNode> columns = mapper.readTree(elasticDataSchema).get("column").elements(); //$NON-NLS-1$
final Iterator<ColumnMetadata> schemaColumns = metadata.getRow().getColumns().iterator();
for (; columns.hasNext() && schemaColumns.hasNext(); ) {
final JsonNode column = columns.next();
final ColumnMetadata schemaColumn = schemaColumns.next();
// Get best type for column
final String typeName = column.get("suggested type").asText(); //$NON-NLS-1$
if (Type.has(typeName)) {
// Go through Type to ensure normalized type names.
schemaColumn.setType(Type.get(typeName).getName());
} else {
LOGGER.error("Type '{}' does not exist.", typeName);
}
// Compute record count
final ArrayNode types = (ArrayNode) column.get("types"); //$NON-NLS-1$
int columnOccurrenceCount = 0;
for (JsonNode type : types) {
columnOccurrenceCount += type.get("occurrences").asInt(); //$NON-NLS-1$
}
recordCount = Math.max(recordCount, columnOccurrenceCount);
metadata.getContent().setNbRecords(recordCount);
}
if (columns.hasNext() || schemaColumns.hasNext()) {
// Awkward situation: analysis code and parsed content information did not find same number of columns
LOGGER.warn(
"Column type analysis and parsed columns for #{} do not yield same number of columns (content parsed: {} / analysis: {}).",
dataSetId, schemaColumns.hasNext(), columns.hasNext());
}
LOGGER.info("Analyzed schema in dataset #{}.", dataSetId);
metadata.getLifecycle().schemaAnalyzed(true);
repository.add(metadata);
// Asks for a in depth schema analysis (for column type information).
jmsTemplate.send(Destinations.QUALITY_ANALYSIS, session -> {
Message schemaAnalysisMessage = session.createMessage();
schemaAnalysisMessage.setStringProperty("dataset.id", dataSetId); //$NON-NLS-1
return schemaAnalysisMessage;
});
} else {
LOGGER.info("Unable to analyze quality of data set #{}: seems to be removed.", dataSetId);
}
} catch(Exception e) {
if (metadata != null) {
metadata.getLifecycle().error(true);
repository.add(metadata);
}
throw new TDPException(DataSetErrorCodes.UNABLE_TO_ANALYZE_COLUMN_TYPES, e);
} finally {
datasetLock.unlock();
message.acknowledge();
}
} catch (JMSException e) {
throw new TDPException(DataSetErrorCodes.UNEXPECTED_JMS_EXCEPTION, e);
}
}
}
|
package org.voltdb.task;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.voltdb.AuthSystem;
import org.voltdb.AuthSystem.AuthUser;
import org.voltdb.ClientInterface;
import org.voltdb.ElasticHashinator;
import org.voltdb.InternalConnectionHandler;
import org.voltdb.StatsAgent;
import org.voltdb.StatsSelector;
import org.voltdb.TheHashinator;
import org.voltdb.VoltTable;
import org.voltdb.VoltTableRow;
import org.voltdb.VoltType;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.Task;
import org.voltdb.catalog.TaskParameter;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.compiler.VoltCompiler;
import org.voltdb.compiler.deploymentfile.TaskSettingsType;
import org.voltdb.task.TaskManager.TaskValidationResult;
import org.voltdb.utils.InMemoryJarfile;
import com.google_voltpatches.common.util.concurrent.Futures;
import com.google_voltpatches.common.util.concurrent.ListenableFuture;
public class TestTaskManager {
static AtomicInteger s_firstActionSchedulerCallCount = new AtomicInteger();
static AtomicInteger s_postRunActionSchedulerCallCount = new AtomicInteger();
private static final String PROCEDURE_NAME = "SomeProcedure";
@Rule
public final TestName m_name = new TestName();
private AuthSystem m_authSystem;
private ClientInterface m_clientInterface;
private InternalConnectionHandler m_internalConnectionHandler;
private TaskManager m_taskManager;
private Database m_database;
private Procedure m_procedure;
private StatsAgent m_statsAgent = new StatsAgent();
private TaskSettingsType m_schedulesConfig = new TaskSettingsType();
private ClientResponse m_response;
@Before
public void setup() {
m_database = new Catalog().getClusters().add("cluster").getDatabases().add("database");
m_procedure = m_database.getProcedures().add(PROCEDURE_NAME);
m_authSystem = mock(AuthSystem.class);
when(m_authSystem.getUser(anyString())).then(m -> mock(AuthUser.class));
m_internalConnectionHandler = mock(InternalConnectionHandler.class);
m_response = when(mock(ClientResponse.class).getStatus()).thenReturn(ClientResponse.SUCCESS).getMock();
when(m_internalConnectionHandler.callProcedure(any(), eq(false), anyInt(), any(), eq(PROCEDURE_NAME), any()))
.then(m -> {
((ProcedureCallback) m.getArgument(3)).clientCallback(m_response);
return true;
});
m_clientInterface = mock(ClientInterface.class);
when(m_clientInterface.getInternalConnectionHandler()).thenReturn(m_internalConnectionHandler);
when(m_clientInterface.getProcedureFromName(eq(PROCEDURE_NAME))).thenReturn(m_procedure);
m_taskManager = new TaskManager(m_clientInterface, m_statsAgent, 0);
s_firstActionSchedulerCallCount.set(0);
s_postRunActionSchedulerCallCount.set(0);
}
@After
public void teardown() throws InterruptedException, ExecutionException {
m_taskManager.shutdown().get();
}
/*
* Test that a system schedule is only executed when the scheduler is the leader and then is stopped when the
* configuration is removed
*/
@Test
public void systemScheduleCreateDrop() throws Exception {
Task task = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_DATABASE);
startSync();
assertEquals(0, s_firstActionSchedulerCallCount.get());
processUpdateSync(task);
assertEquals(0, s_firstActionSchedulerCallCount.get());
promoteToLeaderSync(task);
// Long sleep because it sometimes takes a while for the first execution
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertTrue("ActionScheduler should have been called at least once: " + s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > 0);
dropScheduleAndAssertCounts();
}
/*
* Test that a host schedule is once configured and then is stopped when the configuration is removed
*/
@Test
public void hostScheduleCreateDrop() throws Exception {
Task task = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_HOSTS);
m_procedure.setTransactional(false);
startSync();
assertEquals(0, s_firstActionSchedulerCallCount.get());
processUpdateSync(task);
// Long sleep because it sometimes takes a while for the first execution
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertTrue("ActionScheduler should have been called at least once: " + s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > 0);
dropScheduleAndAssertCounts();
}
/*
* Test that a partition schedule is only executed when the host is a leader of a partition and then is stopped when
* the partition is demoted or configuration is removed
*/
@Test
public void partitionScheduleCreateDrop() throws Exception {
TheHashinator.initialize(ElasticHashinator.class, new ElasticHashinator(6).getConfigBytes());
Task task = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_PARTITIONS);
m_procedure.setTransactional(true);
m_procedure.setSinglepartition(true);
m_procedure.setPartitionparameter(0);
Column column = new Column();
column.setType(VoltType.INTEGER.getValue());
m_procedure.setPartitioncolumn(column);
startSync();
assertEquals(0, s_firstActionSchedulerCallCount.get());
processUpdateSync(task);
assertEquals(0, s_firstActionSchedulerCallCount.get());
promotedPartitionsSync(0, 4);
// Long sleep because it sometimes takes a while for the first execution
Thread.sleep(50);
assertEquals(2, s_firstActionSchedulerCallCount.get());
assertTrue("ActionScheduler should have been called at least once: " + s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > 0);
demotedPartitionsSync(0, 4);
assertCountsAfterScheduleCanceled(2);
int previousCount = s_postRunActionSchedulerCallCount.get();
promotedPartitionsSync(0);
// Long sleep because it sometimes takes a while for the first execution
Thread.sleep(20);
assertTrue(
"ActionScheduler should have been called at least " + previousCount + " times: "
+ s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > previousCount);
dropScheduleAndAssertCounts(3);
}
/*
* Test that a scheduler which takes paramaters can be constructed and executed
*/
@Test
public void schedulerWithParameters() throws Exception {
Task task = createSchedulerTask(TestActionSchedulerParams.class, TaskManager.SCOPE_DATABASE, 5, "TESTING", "AFFA47");
startSync();
assertEquals(0, s_firstActionSchedulerCallCount.get());
processUpdateSync(task);
assertEquals(0, s_firstActionSchedulerCallCount.get());
promoteToLeaderSync(task);
// Long sleep because it sometimes takes a while for the first execution
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertTrue("ActionScheduler should have been called at least once: " + s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > 0);
dropScheduleAndAssertCounts();
}
/*
* Test that when bad parameters are passed to a scheduler they are appropriately handled
*/
@Test
public void schedulerWithBadParameters() throws Exception {
Task task = createSchedulerTask(TestActionSchedulerParams.class, TaskManager.SCOPE_DATABASE, 5, "TESTING", "ZZZ");
assertFalse(validateTask(task).isValid());
task.getSchedulerparameters().get("0").setParameter("NAN");
task.getSchedulerparameters().get("2").setParameter("7894");
assertFalse(validateTask(task).isValid());
task.setSchedulerclass(TestActionScheduler.class.getName());
assertFalse(validateTask(task).isValid());
}
/*
* Test that the scheduler manager can succesfully be shutdown with active schedules running
*/
@Test
public void shutdownWithSchedulesActive() throws Exception {
TheHashinator.initialize(ElasticHashinator.class, new ElasticHashinator(6).getConfigBytes());
Task task1 = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_DATABASE);
Task task2 = createTask(m_name.getMethodName() + "_p", TestActionScheduler.class, TaskManager.SCOPE_PARTITIONS);
m_procedure.setTransactional(true);
m_procedure.setSinglepartition(true);
m_procedure.setPartitionparameter(0);
Column column = new Column();
column.setType(VoltType.INTEGER.getValue());
m_procedure.setPartitioncolumn(column);
startSync(task1, task2);
promoteToLeaderSync(task1, task2);
promotedPartitionsSync(0, 1, 2, 3);
Thread.sleep(50);
assertEquals(5, s_firstActionSchedulerCallCount.get());
m_taskManager.shutdown().get();
}
/*
* Test that a scheduler can just schedule itself to be rerun multple times
*/
@Test
public void rerunActionScheduler() throws Exception {
Task task = createSchedulerTask(TestActionSchedulerRerun.class, TaskManager.SCOPE_DATABASE, 5);
startSync(task);
promoteToLeaderSync(task);
// Long sleep because it sometimes takes a while for the first execution
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertEquals(4, s_postRunActionSchedulerCallCount.get());
}
/*
* Test that stats are maintained while a previously running procedure is disabled but scheduler is restarted when
* enabled
*/
@Test
public void disableReenableActionScheduler() throws Exception {
Task task = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_DATABASE);
startSync();
promoteToLeaderSync(task);
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
task.setEnabled(false);
processUpdateSync(task);
Thread.sleep(5);
validateStats("DISABLED", null);
task.setEnabled(true);
processUpdateSync(task);
Thread.sleep(20);
dropScheduleAndAssertCounts(2);
}
/*
* Test that newly promoted partitions honor the enable flag of a procedure
*/
@Test
public void partitionPromotionAndDisabledSchedules() throws Exception {
Task task = createSchedulerTask(TestActionSchedulerRerun.class, TaskManager.SCOPE_PARTITIONS, 5);
startSync(task);
task.setEnabled(false);
processUpdateSync(task);
promotedPartitionsSync(0, 1);
assertEquals(0, getScheduleStats().getRowCount());
task.setEnabled(true);
processUpdateSync(task);
assertEquals(2, getScheduleStats().getRowCount());
promotedPartitionsSync(2, 3);
assertEquals(4, getScheduleStats().getRowCount());
task.setEnabled(false);
processUpdateSync(task);
promotedPartitionsSync(4, 5);
assertEquals(4, getScheduleStats().getRowCount());
task.setEnabled(true);
processUpdateSync(task);
assertEquals(6, getScheduleStats().getRowCount());
task.setEnabled(false);
processUpdateSync(task);
demotedPartitionsSync(3, 4, 5);
assertEquals(3, getScheduleStats().getRowCount());
}
/*
* Test that minimum delay configuration is honored
*/
@Test
public void minDelay() throws Exception {
m_schedulesConfig.setMinDelayMs(10000);
Task task = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_DATABASE);
startSync();
promoteToLeaderSync(task);
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertEquals(0, s_postRunActionSchedulerCallCount.get());
}
/*
* Test that max run frequency configuration is honored
*/
@Test
public void maxRunFrequency() throws Exception {
m_schedulesConfig.setMaxRunFrequency(1.0);
Task task = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_DATABASE);
startSync();
promoteToLeaderSync(task);
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertEquals(1, s_postRunActionSchedulerCallCount.get());
}
/*
* Test that schedules are only restarted when classes are updated and only if the class or one of its deps change
*
* TODO test changing the class restarts the schedule
*/
@Test
public void relaodWithInMemoryJarFile() throws Exception {
InMemoryJarfile jarFile = new InMemoryJarfile();
VoltCompiler vc = new VoltCompiler(false);
vc.addClassToJar(jarFile, TestTaskManager.class);
Task task1 = createTask("TestActionScheduler", TestActionScheduler.class, TaskManager.SCOPE_DATABASE);
Task task2 = createTask("TestActionSchedulerRerun", TestActionSchedulerRerun.class, TaskManager.SCOPE_DATABASE,
Integer.MAX_VALUE);
startSync();
promoteToLeaderSync();
processUpdateSync(jarFile.getLoader(), false, task1, task2);
Thread.sleep(30);
VoltTable table = getScheduleStats();
Map<String, Long> invocationCounts = new HashMap<>();
while (table.advanceRow()) {
invocationCounts.put(table.getString("NAME"), table.getLong("SCHEDULER_INVOCATIONS"));
}
// No schedules should restart since class and deps did not change
processUpdateSync(jarFile.getLoader(), false, task1, task2);
Thread.sleep(5);
table = getScheduleStats();
while (table.advanceRow()) {
String scheduleName = table.getString("NAME");
long currentCount = table.getLong("SCHEDULER_INVOCATIONS");
assertTrue("Count decreased for " + scheduleName,
invocationCounts.put(scheduleName, currentCount) < currentCount);
}
Thread.sleep(5);
// Only schedules which do not specify deps should restart
processUpdateSync(jarFile.getLoader(), true, task1, task2);
Thread.sleep(5);
table = getScheduleStats();
while (table.advanceRow()) {
String scheduleName = table.getString("NAME");
long currentCount = table.getLong("SCHEDULER_INVOCATIONS");
long previousCount = invocationCounts.put(scheduleName, currentCount);
if (scheduleName.equals("TestActionScheduler")) {
assertTrue("Count decreased for " + scheduleName, previousCount < currentCount);
} else {
assertTrue("Count increased for " + scheduleName + " from " + previousCount + " to " + currentCount,
previousCount * 3 / 2 > currentCount);
}
}
Thread.sleep(5);
// Update class dep so all should restart
vc = new VoltCompiler(false);
jarFile = new InMemoryJarfile();
vc.addClassToJar(jarFile, TestTaskManager.class);
jarFile.removeClassFromJar(TestActionSchedulerParams.class.getName());
processUpdateSync(jarFile.getLoader(), true, task1, task2);
Thread.sleep(5);
table = getScheduleStats();
while (table.advanceRow()) {
String scheduleName = table.getString("NAME");
long currentCount = table.getLong("SCHEDULER_INVOCATIONS");
long previousCount = invocationCounts.put(scheduleName, currentCount);
assertTrue("Count increased for " + scheduleName + " from " + previousCount + " to " + currentCount,
previousCount * 3 / 2 > currentCount);
}
}
@Test
public void changeOnErrorWhileRunning() throws Exception {
when(m_response.getStatus()).thenReturn(ClientResponse.USER_ABORT);
Task task = createSchedulerTask(TestActionScheduler.class, TaskManager.SCOPE_PARTITIONS);
m_procedure.setSinglepartition(true);
task.setOnerror("IGNORE");
startSync(task);
promotedPartitionsSync(0, 1, 2, 3, 4, 5);
// Long sleep because it sometimes takes a while for the first execution
Thread.sleep(50);
assertEquals(6, s_firstActionSchedulerCallCount.get());
assertTrue("ActionScheduler should have been called at least once: " + s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > 0);
validateStats("RUNNING", r -> assertNull(r.getString("SCHEDULER_STATUS")));
task.setOnerror("ABORT");
processUpdateSync(task);
Thread.sleep(5);
validateStats("ERROR", r -> assertTrue(r.getString("SCHEDULER_STATUS").startsWith("Procedure ")));
}
/*
* Test that the validate parameters method is being called correctly
*/
@Test
public void testValidateParameters() throws Exception {
Task task = createSchedulerTask(TestActionSchedulerValidateParams.class, TaskManager.SCOPE_HOSTS, new Object[1]);
assertTrue(validateTask(task).isValid());
task.setSchedulerclass(TestActionSchedulerValidateParamsWithHelper.class.getName());
assertTrue(validateTask(task).isValid());
// Parameter fails validation
task.getSchedulerparameters().get("0").setParameter("FAIL");
assertFalse(validateTask(task).isValid());
task.setSchedulerclass(TestActionSchedulerValidateParams.class.getName());
assertFalse(validateTask(task).isValid());
}
/*
* Test providing a custom ActionSchedule to the manager
*/
@Test
public void testCustomSchedule() throws Exception {
Task task = createSchedulerTask(TestActionSchedule.class, TaskManager.SCOPE_DATABASE, 50, 250);
startSync();
promoteToLeaderSync(task);
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertTrue("ActionSchedule should have been called at least once: " + s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > 0);
dropScheduleAndAssertCounts(1);
}
/*
* Test providing a custom ActionGenerator to the manager
*/
@Test
public void testCustomGenerator() throws Exception {
Task task = createSchedulerTask(TestActionGenerator.class, TaskManager.SCOPE_DATABASE);
startSync();
promoteToLeaderSync(task);
Thread.sleep(50);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertTrue("ActionSchedule should have been called at least once: " + s_postRunActionSchedulerCallCount.get(),
s_postRunActionSchedulerCallCount.get() > 0);
validateStats();
processUpdateSync();
// Same as assertCountsAfterScheduleCanceled(1) except only 1/2 the calls are to the procedure
int previousCount = s_postRunActionSchedulerCallCount.get();
Thread.sleep(10);
assertEquals(1, s_firstActionSchedulerCallCount.get());
assertEquals(previousCount, s_postRunActionSchedulerCallCount.get());
int procedureCalls = previousCount/2;
verify(m_internalConnectionHandler, atLeast(procedureCalls)).callProcedure(any(), eq(false), anyInt(), any(),
eq(PROCEDURE_NAME), any());
verify(m_internalConnectionHandler, atMost(procedureCalls + 1)).callProcedure(any(), eq(false),
anyInt(), any(), eq(PROCEDURE_NAME), any());
verify(m_clientInterface, atLeast(procedureCalls)).getProcedureFromName(eq(PROCEDURE_NAME));
verify(m_clientInterface, atMost(procedureCalls + 1)).getProcedureFromName(eq(PROCEDURE_NAME));
}
private void dropScheduleAndAssertCounts() throws Exception {
dropScheduleAndAssertCounts(1);
}
private void dropScheduleAndAssertCounts(int startCount) throws Exception {
validateStats();
processUpdateSync();
assertCountsAfterScheduleCanceled(startCount);
}
private void assertCountsAfterScheduleCanceled(int startCount)
throws InterruptedException {
int previousCount = s_postRunActionSchedulerCallCount.get();
Thread.sleep(10);
assertEquals(startCount, s_firstActionSchedulerCallCount.get());
assertEquals(previousCount, s_postRunActionSchedulerCallCount.get());
verify(m_internalConnectionHandler, atLeast(previousCount)).callProcedure(any(), eq(false), anyInt(), any(),
eq(PROCEDURE_NAME), any());
verify(m_internalConnectionHandler, atMost(previousCount + startCount)).callProcedure(any(), eq(false),
anyInt(), any(), eq(PROCEDURE_NAME), any());
verify(m_clientInterface, atLeast(previousCount)).getProcedureFromName(eq(PROCEDURE_NAME));
verify(m_clientInterface, atMost(previousCount + startCount)).getProcedureFromName(eq(PROCEDURE_NAME));
}
private Task createSchedulerTask(Class<? extends Initializable> clazz, String scope, Object... params) {
return createTask(m_name.getMethodName(), clazz, scope, params);
}
private Task createTask(String name, Class<? extends Initializable> clazz, String scope,
Object... params) {
Task task = initializeTask(name, scope);
if (ActionScheduler.class.isAssignableFrom(clazz)) {
task.setSchedulerclass(clazz.getName());
setParameters(task.getSchedulerparameters(), params);
} else if (ActionGenerator.class.isAssignableFrom(clazz)) {
task.setActiongeneratorclass(clazz.getName());
setParameters(task.getActiongeneratorparameters(), params);
task.setScheduleclass(DelaySchedule.class.getName());
setParameters(task.getScheduleparameters(), 1, "MILLISECONDS");
} else if (ActionSchedule.class.isAssignableFrom(clazz)) {
task.setScheduleclass(clazz.getName());
setParameters(task.getScheduleparameters(), params);
task.setActiongeneratorclass(SingleProcGenerator.class.getName());
setParameters(task.getActiongeneratorparameters(), PROCEDURE_NAME);
} else {
fail("Unsupported class: " + clazz);
}
return task;
}
private void setParameters(CatalogMap<TaskParameter> paramMap, Object... params) {
for (int i = 0; i < params.length; ++i) {
TaskParameter tp = paramMap.add(Integer.toString(i));
tp.setIndex(i);
tp.setParameter(params[i] == null ? null : params[i].toString());
}
}
private Task initializeTask(String name, String scope) {
Task task = m_database.getTasks().add(name);
task.setEnabled(true);
task.setName(name);
task.setScope(scope);
task.setUser("user");
task.setOnerror("ABORT");
return task;
}
private void startSync(Task... tasks) throws InterruptedException, ExecutionException {
m_taskManager.start(m_schedulesConfig, Arrays.asList(tasks), m_authSystem, getClass().getClassLoader())
.get();
}
public void promoteToLeaderSync(Task... tasks) throws InterruptedException, ExecutionException {
m_taskManager
.promoteToLeader(m_schedulesConfig, Arrays.asList(tasks), m_authSystem, getClass().getClassLoader())
.get();
}
private void processUpdateSync(Task... tasks) throws InterruptedException, ExecutionException {
processUpdateSync(getClass().getClassLoader(), false, tasks);
}
private void processUpdateSync(ClassLoader classLoader, boolean classesUpdated, Task... tasks)
throws InterruptedException, ExecutionException {
m_taskManager
.processUpdate(m_schedulesConfig, Arrays.asList(tasks), m_authSystem, classLoader, classesUpdated)
.get();
}
private void promotedPartitionsSync(int... partitionIds) throws InterruptedException, ExecutionException {
List<ListenableFuture<?>> futures = new ArrayList<>(partitionIds.length);
for (int partitionId : partitionIds) {
futures.add(m_taskManager.promotedPartition(partitionId));
}
Futures.whenAllSucceed(futures).call(() -> null).get();
}
private void demotedPartitionsSync(int... partitionIds) throws InterruptedException, ExecutionException {
List<ListenableFuture<?>> futures = new ArrayList<>(partitionIds.length);
for (int partitionId : partitionIds) {
futures.add(m_taskManager.demotedPartition(partitionId));
}
Futures.whenAllSucceed(futures).call(() -> null).get();
}
private VoltTable getScheduleStats() {
return m_statsAgent.getStatsAggregate(StatsSelector.TASK, false, System.currentTimeMillis());
}
private void validateStats() {
validateStats("RUNNING", null);
}
private void validateStats(String state, Consumer<VoltTableRow> validator) {
VoltTable table = getScheduleStats();
long totalActionSchedulerInvocations = 0;
long totalProcedureInvocations = 0;
while (table.advanceRow()) {
if (validator != null) {
validator.accept(table);
}
assertEquals(state, table.getString("STATE"));
totalActionSchedulerInvocations += table.getLong("SCHEDULER_INVOCATIONS");
totalProcedureInvocations += table.getLong("PROCEDURE_INVOCATIONS");
}
assertTrue(totalActionSchedulerInvocations >= totalProcedureInvocations);
assertTrue(totalActionSchedulerInvocations <= s_firstActionSchedulerCallCount.get()
+ s_postRunActionSchedulerCallCount.get());
}
private TaskValidationResult validateTask(Task task) {
return TaskManager.validateTask(task, null, getClass().getClassLoader());
}
public static class TestActionScheduler implements ActionScheduler {
@Override
public DelayedAction getFirstDelayedAction() {
s_firstActionSchedulerCallCount.getAndIncrement();
return DelayedAction.createProcedure(100, TimeUnit.MICROSECONDS, this::getNextAction, PROCEDURE_NAME);
}
public DelayedAction getNextAction(ActionResult previousProcedureRun) {
s_postRunActionSchedulerCallCount.getAndIncrement();
return DelayedAction.createProcedure(100, TimeUnit.MICROSECONDS, this::getNextAction, PROCEDURE_NAME);
}
@Override
public Collection<String> getDependencies() {
return Collections.singleton(TestActionSchedulerParams.class.getName());
}
}
public static class TestActionSchedulerParams implements ActionScheduler {
public void initialize(int arg1, String arg2, byte[] arg3) {}
@Override
public DelayedAction getFirstDelayedAction() {
s_firstActionSchedulerCallCount.getAndIncrement();
return DelayedAction.createProcedure(100, TimeUnit.MICROSECONDS, this::getNextAction, PROCEDURE_NAME);
}
public DelayedAction getNextAction(ActionResult previousProcedureRun) {
s_postRunActionSchedulerCallCount.getAndIncrement();
return DelayedAction.createProcedure(100, TimeUnit.MICROSECONDS, this::getNextAction, PROCEDURE_NAME);
}
}
public static class TestActionSchedulerRerun implements ActionScheduler {
private int m_maxRunCount;
private int m_runCount = 0;
public void initialize(int maxRunCount) {
m_maxRunCount = maxRunCount;
}
@Override
public DelayedAction getFirstDelayedAction() {
s_firstActionSchedulerCallCount.getAndIncrement();
return ++m_runCount < m_maxRunCount
? DelayedAction.createCallback(100, TimeUnit.MICROSECONDS, this::getNextAction)
: DelayedAction.createExit(null);
}
public DelayedAction getNextAction(ActionResult previousProcedureRun) {
assertNull(previousProcedureRun.getProcedure());
s_postRunActionSchedulerCallCount.getAndIncrement();
return ++m_runCount < m_maxRunCount
? DelayedAction.createCallback(100, TimeUnit.MICROSECONDS, this::getNextAction)
: DelayedAction.createExit(null);
}
}
public static class TestActionSchedulerValidateParams implements ActionScheduler {
public static String validateParameters(String value) {
return value;
}
public void initialize(String value) {}
@Override
public DelayedAction getFirstDelayedAction() {
return null;
}
}
public static class TestActionSchedulerValidateParamsWithHelper extends TestActionSchedulerValidateParams {
public static String validateParameters(TaskHelper helper, String value) {
return TestActionSchedulerValidateParams.validateParameters(value);
}
public void initialize(TaskHelper helper, String value) {
super.initialize(value);
}
}
public static class TestActionSchedule implements ActionSchedule {
private long m_min;
private long m_max;
public void initialize(long min, long max) {
m_min = min;
m_max = max;
}
@Override
public ActionDelay getFirstDelay() {
s_firstActionSchedulerCallCount.getAndIncrement();
return new ActionDelay(ThreadLocalRandom.current().nextLong(m_min, m_max), TimeUnit.NANOSECONDS,
this::getNextDelay);
}
private ActionDelay getNextDelay(ActionResult result) {
s_postRunActionSchedulerCallCount.getAndIncrement();
return new ActionDelay(ThreadLocalRandom.current().nextLong(m_min, m_max), TimeUnit.NANOSECONDS,
this::getNextDelay);
}
}
public static class TestActionGenerator implements ActionGenerator {
private long m_count = 0;
@Override
public Action getFirstAction() {
s_firstActionSchedulerCallCount.getAndIncrement();
return Action.createProcedure(this::getNextAction, PROCEDURE_NAME);
}
private Action getNextAction(ActionResult result) {
s_postRunActionSchedulerCallCount.getAndIncrement();
return (++m_count & 0x1) == 0 ? Action.createProcedure(this::getNextAction, PROCEDURE_NAME)
: Action.createCallback(this::getNextAction);
}
}
}
|
//$HeadURL$
package org.deegree.feature.persistence.postgis;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import junit.framework.Assert;
import org.deegree.commons.jdbc.ConnectionManager;
import org.deegree.commons.xml.stax.FormattingXMLStreamWriter;
import org.deegree.cs.exceptions.TransformationException;
import org.deegree.cs.exceptions.UnknownCRSException;
import org.deegree.feature.FeatureCollection;
import org.deegree.feature.persistence.FeatureStoreException;
import org.deegree.feature.persistence.FeatureStoreManager;
import org.deegree.feature.persistence.query.FeatureResultSet;
import org.deegree.feature.persistence.query.Query;
import org.deegree.feature.types.ApplicationSchema;
import org.deegree.feature.types.FeatureType;
import org.deegree.filter.Filter;
import org.deegree.filter.FilterEvaluationException;
import org.deegree.filter.OperatorFilter;
import org.deegree.filter.comparison.PropertyIsEqualTo;
import org.deegree.filter.expression.Literal;
import org.deegree.filter.expression.PropertyName;
import org.deegree.geometry.Envelope;
import org.deegree.gml.GMLOutputFactory;
import org.deegree.gml.GMLStreamWriter;
import org.deegree.gml.GMLVersion;
import org.deegree.protocol.wfs.getfeature.TypeName;
import org.junit.Test;
/**
* The <code></code> class TODO add class documentation here.
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class PostGISFeatureStoreTest {
@Test
public void testInstantiation()
throws FeatureStoreException {
// ConnectionManager.addConnection( "philosopher-db", "jdbc:postgresql://hurricane:5432/deegreetest",
// "deegreetest", "deegreetest", 1, 10 );
// URL configURL = this.getClass().getResource( "philosopher.xml" );
// PostGISFeatureStore fs = (PostGISFeatureStore) FeatureStoreManager.create( configURL );
// fs.init();
// ApplicationSchema schema = fs.getSchema();
// Assert.assertEquals( 1, schema.getFeatureTypes().length );
// FeatureType ft = schema.getFeatureTypes()[0];
// System.out.println( ft );
// Envelope env = fs.getEnvelope( countryName );
// System.out.println( env );
}
@Test
public void testQueryCountry()
throws FeatureStoreException, FilterEvaluationException, XMLStreamException,
FactoryConfigurationError, UnknownCRSException, TransformationException {
// ConnectionManager.addConnection( "philosopher-db", "jdbc:postgresql://hurricane:5432/deegreetest",
// "deegreetest", "deegreetest", 1, 10 );
// URL configURL = this.getClass().getResource( "philosopher.xml" );
// PostGISFeatureStore fs = (PostGISFeatureStore) FeatureStoreManager.create( configURL );
// fs.init();
// ApplicationSchema schema = fs.getSchema();
// Assert.assertEquals( 1, schema.getFeatureTypes().length );
// FeatureType ft = schema.getFeatureTypes()[0];
// System.out.println( ft );
// null ) };
// Query query = new Query( typeNames, null, null, null, null );
// FeatureResultSet rs = fs.query( query );
// try {
// FeatureCollection fc = rs.toCollection();
// XMLStreamWriter xmlStream = new FormattingXMLStreamWriter(
// XMLOutputFactory.newInstance().createXMLStreamWriter(
// System.out ) );
// GMLStreamWriter gmlStream = GMLOutputFactory.createGMLStreamWriter( GMLVersion.GML_31, xmlStream );
// gmlStream.write( fc );
// gmlStream.close();
// } finally {
// rs.close();
}
@Test
public void testQueryCountryWithFilter()
throws FeatureStoreException, FilterEvaluationException, XMLStreamException,
FactoryConfigurationError, UnknownCRSException, TransformationException {
// ConnectionManager.addConnection( "philosopher-db", "jdbc:postgresql://hurricane:5432/deegreetest",
// "deegreetest", "deegreetest", 1, 10 );
// URL configURL = this.getClass().getResource( "philosopher.xml" );
// PostGISFeatureStore fs = (PostGISFeatureStore) FeatureStoreManager.create( configURL );
// fs.init();
// ApplicationSchema schema = fs.getSchema();
// Assert.assertEquals( 1, schema.getFeatureTypes().length );
// FeatureType ft = schema.getFeatureTypes()[0];
// System.out.println( ft );
// null ) };
// Literal literal = new Literal( "United Kingdom" );
// PropertyIsEqualTo propIsEqualTo = new PropertyIsEqualTo( propName, literal, false );
// Filter filter = new OperatorFilter( propIsEqualTo );
// Query query = new Query( typeNames, filter, null, null, null );
// FeatureResultSet rs = fs.query( query );
// try {
// FeatureCollection fc = rs.toCollection();
// XMLStreamWriter xmlStream = new FormattingXMLStreamWriter(
// XMLOutputFactory.newInstance().createXMLStreamWriter(
// System.out ) );
// GMLStreamWriter gmlStream = GMLOutputFactory.createGMLStreamWriter( GMLVersion.GML_31, xmlStream );
// gmlStream.write( fc );
// gmlStream.close();
// } finally {
// rs.close();
}
}
|
//$HeadURL$
package org.deegree.services.wms;
import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.deegree.services.wms.controller.sld.SLDParser.getStyles;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import javax.xml.bind.JAXBElement;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.deegree.commons.annotations.LoggingNotes;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.xml.XMLAdapter;
import org.deegree.filter.Filter;
import org.deegree.rendering.r2d.se.parser.SymbologyParser;
import org.deegree.rendering.r2d.se.unevaluated.Style;
import org.deegree.services.jaxb.wms.DirectStyleType;
import org.deegree.services.jaxb.wms.SLDStyleType;
import org.slf4j.Logger;
/**
* <code>StyleRegistry</code>
*
* @author <a href="mailto:schmitz@lat-lon.de">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
@LoggingNotes(info = "logs when style files cannot be loaded", trace = "logs stack traces", debug = "logs information about loading/reloading of style files")
public class StyleRegistry extends TimerTask {
private static final Logger LOG = getLogger( StyleRegistry.class );
private HashMap<String, HashMap<String, Style>> registry = new HashMap<String, HashMap<String, Style>>();
private HashMap<String, HashMap<String, Style>> legendRegistry = new HashMap<String, HashMap<String, Style>>();
private HashMap<File, Pair<Long, String>> monitoredFiles = new HashMap<File, Pair<Long, String>>();
private HashMap<File, Pair<Long, String>> monitoredLegendFiles = new HashMap<File, Pair<Long, String>>();
private HashSet<String> soleStyleFiles = new HashSet<String>();
private HashSet<String> soleLegendFiles = new HashSet<String>();
/**
* @param layerName
* @param style
* @param clear
* if true, all other styles will be removed for the layer
*/
public void put( String layerName, Style style, boolean clear ) {
HashMap<String, Style> styles = registry.get( layerName );
if ( styles == null ) {
styles = new HashMap<String, Style>();
registry.put( layerName, styles );
styles.put( "default", style );
} else if ( clear ) {
styles.clear();
styles.put( "default", style );
}
if ( style.getName() == null ) {
LOG.debug( "Overriding default style since new style does not have name." );
styles.put( "default", style );
} else {
styles.put( style.getName(), style );
}
}
/**
* @param layerName
* @param style
* @param clear
*/
public void putLegend( String layerName, Style style, boolean clear ) {
HashMap<String, Style> styles = legendRegistry.get( layerName );
if ( styles == null ) {
styles = new HashMap<String, Style>();
legendRegistry.put( layerName, styles );
styles.put( "default", style );
} else if ( clear ) {
styles.clear();
styles.put( "default", style );
}
if ( style.getName() == null ) {
LOG.debug( "Overriding default style since new style does not have name." );
styles.put( "default", style );
} else {
styles.put( style.getName(), style );
}
}
/**
* @param layerName
* @param style
*/
public void putAsDefault( String layerName, Style style ) {
HashMap<String, Style> styles = registry.get( layerName );
if ( styles == null ) {
styles = new HashMap<String, Style>();
registry.put( layerName, styles );
}
styles.put( "default", style );
styles.put( style.getName(), style );
}
/**
* @param layerName
* @param styleName
* may be null, in which case the default style will be searched for
* @return null, if not available
*/
public Style getLegendStyle( String layerName, String styleName ) {
if ( styleName == null ) {
styleName = "default";
}
if ( legendRegistry.get( layerName ) != null && legendRegistry.get( layerName ).containsKey( styleName ) ) {
return legendRegistry.get( layerName ).get( styleName );
}
return get( layerName, styleName );
}
/**
* @param layerName
* @param styleName
* @return true, if the layer has a style with the name
*/
public boolean hasStyle( String layerName, String styleName ) {
HashMap<String, Style> styles = registry.get( layerName );
return styles != null && styles.get( styleName ) != null;
}
/**
* @param layerName
* @param styleName
* may be null, in which case the default style will be searched for
* @return null, if not available
*/
public Style get( String layerName, String styleName ) {
HashMap<String, Style> styles = registry.get( layerName );
if ( styles == null ) {
return null;
}
if ( styleName == null ) {
styleName = "default";
}
return styles.get( styleName );
}
/**
* @param layerName
* @return all styles for the layer
*/
public ArrayList<Style> getAll( String layerName ) {
HashMap<String, Style> map = registry.get( layerName );
if ( map == null ) {
return new ArrayList<Style>();
}
ArrayList<Style> styles = new ArrayList<Style>( map.size() );
styles.addAll( map.values() );
return styles;
}
private Style loadNoImport( String layerName, File file, boolean legend ) {
XMLInputFactory fac = XMLInputFactory.newInstance();
FileInputStream in = null;
try {
LOG.debug( "Trying to load{} style from '{}'", legend ? "" : " legend", file );
in = new FileInputStream( file );
Style sty = SymbologyParser.INSTANCE.parse( fac.createXMLStreamReader( file.toString(), in ) );
if ( legend ) {
monitoredLegendFiles.put( file, new Pair<Long, String>( file.lastModified(), layerName ) );
} else {
monitoredFiles.put( file, new Pair<Long, String>( file.lastModified(), layerName ) );
}
return sty;
} catch ( FileNotFoundException e ) {
LOG.info( "Style file '{}' for layer '{}' could not be found: '{}'",
new Object[] { file, layerName, e.getLocalizedMessage() } );
} catch ( XMLStreamException e ) {
LOG.trace( "Stack trace:", e );
LOG.info( "Style file '{}' for layer '{}' could not be loaded: '{}'",
new Object[] { file, layerName, e.getLocalizedMessage() } );
} finally {
closeQuietly( in );
}
return null;
}
/**
* @param layerName
* @param file
* @return true, if actually loaded
*/
public boolean load( String layerName, File file ) {
Style sty = loadNoImport( layerName, file, false );
if ( sty != null ) {
put( layerName, sty, soleStyleFiles.contains( file.getName() ) );
return true;
}
return false;
}
/**
* @param layerName
* @param file
* @return true, if actually loaded
*/
public boolean loadLegend( String layerName, File file ) {
Style sty = loadNoImport( layerName, file, true );
if ( sty != null ) {
putLegend( layerName, sty, soleLegendFiles.contains( file.getName() ) );
return true;
}
return false;
}
/**
* @param layerName
* @param styles
* @param adapter
*/
public void load( String layerName, List<DirectStyleType> styles, XMLAdapter adapter ) {
for ( DirectStyleType sty : styles ) {
try {
File file = new File( adapter.resolve( sty.getFile() ).toURI() );
String name = sty.getName();
Style style = loadNoImport( layerName, file, false );
if ( style != null ) {
if ( name != null ) {
style.setName( name );
}
if ( styles.size() == 1 ) {
soleStyleFiles.add( file.getName() );
}
put( layerName, style, false );
if ( sty.getLegendGraphicFile() != null ) {
File legend = new File( adapter.resolve( sty.getLegendGraphicFile() ).toURI() );
style.setLegendFile( legend );
}
}
} catch ( MalformedURLException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName );
} catch ( URISyntaxException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName );
}
try {
if ( sty.getLegendConfigurationFile() != null ) {
File file = new File( adapter.resolve( sty.getLegendConfigurationFile() ).toURI() );
String name = sty.getName();
Style style = loadNoImport( layerName, file, true );
if ( style != null ) {
if ( name != null ) {
style.setName( name );
}
if ( styles.size() == 1 ) {
soleLegendFiles.add( file.getName() );
}
putLegend( layerName, style, false );
}
}
} catch ( MalformedURLException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName );
} catch ( URISyntaxException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName );
}
}
}
/**
* @param layerName
* @param styles
* @param adapter
*/
public void load( String layerName, XMLAdapter adapter, List<SLDStyleType> styles ) {
for ( SLDStyleType sty : styles ) {
FileInputStream is = null;
try {
File file = new File( adapter.resolve( sty.getFile() ).toURI() );
String namedLayer = sty.getNamedLayer();
LOG.debug( "Will read styles from SLD '{}', for named layer '{}'.", file, namedLayer );
Map<String, String> map = new HashMap<String, String>();
Map<String, File> legends = new HashMap<String, File>();
String name = null, lastName = null;
for ( JAXBElement<String> elem : sty.getNameAndUserStyleAndLegendConfigurationFile() ) {
if ( elem.getName().getLocalPart().equals( "Name" ) ) {
name = elem.getValue();
} else if ( elem.getName().getLocalPart().equals( "LegendConfigurationFile" ) ) {
File legendFile = new File( adapter.resolve( elem.getValue() ).toURI() );
Style style = loadNoImport( layerName, legendFile, true );
if ( style != null ) {
if ( name != null ) {
style.setName( name );
}
putLegend( layerName, style, false );
}
} else if ( elem.getName().getLocalPart().equals( "LegendGraphicFile" ) ) {
File legend = new File( adapter.resolve( elem.getValue() ).toURI() );
legends.put( lastName, legend );
} else if ( elem.getName().getLocalPart().equals( "UserStyle" ) ) {
if ( name == null ) {
name = elem.getValue();
}
LOG.debug( "Will load user style with name '{}', it will be known as '{}'.", elem.getValue(),
name );
map.put( elem.getValue(), name );
lastName = name;
name = null;
}
}
XMLInputFactory fac = XMLInputFactory.newInstance();
is = new FileInputStream( file );
XMLStreamReader in = fac.createXMLStreamReader( file.toURI().toURL().toString(), is );
Pair<LinkedList<Filter>, LinkedList<Style>> parsedStyles = getStyles( in, namedLayer, map );
for ( Style s : parsedStyles.second ) {
put( layerName, s, false );
s.setLegendFile( legends.get( s.getName() ) );
}
} catch ( MalformedURLException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName );
} catch ( FileNotFoundException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be found.", sty.getFile(), layerName );
} catch ( XMLStreamException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be parsed: '{}'.",
new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } );
} catch ( URISyntaxException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName );
} catch ( IOException e ) {
LOG.trace( "Stack trace", e );
LOG.info( "Style file '{}' for layer '{}' could not be closed: '{}'.",
new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } );
} finally {
closeQuietly( is );
}
}
}
/**
* @param layerName
* @param file
* @param isSoleStyle
* if true, all styles will be cleared upon update
* @return true, if actually loaded
*/
public boolean register( String layerName, File file, boolean isSoleStyle ) {
if ( !monitoredFiles.containsKey( file ) ) {
if ( isSoleStyle ) {
soleStyleFiles.add( file.getName() );
}
return load( layerName, file );
}
return false;
}
@Override
public void run() {
for ( File f : monitoredFiles.keySet() ) {
Pair<Long, String> pair = monitoredFiles.get( f );
if ( f.lastModified() != pair.first ) {
LOG.debug( "Reloading style file '{}'", f );
load( pair.second, f );
}
}
for ( File f : monitoredLegendFiles.keySet() ) {
Pair<Long, String> pair = monitoredLegendFiles.get( f );
if ( f.lastModified() != pair.first ) {
LOG.debug( "Reloading legend style file '{}'", f );
loadLegend( pair.second, f );
}
}
}
}
|
package org.owasp.dependencycheck.data.update.task;
import org.owasp.dependencycheck.data.update.xml.NvdCve20Handler;
import org.owasp.dependencycheck.data.update.xml.NvdCve12Handler;
import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.data.update.StandardUpdate;
import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.xml.sax.SAXException;
/**
* A callable task that will process a given set of NVD CVE xml files and update
* the Cve Database accordingly.
*
* @author Jeremy Long (jeremy.long@owasp.org)
*/
public class ProcessTask implements Callable<ProcessTask> {
/**
* A field to store any update exceptions that occur during the "call".
*/
private UpdateException exception = null;
/**
* Get the value of exception.
*
* @return the value of exception
*/
public UpdateException getException() {
return exception;
}
/**
* Set the value of exception.
*
* @param exception new value of exception
*/
public void setException(UpdateException exception) {
this.exception = exception;
}
/**
* A reference to the CveDB.
*/
private final CveDB cveDB;
/**
* A reference to the callable download task.
*/
private final CallableDownloadTask filePair;
/**
* A reference to the properties.
*/
private final DatabaseProperties properties;
/**
* Constructs a new ProcessTask used to process an NVD CVE update.
*
* @param cveDB the data store object
* @param filePair the download task that contains the URL references to
* download
*/
public ProcessTask(final CveDB cveDB, final CallableDownloadTask filePair) {
this.cveDB = cveDB;
this.filePair = filePair;
this.properties = cveDB.getDatabaseProperties();
}
/**
* Implements the callable interface.
*
* @return this object
* @throws Exception thrown if there is an exception; note that any
* UpdateExceptions are simply added to the tasks exception collection
*/
@Override
public ProcessTask call() throws Exception {
try {
processFiles();
} catch (UpdateException ex) {
this.exception = ex;
}
return this;
}
/**
* Imports the NVD CVE XML File into the Lucene Index.
*
* @param file the file containing the NVD CVE XML
* @param oldVersion contains the file containing the NVD CVE XML 1.2
* @throws ParserConfigurationException is thrown if there is a parser
* configuration exception
* @throws SAXException is thrown if there is a SAXException
* @throws IOException is thrown if there is a IO Exception
* @throws SQLException is thrown if there is a SQL exception
* @throws DatabaseException is thrown if there is a database exception
* @throws ClassNotFoundException thrown if the h2 database driver cannot be
* loaded
*/
protected void importXML(File file, File oldVersion) throws ParserConfigurationException,
SAXException, IOException, SQLException, DatabaseException, ClassNotFoundException {
final SAXParserFactory factory = SAXParserFactory.newInstance();
final SAXParser saxParser = factory.newSAXParser();
final NvdCve12Handler cve12Handler = new NvdCve12Handler();
saxParser.parse(oldVersion, cve12Handler);
final Map<String, List<VulnerableSoftware>> prevVersionVulnMap = cve12Handler.getVulnerabilities();
final NvdCve20Handler cve20Handler = new NvdCve20Handler();
cve20Handler.setCveDB(cveDB);
cve20Handler.setPrevVersionVulnMap(prevVersionVulnMap);
saxParser.parse(file, cve20Handler);
}
/**
* Processes the NVD CVE XML file and imports the data into the DB.
*
* @throws UpdateException thrown if there is an error loading the data into
* the database
*/
private void processFiles() throws UpdateException {
String msg = String.format("Processing Started for NVD CVE - %s", filePair.getNvdCveInfo().getId());
Logger.getLogger(StandardUpdate.class.getName()).log(Level.INFO, msg);
try {
importXML(filePair.getFirst(), filePair.getSecond());
cveDB.commit();
properties.save(filePair.getNvdCveInfo());
} catch (FileNotFoundException ex) {
throw new UpdateException(ex);
} catch (ParserConfigurationException ex) {
throw new UpdateException(ex);
} catch (SAXException ex) {
throw new UpdateException(ex);
} catch (IOException ex) {
throw new UpdateException(ex);
} catch (SQLException ex) {
throw new UpdateException(ex);
} catch (DatabaseException ex) {
throw new UpdateException(ex);
} catch (ClassNotFoundException ex) {
throw new UpdateException(ex);
} finally {
filePair.cleanup();
}
msg = String.format("Processing Complete for NVD CVE - %s", filePair.getNvdCveInfo().getId());
Logger.getLogger(StandardUpdate.class.getName()).log(Level.INFO, msg);
}
}
|
package org.owasp.dependencycheck.analyzer;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.data.cpe.BaseIndexTestCase;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.Settings;
/**
*
* @author Jeremy Long (jeremy.long@owasp.org)
*/
public class ArchiveAnalyzerTest extends BaseIndexTestCase {
public ArchiveAnalyzerTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() throws Exception {
super.setUp();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of getSupportedExtensions method, of class ArchiveAnalyzer.
*/
@Test
public void testGetSupportedExtensions() {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
Set expResult = new HashSet<String>();
expResult.add("zip");
expResult.add("war");
expResult.add("ear");
expResult.add("tar");
expResult.add("gz");
expResult.add("tgz");
Set result = instance.getSupportedExtensions();
assertEquals(expResult, result);
}
/**
* Test of getName method, of class ArchiveAnalyzer.
*/
@Test
public void testGetName() {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
String expResult = "Archive Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
}
/**
* Test of supportsExtension method, of class ArchiveAnalyzer.
*/
@Test
public void testSupportsExtension() {
String extension = "7z"; //not supported
ArchiveAnalyzer instance = new ArchiveAnalyzer();
boolean expResult = false;
boolean result = instance.supportsExtension(extension);
assertEquals(expResult, result);
extension = "war"; //supported
expResult = true;
result = instance.supportsExtension(extension);
assertEquals(expResult, result);
extension = "ear"; //supported
result = instance.supportsExtension(extension);
assertEquals(expResult, result);
extension = "zip"; //supported
result = instance.supportsExtension(extension);
assertEquals(expResult, result);
}
/**
* Test of getAnalysisPhase method, of class ArchiveAnalyzer.
*/
@Test
public void testGetAnalysisPhase() {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
AnalysisPhase expResult = AnalysisPhase.INITIAL;
AnalysisPhase result = instance.getAnalysisPhase();
assertEquals(expResult, result);
}
/**
* Test of initialize and close methods, of class ArchiveAnalyzer.
*/
@Test
public void testInitialize() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initialize();
instance.close();
//no exception means things worked.
}
/**
* Test of analyze method, of class ArchiveAnalyzer.
*/
@Test
public void testAnalyze() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
try {
instance.initialize();
File file = new File(this.getClass().getClassLoader().getResource("daytrader-ear-2.1.7.ear").getPath());
Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine engine = new Engine();
int initial_size = engine.getDependencies().size();
instance.analyze(dependency, engine);
int ending_size = engine.getDependencies().size();
assertTrue(initial_size < ending_size);
} finally {
instance.close();
}
}
/**
* Test of analyze method, of class ArchiveAnalyzer.
*/
@Test
public void testAnalyzeTar() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
try {
instance.initialize();
File file = new File(this.getClass().getClassLoader().getResource("file.tar").getPath());
Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine engine = new Engine();
int initial_size = engine.getDependencies().size();
instance.analyze(dependency, engine);
int ending_size = engine.getDependencies().size();
assertTrue(initial_size < ending_size);
} finally {
instance.close();
}
}
/**
* Test of analyze method, of class ArchiveAnalyzer.
*/
@Test
public void testAnalyzeTarGz() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
try {
instance.initialize();
File file = new File(this.getClass().getClassLoader().getResource("file.tar.gz").getPath());
//Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine engine = new Engine();
int initial_size = engine.getDependencies().size();
//instance.analyze(dependency, engine);
engine.scan(file);
engine.analyzeDependencies();
int ending_size = engine.getDependencies().size();
assertTrue(initial_size < ending_size);
} finally {
instance.close();
}
}
/**
* Test of analyze method, of class ArchiveAnalyzer.
*/
@Test
public void testAnalyzeTgz() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
try {
instance.initialize();
File file = new File(this.getClass().getClassLoader().getResource("file.tgz").getPath());
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine engine = new Engine();
int initial_size = engine.getDependencies().size();
engine.scan(file);
engine.analyzeDependencies();
int ending_size = engine.getDependencies().size();
assertTrue(initial_size < ending_size);
} finally {
instance.close();
}
}
/**
* Test of analyze method, of class ArchiveAnalyzer.
*/
@Test
public void testAnalyze_badZip() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
try {
instance.initialize();
File file = new File(this.getClass().getClassLoader().getResource("test.zip").getPath());
Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine engine = new Engine();
int initial_size = engine.getDependencies().size();
// boolean failed = false;
// try {
instance.analyze(dependency, engine);
// } catch (java.lang.UnsupportedClassVersionError ex) {
// failed = true;
// assertTrue(failed);
int ending_size = engine.getDependencies().size();
assertEquals(initial_size, ending_size);
} finally {
instance.close();
}
}
}
|
package com.sdl.delivery.ish.webapp.module.providers;
import com.google.common.io.Files;
import com.sdl.web.api.content.BinaryContentRetriever;
import com.sdl.web.api.meta.WebComponentMetaFactory;
import com.sdl.web.api.meta.WebComponentMetaFactoryImpl;
import com.sdl.webapp.common.api.WebRequestContext;
import com.sdl.webapp.common.api.content.ContentProviderException;
import com.sdl.webapp.common.api.localization.Localization;
import com.sdl.webapp.common.api.model.PageModel;
import com.sdl.webapp.common.util.LocalizationUtils;
import com.sdl.webapp.common.util.TcmUtils;
import com.sdl.webapp.tridion.mapping.DefaultContentProvider;
import com.sdl.webapp.tridion.mapping.ModelBuilderPipeline;
import com.tridion.data.BinaryData;
import com.tridion.meta.ComponentMeta;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dd4t.contentmodel.impl.PageImpl;
import org.dd4t.core.exceptions.FactoryException;
import org.dd4t.core.exceptions.ItemNotFoundException;
import org.dd4t.core.factories.PageFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import java.io.File;
import java.io.IOException;
import static com.sdl.webapp.common.util.LocalizationUtils.findPageByPath;
import static org.dd4t.core.util.TCMURI.Namespace;
/**
* Dita content provider.
*/
@Component
@Slf4j
@Primary
public class DitaContentProvider extends DefaultContentProvider {
private static final String STATIC_FILES_DIR = "BinaryData";
@Autowired
private PageFactory dd4tPageFactory;
@Autowired
private BinaryContentRetriever binaryContentRetriever;
@Autowired
private ModelBuilderPipeline modelBuilderPipeline;
@Autowired
private WebRequestContext webRequestContext;
@Autowired
private WebApplicationContext webApplicationContext;
/**
* Get a page model by it's item id.
*
* @param pageId The page id
* @param localization Localization
* @return
* @throws ContentProviderException
*/
@Override
public PageModel getPageModel(final String pageId, final Localization localization)
throws ContentProviderException {
return findPageByPath(pageId, localization, new LocalizationUtils.TryFindPage<PageModel>() {
public PageModel tryFindPage(String path, int publicationId) throws ContentProviderException {
final org.dd4t.contentmodel.Page genericPage;
try {
Namespace namespace = Namespace.valueOf(localization.getCmUriScheme().toUpperCase());
String cmId = TcmUtils.buildCmUri(namespace, Integer.toString(publicationId), pageId, "16");
String source = dd4tPageFactory.findSourcePageByTcmId(cmId);
if (source != null) {
genericPage = dd4tPageFactory.deserialize(source, PageImpl.class);
} else {
return null;
}
} catch (ItemNotFoundException e) {
log.debug("Page not found: [{}] {}", publicationId, path, e);
return null;
} catch (FactoryException e) {
throw new ContentProviderException("Exception while getting page model for: [" + publicationId +
"] " + path, e);
}
PageModel pageModel = modelBuilderPipeline.createPageModel(genericPage, localization,
DitaContentProvider.this);
if (pageModel != null) {
pageModel.setUrl(LocalizationUtils.stripDefaultExtension(path));
webRequestContext.setPage(pageModel);
}
return pageModel;
}
});
}
public byte[] getBinaryContent(final Integer pageId, final Integer binaryId) throws ContentProviderException {
WebComponentMetaFactory factory = new WebComponentMetaFactoryImpl(pageId);
ComponentMeta componentMeta = factory.getMeta(binaryId);
if (componentMeta == null) {
throw new BinaryNotFoundException("No meta meta found for: [" + pageId + "-" + binaryId + "]");
}
String parentDir = StringUtils.join(new String[]{
webApplicationContext.getServletContext().getRealPath("/"), STATIC_FILES_DIR, pageId.toString()
}, File.separator);
File file = new File(parentDir, binaryId.toString());
long componentTime = componentMeta.getLastPublicationDate().getTime();
byte[] data;
if (isToBeRefreshed(file, componentTime)) {
data = getBinaryFromContentService(pageId, binaryId);
try {
Files.write(data, file);
} catch (IOException e) {
log.error("Unable to write local file: " + file.getAbsolutePath(), e);
}
} else {
try {
data = Files.toByteArray(file);
} catch (IOException e) {
throw new BinaryNotFoundException("Unable to read locally stored file: " + file.getAbsolutePath(), e);
}
}
return data;
}
private byte[] getBinaryFromContentService(Integer pageId, Integer binaryId) throws ContentProviderException {
BinaryData data = binaryContentRetriever.getBinary(pageId, binaryId);
if (data == null) {
throw new BinaryNotFoundException("Unable to retrieve binary from content service");
}
try {
return data.getBytes();
} catch (IOException e) {
throw new ContentProviderException("Unable to extract data from BinaryData object", e);
}
}
}
|
package org.jboss.as.domain.management.security;
import org.jboss.as.domain.management.ModelDescriptionConstants;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
public class KeystoreAttributes {
public static final SimpleAttributeDefinition ALIAS = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.ALIAS,
ModelType.STRING, true).setXmlName(ModelDescriptionConstants.ALIAS)
.setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true))
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).build();
public static final SimpleAttributeDefinition KEY_PASSWORD = new SimpleAttributeDefinitionBuilder(
ModelDescriptionConstants.KEY_PASSWORD, ModelType.STRING, true).setXmlName(ModelDescriptionConstants.KEY_PASSWORD)
.setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)).setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).build();
public static final SimpleAttributeDefinition KEYSTORE_PASSWORD = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.KEYSTORE_PASSWORD, ModelType.STRING, false)
.setXmlName(ModelDescriptionConstants.KEYSTORE_PASSWORD).setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)).setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).build();
public static final SimpleAttributeDefinition KEYSTORE_PATH = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.KEYSTORE_PATH, ModelType.STRING, true)
.setXmlName(ModelDescriptionConstants.PATH)
.setAllowExpression(true)
.setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true))
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).build();
public static final SimpleAttributeDefinition KEYSTORE_RELATIVE_TO = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.KEYSTORE_RELATIVE_TO, ModelType.STRING, true)
.setXmlName(ModelDescriptionConstants.RELATIVE_TO).setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, false))
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).build();
public static final SimpleAttributeDefinition KEYSTORE_PROVIDER = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.KEYSTORE_PROVIDER, ModelType.STRING, true)
.setXmlName(ModelDescriptionConstants.PROVIDER)
.setDefaultValue(new ModelNode(ModelDescriptionConstants.JKS))
.setAllowExpression(true)
.setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true))
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
public static final SimpleAttributeDefinition GENERATE_SELF_SIGNED_CERTIFICATE_HOST = new SimpleAttributeDefinitionBuilder(org.jboss.as.controller.descriptions.ModelDescriptionConstants.GENERATE_SELF_SIGNED_CERTIFICATE_HOST, ModelType.STRING, true)
.setAllowExpression(true)
.setAllowNull(true)
.setRequires(ModelDescriptionConstants.KEY_PASSWORD)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
/** Prevent instantiation */
private KeystoreAttributes() {}
}
|
package org.apache.tinkerpop.gremlin.orientdb.gremlintest;
import static java.util.Arrays.asList;
import static org.junit.Assume.assumeFalse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.AbstractGraphProvider;
import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.orientdb.OrientEdge;
import org.apache.tinkerpop.gremlin.orientdb.OrientElement;
import org.apache.tinkerpop.gremlin.orientdb.OrientGraph;
import org.apache.tinkerpop.gremlin.orientdb.OrientProperty;
import org.apache.tinkerpop.gremlin.orientdb.OrientVertex;
import org.apache.tinkerpop.gremlin.orientdb.OrientVertexProperty;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.FeatureSupportTest.GraphFunctionalityTest;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.GraphTest;
import org.apache.tinkerpop.gremlin.structure.SerializationTest.GryoTest;
import org.junit.AssumptionViolatedException;
import com.google.common.collect.Sets;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
public class OrientGraphProvider extends AbstractGraphProvider {
static {
File buildDir = new File("target/builddir");
buildDir.mkdirs();
System.setProperty("build.dir", buildDir.getAbsolutePath());
}
private static final Map<Class<?>, List<String>> IGNORED_TESTS;
static {
IGNORED_TESTS = new HashMap<>();
IGNORED_TESTS.put(GraphTest.class, asList(
"shouldNotMixTypesForGettingSpecificEdgesWithStringFirst",
"shouldNotMixTypesForGettingSpecificEdgesWithEdgeFirst",
"shouldNotMixTypesForGettingSpecificVerticesWithStringFirst",
"shouldNotMixTypesForGettingSpecificVerticesWithVertexFirst"));
// OrientDB can not modify schema when the transaction is on, which
// break the tests
IGNORED_TESTS.put(GraphFunctionalityTest.class, asList("shouldSupportTransactionsIfAGraphConstructsATx"));
//This tests become broken after gremlin 3.2.0
IGNORED_TESTS.put(GryoTest.class, asList("shouldSerializeTree"));
}
@Override
public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName, LoadGraphWith.GraphData loadGraphWith) {
if (IGNORED_TESTS.containsKey(test) && IGNORED_TESTS.get(test).contains(testMethodName))
throw new AssumptionViolatedException("We allow mixed ids");
HashMap<String, Object> configs = new HashMap<String, Object>();
configs.put(Graph.GRAPH, OrientGraph.class.getName());
configs.put("name", graphName);
if (testMethodName.equals("shouldPersistDataOnClose"))
configs.put(OrientGraph.CONFIG_URL, "memory:test-" + graphName + "-" + test.getSimpleName() + "-" + testMethodName);
Random random = new Random();
if (random.nextBoolean())
configs.put(OrientGraph.CONFIG_POOL_SIZE, random.nextInt(10) + 1);
return configs;
}
@SuppressWarnings({ "rawtypes" })
@Override
public Set<Class> getImplementations() {
return Sets.newHashSet(
OrientEdge.class,
OrientElement.class,
OrientGraph.class,
OrientProperty.class,
OrientVertex.class,
OrientVertexProperty.class);
}
@Override
public void clear(Graph graph, Configuration configuration) throws Exception {
if (graph != null)
graph.close();
}
@Override
public Graph openTestGraph(Configuration config) {
if (config.getString("name").equals("readGraph"))
// FIXME eventually ne need to get ride of this
assumeFalse("there is some technical limitation on orientDB that makes tests enter in an infinite loop when reading and writing to orientDB", true);
return super.openTestGraph(config);
}
@Override
public ORID convertId(Object id, Class<? extends Element> c) {
if (id instanceof Number) {
long numericId = ((Number) id).longValue();
return new ORecordId(new Random(numericId).nextInt(32767), numericId);
}
if (id instanceof String) {
Integer numericId;
try {
numericId = new Integer(id.toString());
} catch (NumberFormatException e) {
return new MockORID("Invalid id: " + id + " for " + c);
}
return new ORecordId(numericId, numericId.longValue());
}
return new MockORID("Invalid id: " + id + " for " + c);
}
}
|
package org.jeasy.batch.jdbc;
import org.jeasy.batch.core.mapper.BeanIntrospectionException;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import static java.lang.String.format;
/**
* A prepared statement provider that prepares a statement by introspecting record fields.
*
* @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*/
public class BeanPropertiesPreparedStatementProvider implements PreparedStatementProvider {
private String[] properties;
private PropertyDescriptor[] propertyDescriptors;
private final Map<Class<?>, Integer> javaTypesToSqlTypes = new HashMap<Class<?>, Integer>() {{
put(boolean.class, Types.BOOLEAN);
put(Boolean.class, Types.BOOLEAN);
put(byte.class, Types.TINYINT);
put(Byte.class, Types.TINYINT);
put(short.class, Types.SMALLINT);
put(Short.class, Types.SMALLINT);
put(int.class, Types.INTEGER);
put(Integer.class, Types.INTEGER);
put(long.class, Types.BIGINT);
put(Long.class, Types.BIGINT);
put(BigInteger.class, Types.BIGINT);
put(float.class, Types.FLOAT);
put(Float.class, Types.FLOAT);
put(double.class, Types.DOUBLE);
put(Double.class, Types.DOUBLE);
put(BigDecimal.class, Types.DECIMAL);
put(java.util.Date.class, Types.DATE);
put(java.util.Calendar.class, Types.DATE);
put(java.sql.Date.class, Types.DATE);
put(java.sql.Time.class, Types.TIME);
put(java.sql.Timestamp.class, Types.TIMESTAMP);
put(java.time.LocalDate.class, Types.DATE);
put(java.time.LocalTime.class, Types.TIME);
put(java.time.LocalDateTime.class, Types.TIMESTAMP);
put(java.time.OffsetTime.class, Types.TIME_WITH_TIMEZONE);
put(java.time.OffsetDateTime.class, Types.TIMESTAMP_WITH_TIMEZONE);
put(java.sql.Blob.class, Types.BLOB);
put(java.sql.Clob.class, Types.CLOB);
put(CharSequence.class, Types.VARCHAR);
put(String.class, Types.VARCHAR);
put(StringBuffer.class, Types.VARCHAR);
put(StringBuilder.class, Types.VARCHAR);
}};
/**
* Create a new {@link BeanPropertiesPreparedStatementProvider}.
*
* @param type the record type
* @param properties the properties to set in the statement in that order.
* @throws BeanIntrospectionException when unable to introspect the record type
*/
public BeanPropertiesPreparedStatementProvider(Class<?> type, String... properties) throws BeanIntrospectionException {
this.properties = properties;
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(type);
propertyDescriptors = beanInfo.getPropertyDescriptors();
} catch (IntrospectionException e) {
throw new BeanIntrospectionException("Unable to introspect type " + type, e);
}
}
@Override
public void prepareStatement(PreparedStatement preparedStatement, Object record) throws SQLException {
int index = 1;
for (String property: properties) {
try {
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getName().equals(property)) {
Object value = propertyDescriptor.getReadMethod().invoke(record);
Integer sqlType = javaTypesToSqlTypes.get(value.getClass());
if (sqlType != null) {
preparedStatement.setObject(index++, value, sqlType);
} else {
preparedStatement.setObject(index++, value);
}
break;
}
}
} catch (IllegalAccessException | InvocationTargetException e) {
throw new BeanIntrospectionException(format("Unable to get property %s from type %s", property, record.getClass().getName()), e);
}
}
}
}
|
package dev.game.spacechaos.engine.entity.component.draw;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import dev.game.spacechaos.engine.camera.CameraWrapper;
import dev.game.spacechaos.engine.entity.BaseComponent;
import dev.game.spacechaos.engine.entity.Entity;
import dev.game.spacechaos.engine.entity.IDrawComponent;
import dev.game.spacechaos.engine.entity.component.PositionComponent;
import dev.game.spacechaos.engine.entity.listener.TextureChangedListener;
import dev.game.spacechaos.engine.entity.priority.ECSPriority;
import dev.game.spacechaos.engine.game.BaseGame;
import dev.game.spacechaos.engine.time.GameTime;
import java.util.ArrayList;
import java.util.List;
public class DrawTextureComponent extends BaseComponent implements IDrawComponent {
protected PositionComponent positionComponent = null;
protected List<TextureChangedListener> textureChangedListenerList = new ArrayList<>();
protected Texture texture = null;
protected float originX = 0;
protected float originY = 0;
protected float width = 0;
protected float height = 0;
float scaleX = 1f;
float scaleY = 1f;
float angle = 0;
protected boolean visible = true;
public DrawTextureComponent(Texture texture) {
if (texture == null) {
throw new NullPointerException("texture cannot be null.");
}
if (!texture.isManaged()) {
throw new IllegalStateException("texture isnt loaded.");
}
this.texture = texture;
if (this.texture != null) {
//update dimension
this.width = this.texture.getWidth();
this.height = this.texture.getHeight();
}
}
@Override
public void onInit (BaseGame game, Entity entity) {
this.positionComponent = entity.getComponent(PositionComponent.class);
if (this.positionComponent == null) {
throw new IllegalStateException("entity doesnt have an PositionComponent.");
}
//set new width and height of entity
positionComponent.setDimension(texture.getWidth(), texture.getHeight());
}
@Override public void draw(GameTime time, CameraWrapper camera, SpriteBatch batch) {
//only draw texture, if entity is visible
if (this.visible) {
//draw texture
batch.draw(this.texture,
this.positionComponent.getX() - originX,
this.positionComponent.getY() - originY,
originX,
originY,
getWidth(),
getHeight(),
scaleX,
scaleY,
angle,
0,//srcX
0,//srcY
this.texture.getWidth(),
this.texture.getHeight(),
false,
false
);
}
}
@Override public ECSPriority getDrawOrder() {
return ECSPriority.LOW;
}
public Texture getTexture () {
return this.texture;
}
public void setTexture (Texture texture, boolean setNewDimension) {
Texture oldTexture = this.texture;
this.texture = texture;
if (setNewDimension) {
//update width and height
this.positionComponent.setDimension(texture.getWidth(), texture.getHeight());
if (this.texture != null) {
//update dimension
this.width = this.texture.getWidth();
this.height = this.texture.getHeight();
}
}
this.textureChangedListenerList.stream().forEach(listener -> {
listener.onTextureChanged(oldTexture, this.texture);
});
}
public float getWidth () {
return this.width;
}
public float getHeight () {
return this.height;
}
public boolean isVisible () {
return this.visible;
}
public void setVisible (boolean visible) {
this.visible = visible;
}
public void addTextureChangedListener (TextureChangedListener listener) {
this.textureChangedListenerList.add(listener);
}
public void removeTextureChangedListener (TextureChangedListener listener) {
this.textureChangedListenerList.remove(listener);
}
}
|
package org.ihtsdo.rvf.execution.service;
import java.sql.*;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.naming.ConfigurationException;
import org.apache.commons.dbcp.BasicDataSource;
import org.ihtsdo.rvf.entity.*;
import org.ihtsdo.rvf.execution.service.config.MysqlExecutionConfig;
import org.ihtsdo.rvf.importer.AssertionGroupImporter.ProductName;
import org.ihtsdo.rvf.service.AssertionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class AssertionExecutionService {
private static final String FAILED_TO_FIND_RVF_DB_SCHEMA = "Failed to find rvf db schema for ";
@Autowired
private AssertionService assertionService;
@Resource(name = "dataSource")
private BasicDataSource dataSource;
@Autowired
private RvfDynamicDataSource rvfDynamicDataSource;
@Value("${rvf.qa.result.table.name}")
private String qaResulTableName;
private String deltaTableSuffix = "d";
private String snapshotTableSuffix = "s";
private String fullTableSuffix = "f";
private ExecutorService executorService = Executors.newCachedThreadPool();
private final Logger logger = LoggerFactory.getLogger(AssertionExecutionService.class);
public TestRunItem executeAssertionTest(final AssertionTest assertionTest, final MysqlExecutionConfig config) {
return executeTest(assertionTest.getAssertion(), assertionTest.getTest(), config);
}
public Collection<TestRunItem> executeAssertionTests(final Collection<AssertionTest> assertionTests, final MysqlExecutionConfig config) {
final Collection<TestRunItem> items = new ArrayList<>();
for(final AssertionTest at: assertionTests){
items.add(executeAssertionTest(at, config));
}
return items;
}
public Collection<TestRunItem> executeAssertion(final Assertion assertion, final MysqlExecutionConfig config) {
final Collection<TestRunItem> runItems = new ArrayList<>();
//get tests for given assertion
for(final Test test: assertionService.getTests(assertion))
{
runItems.add(executeTest(assertion, test, config));
}
return runItems;
}
public Collection<TestRunItem> executeAssertions(final Collection<Assertion> assertions, final MysqlExecutionConfig config) {
final Collection<TestRunItem> items = new ArrayList<>();
for(final Assertion assertion : assertions){
items.addAll(executeAssertion(assertion, config));
}
return items;
}
public List<TestRunItem> executeAssertionsConcurrently(List<Assertion> assertions, final MysqlExecutionConfig executionConfig) {
final List<Future<Collection<TestRunItem>>> concurrentTasks = new ArrayList<>();
final List<TestRunItem> results = new ArrayList<>();
int counter = 1;
List<Assertion> batch = null;
for (final Assertion assertion: assertions) {
if (batch == null) {
batch = new ArrayList<Assertion>();
}
batch.add(assertion);
if (counter % 10 == 0 || counter == assertions.size()) {
final List<Assertion> work = batch;
logger.info(String.format("Started executing assertion [%1s] of [%2s]", counter, assertions.size()));
final Future<Collection<TestRunItem>> future = executorService.submit(new Callable<Collection<TestRunItem>>() {
@Override
public Collection<TestRunItem> call() throws Exception {
return executeAssertions(work, executionConfig);
}
});
logger.info(String.format("Finished executing assertion [%1s] of [%2s]", counter, assertions.size()));
//reporting every 10 assertions
concurrentTasks.add(future);
batch = null;
}
counter++;
}
// Wait for all concurrent tasks to finish
for (final Future<Collection<TestRunItem>> concurrentTask : concurrentTasks) {
try {
results.addAll(concurrentTask.get());
} catch (ExecutionException | InterruptedException e) {
logger.error("Thread interrupted while waiting for future result.", e);
}
}
return results;
}
/** Executes an update using statement sql and logs the time taken **/
private int executeUpdateStatement (final Connection connection, final String sql) throws SQLException{
final long startTime = System.currentTimeMillis();
logger.info("Executing {} statement:", sql.replaceAll("\n", " " ).replaceAll("\t", ""));
try (Statement statement = connection.createStatement()) {
//try block will close statement in all circumstances
final int result = statement.executeUpdate(sql);
final long timeTaken = System.currentTimeMillis() - startTime;
logger.info("Completed in {}ms, result = {}", timeTaken, result);
return result;
}
}
public TestRunItem executeTest(final Assertion assertion, final Test test, final MysqlExecutionConfig config) {
long timeStart = System.currentTimeMillis();
logger.debug("Start executing assertion:" + assertion.getUuid());
final TestRunItem runItem = new TestRunItem();
runItem.setTestCategory(assertion.getKeywords());
runItem.setAssertionText(assertion.getAssertionText());
runItem.setAssertionUuid(assertion.getUuid());
runItem.setSeverity(assertion.getSeverity());
// get command from test and validate the included command object
final ExecutionCommand command = test.getCommand();
if (command != null)
{
// execute sql and get result
// create a single connection for entire test and close it after running test - avoid creating too many connections
try (Connection connection = rvfDynamicDataSource.getConnection(config.getProspectiveVersion())) {
executeCommand(assertion, config, command, connection);
long timeEnd = System.currentTimeMillis();
runItem.setRunTime((timeEnd - timeStart));
} catch (final Exception e) {
e.printStackTrace();
logger.warn("Failed to excute command {},Nested exception is : " + e.fillInStackTrace(), command.toString());
runItem.setFailureMessage("Error executing SQL command object Nested exception : " + e.fillInStackTrace());
return runItem;
}
} else {
runItem.setFailureMessage("Test does not have any associated execution command:" + test);
return runItem;
}
logger.info(runItem.toString());
return runItem;
}
private void executeCommand(final Assertion assertion, final MysqlExecutionConfig config,
final ExecutionCommand command, final Connection connection)
throws SQLException, ConfigurationException {
String[] parts = {""};
if (command.getStatements().size() == 0)
{
final String sql = command.getTemplate();
if (sql != null) {
parts = sql.split(";");
}
}else {
parts = command.getStatements().toArray(new String[command.getStatements().size()]);
}
// parse sql to get select statement
final List<String> sqlStatements = transformSql(parts, assertion, config);
for (String sqlStatement: sqlStatements)
{
// remove any leading and train white space
sqlStatement = sqlStatement.trim();
if (sqlStatement.startsWith("call")) {
logger.info("Start calling stored proecure {}", sqlStatement);
try ( CallableStatement cs = connection.prepareCall(sqlStatement)) {
cs.execute();
}
logger.info("End of calling stored proecure {}", sqlStatement);
} else if (sqlStatement.toLowerCase().startsWith("select")){
//TODO need to verify this is required.
logger.info("Select query found:" + sqlStatement);
final Long executionId = config.getExecutionId();
try (PreparedStatement preparedStatement = connection.prepareStatement(sqlStatement)) {
try (ResultSet execResult = preparedStatement.executeQuery()) {
final String insertSQL = "insert into " + qaResulTableName + " (run_id, assertion_id, details) values (?, ?, ?)";
try (Connection qaDbConnecion = dataSource.getConnection()) {
try (PreparedStatement insertStatement = qaDbConnecion.prepareStatement(insertSQL)) {
while(execResult.next())
{
insertStatement.setLong(1, executionId);
insertStatement.setLong(2, assertion.getAssertionId());
insertStatement.setString(3, execResult.getString(3));
insertStatement.addBatch();
}
// execute insert statement
insertStatement.executeBatch();
logger.debug("batch insert completed for assertion:" + assertion.getAssertionText());
}
}
}
}
}
else {
if (sqlStatement.startsWith("create table")){
// only add engine if we do not create using a like statement
if (!(sqlStatement.contains("like") || sqlStatement.contains("as"))) {
sqlStatement = sqlStatement + " ENGINE = MyISAM";
}
}
executeUpdateStatement(connection, sqlStatement);
}
}
}
private List<String> transformSql(String[] parts, Assertion assertion, MysqlExecutionConfig config) throws ConfigurationException {
List<String> result = new ArrayList<>();
String defaultCatalog = dataSource.getDefaultCatalog();
String prospectiveSchema = config.getProspectiveVersion();
final String[] nameParts = config.getProspectiveVersion().split("_");
String moduleId = (nameParts.length >= 2 ? ProductName.toModuleId(nameParts[1]) : "NOT_SUPPLIED");
String version = (nameParts.length >= 3 ? nameParts[2] : "NOT_SUPPLIED");
String previousReleaseSchema = config.getPreviousVersion();
String dependencyReleaseSchema = config.getExtensionDependencyVersion();
//We need both these schemas to exist
if (prospectiveSchema == null) {
throw new ConfigurationException (FAILED_TO_FIND_RVF_DB_SCHEMA + prospectiveSchema);
}
if (config.isReleaseValidation() && !config.isFirstTimeRelease() && previousReleaseSchema == null) {
throw new ConfigurationException (FAILED_TO_FIND_RVF_DB_SCHEMA + previousReleaseSchema);
}
for( String part : parts) {
if ((part.contains("<PREVIOUS>") && previousReleaseSchema == null)
|| (part.contains("<DEPENDENCY>") && dependencyReleaseSchema == null)) {
continue;
}
logger.debug("Original sql statement: {}", part);
// remove all SQL comments - //TODO might throw errors for -- style comments
final Pattern commentPattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL);
part = commentPattern.matcher(part).replaceAll("");
// replace all substitutions for exec
part = part.replaceAll("<RUNID>", String.valueOf(config.getExecutionId()));
part = part.replaceAll("<ASSERTIONUUID>", String.valueOf(assertion.getAssertionId()));
part = part.replaceAll("<MODULEID>", moduleId);
part = part.replaceAll("<VERSION>", version);
// watch out for any 's that users might have introduced
part = part.replaceAll("qa_result", defaultCatalog+ "." + qaResulTableName);
part = part.replaceAll("<PROSPECTIVE>", prospectiveSchema);
part = part.replaceAll("<TEMP>", prospectiveSchema);
if (previousReleaseSchema != null) {
part = part.replaceAll("<PREVIOUS>", previousReleaseSchema);
}
if (dependencyReleaseSchema != null) {
part = part.replaceAll("<DEPENDENCY>", dependencyReleaseSchema);
}
part = part.replaceAll("<DELTA>", deltaTableSuffix);
part = part.replaceAll("<SNAPSHOT>", snapshotTableSuffix);
part = part.replaceAll("<FULL>", fullTableSuffix);
part.trim();
logger.debug("Transformed sql statement: {}", part);
result.add(part);
}
return result;
}
public void setQaResulTableName(final String qaResulTableName) {
this.qaResulTableName = qaResulTableName;
}
}
|
package com.netflix.fabricator.jackson;
import java.util.Properties;
import java.util.Set;
import org.codehaus.jackson.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.netflix.fabricator.ComponentConfiguration;
import com.netflix.fabricator.jackson.JacksonComponentConfiguration;
import com.netflix.fabricator.supplier.ListenableSupplier;
public class JacksonComponentConfiguration implements ComponentConfiguration {
private static Logger LOG = LoggerFactory.getLogger(JacksonComponentConfiguration.class);
public static abstract class StaticListenableSupplier<T> implements ListenableSupplier<T> {
StaticListenableSupplier() {
}
@Override
public void onChange(Function<T, Void> func) {
throw new IllegalStateException("Change notification not supported");
}
}
private final String id;
private final String type;
private final JsonNode node;
public JacksonComponentConfiguration(String id, String type, JsonNode node) {
super();
this.id = id;
this.type = type;
this.node = node;
}
@Override
public String getId() {
return id;
}
@Override
public String getType() {
return type;
}
@Override
public ComponentConfiguration getChild(String name) {
return new JacksonComponentConfiguration(null, null, node.get(name));
}
@Override
public boolean isSimpleProperty(String propertyName) {
JsonNode child = node.get(propertyName);
if (child == null)
return true;
return !child.isObject();
}
@Override
public boolean hasProperty(String propertyName) {
return node.get(propertyName) != null;
}
@Override
public Set<String> getUnknownProperties(Set<String> supportedProperties) {
return null;
}
@Override
public <T> T getValue(String propertyName, Class<T> type) {
Supplier<T> supplier = this.getDynamicValue(propertyName, type);
if (supplier != null)
return supplier.get();
return null;
}
@SuppressWarnings("unchecked")
@Override
public <T> ListenableSupplier<T> getDynamicValue(final String propertyName, Class<T> type) {
if ( String.class.isAssignableFrom(type) ) {
return (ListenableSupplier<T>) new StaticListenableSupplier<String>() {
@Override
public String get() {
JsonNode child = node.get(propertyName);
if (child == null)
return null;
return child.asText();
}
};
}
else if ( Boolean.class.isAssignableFrom(type)
|| Boolean.TYPE.isAssignableFrom(type)
|| boolean.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Boolean>() {
@Override
public Boolean get() {
JsonNode child = node.get(propertyName);
if (child == null)
return null;
return child.asBoolean();
}
};
}
else if ( Integer.class.isAssignableFrom(type)
|| Integer.TYPE.isAssignableFrom(type)
|| int.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Integer>() {
@Override
public Integer get() {
JsonNode child = node.get(propertyName);
if (child == null)
return null;
return child.asInt();
}
};
}
else if ( Long.class.isAssignableFrom(type)
|| Long.TYPE.isAssignableFrom(type)
|| long.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Long>() {
@Override
public Long get() {
JsonNode child = node.get(propertyName);
if (child == null)
return null;
return child.asLong();
}
};
}
else if ( Double.class.isAssignableFrom(type)
|| Double.TYPE.isAssignableFrom(type)
|| double.class.equals(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Double>() {
@Override
public Double get() {
JsonNode child = node.get(propertyName);
if (child == null)
return null;
return child.asDouble();
}
};
}
else if ( Properties.class.isAssignableFrom(type)) {
return (ListenableSupplier<T>) new StaticListenableSupplier<Properties>() {
@Override
public Properties get() {
JsonNode child = node.get(propertyName);
if (child == null)
return null;
Properties result = new Properties();
for (String prop : Lists.newArrayList(child.getFieldNames())) {
result.setProperty(prop, child.get(prop).asText());
}
return result;
}
};
}
else {
LOG.warn(String.format("Unknown type '%s' for property '%s'", type.getCanonicalName(), propertyName));
return null;
}
}
@Override
public String toString() {
return "JacksonComponentConfiguration [id=" + id + ", type=" + type
+ ", node=" + node + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((node == null) ? 0 : node.hashCode());
result = prime * result + ((type == null) ? 0 : type.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;
JacksonComponentConfiguration other = (JacksonComponentConfiguration) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (node == null) {
if (other.node != null)
return false;
} else if (!node.equals(other.node))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
|
package org.flymine.dataconversion;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.HashSet;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
import org.intermine.InterMineException;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
import org.intermine.xml.full.ReferenceList;
import org.intermine.xml.full.ItemHelper;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.dataconversion.ItemReader;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.dataconversion.DataTranslator;
import org.intermine.dataconversion.FieldNameAndValue;
import org.intermine.dataconversion.ItemPrefetchDescriptor;
import org.intermine.dataconversion.ItemPrefetchConstraintDynamic;
import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl;
import org.intermine.metadata.Model;
import org.intermine.util.XmlUtil;
import org.apache.log4j.Logger;
/**
* Convert Ensembl data in fulldata Item format conforming to a source OWL definition
* to fulldata Item format conforming to InterMine OWL definition.
*
* @author Wenyan Ji
* @author Richard Smith
* @author Andrew Varley
* @author Mark Woodbridge
*/
public class EnsemblHumanDataTranslator extends DataTranslator
{
protected static final Logger LOG = Logger.getLogger(EnsemblHumanDataTranslator.class);
private Item ensemblDb;
private Reference ensemblRef;
private Item emblDb;
private Reference emblRef;
private Item uniprotDb;
private Reference uniprotRef;
private Item refSeqDb;
private Reference refSeqRef;
private Item hugoDb;
private Reference hugoRef;
private Item genbankDb;
private Reference genbankRef;
private Item gdbDb;
private Reference gdbRef;
private Item unistsDb;
private Reference unistsRef;
private Map supercontigs = new HashMap();
private Map scLocs = new HashMap();
private String orgAbbrev;
private Item organism;
private Reference orgRef;
private Map proteins = new HashMap();
private Map proteinIds = new HashMap();
private Set proteinSynonyms = new HashSet();
private Map chr2Contig = new HashMap();
private Map sc2Contig = new HashMap();
private Map clone2Contig = new HashMap();
private Set chrSet = new HashSet();
private Set scSet = new HashSet();
private Set contigSet = new HashSet();
private Set cloneSet = new HashSet();
private Map seqIdMap = new HashMap();
private Map markerSynonymMap = new HashMap();
/**
* @see DataTranslator#DataTranslator
*/
public EnsemblHumanDataTranslator(ItemReader srcItemReader, Properties mapping, Model srcModel,
Model tgtModel, String orgAbbrev) {
super(srcItemReader, mapping, srcModel, tgtModel);
this.orgAbbrev = orgAbbrev;
}
/**
* @see DataTranslator#translate
*/
public void translate(ItemWriter tgtItemWriter)
throws ObjectStoreException, InterMineException {
tgtItemWriter.store(ItemHelper.convert(getOrganism()));
tgtItemWriter.store(ItemHelper.convert(getEnsemblDb()));
tgtItemWriter.store(ItemHelper.convert(getEmblDb()));
tgtItemWriter.store(ItemHelper.convert(getUniprotDb()));
tgtItemWriter.store(ItemHelper.convert(getHugoDb()));
tgtItemWriter.store(ItemHelper.convert(getRefSeqDb()));
tgtItemWriter.store(ItemHelper.convert(getGenbankDb()));
tgtItemWriter.store(ItemHelper.convert(getGdbDb()));
tgtItemWriter.store(ItemHelper.convert(getUnistsDb()));
super.translate(tgtItemWriter);
Iterator i = proteins.values().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = proteinSynonyms.iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
}
/**
* @see DataTranslator#translateItem
*/
protected Collection translateItem(Item srcItem)
throws ObjectStoreException, InterMineException {
Collection result = new HashSet();
String srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName());
String className = XmlUtil.getFragmentFromURI(srcItem.getClassName());
Collection translated = super.translateItem(srcItem);
if (translated != null) {
for (Iterator i = translated.iterator(); i.hasNext();) {
boolean storeTgtItem = true;
Item tgtItem = (Item) i.next();
if ("karyotype".equals(className)) {
tgtItem.addReference(getOrgRef());
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
if (srcItem.hasReference("seq_region")) {
Item seq = (Item) getSeqItem(srcItem.getReference("seq_region").getRefId());
tgtItem.addReference(new Reference("chromosome",
seq.getIdentifier()));
}
} else if ("exon".equals(className)) {
tgtItem.addReference(getOrgRef());
Item stableId = getStableId("exon", srcItem.getIdentifier(), srcNs);
// <- exon_stable_id.exon
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
}
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
result.add(location);
} else if ("gene".equals(className)) {
tgtItem.addReference(getOrgRef());
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item comment = createComment(srcItem, tgtItem);
if (comment != null) {
result.add(comment);
}
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
result.add(location);
Item anaResult = createAnalysisResult(srcItem, tgtItem); // analysis
result.add(anaResult);
// List comments = getCommentIds(srcItem.getIdentifier(), srcNs);
// if (!comments.isEmpty()) {
// tgtItem.addCollection(new ReferenceList("comments", comments));
// gene organismDbId should be its stable id (or identifier if none)
Item stableId = null;
stableId = getStableId("gene", srcItem.getIdentifier(), srcNs);
// <- gene_stable_id.gene
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "organismDbId");
} else {
tgtItem.addAttribute(new Attribute("organismDbId",
srcItem.getIdentifier()));
}
String identifier = tgtItem.getAttribute("organismDbId").getValue();
result.addAll(setGeneSynonyms(srcItem, tgtItem, srcNs, identifier));
// display_xref
// display_xref.external_db
// if no organismDbId set to be same as identifier
if (!tgtItem.hasAttribute("organismDbId")) {
tgtItem.addAttribute(new Attribute("organismDbId",
tgtItem.getAttribute("identifier").getValue()));
}
} else if ("transcript".equals(className)) {
tgtItem.addReference(getOrgRef());
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item geneRelation = createItem(tgtNs + "SimpleRelation", "");
addReferencedItem(tgtItem, geneRelation, "objects", true, "subject", false);
moveField(srcItem, geneRelation, "gene", "object");
result.add(geneRelation);
// if no identifier set the identifier as name (primary key)
if (!tgtItem.hasAttribute("identifier")) {
Item stableId = getStableId("transcript", srcItem.getIdentifier(), srcNs);
// <- transcript_stable_id.transcript
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
} else {
tgtItem.addAttribute(new Attribute("identifier",
srcItem.getIdentifier()));
}
}
Item location = createLocation(srcItem, tgtItem, true); // seq_region
// seq_region.coord-sys
result.add(location);
} else if ("translation".equals(className)) {
Item protein = getProteinByPrimaryAccession(srcItem, srcNs);
// transcript
// transcript.display_xref
// transcript.display_xref.external_db
if (protein != null && srcItem.hasReference("transcript")) {
String transcriptId = srcItem.getReference("transcript").getRefId();
// transcript
Item transRelation = createItem(tgtNs + "SimpleRelation", "");
transRelation.addReference(new Reference("subject", transcriptId));
addReferencedItem(protein, transRelation, "subjects", true,
"object", false);
result.add(transRelation);
}
storeTgtItem = false;
// stable_ids become syonyms, need ensembl DataSource as source
} else if (className.endsWith("_stable_id")) {
if (className.endsWith("translation_stable_id")) {
storeTgtItem = false;
} else {
tgtItem.addReference(getEnsemblRef());
tgtItem.addAttribute(new Attribute("type", "identifier"));
}
} else if ("repeat_feature".equals(className)) {
tgtItem.addReference(getOrgRef());
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
result.add(createAnalysisResult(srcItem, tgtItem));
// analysis
result.add(createLocation(srcItem, tgtItem, true));
// seq_region
// seq_region.coord_system
promoteField(tgtItem, srcItem, "consensus", "repeat_consensus",
"repeat_consensus");
// repeat_consensus
promoteField(tgtItem, srcItem, "type", "repeat_consensus", "repeat_class");
// repeat_consensus
promoteField(tgtItem, srcItem, "identifier", "repeat_consensus", "repeat_name");
// repeat_consensus
} else if ("marker".equals(className)) {
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Set locations = createLocations(srcItem, tgtItem, srcNs);
// <- marker_feature.marker
// (<- marker_feature.marker).seq_region
// (<- marker_feature.marker).seq_region.coord_system
List locationIds = new ArrayList();
for (Iterator j = locations.iterator(); j.hasNext(); ) {
Item location = (Item) j.next();
locationIds.add(location.getIdentifier());
result.add(location);
}
setNameAttribute(srcItem, tgtItem);
// display_marker_synonym
}
if (storeTgtItem) {
result.add(tgtItem);
}
}
} else if ("marker_synonym".equals(className)) {
Item synonym = getMarkerSynonym(srcItem);
if (synonym != null) {
result.add(synonym);
}
// assembly maps to null but want to create location on a supercontig
} else if ("assembly".equals(className)) {
Item location = createAssemblyLocation(srcItem);
result.add(location);
// seq_region map to null, become Chromosome, Supercontig, Clone and Contig respectively
} else if ("seq_region".equals(className)) {
Item seq = getSeqItem(srcItem.getIdentifier());
seq.addReference(getOrgRef());
result.add(seq);
//simple_feature map to null, become TRNA/CpGIsland depending on analysis_id(logic_name)
} else if ("simple_feature".equals(className)) {
Item simpleFeature = createSimpleFeature(srcItem);
if (simpleFeature.getIdentifier() != null && simpleFeature.getIdentifier() != "") {
result.add(simpleFeature);
result.add(createLocation(srcItem, simpleFeature, true));
result.add(createAnalysisResult(srcItem, simpleFeature));
}
}
return result;
}
/**
* Translate a "located" Item into an Item and a location
* @param srcItem the source Item
* @param tgtItem the target Item (after translation)
* @param srcItemIsChild true if srcItem should be subject of Location
* @throws ObjectStoreException when anything goes wrong.
* @return the location item
*/
protected Item createLocation(Item srcItem, Item tgtItem, boolean srcItemIsChild)
throws ObjectStoreException {
Item location = createItem(tgtNs + "Location", "");
Item seq = new Item();
if (srcItem.hasAttribute("seq_region_start")) {
moveField(srcItem, location, "seq_region_start", "start");
}
if (srcItem.hasAttribute("seq_region_end")) {
moveField(srcItem, location, "seq_region_end", "end");
}
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
if (srcItem.hasAttribute("seq_region_strand")) {
moveField(srcItem, location, "seq_region_strand", "strand");
}
if (srcItem.hasAttribute("phase")) {
moveField(srcItem, location, "phase", "phase");
}
if (srcItem.hasAttribute("end_phase")) {
moveField(srcItem, location, "end_phase", "endPhase");
}
if (srcItem.hasAttribute("ori")) {
moveField(srcItem, location, "ori", "strand");
}
if (srcItem.hasReference("seq_region")) {
String refId = srcItem.getReference("seq_region").getRefId();
seq = (Item) getSeqItem(refId);
}
if (srcItemIsChild) {
addReferencedItem(tgtItem, location, "objects", true, "subject", false);
location.addReference(new Reference("object", seq.getIdentifier()));
} else {
addReferencedItem(tgtItem, location, "subjects", true, "object", false);
location.addReference(new Reference("subject", seq.getIdentifier()));
}
return location;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @param srcNs source namespace
* @throws ObjectStoreException when anything goes wrong.
* @return set of locations
*/
protected Set createLocations(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Set result = new HashSet();
Set constraints = new HashSet();
String value = srcItem.getIdentifier();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + "marker_feature", false));
constraints.add(new FieldNameAndValue("marker", value, true));
Item location = new Item();
for (Iterator i = srcItemReader.getItemsByDescription(constraints).iterator();
i.hasNext(); ) {
Item feature = ItemHelper.convert((org.intermine.model.fulldata.Item) i.next());
location = createLocation(feature, tgtItem, true);
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
}
return result;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @throws ObjectStoreException when anything goes wrong.
*/
protected void setNameAttribute(Item srcItem, Item tgtItem) throws ObjectStoreException {
if (srcItem.hasReference("display_marker_synonym")) {
Item synonym = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("display_marker_synonym").getRefId()));
if (synonym.hasAttribute("name")) {
String name = synonym.getAttribute("name").getValue();
tgtItem.addAttribute(new Attribute("name", name));
}
}
}
/**
* @param srcItem = assembly
* @return location item which reflects the relations between chromosome and contig,
* supercontig and contig, clone and contig
* @throws ObjectStoreException when anything goes wrong.
*/
protected Item createAssemblyLocation(Item srcItem) throws ObjectStoreException {
int start, end, asmStart, cmpStart, asmEnd, cmpEnd;
int contigLength, bioEntityLength, length;
String ori, contigId, bioEntityId;
contigId = srcItem.getReference("cmp_seq_region").getRefId();
bioEntityId = srcItem.getReference("asm_seq_region").getRefId();
Item contig = ItemHelper.convert(srcItemReader.getItemById(contigId));
Item bioEntity = ItemHelper.convert(srcItemReader.getItemById(bioEntityId));
contigLength = Integer.parseInt(contig.getAttribute("length").getValue());
bioEntityLength = Integer.parseInt(bioEntity.getAttribute("length").getValue());
asmStart = Integer.parseInt(srcItem.getAttribute("asm_start").getValue());
cmpStart = Integer.parseInt(srcItem.getAttribute("cmp_start").getValue());
asmEnd = Integer.parseInt(srcItem.getAttribute("asm_end").getValue());
cmpEnd = Integer.parseInt(srcItem.getAttribute("cmp_end").getValue());
ori = srcItem.getAttribute("ori").getValue();
//some occasions in ensembl, e.g. contig AC087365.3.1.104495 ||AC144832.1.1.45226
//Chromosome, Supercontig have shorter length than contig
//need to truncate the longer part
if (contigLength < bioEntityLength) {
length = contigLength;
} else {
length = bioEntityLength;
}
if (ori.equals("1")) {
start = asmStart - cmpStart + 1;
end = start + length - 1;
} else {
if (cmpEnd == length) {
start = asmStart;
end = start + length - 1;
} else {
start = asmStart - (length - cmpEnd);
end = start + length - 1;
}
}
Item location = createItem(tgtNs + "Location", "");
location.addAttribute(new Attribute("start", Integer.toString(start)));
location.addAttribute(new Attribute("end", Integer.toString(end)));
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
location.addAttribute(new Attribute("strand", srcItem.getAttribute("ori").getValue()));
Item seq = new Item();
seq = (Item) getSeqItem(contigId);
location.addReference(new Reference("subject", seq.getIdentifier()));
seq = (Item) getSeqItem(bioEntityId);
location.addReference(new Reference("object", seq.getIdentifier()));
return location;
}
/**
* @param refId = refId for the seq_region
* @return seq item it could be chromosome, supercontig, clone or contig
* @throws ObjectStoreException when anything goes wrong.
*/
protected Item getSeqItem(String refId) throws ObjectStoreException {
Item seq = new Item();
Item seqRegion = ItemHelper.convert(srcItemReader.getItemById(refId));
if (seqIdMap.containsKey(refId)) {
seq = (Item) seqIdMap.get(refId);
} else {
String property = null;
if (seqRegion.hasReference("coord_system")) {
Item coord = ItemHelper.convert(srcItemReader.getItemById(
seqRegion.getReference("coord_system").getRefId()));
if (coord.hasAttribute("name")) {
property = coord.getAttribute("name").getValue();
}
}
if (property != null && property != "") {
String s = (property.substring(0, 1)).toUpperCase().concat(property.substring(1));
seq = createItem(tgtNs + s, "");
if (seqRegion.hasAttribute("name")) {
seq.addAttribute(new Attribute("identifier",
seqRegion.getAttribute("name").getValue()));
}
if (seqRegion.hasAttribute("length")) {
seq.addAttribute(new Attribute("length",
seqRegion.getAttribute("length").getValue()));
}
addReferencedItem(seq, getEnsemblDb(), "evidence", true, "", false);
seqIdMap.put(refId, seq);
}
}
return seq;
}
/**
* Create an AnalysisResult pointed to by tgtItem evidence reference. Move srcItem
* analysis reference and score to new AnalysisResult.
* @param srcItem item in src namespace to move fields from
* @param tgtItem item that will reference AnalysisResult
* @throws ObjectStoreException when anything goes wrong.
* @return new AnalysisResult item
*/
protected Item createAnalysisResult(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Item result = createItem(tgtNs + "ComputationalResult", "");
if (srcItem.hasReference("analysis")) {
moveField(srcItem, result, "analysis", "analysis");
}
if (srcItem.hasAttribute("score")) {
moveField(srcItem, result, "score", "score");
}
result.addReference(getEnsemblRef());
ReferenceList evidence = new ReferenceList("evidence", Arrays.asList(new Object[]
{result.getIdentifier(), getEnsemblDb().getIdentifier()}));
tgtItem.addCollection(evidence);
return result;
}
/**
* Create comment class referenced by Gene item if there is a description field
* in gene
* @param srcItem gene
* @param tgtItem gene
* @throws ObjectStoreException when anything goes wrong.
* @return new comment item
*/
protected Item createComment(Item srcItem, Item tgtItem)
throws ObjectStoreException {
Item comment = null;
if (srcItem.hasAttribute("description")) {
comment = createItem(tgtNs + "Comment", "");
moveField(srcItem, comment, "description", "text");
//comment.addReference(new Reference("subject", srcItem.getIdentifier()));
tgtItem.addReference(new Reference("comment", comment.getIdentifier()));
}
return comment;
}
/**
* Create a simpleFeature item depends on the logic_name attribute in analysis
* will become TRNA, or CpGIsland
* @param srcItem ensembl: simple_feature
* @return new simpleFeature item
* @throws ObjectStoreException when anything goes wrong.
*/
protected Item createSimpleFeature(Item srcItem) throws ObjectStoreException {
Item simpleFeature = new Item();
if (srcItem.hasReference("analysis")) {
Item analysis = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("analysis").getRefId()));
if (analysis.hasAttribute("logic_name")) {
String name = analysis.getAttribute("logic_name").getValue();
if (name.equals("tRNAscan")) {
simpleFeature = createItem(tgtNs + "TRNA", "");
} else if (name.equals("CpG")) {
simpleFeature = createItem(tgtNs + "CpGIsland", "");
} else if (name.equals("Eponine")) {
simpleFeature = createItem(tgtNs + "TranscriptionStartSite", "");
//} else if (name.equals("FirstEF")) {
//5 primer exon and promoter including coding and noncoding
}
simpleFeature.addReference(getOrgRef());
simpleFeature.addAttribute(new Attribute("identifier", srcItem.getIdentifier()));
addReferencedItem(simpleFeature, getEnsemblDb(), "evidence", true, "", false);
}
}
return simpleFeature;
}
/**
* @param Item srcItem = e:translation
* @param String srcNs sourceNamespace
* @return Item for :Protein
* @throws ObjectStoreException if anything goes wrong
*/
private Item getProteinByPrimaryAccession(Item srcItem, String srcNs)
throws ObjectStoreException {
Item protein = createItem(tgtNs + "Protein", "");
Set synonyms = new HashSet();
String value = srcItem.getIdentifier();
String uniprotId = null;
String identifier = null;
String transcriptRefId = null;
if (srcItem.hasReference("transcript")) {
transcriptRefId = srcItem.getReference("transcript").getRefId();
Item transcript = ItemHelper.convert(srcItemReader.getItemById(transcriptRefId));
if (transcript.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader.getItemById(
transcript.getReference("display_xref").getRefId()));
String accession = null;
String dbname = null;
if (xref != null) {
accession = xref.getAttribute("dbprimary_acc").getValue();
Item externalDb = ItemHelper.convert(srcItemReader
.getItemById(xref.getReference("external_db").getRefId()));
if (externalDb != null) {
dbname = externalDb.getAttribute("db_name").getValue();
}
}
if (accession != null && !accession.equals("")
&& dbname != null && !dbname.equals("")) {
if (dbname.equals("Uniprot/SWISSPROT") //Uniprot/SWISSPROT
|| dbname.equals("Uniprot/SPTREMBL")) { // Uniprot/SPTREMBL
uniprotId = accession;
Item synonym = createSynonym(srcItem.getIdentifier(),
"accession", accession, getUniprotRef());
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonyms.add(synonym);
if (xref.hasAttribute("display_label")
&& !xref.getAttribute("display_label").getValue().equals("")) {
identifier = xref.getAttribute("display_label").getValue();
synonym = createSynonym(srcItem.getIdentifier(),
"identifier", identifier, getUniprotRef());
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonyms.add(synonym);
}
}
}
}
}
String primaryAcc = null;
if (uniprotId != null) {
primaryAcc = uniprotId;
} else {
// there was no protein accession so use ensembl stable id
Item stableId = getStableId("translation", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
primaryAcc = stableId.getAttribute("stable_id").getValue();
}
}
Item chosenProtein = (Item) proteins.get(primaryAcc);
if (chosenProtein == null && primaryAcc != null) {
protein.addAttribute(new Attribute("primaryAccession", primaryAcc));
if (identifier != null) {
protein.addAttribute(new Attribute("identifier", identifier));
}
if (transcriptRefId != null) {
protein.addReference(new Reference("transcript", transcriptRefId));
}
addReferencedItem(protein, getEnsemblDb(), "evidence", true, "", false);
// set up additional references/collections
protein.addReference(getOrgRef());
if (srcItem.hasReference("start_exon")) {
protein.addReference(new Reference("startExon",
srcItem.getReference("start_exon").getRefId()));
}
if (srcItem.hasReference("end_exon")) {
protein.addReference(new Reference("endExon",
srcItem.getReference("end_exon").getRefId()));
}
proteins.put(primaryAcc, protein);
proteinSynonyms.addAll(synonyms);
chosenProtein = protein;
}
if (chosenProtein != null) {
proteinIds.put(srcItem.getIdentifier(), chosenProtein.getIdentifier());
} else {
LOG.info("no protein created for translation: " + srcItem.getIdentifier());
}
return chosenProtein;
}
/**
* Find external database accession numbers in ensembl to set as Synonyms
* @param srcItem it in source format ensembl:gene
* @param tgtItem translate item flymine:Gene
* @param srcNs namespace of source model
* @param geneIdentifier use ensembl ENSG??? as geneIdentifier if no hugo identifier presented
* @return a set of Synonyms
* @throws ObjectStoreException if problem retrieving items
*/
protected Set setGeneSynonyms(Item srcItem, Item tgtItem, String srcNs, String geneIdentifier)
throws ObjectStoreException {
// additional gene information is in xref table only accessible via translation
Set synonyms = new HashSet();
if (srcItem.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader
.getItemById(srcItem.getReference("display_xref").getRefId()));
String accession = null;
String dbname = null;
String symbol = null;
if (xref.hasAttribute("dbprimary_acc")) {
accession = xref.getAttribute("dbprimary_acc").getValue();
}
if (xref.hasAttribute("display_label")) {
symbol = xref.getAttribute("display_label").getValue();
}
if (xref.hasReference("external_db")) {
Item externalDb = ItemHelper.convert(srcItemReader
.getItemById(xref.getReference("external_db").getRefId()));
if (externalDb != null) {
dbname = externalDb.getAttribute("db_name").getValue();
}
}
if (accession != null && !accession.equals("")
&& dbname != null && !dbname.equals("")) {
//dbname could be one of HUGO, RefSeq_dna, RefSeq_dna_predicted,
//RefSeq_peptide,RefSeq_peptide_predicted, Uniprot/SWISSPROT Uniprot/SPTREMBL
//HUGO identifier is used as gene Identifier, if no HUGO refed
//then ensembl_stable_id(eg ENSG???????????) used as identifier
Item synonym = new Item();
if (dbname.equals("HUGO")) {
synonym = createSynonym(tgtItem.getIdentifier(),
"symbol", symbol, getHugoRef());
synonyms.add(synonym);
addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false);
synonym = createSynonym(tgtItem.getIdentifier(),
"accession", accession, getHugoRef());
synonyms.add(synonym);
addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false);
tgtItem.addAttribute(new Attribute("identifier", accession));
tgtItem.addAttribute(new Attribute("symbol", symbol));
} else if (dbname.equals("RefSeq_dna") || dbname.equals("RefSeq_dna_predicted")) {
synonym = createSynonym(tgtItem.getIdentifier(),
"accession", accession, getRefSeqRef());
synonyms.add(synonym);
addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false);
tgtItem.addAttribute(new Attribute("accession", accession));
tgtItem.addAttribute(new Attribute("identifier", geneIdentifier));
} else if (dbname.equals("Uniprot/SWISSPROT") ||(dbname.equals("Uniprot/SWISSPROT_predicted")
|| dbname.equals("Uniprot/SPTREMBL") || dbname.equals("Uniprot/SPTREMBL_predicted")
|| dbname.equals("RefSeq_peptide") || dbname.equals("RefSeq_peptide_predicted")) {
tgtItem.addAttribute(new Attribute("identifier", geneIdentifier));
}
}
}
return synonyms;
}
/**
* Find stable_id for various ensembl type
* @param ensemblType could be gene, exon, transcript or translation
* it should be part of name before _stable_id
* @param identifier srcItem identifier, srcItem could be gene, exon, transcript/translation
* @param srcNs namespace of source model
* @return a set of Synonyms
* @throws ObjectStoreException if problem retrieving items
*/
private Item getStableId(String ensemblType, String identifier, String srcNs) throws
ObjectStoreException {
String value = identifier;
Set constraints = new HashSet();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + ensemblType + "_stable_id", false));
constraints.add(new FieldNameAndValue(ensemblType, value, true));
Iterator stableIds = srcItemReader.getItemsByDescription(constraints).iterator();
if (stableIds.hasNext()) {
return ItemHelper.convert((org.intermine.model.fulldata.Item) stableIds.next());
} else {
return null;
}
}
/**
* Create synonym item
* @param subjectId = synonym reference to subject
* @param type = synonym type
* @param value = synonym value
* @param ref = synonym reference to source
* @return synonym item
*/
private Item createSynonym(String subjectId, String type, String value, Reference ref) {
Item synonym = createItem(tgtNs + "Synonym", "");
synonym.addReference(new Reference("subject", subjectId));
synonym.addAttribute(new Attribute("type", type));
synonym.addAttribute(new Attribute("value", value));
synonym.addReference(ref);
return synonym;
}
/**
* Create synonym item for marker
* @param srcItem = marker_synonym
* marker_synonym in ensembl may have same marker_id, source and name
* but with different marker_synonym_id,
* check before create synonym
* @return synonym item
*/
private Item getMarkerSynonym(Item srcItem) {
Item synonym = new Item();
String subjectId = srcItem.getReference("marker").getRefId();
Set synonymSet = new HashSet();
synonymSet = (HashSet) markerSynonymMap.get(subjectId);
String value = srcItem.getAttribute("name").getValue();
Reference ref = new Reference();
if (srcItem.hasAttribute("source")) {
String source = srcItem.getAttribute("source").getValue();
if (source.equals("genbank")) {
ref = getGenbankRef();
} else if (source.equals("gdb")) {
ref = getGdbRef();
} else if (source.equals("unists")) {
ref = getUnistsRef();
} else {
ref = getEnsemblRef();
}
} else {
ref = getEnsemblRef();
}
int createItem = 1;
int flag;
if (synonymSet == null) {
synonym = createSynonym(subjectId, "identifier", value, ref);
synonymSet = new HashSet(Arrays.asList(new Object[] {synonym}));
markerSynonymMap.put(subjectId, synonymSet);
} else {
Iterator i = synonymSet.iterator();
while (i.hasNext()) {
Item item = (Item) i.next();
if (item.getReference("source").getRefId().equals(ref.getRefId())
&& item.getAttribute("value").getValue().equalsIgnoreCase(value)) {
flag = 0;
} else {
flag = 1;
}
createItem = createItem * flag;
}
if (createItem == 1) {
synonym = createSynonym(subjectId, "identifier", value, ref);
synonymSet.add(synonym);
markerSynonymMap.put(subjectId, synonymSet);
} else {
synonym = null;
}
}
return synonym;
}
/**
* change description class to comments
* @param identifier ensembl:gene srcItem identifier
* @param tgtItem translate item flymine:Gene
* @param srcNs namespace of source model
* @return a list of commentIds
* @throws ObjectStoreException if problem retrieving items
*/
//not suitable for homo_sapiens_core_31_35d
// private List getCommentIds(String identifier, String srcNs) throws
// ObjectStoreException {
// String value = identifier;
// Set constraints = new HashSet();
// constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
// srcNs + "gene_description", false));
// constraints.add(new FieldNameAndValue("gene", value, true));
// List commentIds = new ArrayList();
// for (Iterator i = srcItemReader.getItemsByDescription(constraints).iterator();
// i.hasNext(); ) {
// Item comment = ItemHelper.convert((org.intermine.model.fulldata.Item) i.next());
// commentIds.add((String) comment.getIdentifier());
// return commentIds;
/**
* set database object
* @return db item
*/
private Item getEnsemblDb() {
if (ensemblDb == null) {
ensemblDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "ensembl");
Attribute url = new Attribute("url", "http:
ensemblDb.addAttribute(title);
ensemblDb.addAttribute(url);
}
return ensemblDb;
}
/**
* @return db reference
*/
private Reference getEnsemblRef() {
if (ensemblRef == null) {
ensemblRef = new Reference("source", getEnsemblDb().getIdentifier());
}
return ensemblRef;
}
/**
* set database object
* @return db item
*/
private Item getEmblDb() {
if (emblDb == null) {
emblDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "embl");
Attribute url = new Attribute("url", "http:
emblDb.addAttribute(title);
emblDb.addAttribute(url);
}
return emblDb;
}
/**
* @return db reference
*/
private Reference getEmblRef() {
if (emblRef == null) {
emblRef = new Reference("source", getEmblDb().getIdentifier());
}
return emblRef;
}
/**
* set database object
* @return db item
*/
private Item getUniprotDb() {
if (uniprotDb == null) {
uniprotDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "UniProt");
Attribute url = new Attribute("url", "http:
uniprotDb.addAttribute(title);
uniprotDb.addAttribute(url);
}
return uniprotDb;
}
/**
* @return db reference
*/
private Reference getUniprotRef() {
if (uniprotRef == null) {
uniprotRef = new Reference("source", getUniprotDb().getIdentifier());
}
return uniprotRef;
}
/**
* set database object
* @return db item
*/
private Item getRefSeqDb() {
if (refSeqDb == null) {
refSeqDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "RefSeq");
Attribute url = new Attribute("url", "http:
refSeqDb.addAttribute(title);
refSeqDb.addAttribute(url);
}
return refSeqDb;
}
/**
* @return db reference
*/
private Reference getRefSeqRef() {
if (refSeqRef == null) {
refSeqRef = new Reference("source", getRefSeqDb().getIdentifier());
}
return refSeqRef;
}
/**
* set database object
* @return db item
*/
private Item getHugoDb() {
if (hugoDb == null) {
hugoDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "HUGO");
Attribute url = new Attribute("url", "http:
hugoDb.addAttribute(title);
hugoDb.addAttribute(url);
}
return hugoDb;
}
/**
* @return db reference
*/
private Reference getHugoRef() {
if (hugoRef == null) {
hugoRef = new Reference("source", getHugoDb().getIdentifier());
}
return hugoRef;
}
/**
* @return db reference
*/
private Reference getGenbankRef() {
if (genbankRef == null) {
genbankRef = new Reference("source", getGenbankDb().getIdentifier());
}
return genbankRef;
}
/**
* set database object
* @return db item
*/
private Item getGenbankDb() {
if (genbankDb == null) {
genbankDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "GenBank");
Attribute url = new Attribute("url", "http:
genbankDb.addAttribute(title);
genbankDb.addAttribute(url);
}
return genbankDb;
}
/**
* @return db reference
*/
private Reference getGdbRef() {
if (gdbRef == null) {
gdbRef = new Reference("source", getGdbDb().getIdentifier());
}
return gdbRef;
}
/**
* set database object
* @return db item
*/
private Item getGdbDb() {
if (gdbDb == null) {
gdbDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "GDB");
Attribute url = new Attribute("url", "http:
gdbDb.addAttribute(title);
gdbDb.addAttribute(url);
}
return gdbDb;
}
/**
* @return db reference
*/
private Reference getUnistsRef() {
if (unistsRef == null) {
unistsRef = new Reference("source", getUnistsDb().getIdentifier());
}
return unistsRef;
}
/**
* set database object
* @return db item
*/
private Item getUnistsDb() {
if (unistsDb == null) {
unistsDb = createItem(tgtNs + "DataSource", "");
Attribute title = new Attribute("name", "UniSTS");
Attribute url = new Attribute("url",
"http:
unistsDb.addAttribute(title);
unistsDb.addAttribute(url);
}
return unistsDb;
}
/**
* @return organism item, for homo_sapiens, abbreviation is HS
*/
private Item getOrganism() {
if (organism == null) {
organism = createItem(tgtNs + "Organism", "");
organism.addAttribute(new Attribute("abbreviation", orgAbbrev));
organism.addAttribute(new Attribute("name", "Homo sapiens"));
organism.addAttribute(new Attribute("shortName", "H.sapiens"));
organism.addAttribute(new Attribute("taxonId", "9606"));
organism.addAttribute(new Attribute("genus", "homo"));
organism.addAttribute(new Attribute("species", "sapiens"));
}
return organism;
}
/**
* @return organism reference
*/
private Reference getOrgRef() {
if (orgRef == null) {
orgRef = new Reference("organism", getOrganism().getIdentifier());
}
return orgRef;
}
/**
* @see DataTranslatorTask#execute
*/
public static Map getPrefetchDescriptors() {
Map paths = new HashMap();
String identifier = ObjectStoreItemPathFollowingImpl.IDENTIFIER;
String classname = ObjectStoreItemPathFollowingImpl.CLASSNAME;
//karyotype
ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("karyotype.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
ItemPrefetchDescriptor desc1 = new ItemPrefetchDescriptor(
"karyotype.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
paths.put("http://www.flymine.org/model/ensembl-human#karyotype",
Collections.singleton(desc));
//exon
Set descSet = new HashSet();
desc = new ItemPrefetchDescriptor("exon <- exon_stable_id.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "exon"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#exon_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("exon.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("exon.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#exon", descSet);
//gene
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("gene <- gene_stable_id.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "gene"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#gene_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("gene.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
//not suitable for homo_sapiens_core_31_35d
//desc = new ItemPrefetchDescriptor("gene <- gene_description.gene");
//desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "gene"));
//desc.addConstraint(new FieldNameAndValue(classname,
// "http://www.flymine.org/model/ensembl-human#gene_description", false));
//descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.display_xref");
desc.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
desc1 = new ItemPrefetchDescriptor("gene.display_xref.external_db");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#gene", descSet);
//transcript
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("transcript <- transcript_stable_id.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "transcript"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#transcript_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic("gene", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("transcript.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#transcript", descSet);
//translation
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("translation <- translation_stable_id.translation");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "translation"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#translation_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("translation.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
descSet.add(desc);
desc1 = new ItemPrefetchDescriptor("translation.transcript.display_xref");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor(
"translation.transcript.display_xref.external_db");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#translation", descSet);
//repeat_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("repeat_feature.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.repeat_consensus");
desc.addConstraint(new ItemPrefetchConstraintDynamic("repeat_consensus", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("repeat_feature.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#repeat_feature", descSet);
//marker
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("marker.display_marker_synonym");
desc.addConstraint(new ItemPrefetchConstraintDynamic("marker_synonym", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("marker <- marker_feature.marker");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "marker"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#marker_feature", false));
desc1 = new ItemPrefetchDescriptor("(<- marker_feature.marker).seq_region");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc2 = new ItemPrefetchDescriptor(
"(<- marker_feature.marker).seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#marker",
Collections.singleton(desc));
//assembly
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("assembly.asm_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("assembly.asm_seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc2);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("assembly.cmp_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc2 = new ItemPrefetchDescriptor("assembly.cmp_seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc2);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#assembly", descSet);
//seq_region
desc = new ItemPrefetchDescriptor("seq_region.coord_system");
desc.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
paths.put("http://www.flymine.org/model/ensembl-human#seq_region",
Collections.singleton(desc));
//simple_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("simple_feature.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("simple_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("simple_feature.seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#simple_feature", descSet);
return paths;
}
}
|
package genecode;
import genecode.gene.Gene;
import genecode.gene.GeneFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
/**
* A full genome.
*
* <p>Instances of this class are the canonical location for all the
* genes in a single "organism". One gene instance may refer to
* another via a handle; however that other gene may, or may not,
* exist within the same genome. I.e. It's possible for one gene to
* depend on another which isn't available to it.
*/
public class Genome
implements Cloneable
{
private static final long serialVersionUID = 87489987234876120L;
/**
* A functional interface which yields a "health" of a genome.
*
* <p>It's worth noting that factoring in the graph size to the
* health function can possibly help in certain scenarios. This is
* because it helps keep the search-space small and penalises the
* genome for getting needlessly large (which can happen with
* array functions). Having the graph size be too much of a
* factor, however, can be counter-productive, as it prevents the
* search-space from being adequately explored...
*/
public static interface Health
{
/**
* The best health value. This is {@code Double.MAX_VALUE}.
*/
public static final double MAX_HEALTH = Double.MAX_VALUE;
/**
* The worst health value. This is zero.
*/
public static final double MIN_HEALTH = 0;
/**
* Get the relative "health" of a genome.
*
* @param genome The genome to get the health of.
*
* @return The relative health of the given genome, never
* {@code Double.NaN}. A larger value is healthier
* than a smaller one. Valid ranges are between
* {@link MIN_HEALTH} and {@link MAX_HEALTH} inclusive.
*/
public double healthOf(final Genome genome);
/**
* Get the context coverage of a genome.
*
* <p>This is the fraction of tested {@link Context}s which the genome
* was able to yield a value for.
*
* @param genome The genome to get the coverage of.
*
* @return The fraction, between {@code 0.0} and {@code 1.0} inclusive.
*/
public double coverage(final Genome genome);
}
/**
* How we uniquely number the genomes.
*/
private static final AtomicLong ourNextId = new AtomicLong();
/**
* How we uniquely number the families.
*/
private static final AtomicLong ourNextFamily = new AtomicLong();
/**
* Our unique ID.
*/
private long myId;
/**
* Our family's unique ID.
*/
private long myFamily;
/**
* Our parent's ID.
*/
private long myParentId;
/**
* Our generation; starting at 1.
*/
private int myGeneration;
/**
* How we create new gene instances.
*/
private final GeneFactory myFactory;
/**
* The maximum allowed genome size.
*/
public final int myMaxSize;
/**
* The maximum allowed mutatioon factor.
*/
public final double myMaxMutationFactor;
/**
* The mapping from handle to gene.
*/
private Map<Gene.Handle,Gene> myGenes;
/**
* All the gene handles.
*/
private List<Gene.Handle> myHandles;
/**
* The gene handles, keyed by return type.
*/
private Map<Class<?>,List<Gene.Handle>> myHandlesByClass;
/**
* The types of our outputs.
*/
private List<Class<?>> myOutputTypes;
/**
* The names of our outputs, of any.
*/
private List<String> myOutputNames;
/**
* The outputs of our genome.
*/
private Gene.Handle[] myOutputs;
/**
* The mutation factor.
*/
private double myMutationFactor;
/**
* CTOR with various sensible defaults.
*
* @param factory How genes can be created for inclusion in the genome.
* @param outputTypes The types of the values which this genome computes.
* @param genes The genes for this genome. The genome takes ownership.
*/
public Genome(final GeneFactory factory,
final List<Class<?>> outputTypes,
final Collection<Gene> genes)
{
this(factory, genes, 100, outputTypes, null, 0.05);
}
/**
* CTOR.
*
* @param factory How genes can be created for inclusion in the genome.
* @param genes The gene for this genome. The genome takes
* ownership of these.
* @param maxSize How many genes we may contain.
* @param outputTypes The types of the values which this genome computes.
* @param maxMutationFactor The maximum mutation factor, between 0.0 and 1.0.
*/
public Genome(final GeneFactory factory,
final Collection<Gene> genes,
final int maxSize,
final List<Class<?>> outputTypes,
final List<String> outputNames,
final double maxMutationFactor)
{
// I am not a number! I am a-- oh wait...
myId = ourNextId .getAndIncrement();
myFamily = ourNextFamily.getAndIncrement();
// If we are newly generated then no parent and we are the
// first generation
myParentId = -1;
myGeneration = 1;
// How we create random genes
myFactory = factory;
// How big we may grow and how much we may mutate
myMaxSize = maxSize;
myMaxMutationFactor = Math.max(0.0, Math.min(1.0, maxMutationFactor));
// All the genes
myGenes = new HashMap<>(genes.size());
genes.forEach(gene -> myGenes.put(gene.getHandle(), gene));
// Handles...
myHandles = new ArrayList<>(myGenes.keySet());
myHandlesByClass = new HashMap<>();
for (Map.Entry<Gene.Handle,Gene> entry : myGenes.entrySet()) {
myHandlesByClass.computeIfAbsent(entry.getValue().getReturnType(),
klass -> new ArrayList<>())
.add(entry.getKey());
}
// Set up our parameter genes
myMutationFactor = Math.random() * myMaxMutationFactor;
// Init all the genes now
myGenes.values().forEach(gene -> gene.init(this));
// And set up the outputs
myOutputTypes =
Collections.unmodifiableList(new ArrayList<>(outputTypes));
final List<String> tweakedOutputNames = new ArrayList<>();
for (int i=0; i < outputTypes.size(); i++) {
tweakedOutputNames.add(
(outputNames != null && i < outputNames.size())
? outputNames.get(i)
: "OUTPUT[" + i + "]"
);
}
myOutputNames =
Collections.unmodifiableList(tweakedOutputNames);
myOutputs = new Gene.Handle[outputTypes.size()];
for (int i=0; i < myOutputs.length; i++) {
myOutputs[i] = pickAnyHandle(myOutputTypes.get(i));
}
}
/**
* The genome's globally unique ID.
*
* @return The ID.
*/
public long getId()
{
return myId;
}
/**
* The genome family's globally unique ID.
*
* @return The family ID.
*/
public long getFamily()
{
return myId;
}
/**
* The genome's parent's ID, if any.
*
* @return The ID of our parent genome, or {@code -1} if we have none.
*/
public long getParentId()
{
return myParentId;
}
/**
* Which generation this genome is from, starting at {@code 1}.
*
* @return Which generation this genome is.
*/
public int getGeneration()
{
return myGeneration;
}
/**
* Pick a handle at random from the genome.
*
* @param klass The return type of the gene.
*
* @return The handle.
*/
public Gene.Handle pickAnyHandle(final Class<?> klass)
{
final List<Gene.Handle> handles =
myHandlesByClass.getOrDefault(klass, Collections.emptyList());
if (handles.isEmpty()) {
return null;
}
else {
return handles.get((int)(Math.random() * handles.size()));
}
}
/**
* Get the gene with the given handle, if any. Do <b>NOT</b>
* retain or mutate the value which you get back.
*
* @param handle The handle of the gene to get.
*
* @return The {@link Gene} for the given handle, or {@code nhll}
* if it does not exist.
*/
public Gene get(final Gene.Handle handle)
{
return myGenes.get(handle);
}
/**
* Get the gene at the given index. Do <b>NOT</b> retain or mutate
* the value which you get back.
*
* @param index The index of the gene to get.
*
* @return The {@link Gene}.
*/
public Gene get(final int index)
{
return get(myHandles.get(index));
}
/**
* Get the gene handle at the given index.
*
* @param index The index of the gene to get.
*
* @return The {@link Gene.Handle}.
*/
public Gene.Handle getHandle(final int index)
{
return myHandles.get(index);
}
/**
* The number of genes in this genome.
*
* @return The number of genes.
*/
public int getGenomeSize()
{
return myHandles.size();
}
/**
* The maximum number of genes in this genome.
*
* @return Then maximum number of genes.
*/
public int getGenomeMaxSize()
{
return myMaxSize;
}
/**
* Get the graph size of this genome. This is the number of nodes
* in all the evaluate trees and the criterion.
*
* @return The number of nodes.
*/
public int getGraphSize()
{
int size = 0;
for (Gene.Handle handle : myOutputs) {
final Gene gene = myGenes.get(handle);
if (gene != null) {
size += gene.getGraphSize(this);
}
}
return size;
}
/**
* The number of outputs which this genome has.
*
* @return The number of outputs.
*/
public int numOutputs()
{
return myOutputs.length;
}
/**
* Get the type of the output for the given index.
*
* @param output The index of the required output.
*
* @return The type of the output.
*
* @throws IndexOutOfBoundsException If the given output was not
* in bounds.
*/
public Class<?> getOutputType(final int output)
{
return myOutputTypes.get(output);
}
/**
* Evaluate the genome in the given context.
*
* @param context The context to evaluate the genome in.
* @param output The index of the output to evaluate.
*
* @return {@code null} if the gene could not be evaluated.
*
* @throws IndexOutOfBoundsException If the given output was not
* in bounds.
*/
public Object evaluate(final Context context, final int output)
throws IndexOutOfBoundsException
{
final Gene gene = myGenes.get(myOutputs[output]);
return (gene == null) ? null : gene.evaluate(context, this);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
return Long.hashCode(myId);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object that)
{
return (that instanceof Genome) && ((Genome)that).myId == myId;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("GENOME[").append(myId).append(']')
.append('{');
sb.append("FAMILY=").append(myFamily);
sb.append(",PARENT_ID=").append(myParentId);
sb.append(",GENERATION=").append(myGeneration);
sb.append(",NUM_GENES=").append(getGenomeSize());
sb.append(",GRAPH_SIZE=").append(getGraphSize());
sb.append(",MUTATION_FACTOR={")
.append(myMutationFactor)
.append("}");
for (int i=0; i < myOutputs.length; i++) {
final Gene gene = myGenes.get(myOutputs[i]);
final String output;
if (gene == null) {
output = "null";
}
else {
output = gene.toString(this);
}
sb.append(',').append(myOutputNames.get(i)).append("={")
.append(output)
.append('}');
}
sb.append('}');
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public Genome clone()
{
try {
final Genome result = (Genome)super.clone();
result.myId = ourNextId.getAndIncrement();
// myFamily is inherited
result.myParentId = myId;
result.myGeneration++;
result.myOutputs = result.myOutputs.clone();
// myOutputTypes is immutable so we can hold the cloned value
result.myGenes = new HashMap<>();
for (Map.Entry<Gene.Handle,Gene> entry : myGenes.entrySet()) {
result.myGenes.put(entry.getKey(), entry.getValue().clone());
}
result.myHandles = new ArrayList<>(result.myGenes.keySet());
result.myHandlesByClass = new HashMap<>();
for (Map.Entry<Class<?>,List<Gene.Handle>> entry :
myHandlesByClass.entrySet())
{
result.myHandlesByClass.put(entry.getKey(),
new ArrayList<>(entry.getValue()));
}
return result;
}
catch (CloneNotSupportedException e) {
// Should not happen
throw new RuntimeException(e);
}
}
/**
* Perform a gene exchange with another Genome instance.
*
* <p>This only affects this instance, not the given one.
*
* @param that The genome to copy from.
*/
public void copyFrom(final Genome that)
{
// Walk the genes in the other genome and possibly pull them
// into ours
for (Map.Entry<Gene.Handle,Gene> entry : that.myGenes.entrySet()) {
// Choose whether we want to take this gene
if (Math.random() > myMutationFactor) {
// Do nothing for this gene
continue;
}
// We're going to take this gene. We need to get a copy
// since we must never share instances between genomes.
final Gene.Handle handle = entry.getKey();
final Gene gene = entry.getValue().clone();
// If we already have this gene then we replace our
// existing copy
if (myGenes.containsKey(handle)) {
myGenes.put(handle, gene);
}
else if (myGenes.isEmpty() ||
Math.random() > (double)getGenomeSize() / myMaxSize)
{
// Copy in the gene directly
myGenes .put(handle, gene);
myHandles .add(handle);
myHandlesByClass.computeIfAbsent(gene.getReturnType(),
klass -> new ArrayList<>())
.add(handle);
}
else {
// Replace an existing gene with this one. First,
// choose a random gene and junk it.
removeRandomGene();
// And then add in the new gene
myGenes .put(handle, gene);
myHandles .add(handle);
myHandlesByClass.computeIfAbsent(gene.getReturnType(),
klass -> new ArrayList<>())
.add(handle);
}
}
}
/**
* Mutate the genome.
*/
public void mutate()
{
// First, mutate the mutation factor
myMutationFactor =
Math.max(
0.0,
Math.min(
myMaxMutationFactor,
myMutationFactor +
(myMaxMutationFactor * 0.1 * (Math.random() - 0.5))
)
);
// Mutate all the genes
myGenes.forEach(
(handle, gene) -> gene.mutate(this,
myMutationFactor)
);
// Possibly insert or remove a random gene
if (Math.random() < myMutationFactor) {
// Which?
if (Math.random() >= 0.5) {
if (!myGenes.isEmpty()) {
removeRandomGene();
}
}
else {
if (myGenes.size() < myMaxSize) {
final Gene gene = myFactory.generate();
gene.init(this);
myGenes .put(gene.getHandle(), gene);
myHandles .add(gene.getHandle());
myHandlesByClass.computeIfAbsent(gene.getReturnType(),
klass -> new ArrayList<>())
.add(gene.getHandle());
}
}
}
}
/**
* Get the graph size for a handle.
*/
private void getGraphHandles(final Gene.Handle handle,
final List<Gene.Handle> dest)
{
final Gene gene = myGenes.get(handle);
if (gene == null) {
dest.add(handle);
}
else {
gene.getGraphHandles(this, dest);
}
}
/**
* Remove a random gene.
*/
private void removeRandomGene()
{
if (!myGenes.isEmpty()) {
final int index = (int)(Math.random() * myHandles.size());
final Gene.Handle handle = myHandles.remove(index);
final Gene gene = myGenes .remove(handle);
myHandlesByClass.getOrDefault(gene.getReturnType(),
Collections.emptyList())
.remove(handle);
}
}
}
|
package io.bitsquare.gui.main.portfolio.pendingtrades.steps;
import io.bitsquare.arbitration.Dispute;
import io.bitsquare.gui.components.TitledGroupBg;
import io.bitsquare.gui.main.help.Help;
import io.bitsquare.gui.main.help.HelpId;
import io.bitsquare.gui.main.portfolio.pendingtrades.PendingTradesViewModel;
import io.bitsquare.gui.popups.Popup;
import io.bitsquare.gui.util.Layout;
import io.bitsquare.trade.Trade;
import javafx.geometry.HPos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import org.bitcoinj.core.*;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Optional;
import static io.bitsquare.gui.util.FormBuilder.*;
public abstract class TradeStepDetailsView extends AnchorPane {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
protected final PendingTradesViewModel model;
protected final GridPane gridPane;
protected int gridRow = 0;
private final BlockChainListener blockChainListener;
private long checkPaymentTimeInBlocks;
protected long openDisputeTimeInBlocks;
protected Label infoLabel;
protected TitledGroupBg infoTitledGroupBg;
protected Button openDisputeButton;
protected Button openSupportTicketButton;
private Trade trade;
private Subscription errorMessageSubscription;
private Subscription disputeStateSubscription;
private Subscription tradePeriodStateSubscription;
// Constructor, Initialisation
public TradeStepDetailsView(PendingTradesViewModel model) {
this.model = model;
AnchorPane.setLeftAnchor(this, 0d);
AnchorPane.setRightAnchor(this, 0d);
AnchorPane.setTopAnchor(this, -10d);
AnchorPane.setBottomAnchor(this, 0d);
gridPane = addGridPane(this);
buildGridEntries();
blockChainListener = new BlockChainListener() {
@Override
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
setDateFromBlocks(block.getHeight());
}
@Override
public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException {
setDateFromBlocks(model.getBestChainHeight());
}
@Override
public boolean isTransactionRelevant(Transaction tx) throws ScriptException {
return false;
}
@Override
public void receiveFromBlock(Transaction tx, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset) throws
VerificationException {
}
@Override
public boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset)
throws VerificationException {
return false;
}
};
}
// That is called at every state change!
public void doActivate() {
trade = model.getTrade();
errorMessageSubscription = EasyBind.subscribe(trade.errorMessageProperty(), newValue -> {
if (newValue != null) {
addErrorLabel();
}
});
disputeStateSubscription = EasyBind.subscribe(trade.disputeStateProperty(), newValue -> {
if (newValue != null) {
updateDisputeState(newValue);
}
});
tradePeriodStateSubscription = EasyBind.subscribe(trade.getTradePeriodStateProperty(), newValue -> {
if (newValue != null) {
updateTradePeriodState(newValue);
}
});
setDateFromBlocks(model.getBestChainHeight());
// first call updateTradePeriodState as there is the dispute button created in case we are in period over time
updateTradePeriodState(trade.getTradePeriodState());
updateDisputeState(trade.getDisputeState());
model.addBlockChainListener(blockChainListener);
}
public void doDeactivate() {
model.removeBlockChainListener(blockChainListener);
if (errorMessageSubscription != null)
errorMessageSubscription.unsubscribe();
if (disputeStateSubscription != null)
disputeStateSubscription.unsubscribe();
if (tradePeriodStateSubscription != null)
tradePeriodStateSubscription.unsubscribe();
if (openDisputeButton != null)
openDisputeButton.setOnAction(null);
if (openSupportTicketButton != null)
openSupportTicketButton.setOnAction(null);
}
protected void disputeInProgress() {
if (openDisputeButton != null)
openDisputeButton.setDisable(true);
addDisputeInfoLabel();
}
protected void addDisputeInfoLabel() {
if (infoLabel == null) {
infoTitledGroupBg = addTitledGroupBg(gridPane, ++gridRow, 1, "Information", Layout.GROUP_DISTANCE);
infoLabel = addMultilineLabel(gridPane, gridRow, Layout.FIRST_ROW_AND_GROUP_DISTANCE);
}
infoLabel.setStyle(" -fx-text-fill: -bs-error-red;");
}
protected void addOpenDisputeButton() {
if (openDisputeButton == null) {
openDisputeButton = addButtonAfterGroup(gridPane, ++gridRow, "Open a dispute with arbitrator");
GridPane.setColumnIndex(openDisputeButton, 0);
GridPane.setHalignment(openDisputeButton, HPos.LEFT);
openDisputeButton.setOnAction(e -> {
openDisputeButton.setDisable(true);
disputeInProgress();
model.dataModel.onOpenDispute();
});
}
}
private void addErrorLabel() {
new Popup().warning(trade.errorMessageProperty().getValue()
+ "\n\nPlease report the problem to your arbitrator. He will forward it to the developers to investigate the problem.\n" +
"After the problem has be analysed you will get back all the funds you paid in.\n" +
"There will be no arbitration fee charged if it was a technical error.").show();
/*if (infoLabel == null) {
infoTitledGroupBg = addTitledGroupBg(gridPane, ++gridRow, 1, "Error", Layout.GROUP_DISTANCE);
infoLabel = addMultilineLabel(gridPane, gridRow, Layout.FIRST_ROW_AND_GROUP_DISTANCE);
}
infoTitledGroupBg.setText("Error message");
infoLabel.setText(trade.errorMessageProperty().getValue()
+ "\n\nPlease report the problem to your arbitrator. He will forward it to the developers to investigate the problem.\n" +
"After the problem has be analysed you will get back all the funds you paid in.\n" +
"There will be no arbitration fee charged if it was a technical error.");
infoLabel.setStyle(" -fx-text-fill: -bs-error-red;");*/
if (openSupportTicketButton == null) {
openSupportTicketButton = addButton(gridPane, ++gridRow, "Request support");
GridPane.setHalignment(openSupportTicketButton, HPos.LEFT);
openSupportTicketButton.setOnAction(e -> model.dataModel.onOpenSupportTicket());
}
}
private void updateDisputeState(Trade.DisputeState disputeState) {
Optional<Dispute> ownDispute = model.dataModel.getDisputeManager().findOwnDispute(trade.getId());
switch (disputeState) {
case NONE:
break;
case DISPUTE_REQUESTED:
disputeInProgress();
ownDispute.ifPresent(dispute -> {
String msg;
if (dispute.isSupportTicket())
msg = "You opened already a support ticket.\n" +
"Please communicate in the support section with the arbitrator.";
else
msg = "You opened already a dispute.\n" +
"Please communicate in the support section with the arbitrator.";
infoLabel.setText(msg);
});
break;
case DISPUTE_STARTED_BY_PEER:
disputeInProgress();
ownDispute.ifPresent(dispute -> {
String msg;
if (dispute.isSupportTicket())
msg = "Your trading peer opened a support ticket due technical problems.\n" +
"Please communicate in the support section with the arbitrator.";
else
msg = "Your trading peer opened a dispute.\n" +
"Please communicate in the support section with the arbitrator.";
infoLabel.setText(msg);
});
break;
case DISPUTE_CLOSED:
break;
}
}
private void updateTradePeriodState(Trade.TradePeriodState tradePeriodState) {
switch (tradePeriodState) {
case NORMAL:
break;
case HALF_REACHED:
displayRequestCheckPayment();
break;
case TRADE_PERIOD_OVER:
displayOpenForDisputeForm();
break;
}
}
private void setDateFromBlocks(long bestBlocKHeight) {
checkPaymentTimeInBlocks = model.getCheckPaymentTimeAsBlockHeight() - bestBlocKHeight;
openDisputeTimeInBlocks = model.getOpenDisputeTimeAsBlockHeight() - bestBlocKHeight;
updateDateFromBlocks(bestBlocKHeight);
}
protected void updateDateFromBlocks(long bestBlocKHeight) {
}
// UI Handlers
protected void onOpenHelp() {
Help.openWindow(model.isOfferer() ? HelpId.PENDING_TRADE_OFFERER : HelpId.PENDING_TRADE_TAKER);
}
// Build view
abstract void buildGridEntries();
protected void displayRequestCheckPayment() {
}
protected void displayOpenForDisputeForm() {
}
}
|
package com.splicemachine.si.data.hbase.coprocessor;
import com.splicemachine.access.HConfiguration;
import com.splicemachine.access.api.DistributedFileSystem;
import com.splicemachine.access.api.SConfiguration;
import com.splicemachine.access.api.PartitionFactory;
import com.splicemachine.concurrent.Clock;
import com.splicemachine.si.api.SIConfigurations;
import com.splicemachine.si.api.data.ExceptionFactory;
import com.splicemachine.si.api.data.OperationFactory;
import com.splicemachine.si.api.data.OperationStatusFactory;
import com.splicemachine.si.api.data.TxnOperationFactory;
import com.splicemachine.si.api.readresolve.KeyedReadResolver;
import com.splicemachine.si.api.readresolve.RollForward;
import com.splicemachine.si.api.txn.KeepAliveScheduler;
import com.splicemachine.si.api.txn.TxnStore;
import com.splicemachine.si.api.txn.TxnSupplier;
import com.splicemachine.si.data.HExceptionFactory;
import com.splicemachine.si.data.hbase.HOperationStatusFactory;
import com.splicemachine.si.impl.*;
import com.splicemachine.si.impl.driver.SIDriver;
import com.splicemachine.si.impl.driver.SIEnvironment;
import com.splicemachine.si.impl.readresolve.SynchronousReadResolver;
import com.splicemachine.si.impl.rollforward.NoopRollForward;
import com.splicemachine.si.impl.store.CompletedTxnCacheSupplier;
import com.splicemachine.si.impl.store.IgnoreTxnCacheSupplier;
import com.splicemachine.storage.*;
import com.splicemachine.timestamp.api.TimestampSource;
import com.splicemachine.timestamp.hbase.ZkTimestampSource;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
public class HBaseSIEnvironment implements SIEnvironment{
private static volatile HBaseSIEnvironment INSTANCE;
private final TimestampSource timestampSource;
private final PartitionFactory<TableName> partitionFactory;
private final TxnStore txnStore;
private final TxnSupplier txnSupplier;
private final IgnoreTxnCacheSupplier ignoreTxnSupplier;
private final TxnOperationFactory txnOpFactory;
private final PartitionInfoCache partitionCache;
private final KeepAliveScheduler keepAlive;
private final SConfiguration config;
private final HOperationFactory opFactory;
private final Clock clock;
private final DistributedFileSystem fileSystem;
private SIDriver siDriver;
public static HBaseSIEnvironment loadEnvironment(Clock clock,RecoverableZooKeeper rzk) throws IOException{
HBaseSIEnvironment env = INSTANCE;
if(env==null){
synchronized(HBaseSIEnvironment.class){
env = INSTANCE;
if(env==null){
env = INSTANCE = new HBaseSIEnvironment(rzk,clock);
}
}
}
return env;
}
public static void setEnvironment(HBaseSIEnvironment siEnv){
INSTANCE = siEnv;
}
public HBaseSIEnvironment(TimestampSource timeSource,Clock clock) throws IOException{
this.config=HConfiguration.INSTANCE;
this.config.addDefaults(StorageConfiguration.defaults);
this.config.addDefaults(SIConfigurations.defaults);
this.timestampSource =timeSource;
this.partitionCache = PartitionCacheService.loadPartitionCache(config);
this.partitionFactory =TableFactoryService.loadTableFactory(clock,this.config,partitionCache);
TxnNetworkLayerFactory txnNetworkLayerFactory= TableFactoryService.loadTxnNetworkLayer(this.config);
this.txnStore = new CoprocessorTxnStore(txnNetworkLayerFactory,timestampSource,null);
int completedTxnCacheSize = config.getInt(SIConfigurations.completedTxnCacheSize);
int completedTxnConcurrency = config.getInt(SIConfigurations.completedTxnConcurrency);
this.txnSupplier = new CompletedTxnCacheSupplier(txnStore,completedTxnCacheSize,completedTxnConcurrency);
this.txnStore.setCache(txnSupplier);
this.opFactory =HOperationFactory.INSTANCE;
this.ignoreTxnSupplier = new IgnoreTxnCacheSupplier(opFactory, partitionFactory);
this.txnOpFactory = new SimpleTxnOperationFactory(exceptionFactory(),opFactory);
this.clock = clock;
this.fileSystem =new HNIOFileSystem(FileSystem.get(((HConfiguration)config).unwrapDelegate()),exceptionFactory());
this.keepAlive = new QueuedKeepAliveScheduler(config.getLong(SIConfigurations.TRANSACTION_KEEP_ALIVE_INTERVAL),
config.getLong(SIConfigurations.TRANSACTION_TIMEOUT),
config.getInt(SIConfigurations.TRANSACTION_KEEP_ALIVE_THREADS),
txnStore);
siDriver = SIDriver.loadDriver(this);
}
@SuppressWarnings("unchecked")
public HBaseSIEnvironment(RecoverableZooKeeper rzk,Clock clock) throws IOException{
this.config=HConfiguration.INSTANCE;
this.config.addDefaults(StorageConfiguration.defaults);
this.config.addDefaults(SIConfigurations.defaults);
this.timestampSource =new ZkTimestampSource(config,rzk);
this.partitionCache = PartitionCacheService.loadPartitionCache(config);
this.partitionFactory =TableFactoryService.loadTableFactory(clock, this.config,partitionCache);
TxnNetworkLayerFactory txnNetworkLayerFactory= TableFactoryService.loadTxnNetworkLayer(this.config);
this.txnStore = new CoprocessorTxnStore(txnNetworkLayerFactory,timestampSource,null);
int completedTxnCacheSize = config.getInt(SIConfigurations.completedTxnCacheSize);
int completedTxnConcurrency = config.getInt(SIConfigurations.completedTxnConcurrency);
this.txnSupplier = new CompletedTxnCacheSupplier(txnStore,completedTxnCacheSize,completedTxnConcurrency);
this.txnStore.setCache(txnSupplier);
this.opFactory =HOperationFactory.INSTANCE;
this.ignoreTxnSupplier = new IgnoreTxnCacheSupplier(opFactory, partitionFactory);
this.txnOpFactory = new SimpleTxnOperationFactory(exceptionFactory(),opFactory);
this.clock = clock;
this.fileSystem =new HNIOFileSystem(FileSystem.get(((HConfiguration)config).unwrapDelegate()),exceptionFactory());
this.keepAlive = new QueuedKeepAliveScheduler(config.getLong(SIConfigurations.TRANSACTION_KEEP_ALIVE_INTERVAL),
config.getLong(SIConfigurations.TRANSACTION_TIMEOUT),
config.getInt(SIConfigurations.TRANSACTION_KEEP_ALIVE_THREADS),
txnStore);
siDriver = SIDriver.loadDriver(this);
}
@Override public PartitionFactory tableFactory(){ return partitionFactory; }
@Override
public ExceptionFactory exceptionFactory(){
return HExceptionFactory.INSTANCE;
}
@Override
public SConfiguration configuration(){
return config;
}
@Override
public TxnStore txnStore(){
return txnStore;
}
@Override
public TxnSupplier txnSupplier(){
return txnSupplier;
}
@Override
public IgnoreTxnCacheSupplier ignoreTxnSupplier(){
return ignoreTxnSupplier;
}
@Override
public OperationStatusFactory statusFactory(){
return HOperationStatusFactory.INSTANCE;
}
@Override
public TimestampSource timestampSource(){
return timestampSource;
}
@Override
public RollForward rollForward(){
return NoopRollForward.INSTANCE;
}
@Override
public TxnOperationFactory operationFactory(){
return txnOpFactory;
}
@Override
public SIDriver getSIDriver(){
return siDriver;
}
@Override
public PartitionInfoCache partitionInfoCache(){
return partitionCache;
}
@Override
public KeepAliveScheduler keepAliveScheduler(){
return keepAlive;
}
@Override
public DataFilterFactory filterFactory(){
return HFilterFactory.INSTANCE;
}
@Override
public Clock systemClock(){
return clock;
}
@Override
public KeyedReadResolver keyedReadResolver(){
return SynchronousReadResolver.INSTANCE;
}
@Override
public DistributedFileSystem fileSystem(){
return fileSystem;
}
@Override
public OperationFactory baseOperationFactory(){
return opFactory;
}
public void setSIDriver(SIDriver siDriver) {
this.siDriver = siDriver;
}
}
|
package com.facebook.imagepipeline.decoder;
import java.util.Collections;
import java.util.List;
import com.facebook.common.internal.Preconditions;
import com.facebook.imagepipeline.image.ImmutableQualityInfo;
import com.facebook.imagepipeline.image.QualityInfo;
/**
* Simple {@link ProgressiveJpegConfig} with predefined scans to decode and good-enough scan number.
*
* <p/> If no specific scans to decode are provided, every scan is allowed to be decoded.
*/
public class SimpleProgressiveJpegConfig implements ProgressiveJpegConfig {
public interface DynamicValueConfig {
List<Integer> getScansToDecode();
int getGoodEnoughScanNumber();
}
private static class DefaultDynamicValueConfig implements DynamicValueConfig {
public List<Integer> getScansToDecode() {
return Collections.EMPTY_LIST;
}
public int getGoodEnoughScanNumber() {
return 0;
}
}
private final DynamicValueConfig mDynamicValueConfig;
public SimpleProgressiveJpegConfig() {
this (new DefaultDynamicValueConfig());
}
public SimpleProgressiveJpegConfig(DynamicValueConfig dynamicValueConfig) {
mDynamicValueConfig = Preconditions.checkNotNull(dynamicValueConfig);
}
@Override
public int getNextScanNumberToDecode(int scanNumber) {
final List<Integer> scansToDecode = mDynamicValueConfig.getScansToDecode();
if (scansToDecode == null || scansToDecode.isEmpty()) {
return scanNumber + 1;
}
for (int i = 0; i < scansToDecode.size(); i++) {
if (scansToDecode.get(i) > scanNumber) {
return scansToDecode.get(i);
}
}
return Integer.MAX_VALUE;
}
@Override
public QualityInfo getQualityInfo(int scanNumber) {
return ImmutableQualityInfo.of(
scanNumber,
/* isOfGoodEnoughQuality */ scanNumber >= mDynamicValueConfig.getGoodEnoughScanNumber(),
/* isOfFullQuality */ false);
}
}
|
package io.quarkus.arc.processor;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
/**
* Base class for configurators that accept a parameter map.
* <p>
* This construct is not thread-safe.
*/
public abstract class ConfiguratorBase<THIS extends ConfiguratorBase<THIS>> {
protected final Map<String, Object> params = new HashMap<>();
@SuppressWarnings("unchecked")
protected THIS self() {
return (THIS) this;
}
public THIS read(ConfiguratorBase<?> base) {
params.clear();
params.putAll(base.params);
return self();
}
public THIS param(String name, boolean value) {
params.put(name, value);
return self();
}
public THIS param(String name, boolean[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, byte value) {
params.put(name, value);
return self();
}
public THIS param(String name, byte[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, short value) {
params.put(name, value);
return self();
}
public THIS param(String name, short[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, int value) {
params.put(name, value);
return self();
}
public THIS param(String name, int[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, long value) {
params.put(name, value);
return self();
}
public THIS param(String name, long[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, float value) {
params.put(name, value);
return self();
}
public THIS param(String name, float[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, double value) {
params.put(name, value);
return self();
}
public THIS param(String name, double[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, char value) {
params.put(name, value);
return self();
}
public THIS param(String name, char[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, String value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, String[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, Enum<?> value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, Enum<?>[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, Class<?> value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, Class<?>[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, ClassInfo value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, ClassInfo[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, AnnotationInstance value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
public THIS param(String name, AnnotationInstance[] value) {
Objects.requireNonNull(value, "Parameter value can't be null");
params.put(name, value);
return self();
}
}
|
package uk.ac.ebi.quickgo.index.annotation.coterms;
import uk.ac.ebi.quickgo.annotation.common.AnnotationDocument;
import com.google.common.base.Preconditions;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;
import org.springframework.batch.item.support.AbstractItemStreamItemWriter;
import static uk.ac.ebi.quickgo.index.annotation.coterms.CoTerm.calculateProbabilityRatio;
import static uk.ac.ebi.quickgo.index.annotation.coterms.CoTerm.calculateSimilarityRatio;
import static uk.ac.ebi.quickgo.index.annotation.coterms.GeneProductBatch.buildBatch;
public class CoTermsAggregationWriter extends AbstractItemStreamItemWriter<AnnotationDocument> {
//A list of all unique geneProducts encountered - it exists so we can get a count of the total unique gene products.
private final Set<String> geneProductList;
//Determines which annotations get processed.
private final Predicate<AnnotationDocument> toBeProcessed;
private final CoTermMatrix coTerms;
private final TermGPCount geneProductCountForTerms;
private GeneProductBatch geneProductBatch;
CoTermsAggregationWriter(Predicate<AnnotationDocument> toBeProcessed) {
Preconditions
.checkArgument(toBeProcessed != null, "Null predicate passed AnnotationCoOccurringTermsAggregator" +
" constructor.");
this.toBeProcessed = toBeProcessed;
this.coTerms = new CoTermMatrix();
this.geneProductList = new HashSet<>();
this.geneProductCountForTerms = new TermGPCount();
this.geneProductBatch = new GeneProductBatch();
}
/**
* For each AnnotationDocument item passed to this method, check whether it passed the criteria for aggregating,
* and if so add its data to the aggregated data.
*
* @param items a list of AnnotationDocuments.
* @throws java.lang.Exception - if there are errors. The framework will catch the exception and convert or
* rethrow it as appropriate.
*/
@Override
public void write(List<? extends AnnotationDocument> items) throws Exception {
Preconditions.checkArgument(items != null, "Null annotation passed to process");
items.stream()
.filter(this.toBeProcessed::test)
.forEach(this::addGOTermToAggregationForGeneProduct);
}
/**
* When all annotation documents have been processed by the write method then an operation wrap up processing is
* required.
*/
@Override
public void close() {
increaseCountsForTermsInBatch();
}
/**
* Provide an iteration of the all GO Terms with a co-occurrence (which will be all GO Terms annotated, since at
* the very least a term is said to coincide with itself).
* @return an iterator over all the GO Terms that have co-occurring terms.
*/
Iterator<String> getCoTermsIterator() {
return this.coTerms.coTermMatrix.keySet().iterator();
}
/**
* Create a CoTermsForSelectedTerm instance for each compared term.
* @param goTerm The GO Term for which the co-occurrence statistics will be calculated.
* @return CoTermsForSelectedTerm instance with co-occurring statistics calculated for every
* co-occurring term.
*/
CoTermsForSelectedTerm createCoTermsForSelectedTerm(String goTerm) {
Preconditions
.checkArgument(null != goTerm, "Target GO term id passed to createCoTermsForSelectedTerm should not " +
"be null");
final long selected = getCountOfGeneProductsForTerm(goTerm);
if(selected == 0){
return CoTermsForSelectedTerm.Builder.empty();
}
CoTermsForSelectedTerm.Builder coTermsBuilder = new CoTermsForSelectedTerm.Builder()
.setTotalNumberOfGeneProducts(getGeneProductTotal())
.setSelected(selected);
for (String comparedTerm : getCoTermsAndCounts(goTerm).keySet()) {
long together = getTogether(goTerm, comparedTerm);
long compared = getCountOfGeneProductsForTerm(comparedTerm);
coTermsBuilder.addCoTerm(new CoTerm.Builder()
.setTarget(goTerm)
.setComparedTerm(comparedTerm)
.setCompared(getCountOfGeneProductsForTerm(comparedTerm))
.setTogether(getTogether(goTerm, comparedTerm))
.setProbabilityRatio(calculateProbabilityRatio(selected, together, getGeneProductTotal(), compared))
.setSimilarityRatio(calculateSimilarityRatio(selected, together, compared))
.setGpCount(selected)
.build());
}
return coTermsBuilder.build();
}
/**
* We hold a count of the number of unique gene products encountered during processing, for each term.
* @param goTerm GO Term account for which we want the gene product count.
* @return count of the number of unique gene products encountered during processing for the request term.
*/
private long getCountOfGeneProductsForTerm(String goTerm) {
final AtomicLong gpCountForTerm = geneProductCountForTerms.id2Count.get(goTerm);
return gpCountForTerm != null ? gpCountForTerm.get():0L;
}
/**
* Number of unique gene products processed from Annotations
* @return unique gene product count
*/
private long getGeneProductTotal() {
return geneProductList.size();
}
/**
* Get a map of all co-occurring terms to co-occurrence count for the target termId.
* @param termId the termId for which the caller should receive all the co-occurring terms plus co-occurrence count.
* @return map of co-occurring terms to co-occurrence count.
*/
private Map<String, AtomicLong> getCoTermsAndCounts(String termId) {
return coTerms.coTermMatrix.get(termId);
}
private long getTogether(String targetTerm, String comparedTerm) {
return coTerms.coTermMatrix.get(targetTerm).get(comparedTerm).get();
}
/**
* Add the data in an AnnotationDocument instance to the aggregation.
* The documents are processed by this class in the gene product order.
* So the first thing to do is check if this doc has a previously unseen gene product id.
* If it doesn't we use the existing aggregation object (newOrExistingBatch instance) to aggregate too.
* If it is a new gene product the we have a new newOrExistingBatch instance created.
* Add the data in this document to the target newOrExistingBatch.
* Add the gene product id to the list of gene product ids that have been processed (we need a list of all gene
* products processed for the statistics calculations at the end of the calculation.
*
* @param doc an AnnotationDocument instance to be added to aggregation.
*/
private void addGOTermToAggregationForGeneProduct(AnnotationDocument doc) {
if (geneProductBatch.geneProduct == null) {
geneProductBatch.geneProduct = doc.geneProductId;
}
if (!doc.geneProductId.equals(geneProductBatch.geneProduct)) {
increaseCountsForTermsInBatch();
geneProductBatch = buildBatch(doc);
} else {
geneProductBatch.addTerm(doc.goId);
}
geneProductList.add(doc.geneProductId); //set so each gp is only added once.
}
/**
* Got to the end of the list of annotations for this gene product
* Record which terms annotate the same gene products.
*/
private void increaseCountsForTermsInBatch() {
for (String termId : geneProductBatch.terms) {
coTerms.incrementCoTerms(termId, geneProductBatch.terms);
geneProductCountForTerms.incrementGeneProductCountForTerm(termId);
}
}
}
/**
* A data bucket for aggregating annotation document data. Each batch is created for all data with the same gene
* product id.
*/
class GeneProductBatch {
//A set of all terms encountered for a Gene Product. Therefore all these terms are co-occurring with each other.
final Set<String> terms;
//The input file has annotations in gene product order, so we use this value to note changes in gene product.
String geneProduct;
GeneProductBatch() {
terms = new HashSet<>();
}
/**
* Create a new GeneProductBatch to aggregate terms for the 'new' gene product id.
* @param doc an AnnotationDocument instance to be added to aggregation.
* @return an instance of GeneProductBatch which will be used to aggregate co-occurring terms annotating the same
* gene product.
*/
static GeneProductBatch buildBatch(AnnotationDocument doc) {
GeneProductBatch geneProductBatch = new GeneProductBatch();
geneProductBatch.geneProduct = doc.geneProductId;
geneProductBatch.addTerm(doc.goId);
return geneProductBatch;
}
/**
* Add this term id to this list of term ids encountered for the gene product that is currently being read.
* @param termId GO Term processed.
*/
void addTerm(String termId) {
terms.add(termId);
}
}
/**
* This class represents a matrix of term to compared term, and its used to hold the number of permutation occurrences.
*/
class CoTermMatrix {
// Key is the target term, the value is a map of all the GO terms that are used in annotations for the same gene
// product. i.e. Key =>target term, value=> map (key=>co-occurring term, value => AtomicLong For Co-occurrence)
// For example key=>'GO:0003824', value=> map(entry 1 :: key=>'GO:0008152' value=>1346183 hits, entry 2
// key=>'GO:0016740' value=>1043613 hits)
final Map<String, Map<String, AtomicLong>> coTermMatrix;
CoTermMatrix() {
coTermMatrix = new TreeMap<>();
}
/**
* For all terms encountered for gene product batch, increment its count. If this is a new {@code termId}, then
* its count is initialised as 1.
* @param termId single term from batch
* @param termsInBatch a list of all terms encountered in annotations for a particular gene product.
*/
void incrementCoTerms(String termId, Set<String> termsInBatch) {
Map<String, AtomicLong> coTerms = coTermMatrix.computeIfAbsent(termId, k -> new HashMap<>());
//Loop through all the terms we have encountered in this batch and update the quantities
for (String term : termsInBatch) {
//Get 'permanent' record for this termId/termId permutation
AtomicLong permutationCount = coTerms.computeIfAbsent(term, k -> new AtomicLong());
//Update it with a count of 'one' as this batch is for one gene protein and so the count must be one
permutationCount.incrementAndGet();
}
}
}
/**
* State for GO termId::count of gene products for it.
*/
class TermGPCount {
final Map<String, AtomicLong> id2Count;
TermGPCount() {
this.id2Count = new HashMap<>();
}
/**
* For every term, increment by one the count of gene products for this term
*/
void incrementGeneProductCountForTerm(String term) {
if (id2Count.putIfAbsent(term, new AtomicLong(1L)) != null) {
id2Count.get(term).incrementAndGet();
}
}
}
|
package com.io7m.jcanephora.renderstate;
import com.io7m.jareas.core.AreaInclusiveUnsignedLType;
import com.io7m.jcanephora.core.JCGLDepthFunction;
import com.io7m.jcanephora.core.JCGLFaceSelection;
import com.io7m.jcanephora.core.api.JCGLBlendingType;
import com.io7m.jcanephora.core.api.JCGLColorBufferMaskingType;
import com.io7m.jcanephora.core.api.JCGLCullingType;
import com.io7m.jcanephora.core.api.JCGLDepthBuffersType;
import com.io7m.jcanephora.core.api.JCGLInterfaceGL33Type;
import com.io7m.jcanephora.core.api.JCGLScissorType;
import com.io7m.jcanephora.core.api.JCGLStencilBuffersType;
import com.io7m.jnull.NullCheck;
import com.io7m.junreachable.UnreachableCodeException;
import java.util.Optional;
/**
* Functions to manipulate render states.
*/
public final class JCGLRenderStates
{
private JCGLRenderStates()
{
throw new UnreachableCodeException();
}
/**
* Activate the given render state.
*
* @param g An OpenGL interface
* @param r A render state
*/
public static void activate(
final JCGLInterfaceGL33Type g,
final JCGLRenderStateType r)
{
NullCheck.notNull(g);
NullCheck.notNull(r);
JCGLRenderStates.configureBlending(g, r);
JCGLRenderStates.configureCulling(g, r);
JCGLRenderStates.configureColorBufferMasking(g, r);
JCGLRenderStates.configureDepth(g, r);
JCGLRenderStates.configureScissor(g, r);
JCGLRenderStates.configureStencil(g, r);
}
private static void configureStencil(
final JCGLInterfaceGL33Type g,
final JCGLRenderStateType r)
{
final JCGLStencilBuffersType g_s = g.getStencilBuffers();
final JCGLStencilStateType s = r.getStencilState();
if (s.getStencilStrict()) {
if (s.getStencilEnabled()) {
g_s.stencilBufferEnable();
JCGLRenderStates.configureStencilActual(g_s, s);
} else {
g_s.stencilBufferDisable();
}
} else {
if (g_s.stencilBufferGetBits() > 0) {
if (s.getStencilEnabled()) {
JCGLRenderStates.configureStencilActual(g_s, s);
g_s.stencilBufferEnable();
} else {
g_s.stencilBufferDisable();
}
}
}
}
private static void configureStencilActual(
final JCGLStencilBuffersType g_s,
final JCGLStencilStateType s)
{
g_s.stencilBufferOperation(
JCGLFaceSelection.FACE_FRONT,
s.getOperationStencilFailFront(),
s.getOperationDepthFailFront(),
s.getOperationPassFront());
g_s.stencilBufferOperation(
JCGLFaceSelection.FACE_BACK,
s.getOperationStencilFailBack(),
s.getOperationDepthFailBack(),
s.getOperationPassBack());
g_s.stencilBufferMask(
JCGLFaceSelection.FACE_FRONT, s.getWriteMaskFrontFaces());
g_s.stencilBufferMask(
JCGLFaceSelection.FACE_BACK, s.getWriteMaskBackFaces());
g_s.stencilBufferFunction(
JCGLFaceSelection.FACE_FRONT,
s.getTestFunctionFront(),
s.getTestReferenceFront(),
s.getTestMaskFront());
g_s.stencilBufferFunction(
JCGLFaceSelection.FACE_BACK,
s.getTestFunctionBack(),
s.getTestReferenceBack(),
s.getTestMaskBack());
}
private static void configureBlending(
final JCGLInterfaceGL33Type g,
final JCGLRenderStateType r)
{
final JCGLBlendingType g_b = g.getBlending();
final Optional<JCGLBlendStateType> blend_opt = r.getBlendState();
if (blend_opt.isPresent()) {
final JCGLBlendStateType blend_state = blend_opt.get();
g_b.blendingEnableSeparateWithEquationSeparate(
blend_state.getBlendFunctionSourceRGB(),
blend_state.getBlendFunctionSourceAlpha(),
blend_state.getBlendFunctionTargetRGB(),
blend_state.getBlendFunctionTargetAlpha(),
blend_state.getBlendEquationRGB(),
blend_state.getBlendEquationAlpha());
} else {
g_b.blendingDisable();
}
}
private static void configureScissor(
final JCGLInterfaceGL33Type g,
final JCGLRenderStateType r)
{
final JCGLScissorType g_s = g.getScissor();
final Optional<AreaInclusiveUnsignedLType> scissor_opt = r.getScissor();
if (scissor_opt.isPresent()) {
final AreaInclusiveUnsignedLType area = scissor_opt.get();
g_s.scissorEnable(area);
} else {
g_s.scissorDisable();
}
}
private static void configureCulling(
final JCGLInterfaceGL33Type g,
final JCGLRenderStateType r)
{
final JCGLCullingType g_c = g.getCulling();
final Optional<JCGLCullingStateType> cull_opt = r.getCullingState();
if (cull_opt.isPresent()) {
final JCGLCullingStateType cull_state = cull_opt.get();
g_c.cullingEnable(
cull_state.getFaceSelection(), cull_state.getFaceWindingOrder());
} else {
g_c.cullingDisable();
}
}
private static void configureColorBufferMasking(
final JCGLInterfaceGL33Type g,
final JCGLRenderStateType r)
{
final JCGLColorBufferMaskingType g_c = g.getColorBufferMasking();
final JCGLColorBufferMaskingStateType gs = r.getColorBufferMaskingState();
g_c.colorBufferMask(
gs.getRed(), gs.getGreen(), gs.getBlue(), gs.getAlpha());
}
private static void configureDepth(
final JCGLInterfaceGL33Type g,
final JCGLRenderStateType r)
{
final JCGLDepthBuffersType g_d = g.getDepthBuffers();
final JCGLDepthStateType ds = r.getDepthState();
JCGLRenderStates.configureDepthWriting(g_d, ds);
JCGLRenderStates.configureDepthClamping(g_d, ds);
JCGLRenderStates.configureDepthTesting(g_d, ds);
}
private static void configureDepthWriting(
final JCGLDepthBuffersType g_d,
final JCGLDepthStateType ds)
{
/**
* If depth writing should be enabled, attempt to enable it.
*/
switch (ds.getDepthWrite()) {
case DEPTH_WRITE_ENABLED:
switch (ds.getDepthStrict()) {
/**
* If strict checking is required, enable without checking
* that there is a depth buffer - the function will raise an exception
* if there isn't.
*/
case DEPTH_STRICT_ENABLED:
g_d.depthBufferWriteEnable();
break;
/**
* If strict checking is disabled, only enable writing if there
* actually is a depth buffer.
*/
case DEPTH_STRICT_DISABLED:
if (g_d.depthBufferGetBits() > 0) {
g_d.depthBufferWriteEnable();
}
break;
}
break;
case DEPTH_WRITE_DISABLED:
/**
* Disabling depth writing when there is no depth buffer available,
* even with strict checking enabled, is never an error.
*/
if (g_d.depthBufferGetBits() > 0) {
g_d.depthBufferWriteDisable();
}
break;
}
}
private static void configureDepthTesting(
final JCGLDepthBuffersType g_d,
final JCGLDepthStateType ds)
{
/**
* If depth testing should be enabled, attempt to enable it.
*/
final Optional<JCGLDepthFunction> d_opt = ds.getDepthTest();
if (d_opt.isPresent()) {
switch (ds.getDepthStrict()) {
/**
* If strict checking is required, enable without checking
* that there is a depth buffer - the function will raise an exception
* if there isn't.
*/
case DEPTH_STRICT_ENABLED:
g_d.depthBufferTestEnable(d_opt.get());
break;
/**
* If strict checking is disabled, only enable testing if there
* actually is a depth buffer.
*/
case DEPTH_STRICT_DISABLED:
if (g_d.depthBufferGetBits() > 0) {
g_d.depthBufferTestEnable(d_opt.get());
}
break;
}
} else {
/**
* Disabling depth testing when there is no depth buffer, even with
* strict checking enabled, is never an error.
*/
if (g_d.depthBufferGetBits() > 0) {
g_d.depthBufferTestDisable();
}
}
}
private static void configureDepthClamping(
final JCGLDepthBuffersType g_d,
final JCGLDepthStateType ds)
{
/**
* If depth clamping should be enabled, attempt to enable it.
*/
switch (ds.getDepthClamp()) {
case DEPTH_CLAMP_ENABLED:
switch (ds.getDepthStrict()) {
/**
* If strict checking is required, enable without checking
* that there is a depth buffer - the function will raise an exception
* if there isn't.
*/
case DEPTH_STRICT_ENABLED:
g_d.depthClampingEnable();
break;
/**
* If strict checking is disabled, only enable clamping if there
* actually is a depth buffer.
*/
case DEPTH_STRICT_DISABLED:
if (g_d.depthBufferGetBits() > 0) {
g_d.depthClampingEnable();
}
break;
}
break;
case DEPTH_CLAMP_DISABLED:
/**
* Disabling depth clamping when there is no depth buffer, even with
* strict checking enabled, is never an error.
*/
if (g_d.depthBufferGetBits() > 0) {
g_d.depthClampingDisable();
}
}
}
}
|
package org.agilewiki.jactor2.core.impl.stRequests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.agilewiki.jactor2.core.impl.stReactors.ReactorStImpl;
import org.agilewiki.jactor2.core.plant.impl.PlantImpl;
import org.agilewiki.jactor2.core.reactors.CommonReactor;
import org.agilewiki.jactor2.core.reactors.Reactor;
import org.agilewiki.jactor2.core.requests.AOp;
import org.agilewiki.jactor2.core.requests.AsyncNativeRequest;
import org.agilewiki.jactor2.core.requests.AsyncOperation;
import org.agilewiki.jactor2.core.requests.AsyncResponseProcessor;
import org.agilewiki.jactor2.core.requests.BoundResponseProcessor;
import org.agilewiki.jactor2.core.requests.ExceptionHandler;
import org.agilewiki.jactor2.core.requests.SOp;
import org.agilewiki.jactor2.core.requests.SyncNativeRequest;
import org.agilewiki.jactor2.core.requests.impl.AsyncRequestImpl;
import org.agilewiki.jactor2.core.requests.impl.RequestImpl;
import org.agilewiki.jactor2.core.util.Timer;
/**
* Internal implementation of AsyncRequest.
*
* @param <RESPONSE_TYPE> The type of response.
*/
public class AsyncRequestStImpl<RESPONSE_TYPE> extends
RequestStImpl<RESPONSE_TYPE> implements
AsyncNativeRequest<RESPONSE_TYPE> {
private final HashMap<RequestImpl<?>, Boolean> pendingRequests = new HashMap<RequestImpl<?>, Boolean>();
private boolean noHungRequestCheck;
private final AsyncOperation<RESPONSE_TYPE> asyncOperation;
/** Used by the Timer. */
private volatile long start;
/**
* Create an AsyncRequestMtImpl and bind it to its operation and target targetReactor.
*
* @param _asyncOperation The request being implemented.
* @param _targetReactor The targetReactor where this AsyncRequest Objects is passed for processing.
* The thread owned by this targetReactor will process this AsyncRequest.
*/
public AsyncRequestStImpl(
final AsyncOperation<RESPONSE_TYPE> _asyncOperation,
final Reactor _targetReactor) {
super(_targetReactor);
asyncOperation = _asyncOperation;
}
public AsyncRequestStImpl(final Reactor _targetReactor) {
super(_targetReactor);
asyncOperation = this;
}
@Override
public AsyncOperation<RESPONSE_TYPE> asOperation() {
return asyncOperation;
}
/**
* Disable check for hung request.
* This must be called when a response must wait for a subsequent request.
*/
@Override
public void setNoHungRequestCheck() {
noHungRequestCheck = true;
}
/**
* Returns true if no subordinate requests have not yet responded.
*
* @return true if no subordinate requests have not yet responded.
*/
@Override
public final boolean hasNoPendingResponses() {
return pendingRequests.isEmpty();
}
/**
* Removes a RequestImpl from the pending requests; returns true if present.
*
* @param request The request to be removed
*
* @return true if present.
*/
private boolean pendingRequestsRemove(final RequestImpl<?> request) {
final Boolean result = pendingRequests.remove(request);
return (result == null) ? false : result.booleanValue();
}
/**
* Adds a RequestImpl to the pending requests.
*
* @param request The request to be added
*/
private void pendingRequestsAdd(final RequestImpl<?> request) {
pendingRequests.put(request, Boolean.TRUE);
}
/**
* A safe way to copy pendingRequests.
*
* @return A copy of pendingRequests.
*/
private List<RequestImpl<?>> copyPendingRequests() {
return new ArrayList<>(pendingRequests.keySet());
}
/**
* Process the response to this request.
*
* @param _response The response to this request.
*/
@Override
public void processAsyncResponse(final RESPONSE_TYPE _response) {
final Timer timer = asyncOperation.getTimer();
timer.updateNanos(timer.nanos() - start, true);
processObjectResponse(_response);
}
/**
* Returns an exception as a response instead of throwing it.
* But regardless of how a response is returned, if the response is an exception it
* is passed to the exception handler of the request that did the call or send on the request.
*
* @param _response An exception.
*/
@Override
public void processAsyncException(final Exception _response) {
final Timer timer = asyncOperation.getTimer();
timer.updateNanos(timer.nanos() - start, false);
processObjectResponse(_response);
}
private void pendingCheck() throws Exception {
if (incomplete && !isCanceled() && hasNoPendingResponses()
&& !noHungRequestCheck) {
targetReactor.asReactorImpl().error("hung request:\n" + toString());
close();
targetReactorImpl.getRecovery().onHungRequest(this);
}
}
@Override
protected void processRequestMessage() throws Exception {
start = asyncOperation.getTimer().nanos();
asyncOperation.doAsync(this, this);
pendingCheck();
}
@Override
public void responseReceived(final RequestImpl<?> request) {
pendingRequestsRemove(request);
}
@Override
public void responseProcessed() {
try {
pendingCheck();
} catch (final Exception e) {
processException(requestSource, e);
}
}
@Override
public <RT> void send(final RequestImpl<RT> _requestImpl,
final AsyncResponseProcessor<RT> _responseProcessor) {
if (canceled && (_responseProcessor != null)) {
return;
}
if (targetReactorImpl.getCurrentRequest() != this) {
throw new UnsupportedOperationException(
"send called on inactive request");
}
final RequestStImpl<RT> requestImpl = (RequestStImpl<RT>) _requestImpl;
if (_responseProcessor != OneWayResponseProcessor.SINGLETON) {
pendingRequestsAdd(requestImpl);
}
requestImpl.doSend(targetReactorImpl, _responseProcessor);
}
@Override
public <RT, RT2> void send(final RequestImpl<RT> _requestImpl,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
if (canceled) {
return;
}
if (targetReactorImpl.getCurrentRequest() != this) {
throw new UnsupportedOperationException(
"send called on inactive request");
}
final RequestStImpl<RT> requestImpl = (RequestStImpl<RT>) _requestImpl;
pendingRequestsAdd(requestImpl);
requestImpl.doSend(targetReactorImpl, new AsyncResponseProcessor<RT>() {
@Override
public void processAsyncResponse(final RT _response)
throws Exception {
_dis.processAsyncResponse(_fixedResponse);
}
});
}
/**
* Replace the current ExceptionHandler with another.
* <p>
* When an event or request message is processed by a targetReactor, the current
* exception handler is set to null. When a request is sent by a targetReactor, the
* current exception handler is saved in the outgoing message and restored when
* the response message is processed.
* </p>
*
* @param _exceptionHandler The exception handler to be used now.
* May be null if the default exception handler is to be used.
* @return The exception handler that was previously in effect, or null if the
* default exception handler was in effect.
*/
@Override
public ExceptionHandler<RESPONSE_TYPE> setExceptionHandler(
final ExceptionHandler<RESPONSE_TYPE> _exceptionHandler) {
@SuppressWarnings("unchecked")
final ExceptionHandler<RESPONSE_TYPE> old = (ExceptionHandler<RESPONSE_TYPE>) targetReactorImpl
.getExceptionHandler();
targetReactorImpl.setExceptionHandler(_exceptionHandler);
return old;
}
/**
* Returns the current exception handler.
*
* @return The current exception handler, or null.
*/
@SuppressWarnings("unchecked")
public ExceptionHandler<RESPONSE_TYPE> getExceptionHandler() {
return (ExceptionHandler<RESPONSE_TYPE>) targetReactorImpl
.getExceptionHandler();
}
@Override
public void close() {
if (!incomplete) {
return;
}
final List<RequestImpl<?>> pr = copyPendingRequests();
final Iterator<RequestImpl<?>> it = pr.iterator();
while (it.hasNext()) {
final RequestImpl<?> request = it.next();
((RequestStImpl<?>) request).cancel();
}
super.close();
asOperation().onClose(this);
}
/**
* Cancel a subordinate RequestImpl.
*
* @param _requestImpl The subordinate RequestImpl.
* @return True if the subordinate RequestImpl was canceled.
*/
@Override
public boolean cancel(final RequestImpl<?> _requestImpl) {
final RequestStImpl<?> requestImpl = (RequestStImpl<?>) _requestImpl;
if (!pendingRequestsRemove(requestImpl)) {
return false;
}
requestImpl.cancel();
return true;
}
/**
* Cancel all subordinate RequestImpl's.
*/
@Override
public void cancelAll() {
final List<RequestImpl<?>> all = copyPendingRequests();
final Iterator<RequestImpl<?>> it = all.iterator();
while (it.hasNext()) {
cancel(it.next());
}
}
/**
* Cancel this request.
*/
@Override
public void cancel() {
if (canceled) {
return;
}
canceled = true;
asOperation().onCancel(this);
}
@Override
protected void setResponse(final Object _response,
final ReactorStImpl _activeReactor) {
if ((_response instanceof Throwable)
|| (targetReactor instanceof CommonReactor)) {
cancelAll();
}
super.setResponse(_response, _activeReactor);
}
@Override
public <RT> RequestImpl<RT> send(final SOp<RT> _sOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
final RequestImpl<RT> ri = PlantImpl.getSingleton()
.createSyncRequestImpl(_sOp, _sOp.targetReactor);
send(ri, _asyncResponseProcessor);
return ri;
}
@Override
public <RT, RT2> RequestImpl<RT> send(final SOp<RT> _sOp,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
final RequestImpl<RT> ri = PlantImpl.getSingleton()
.createSyncRequestImpl(_sOp, _sOp.targetReactor);
send(ri, _dis, _fixedResponse);
return ri;
}
@Override
public <RT> AsyncRequestImpl<RT> send(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
final AsyncRequestImpl<RT> ari = PlantImpl.getSingleton()
.createAsyncRequestImpl(_aOp, _aOp.targetReactor);
send(ari, _asyncResponseProcessor);
return ari;
}
@Override
public <RT, RT2> AsyncRequestImpl<RT> send(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
final AsyncRequestImpl<RT> ari = PlantImpl.getSingleton()
.createAsyncRequestImpl(_aOp, _aOp.targetReactor);
send(ari, _dis, _fixedResponse);
return ari;
}
@Override
public <RT> void send(final SyncNativeRequest<RT> _syncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_syncNativeRequest,
_syncNativeRequest.getTargetReactor()), _asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final SyncNativeRequest<RT> _syncNativeRequest,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_syncNativeRequest,
_syncNativeRequest.getTargetReactor()), _dis, _fixedResponse);
}
@Override
public <RT> void send(final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(
_asyncNativeRequest, _asyncNativeRequest.getTargetReactor()),
_asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(
final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(
_asyncNativeRequest, _asyncNativeRequest.getTargetReactor()),
_dis, _fixedResponse);
}
@Override
public void onCancel(final AsyncRequestImpl _asyncRequestImpl) {
onCancel();
}
/**
* An optional callback used to signal that the request has been canceled.
* This method must be thread-safe, as there is no constraint on which
* thread is used to call it.
* The default action of onCancel is to call cancelAll and,
* if the reactor is not a common reactor, sends a response of null via
* a bound response processor.
*/
public void onCancel() {
cancelAll();
final Reactor targetReactor = getTargetReactor();
if (!(targetReactor instanceof CommonReactor)) {
try {
new BoundResponseProcessor<RESPONSE_TYPE>(targetReactor, this)
.processAsyncResponse(null);
} catch (final Exception e) {
}
}
}
@Override
public void onClose(final AsyncRequestImpl _asyncRequestImpl) {
onClose();
}
/**
* An optional callback used to signal that the request has been closed.
* This method must be thread-safe, as there is no constraint on which
* thread is used to call it.
* By default, onClose does nothing.
*/
public void onClose() {
}
@Override
public void doAsync(final AsyncRequestImpl _asyncRequestImpl,
final AsyncResponseProcessor<RESPONSE_TYPE> _asyncResponseProcessor)
throws Exception {
if (!_asyncRequestImpl.getTargetReactor().asReactorImpl().isRunning())
throw new IllegalStateException(
"Not thread safe: not called from within an active request");
processAsyncOperation(_asyncRequestImpl, _asyncResponseProcessor);
}
/**
* The processAsyncOperation method will be invoked by the target Reactor on its own thread.
*
* @param _asyncRequestImpl The request context--may be of a different RESPONSE_TYPE.
* @param _asyncResponseProcessor Handles the response.
*/
protected void processAsyncOperation(
final AsyncRequestImpl _asyncRequestImpl,
final AsyncResponseProcessor<RESPONSE_TYPE> _asyncResponseProcessor)
throws Exception {
throw new IllegalStateException();
}
/* (non-Javadoc)
* @see org.agilewiki.jactor2.core.requests.impl.AsyncRequestImpl#setExpectedPendingResponses(int)
*/
@Override
public void setExpectedPendingResponses(final int responses) {
// NOP (We don't care in JavaScript)
}
}
|
package org.jboss.resteasy.examples.twitter;
import java.util.Date;
import java.util.List;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jboss.resteasy.client.ClientExecutor;
import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
public class TwitterClient
{
static final String friendTimeline = "http://twitter.com/statuses/friends_timeline.xml";
public static void main(String[] args) throws Exception
{
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
final ClientExecutor clientExecutor = new ApacheHttpClient4Executor(createClient(args[0], args[1]));
TwitterResource twitter = ProxyFactory.create(TwitterResource.class,
"http://twitter.com", clientExecutor);
System.out.println("===> first run");
printStatuses(twitter.getFriendsTimelines());
twitter
.updateStatus("I programmatically tweeted with the RESTEasy Client at "
+ new Date());
System.out.println("===> second run");
printStatuses(twitter.getFriendsTimelines());
}
public static interface TwitterResource
{
@Path("/statuses/friends_timeline.xml")
@GET
Statuses getFriendsTimelines();
@Path("/statuses/update.xml")
@POST
Status updateStatus(@FormParam("status") String status);
}
private static void printStatuses(Statuses statuses)
{
for (Status status : statuses.status)
System.out.println(status);
}
private static HttpClient createClient(String userId, String password) {
Credentials credentials = new UsernamePasswordCredentials(userId,
password);
HttpClient httpClient = new DefaultHttpClient();
((DefaultHttpClient) httpClient).getCredentialsProvider()
.setCredentials(AuthScope.ANY, credentials);
return httpClient;
}
@XmlRootElement
public static class Statuses
{
public List<Status> status;
}
@XmlRootElement
public static class Status
{
public String text;
public User user;
@XmlElement(name = "created_at")
@XmlJavaTypeAdapter(value = DateAdapter.class)
public Date created;
public String toString()
{
return String.format("== %s: %s (%s)", user.name, text, created);
}
}
public static class User
{
public String name;
}
}
|
package org.junit.gen5.launcher.listeners;
import static java.util.stream.Stream.concat;
import static org.junit.gen5.engine.TestExecutionResult.Status.*;
import java.util.stream.Stream;
import org.junit.gen5.engine.TestExecutionResult;
import org.junit.gen5.launcher.TestExecutionListener;
import org.junit.gen5.launcher.TestIdentifier;
import org.junit.gen5.launcher.TestPlan;
/**
* @since 5.0
*/
public class SummaryCreatingTestListener implements TestExecutionListener {
private TestPlan testPlan;
private TestExecutionSummary summary;
public TestExecutionSummary getSummary() {
return summary;
}
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
this.testPlan = testPlan;
this.summary = new TestExecutionSummary(testPlan);
summary.testsFound.set(testPlan.countTestIdentifiers(TestIdentifier::isTest));
summary.timeStarted = System.currentTimeMillis();
}
@Override
public void testPlanExecutionFinished(TestPlan testPlan) {
summary.finishTestRun("Test run finished");
}
@Override
public void dynamicTestRegistered(TestIdentifier testIdentifier) {
summary.testsFound.incrementAndGet();
}
@Override
public void executionSkipped(TestIdentifier testIdentifier, String reason) {
// @formatter:off
long skippedTests = concat(Stream.of(testIdentifier), testPlan.getDescendants(testIdentifier).stream())
.filter(TestIdentifier::isTest)
.count();
// @formatter:on
summary.testsSkipped.addAndGet(skippedTests);
}
@Override
public void executionStarted(TestIdentifier testIdentifier) {
if (testIdentifier.isTest()) {
summary.testsStarted.incrementAndGet();
}
}
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
if (testIdentifier.isTest()) {
if (testExecutionResult.getStatus() == SUCCESSFUL) {
summary.testsSucceeded.incrementAndGet();
}
else if (testExecutionResult.getStatus() == ABORTED) {
summary.testsAborted.incrementAndGet();
}
else if (testExecutionResult.getStatus() == FAILED) {
summary.testsFailed.incrementAndGet();
}
}
testExecutionResult.getThrowable().ifPresent(throwable -> summary.addFailure(testIdentifier, throwable));
}
}
|
package org.kuali.kfs.module.purap.document.web.struts;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.document.BulkReceivingDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.service.BulkReceivingService;
import org.kuali.kfs.module.purap.document.service.PurchaseOrderService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.vnd.VendorConstants;
import org.kuali.kfs.vnd.businessobject.VendorAddress;
import org.kuali.kfs.vnd.document.service.VendorService;
import org.kuali.kfs.vnd.service.PhoneNumberService;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.kfs.kns.document.authorization.DocumentAuthorizer;
import org.kuali.kfs.kns.question.ConfirmationQuestion;
import org.kuali.kfs.kns.service.DataDictionaryService;
import org.kuali.kfs.kns.service.DocumentHelperService;
import org.kuali.kfs.kns.util.WebUtils;
import org.kuali.kfs.kns.web.struts.action.KualiTransactionalDocumentActionBase;
import org.kuali.kfs.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.kfs.krad.document.Document;
import org.kuali.kfs.krad.service.BusinessObjectService;
import org.kuali.kfs.krad.util.GlobalVariables;
import org.kuali.kfs.krad.util.KRADConstants;
import org.kuali.kfs.krad.util.ObjectUtils;
public class BulkReceivingAction extends KualiTransactionalDocumentActionBase {
protected static final Logger LOG = Logger.getLogger(BulkReceivingAction.class);
protected void createDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
super.createDocument(kualiDocumentFormBase);
BulkReceivingForm blkForm = (BulkReceivingForm) kualiDocumentFormBase;
BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkForm.getDocument();
blkRecDoc.setPurchaseOrderIdentifier(blkForm.getPurchaseOrderId());
blkRecDoc.initiateDocument();
}
public ActionForward continueBulkReceiving(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
BulkReceivingForm blkForm = (BulkReceivingForm) form;
BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkForm.getDocument();
PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(blkRecDoc.getPurchaseOrderIdentifier());
if (ObjectUtils.isNotNull(po)) {
// TODO figure out a more straightforward way to do this. ailish put this in so the link id would be set and the perm
// check would work
blkRecDoc.setAccountsPayablePurchasingDocumentLinkIdentifier(po.getAccountsPayablePurchasingDocumentLinkIdentifier());
// TODO hjs-check to see if user is allowed to initiate doc based on PO sensitive data (add this to all other docs
// except acm doc)
if (!SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(blkRecDoc).isAuthorizedByTemplate(blkRecDoc, KRADConstants.KNS_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_DOCUMENT, GlobalVariables.getUserSession().getPrincipalId())) {
throw buildAuthorizationException("initiate document", blkRecDoc);
}
}
// perform duplicate check
ActionForward forward = isDuplicateDocumentEntry(mapping, form, request, response, blkRecDoc);
if (forward != null) {
return forward;
}
// populate and save bulk Receiving Document from Purchase Order
SpringContext.getBean(BulkReceivingService.class).populateAndSaveBulkReceivingDocument(blkRecDoc);
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
public ActionForward clearInitFields(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
BulkReceivingForm blkRecForm = (BulkReceivingForm) form;
BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkRecForm.getDocument();
blkRecDoc.clearInitFields();
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
protected ActionForward isDuplicateDocumentEntry(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, BulkReceivingDocument bulkReceivingDocument) throws Exception {
ActionForward forward = null;
HashMap<String, String> duplicateMessages = SpringContext.getBean(BulkReceivingService.class).bulkReceivingDuplicateMessages(bulkReceivingDocument);
if (duplicateMessages != null && !duplicateMessages.isEmpty()) {
Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
if (question == null) {
return this.performQuestionWithoutInput(mapping, form, request, response, PurapConstants.BulkReceivingDocumentStrings.DUPLICATE_BULK_RECEIVING_DOCUMENT_QUESTION, duplicateMessages.get(PurapConstants.BulkReceivingDocumentStrings.DUPLICATE_BULK_RECEIVING_DOCUMENT_QUESTION), KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, "");
}
Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
if ((PurapConstants.BulkReceivingDocumentStrings.DUPLICATE_BULK_RECEIVING_DOCUMENT_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
forward = mapping.findForward(KFSConstants.MAPPING_BASIC);
}
}
return forward;
}
public ActionForward printReceivingTicketPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
BulkReceivingForm blkRecForm = (BulkReceivingForm) form;
String docId = blkRecForm.getDocId();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
try {
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PURAP_RECEIVING_TICKET_");
sbFilename.append(docId);
sbFilename.append("_");
sbFilename.append(System.currentTimeMillis());
SpringContext.getBean(BulkReceivingService.class).performPrintReceivingTicketPDF(docId, baosPDF);
WebUtils.saveMimeOutputStreamAsFile(response, KFSConstants.ReportGeneration.PDF_MIME_TYPE, baosPDF, sbFilename.toString());
}
finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
return null;
}
@Override
public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
BulkReceivingForm blkRecForm = (BulkReceivingForm) form;
BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkRecForm.getDocument();
String refreshCaller = blkRecForm.getRefreshCaller();
PhoneNumberService phoneNumberService = SpringContext.getBean(PhoneNumberService.class);
// Format phone numbers
blkRecDoc.setInstitutionContactPhoneNumber(phoneNumberService.formatNumberIfPossible(blkRecDoc.getInstitutionContactPhoneNumber()));
blkRecDoc.setRequestorPersonPhoneNumber(phoneNumberService.formatNumberIfPossible(blkRecDoc.getRequestorPersonPhoneNumber()));
blkRecDoc.setDeliveryToPhoneNumber(phoneNumberService.formatNumberIfPossible(blkRecDoc.getDeliveryToPhoneNumber()));
// Refreshing the fields after returning from a vendor lookup in the vendor tab
if (StringUtils.equals(refreshCaller, VendorConstants.VENDOR_LOOKUPABLE_IMPL) && blkRecDoc.getVendorDetailAssignedIdentifier() != null && blkRecDoc.getVendorHeaderGeneratedIdentifier() != null) {
// retrieve vendor based on selection from vendor lookup
blkRecDoc.refreshReferenceObject("vendorDetail");
blkRecDoc.setVendorName(blkRecDoc.getVendorDetail().getVendorName());
// populate default address based on selected vendor
VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(blkRecDoc.getVendorDetail().getVendorAddresses(), blkRecDoc.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), "");
if (ObjectUtils.isNotNull(defaultAddress)) {
blkRecDoc.setVendorLine1Address(defaultAddress.getVendorLine1Address());
blkRecDoc.setVendorLine2Address(defaultAddress.getVendorLine2Address());
blkRecDoc.setVendorCityName(defaultAddress.getVendorCityName());
blkRecDoc.setVendorStateCode(defaultAddress.getVendorStateCode());
blkRecDoc.setVendorPostalCode(defaultAddress.getVendorZipCode());
blkRecDoc.setVendorCountryCode(defaultAddress.getVendorCountryCode());
}
}
// Refreshing the fields after returning from an address lookup in the vendor tab
if (StringUtils.equals(refreshCaller, VendorConstants.VENDOR_ADDRESS_LOOKUPABLE_IMPL)) {
if (StringUtils.isNotEmpty(request.getParameter(KFSPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.VENDOR_ADDRESS_ID))) {
// retrieve address based on selection from address lookup
VendorAddress refreshVendorAddress = new VendorAddress();
refreshVendorAddress.setVendorAddressGeneratedIdentifier(blkRecDoc.getVendorAddressGeneratedIdentifier());
refreshVendorAddress = (VendorAddress) SpringContext.getBean(BusinessObjectService.class).retrieve(refreshVendorAddress);
if (ObjectUtils.isNotNull(refreshVendorAddress)) {
blkRecDoc.setVendorLine1Address(refreshVendorAddress.getVendorLine1Address());
blkRecDoc.setVendorLine2Address(refreshVendorAddress.getVendorLine2Address());
blkRecDoc.setVendorCityName(refreshVendorAddress.getVendorCityName());
blkRecDoc.setVendorStateCode(refreshVendorAddress.getVendorStateCode());
blkRecDoc.setVendorPostalCode(refreshVendorAddress.getVendorZipCode());
blkRecDoc.setVendorCountryCode(refreshVendorAddress.getVendorCountryCode());
}
}
}
// Refreshing corresponding fields after returning from various kuali lookups
if (StringUtils.equals(refreshCaller, KFSConstants.KUALI_LOOKUPABLE_IMPL)) {
if (request.getParameter("document.deliveryCampusCode") != null) {
// returning from a building or campus lookup on the delivery tab
if (request.getParameter("document.deliveryBuildingName") == null) {
// came from campus lookup not building, so clear building
blkRecDoc.setDeliveryBuildingCode("");
blkRecDoc.setDeliveryBuildingLine1Address("");
blkRecDoc.setDeliveryBuildingLine2Address("");
blkRecDoc.setDeliveryBuildingRoomNumber("");
blkRecDoc.setDeliveryCityName("");
blkRecDoc.setDeliveryStateCode("");
blkRecDoc.setDeliveryPostalCode("");
blkRecDoc.setDeliveryCountryCode("");
}
else {
// came from building lookup then turn off "OTHER" and clear room and line2address
blkRecDoc.setDeliveryBuildingOtherIndicator(false);
blkRecDoc.setDeliveryBuildingRoomNumber("");
blkRecDoc.setDeliveryBuildingLine2Address("");
}
}
}
return super.refresh(mapping, form, request, response);
}
/**
* Setup document to use "OTHER" building
*
* @param mapping An ActionMapping
* @param form An ActionForm
* @param request A HttpServletRequest
* @param response A HttpServletResponse
* @return An ActionForward
* @throws Exception
*/
public ActionForward useOtherDeliveryBuilding(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
BulkReceivingForm baseForm = (BulkReceivingForm) form;
BulkReceivingDocument document = (BulkReceivingDocument) baseForm.getDocument();
document.setDeliveryBuildingOtherIndicator(true);
document.setDeliveryBuildingName("");
document.setDeliveryBuildingCode("");
document.setDeliveryBuildingLine1Address("");
document.setDeliveryBuildingLine2Address("");
document.setDeliveryBuildingRoomNumber("");
document.setDeliveryCityName("");
document.setDeliveryStateCode("");
document.setDeliveryCountryCode("");
document.setDeliveryPostalCode("");
return mapping.findForward(KFSConstants.MAPPING_BASIC);
}
@Override
protected void populateAdHocActionRequestCodes(KualiDocumentFormBase formBase){
Document document = formBase.getDocument();
DocumentAuthorizer documentAuthorizer = getDocumentHelperService().getDocumentAuthorizer(document);
Map<String,String> adHocActionRequestCodes = new HashMap<String,String>();
if (documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_FYI_REQ, GlobalVariables.getUserSession().getPerson())) {
adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_FYI_REQ, KewApiConstants.ACTION_REQUEST_FYI_REQ_LABEL);
}
if ( (document.getDocumentHeader().getWorkflowDocument().isInitiated()
|| document.getDocumentHeader().getWorkflowDocument().isSaved()
|| document.getDocumentHeader().getWorkflowDocument().isEnroute()
)&& documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, GlobalVariables.getUserSession().getPerson())) {
adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL);
}
formBase.setAdHocActionRequestCodes(adHocActionRequestCodes);
}
}
|
package com.wja.base.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import com.wja.base.web.AppContext;
public class DateUtil
{
public static final String DATE = "yyyy-MM-dd";
public static final String TIME = "HH:mm:ss";
public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_MINUTE = "yyyy-MM-dd HH:mm";
/**
* yyyy-MM-dd
*/
public static final DateFormat DEFAULT_DF = new SimpleDateFormat(DATE);
public static final DateFormat DATE_MINUTE_DF = new SimpleDateFormat(DATE_MINUTE);
/**
*
* yyyy-MM-dd
*
* @return
* @see [##]
*/
public static final String getNowDateStr()
{
return DEFAULT_DF.format(new Date());
}
/**
*
* yyyy-MM-dd HH:mm
*
* @return
* @see [##]
*/
public static final String getTodayWorkStartTimeStr()
{
String startTime = AppContext.getSysParam("work.start.time");
int hourOfDay = 9;
int minute = 0;
if (StringUtils.isNotBlank(startTime))
{
String[] hm = startTime.trim().split(":");
try
{
hourOfDay = Integer.parseInt(hm[0]);
if (hm.length > 1)
{
minute = Integer.parseInt(hm[1]);
}
}
catch (Exception e)
{
Log.LOGGER.error("", e);
}
if (hourOfDay > 23 || hourOfDay < 0)
{
hourOfDay = 9;
}
if (minute < 0 || minute > 59)
{
minute = 0;
}
}
return getNowDateMinuteStr(hourOfDay, minute);
}
/**
*
* yyyy-MM-dd HH:mm
*
* @param hourOfDay
* @param minute
* @return
* @see [##]
*/
public static final String getNowDateMinuteStr(int hourOfDay, int minute)
{
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
return DATE_MINUTE_DF.format(c.getTime());
}
public static final DateFormat getDateFormat(String pattern)
{
return new SimpleDateFormat(pattern);
}
/**
*
*
*
* @param cal
* @return
* @see [##]
*/
public static final boolean isRestDay(Calendar cal)
{
int weekDay = cal.get(Calendar.DAY_OF_WEEK);
return weekDay == Calendar.SATURDAY || weekDay == Calendar.SUNDAY;
}
/**
*
*
*
* @param date
* @return
* @see [##]
*/
public static final boolean isRestDay(Date d)
{
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int weekDay = cal.get(Calendar.DAY_OF_WEEK);
return weekDay == Calendar.SATURDAY || weekDay == Calendar.SUNDAY;
}
public static void toNextWorkDay(Calendar cal)
{
if (isRestDay(cal))
{
cal.add(Calendar.DATE, 1);
toNextWorkDay(cal);
}
}
}
|
package be.ibridge.kettle.trans.step.denormaliser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleValueException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Denormalises data based on key-value pairs
*
* @author Matt
* @since 17-jan-2006
*/
public class Denormaliser extends BaseStep implements StepInterface
{
private DenormaliserMeta meta;
private DenormaliserData data;
public Denormaliser(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
meta=(DenormaliserMeta)getStepMeta().getStepMetaInterface();
data=(DenormaliserData)stepDataInterface;
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
Row r=getRow(); // get row!
if (r==null) // no more input to be expected...
{
// Don't forget the last set of rows...
if (data.previous!=null)
{
deNormalise(data.previous);
buildResult(data.previous);
putRow(data.previous);
//System.out.println("Wrote row: "+data.previous);
}
setOutputDone();
return false;
}
if (first)
{
data.keyFieldNr = r.searchValueIndex(meta.getKeyField() );
if (data.keyFieldNr<0)
{
logError(Messages.getString("Denormaliser.Log.KeyFieldNotFound",meta.getKeyField())); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
Hashtable subjects = new Hashtable();
data.fieldNameIndex = new int[meta.getDenormaliserTargetField().length];
for (int i=0;i<meta.getDenormaliserTargetField().length;i++)
{
DenormaliserTargetField field = meta.getDenormaliserTargetField()[i];
int idx = r.searchValueIndex(field.getFieldName());
if (idx<0)
{
logError(Messages.getString("Denormaliser.Log.UnpivotFieldNotFound",field.getFieldName())); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
data.fieldNameIndex[i] = idx;
subjects.put(new Integer(idx), new Integer(idx));
// Fill a hashtable with the key strings and the position(s) of the field(s) in the row to take.
// Store the indexes in a List so that we can accommodate multiple key/value pairs...
List indexes = (List) data.keyValue.get(field.getKeyValue());
if (indexes==null)
{
indexes = new ArrayList(2);
}
indexes.add(new Integer(i)); // Add the index to the list...
data.keyValue.put(field.getKeyValue(), indexes); // store the list
}
Set subjectSet = subjects.keySet();
data.fieldNrs = (Integer[])subjectSet.toArray(new Integer[subjectSet.size()]);
data.groupnrs = new int[meta.getGroupField().length];
for (int i=0;i<meta.getGroupField().length;i++)
{
data.groupnrs[i] = r.searchValueIndex(meta.getGroupField()[i]);
if (data.groupnrs[i]<0)
{
logError(Messages.getString("Denormaliser.Log.GroupingFieldNotFound",meta.getGroupField()[i])); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
return false;
}
}
ArrayList removeList = new ArrayList();
removeList.add(new Integer(data.keyFieldNr));
for (int i=0;i<data.fieldNrs.length;i++)
{
removeList.add(data.fieldNrs[i]);
}
Collections.sort(removeList);
data.removeNrs = new int[removeList.size()];
for (int i=0;i<removeList.size();i++) data.removeNrs[i] = ((Integer)removeList.get(i)).intValue();
data.previous=new Row(r); // copy the row to previous
newGroup(); // Create a new result row (init)
first=false;
}
// System.out.println("Check for same group...");
if (!sameGroup(data.previous, r))
{
// System.out.println("Different group!");
buildResult(data.previous);
putRow(data.previous); // copy row to possible alternate rowset(s).
//System.out.println("Wrote row: "+data.previous);
newGroup(); // Create a new group aggregate (init)
deNormalise(r);
}
else
{
deNormalise(r);
}
data.previous=new Row(r);
if ((linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic(Messages.getString("Denormaliser.Log.LineNumber")+linesRead); //$NON-NLS-1$
return true;
}
private void buildResult(Row inputRow) throws KettleValueException
{
for (int i=data.removeNrs.length-1;i>=0;i
{
inputRow.removeValue(data.removeNrs[i]);
}
// Add the unpivoted fields...
for (int i=0;i<data.targetResult.size();i++)
{
Value resultValue = data.targetResult.getValue(i);
DenormaliserTargetField field = meta.getDenormaliserTargetField()[i];
switch(field.getTargetAggregationType())
{
case DenormaliserTargetField.TYPE_AGGR_AVERAGE :
long count = data.counters[i];
Value sum = data.sum[i];
if (count>0)
{
sum.divide(count);
resultValue.setValue(sum);
}
break;
default: break;
}
inputRow.addValue(resultValue);
}
}
// Is the row r of the same group as previous?
private boolean sameGroup(Row previous, Row r)
{
for (int i=0;i<data.groupnrs.length;i++)
{
Value prev = previous.getValue(data.groupnrs[i]);
Value curr = r.getValue(data.groupnrs[i]);
if (!prev.equals(curr)) return false;
}
return true;
}
/** Initialize a new group... */
private void newGroup()
{
data.targetResult = new Row();
for (int i=0;i<meta.getDenormaliserTargetFields().length;i++)
{
DenormaliserTargetField field = meta.getDenormaliserTargetField()[i];
Value defaultTarget = new Value(field.getTargetName(), field.getTargetType());
defaultTarget.setLength(field.getTargetLength(), field.getTargetPrecision());
defaultTarget.setNull();
data.targetResult.addValue(defaultTarget);
data.counters[i]=0L; // set to 0
data.sum[i]=new Value(field.getTargetName(), field.getTargetType());
data.sum[i].setNull();
}
}
/**
* This method de-normalises a single key-value pair.
* It looks up the key and determines the value name to store it in.
* It converts it to the right type and stores it in the result row.
* @param r
* @throws KettleValueException
*/
private void deNormalise(Row r) throws KettleValueException
{
String key = r.getValue(data.keyFieldNr).getString();
if ( !Const.isEmpty(key) )
{
// Get all the indexes for the given key value...
List indexes = (List) data.keyValue.get(key);
if (indexes!=null) // otherwise we're not interested.
{
for (int i=0;i<indexes.size();i++)
{
Integer keyNr = (Integer) indexes.get(i);
if (keyNr!=null)
{
// keyNr is the field in DenormaliserTargetField[]
int idx = keyNr.intValue();
DenormaliserTargetField field = meta.getDenormaliserTargetField()[idx];
Value targetValue = r.getValue(data.fieldNameIndex[idx]); // This is the value we need to de-normalise, convert, aggregate.
// System.out.println("Value type: "+targetValue.getTypeDesc()+"("+targetValue+"), convert to type : "+field.getTargetTypeDesc());
// See if we need to convert this value
if (targetValue.getType() != field.getTargetType())
{
switch(targetValue.getType())
{
case Value.VALUE_TYPE_STRING:
switch(field.getTargetType())
{
case Value.VALUE_TYPE_DATE:
if (targetValue.isNull() || targetValue.getString()==null || targetValue.getString().length()==0)
{
targetValue.setNull();
targetValue.setType(Value.VALUE_TYPE_DATE);
}
else
{
targetValue.str2dat(field.getTargetFormat());
};
break;
case Value.VALUE_TYPE_INTEGER:
if (targetValue.isNull() || targetValue.getString()==null || targetValue.getString().length()==0)
{
targetValue.setNull();
targetValue.setType(Value.VALUE_TYPE_INTEGER);
}
else
{
targetValue.setType(targetValue.getType());
}
break;
case Value.VALUE_TYPE_NUMBER:
if (targetValue.isNull() || targetValue.getString()==null || targetValue.getString().length()==0)
{
targetValue.setNull();
targetValue.setType(Value.VALUE_TYPE_NUMBER);
}
else
{
targetValue.str2num(field.getTargetFormat(), field.getTargetDecimalSymbol(), field.getTargetGroupingSymbol(), field.getTargetCurrencySymbol());
}
break;
case Value.VALUE_TYPE_BIGNUMBER:
if (targetValue.isNull() || targetValue.getString()==null || targetValue.getString().length()==0)
{
targetValue.setNull();
targetValue.setType(Value.VALUE_TYPE_BIGNUMBER);
}
else
{
targetValue.setType(targetValue.getType());
}
break;
case Value.VALUE_TYPE_BOOLEAN:
if (targetValue.isNull() || targetValue.getString()==null || targetValue.getString().length()==0)
{
targetValue.setNull();
targetValue.setType(Value.VALUE_TYPE_BOOLEAN);
}
else
{
targetValue.setType(targetValue.getType());
}
break;
default:
if (targetValue.isNull() || targetValue.getString()==null || targetValue.getString().length()==0)
{
targetValue.setNull();
}
else
{
targetValue.setType(targetValue.getType());
}
break;
}
default:
if (targetValue.isNull() || targetValue.getString()==null || targetValue.getString().length()==0)
{
targetValue.setNull();
}
else
{
targetValue.setType(targetValue.getType());
}
break;
}
}
Value prevTarget = data.targetResult.getValue(idx);
// System.out.println("TargetValue="+targetValue+", Prev TargetResult="+prevTarget);
switch(field.getTargetAggregationType())
{
case DenormaliserTargetField.TYPE_AGGR_SUM:
prevTarget.plus(targetValue);
break;
case DenormaliserTargetField.TYPE_AGGR_MIN:
if (targetValue.compare(prevTarget)<0) prevTarget.setValue(targetValue);
break;
case DenormaliserTargetField.TYPE_AGGR_MAX:
if (targetValue.compare(prevTarget)>0) prevTarget.setValue(targetValue);
break;
case DenormaliserTargetField.TYPE_AGGR_COUNT_ALL:
if (!targetValue.isNull()) prevTarget.setValue(prevTarget.getInteger()+1);
break;
case DenormaliserTargetField.TYPE_AGGR_AVERAGE:
if (!targetValue.isNull())
{
data.counters[idx]++;
data.sum[idx].plus(targetValue);
}
break;
case DenormaliserTargetField.TYPE_AGGR_NONE:
default:
prevTarget.setValue(targetValue); // Overwrite the previous
break;
}
}
}
}
}
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(DenormaliserMeta)smi;
data=(DenormaliserData)sdi;
if (super.init(smi, sdi))
{
data.counters = new long[meta.getDenormaliserTargetField().length];
data.sum = new Value[meta.getDenormaliserTargetField().length];
return true;
}
return false;
}
// Run is were the action happens!
public void run()
{
try
{
logBasic(Messages.getString("Denormaliser.Log.StartingToRun")); //$NON-NLS-1$
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError(Messages.getString("Denormaliser.Log.UnexpectedError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
|
package ch.idsia.benchmark.mario.environments;
import ch.idsia.agents.Agent;
import ch.idsia.benchmark.mario.engine.*;
import ch.idsia.benchmark.mario.engine.sprites.Mario;
import ch.idsia.benchmark.mario.engine.sprites.Sprite;
import ch.idsia.tools.EvaluationInfo;
import ch.idsia.tools.MarioAIOptions;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class MarioEnvironment implements Environment
{
private int[] marioEgoPos = new int[2];
private int receptiveFieldHeight = -1; // to be setup via MarioAIOptions
private int receptiveFieldWidth = -1; // to be setup via MarioAIOptions
private int prevRFH = -1;
private int prevRFW = -1;
private byte[][] levelSceneZ; // memory is allocated in reset
private byte[][] enemiesZ; // memory is allocated in reset
private byte[][] mergedZZ; // memory is allocated in reset
final public List<Sprite> sprites = new ArrayList<Sprite>();
private int[] serializedLevelScene; // memory is allocated in reset
private int[] serializedEnemies; // memory is allocated in reset
private int[] serializedMergedObservation; // memory is allocated in reset
private final LevelScene levelScene;
// private int frame = 0;
private MarioVisualComponent marioVisualComponent;
private Agent agent;
private static final MarioEnvironment ourInstance = new MarioEnvironment();
private static final EvaluationInfo evaluationInfo = new EvaluationInfo();
private static String marioTraceFile;
private Recorder recorder;
private float intermediateReward = -1;
public static MarioEnvironment getInstance()
{
return ourInstance;
}
private MarioEnvironment()
{
// System.out.println("System.getProperty(\"java.awt.headless\") = " + System.getProperty("java.awt.headless"));
// System.out.println("System.getProperty(\"verbose\") = " + System.getProperty("-verbose"));
// System.out.println("Java: JA ZDES'!!");
// System.out.flush();
System.out.println(GlobalOptions.getBenchmarkName());
levelScene = new LevelScene();
}
public void resetDefault()
{
levelScene.resetDefault();
}
public void reset(String args)
{
MarioAIOptions marioAIOptions = MarioAIOptions.getOptionsByString(args);
this.reset(marioAIOptions);
// MarioAIOptions opts = new MarioAIOptions(setUpOptions);
// int[] intOpts = opts.toIntArray();
// this.reset(intOpts);
}
public void reset(MarioAIOptions setUpOptions)
{
/*System.out.println("\nsetUpOptions = " + setUpOptions);
for (int i = 0; i < setUpOptions.length; ++i)
{
System.out.print(" op[" + i +"] = " + setUpOptions[i]);
}
System.out.println("");
System.out.flush();*/
// if (!setUpOptions.getReplayOptions().equals(""))
this.setAgent(setUpOptions.getAgent());
receptiveFieldWidth = setUpOptions.getReceptiveFieldWidth();
receptiveFieldHeight = setUpOptions.getReceptiveFieldHeight();
if (receptiveFieldHeight != this.prevRFH || receptiveFieldWidth != this.prevRFW)
{
serializedLevelScene = new int[receptiveFieldHeight * receptiveFieldWidth];
serializedEnemies = new int[receptiveFieldHeight * receptiveFieldWidth];
serializedMergedObservation = new int[receptiveFieldHeight * receptiveFieldWidth];
levelSceneZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
enemiesZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
mergedZZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
this.prevRFH = this.receptiveFieldHeight;
this.prevRFW = this.receptiveFieldWidth;
}
marioEgoPos[0] = setUpOptions.getMarioEgoPosRow();
marioEgoPos[1] = setUpOptions.getMarioEgoPosCol();
if (marioEgoPos[0] == 9 && getReceptiveFieldWidth() != 19)
marioEgoPos[0] = getReceptiveFieldWidth() / 2;
if (marioEgoPos[1] == 9 && getReceptiveFieldHeight() != 19)
marioEgoPos[1] = getReceptiveFieldHeight() / 2;
marioTraceFile = setUpOptions.getTraceFileName();
if (setUpOptions.isVisualization())
{
if (marioVisualComponent == null)
marioVisualComponent = MarioVisualComponent.getInstance(setUpOptions, this);
levelScene.reset(setUpOptions);
marioVisualComponent.reset();
marioVisualComponent.postInitGraphicsAndLevel();
marioVisualComponent.setAgent(agent);
marioVisualComponent.setLocation(setUpOptions.getViewLocation());
marioVisualComponent.setAlwaysOnTop(setUpOptions.isViewAlwaysOnTop());
if (setUpOptions.isScale2X())
GlobalOptions.changeScale2x();
} else
levelScene.reset(setUpOptions);
//create recorder
String recordingFileName = setUpOptions.getRecordingFileName();
if (!recordingFileName.equals("off"))
{
if (recordingFileName.equals("on"))
recordingFileName = GlobalOptions.getTimeStamp() + ".zip";
try
{
recorder = new Recorder(recordingFileName);
recorder.createFile("level.lvl");
recorder.writeObject(levelScene.level);
recorder.closeFile();
recorder.createFile("options");
recorder.writeObject(setUpOptions.asString());
recorder.closeFile();
recorder.createFile("actions.act");
} catch (FileNotFoundException e)
{
System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed");
} catch (IOException e)
{
System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed");
e.printStackTrace();
}
}
}
public void tick()
{
levelScene.tick();
if (GlobalOptions.isVisualization)
marioVisualComponent.tick();
}
public float[] getMarioFloatPos()
{
return levelScene.getMarioFloatPos();
}
public int getMarioMode()
{
return levelScene.getMarioMode();
}
public byte[][] getLevelSceneObservationZ(int ZLevel)
{
for (int y = levelScene.mario.mapY - receptiveFieldHeight / 2, row = 0; y <= levelScene.mario.mapY + receptiveFieldHeight / 2; y++, row++)
{
for (int x = levelScene.mario.mapX - receptiveFieldWidth / 2, col = 0; x <= levelScene.mario.mapX + receptiveFieldWidth / 2; x++, col++)
{
if (x >= 0 && x < levelScene.level.xExit && y >= 0 && y < levelScene.level.height)
{
levelSceneZ[row][col] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevel);
} else
{
levelSceneZ[row][col] = 0;
}
}
}
return levelSceneZ;
}
public byte[][] getEnemiesObservationZ(int ZLevel)
{
for (int w = 0; w < enemiesZ.length; w++)
for (int h = 0; h < enemiesZ[0].length; h++)
enemiesZ[w][h] = 0;
for (Sprite sprite : sprites)
{
if (sprite.kind == levelScene.mario.kind)
continue;
if (sprite.mapX >= 0 &&
sprite.mapX >= levelScene.mario.mapX - receptiveFieldWidth / 2 &&
sprite.mapX <= levelScene.mario.mapX + receptiveFieldWidth / 2 &&
sprite.mapY >= 0 &&
sprite.mapY >= levelScene.mario.mapY - receptiveFieldHeight / 2 &&
sprite.mapY <= levelScene.mario.mapY + receptiveFieldHeight / 2)
{
int row = sprite.mapY - levelScene.mario.mapY + receptiveFieldHeight / 2;
int col = sprite.mapX - levelScene.mario.mapX + receptiveFieldWidth / 2;
enemiesZ[row][col] = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevel);
}
}
return enemiesZ;
}
public byte[][] getMergedObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// int MarioXInMap = (int) mario.x / cellSize;
// int MarioYInMap = (int) mario.y / cellSize;
// if (MarioXInMap != (int) mario.x / cellSize ||MarioYInMap != (int) mario.y / cellSize )
// throw new Error("WRONG mario x or y pos");
for (int y = levelScene.mario.mapY - receptiveFieldHeight / 2, row = 0; y <= levelScene.mario.mapY + receptiveFieldHeight / 2; y++, row++)
{
for (int x = levelScene.mario.mapX - receptiveFieldWidth / 2, col = 0; x <= levelScene.mario.mapX + receptiveFieldWidth / 2; x++, col++)
{
if (x >= 0 && x < levelScene.level.xExit && y >= 0 && y < levelScene.level.height)
{
mergedZZ[row][col] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevelScene);
} else
mergedZZ[row][col] = 0;
// if (x == MarioXInMap && y == MarioYInMap)
// mergedZZ[row][col] = mario.kind;
}
}
// for (int w = 0; w < mergedZZ.length; w++)
// for (int h = 0; h < mergedZZ[0].length; h++)
// mergedZZ[w][h] = -1;
for (Sprite sprite : sprites)
{
if (sprite.kind == levelScene.mario.kind)
continue;
if (sprite.mapX >= 0 &&
sprite.mapX > levelScene.mario.mapX - receptiveFieldWidth / 2 &&
sprite.mapX < levelScene.mario.mapX + receptiveFieldWidth / 2 &&
sprite.mapY >= 0 &&
sprite.mapY > levelScene.mario.mapY - receptiveFieldHeight / 2 &&
sprite.mapY < levelScene.mario.mapY + receptiveFieldHeight / 2)
{
int row = sprite.mapY - levelScene.mario.mapY + receptiveFieldHeight / 2;
int col = sprite.mapX - levelScene.mario.mapX + receptiveFieldWidth / 2;
// quick fix TODO: handle this in more general way.
// TODO: !H! RESOLVE, if this is a canon, substitue '14' by explicit statement or remove the condition.
if (mergedZZ[row][col] != 14)
{
byte tmp = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevelEnemies);
if (tmp != Sprite.KIND_NONE)
mergedZZ[row][col] = tmp;
}
}
}
return mergedZZ;
}
public List<String> getObservationStrings(boolean Enemies, boolean LevelMap,
boolean mergedObservationFlag,
int ZLevelScene, int ZLevelEnemies)
{
List<String> ret = new ArrayList<String>();
if (levelScene.level != null && levelScene.mario != null)
{
ret.add("Total levelScene length = " + levelScene.level.length);
ret.add("Total levelScene height = " + levelScene.level.height);
ret.add("Physical Mario Position (x,y): (" + levelScene.mario.x + "," + levelScene.mario.y + ")");
ret.add("Mario Observation (Receptive Field) Width: " + receptiveFieldWidth + " Height: " + receptiveFieldHeight);
ret.add("X Exit Position: " + levelScene.level.xExit);
int MarioXInMap = (int) levelScene.mario.x / levelScene.cellSize;
int MarioYInMap = (int) levelScene.mario.y / levelScene.cellSize;
ret.add("Calibrated Mario Position (x,y): (" + MarioXInMap + "," + MarioYInMap + ")\n");
byte[][] levelScene = getLevelSceneObservationZ(ZLevelScene);
if (LevelMap)
{
ret.add("~ZLevel: Z" + ZLevelScene + " map:\n");
for (int x = 0; x < levelScene.length; ++x)
{
String tmpData = "";
for (int y = 0; y < levelScene[0].length; ++y)
tmpData += mapElToStr(levelScene[x][y]);
ret.add(tmpData);
}
}
byte[][] enemiesObservation = null;
if (Enemies || mergedObservationFlag)
enemiesObservation = getEnemiesObservationZ(ZLevelEnemies);
if (Enemies)
{
ret.add("~ZLevel: Z" + ZLevelScene + " Enemies Observation:\n");
for (int x = 0; x < enemiesObservation.length; x++)
{
String tmpData = "";
for (int y = 0; y < enemiesObservation[0].length; y++)
{
// if (x >=0 && x <= level.xExit)
tmpData += enemyToStr(enemiesObservation[x][y]);
}
ret.add(tmpData);
}
}
if (mergedObservationFlag)
{
byte[][] mergedObs = getMergedObservationZZ(ZLevelScene, ZLevelEnemies);
ret.add("~ZLevelScene: Z" + ZLevelScene + " ZLevelEnemies: Z" + ZLevelEnemies + " ; Merged observation /* Mario ~> #M.# */");
for (int x = 0; x < levelScene.length; ++x)
{
String tmpData = "";
for (int y = 0; y < levelScene[0].length; ++y)
tmpData += mapElToStr(mergedObs[x][y]);
ret.add(tmpData);
}
}
} else
ret.add("~[MarioAI ERROR] level : " + levelScene.level + " mario : " + levelScene.mario);
return ret;
}
private String mapElToStr(int el)
{
String s = "";
if (el == 0 || el == 1)
s = "
s += (el == levelScene.mario.kind) ? "#M.#" : el;
while (s.length() < 4)
s += "
return s + " ";
}
private String enemyToStr(int el)
{
String s = "";
if (el == 0)
s = "";
s += (el == levelScene.mario.kind) ? "-m" : el;
while (s.length() < 2)
s += "
return s + " ";
}
public float[] getEnemiesFloatPos()
{
return levelScene.getEnemiesFloatPos();
}
public boolean isMarioOnGround()
{
return levelScene.isMarioOnGround();
}
public boolean isMarioAbleToJump()
{
return levelScene.isMarioAbleToJump();
}
public boolean isMarioCarrying()
{
return levelScene.isMarioCarrying();
}
public boolean isMarioAbleToShoot()
{
return levelScene.isMarioAbleToShoot();
}
public int getReceptiveFieldWidth()
{
return receptiveFieldWidth;
}
public int getReceptiveFieldHeight()
{
return receptiveFieldHeight;
}
public int getKillsTotal()
{
return levelScene.getKillsTotal();
}
public int getKillsByFire()
{
return levelScene.getKillsByFire();
}
public int getKillsByStomp()
{
return levelScene.getKillsByStomp();
}
public int getKillsByShell()
{
return levelScene.getKillsByShell();
}
public int getMarioStatus()
{
return levelScene.getMarioStatus();
}
public float[] getSerializedFullObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// TODO:TASK:[M], serialize all data to a sole double[]
assert false;
return new float[0];
}
public int[] getSerializedLevelSceneObservationZ(int ZLevelScene)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] levelScene = this.getLevelSceneObservationZ(ZLevelScene);
for (int i = 0; i < serializedLevelScene.length; ++i)
{
final int i1 = i / receptiveFieldWidth;
final int i2 = i % receptiveFieldWidth;
serializedLevelScene[i] = (int) levelScene[i1][i2];
}
return serializedLevelScene;
}
public int[] getSerializedEnemiesObservationZ(int ZLevelEnemies)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] enemies = this.getEnemiesObservationZ(ZLevelEnemies);
for (int i = 0; i < serializedEnemies.length; ++i)
serializedEnemies[i] = (int) enemies[i / receptiveFieldWidth][i % receptiveFieldWidth];
return serializedEnemies;
}
public int[] getSerializedMergedObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] merged = this.getMergedObservationZZ(ZLevelScene, ZLevelEnemies);
for (int i = 0; i < serializedMergedObservation.length; ++i)
serializedMergedObservation[i] = (int) merged[i / receptiveFieldWidth][i % receptiveFieldWidth];
return serializedMergedObservation;
}
public float[] getCreaturesFloatPos()
{
return levelScene.getCreaturesFloatPos();
}
public int[] getMarioState()
{
return levelScene.getMarioState();
}
public void performAction(boolean[] action)
{
try
{
if (recorder != null && action != null)
{
recorder.writeAction(action);
recorder.changeRecordingState(GlobalOptions.isRecording, getTimeSpent());
}
} catch (IOException e)
{
e.printStackTrace();
}
levelScene.performAction(action);
}
public boolean isLevelFinished()
{
return levelScene.isLevelFinished();
}
public int[] getEvaluationInfoAsInts()
{
return this.getEvaluationInfo().toIntArray();
}
public String getEvaluationInfoAsString()
{
return this.getEvaluationInfo().toString();
}
public EvaluationInfo getEvaluationInfo()
{
computeEvaluationInfo();
return evaluationInfo;
}
private void computeEvaluationInfo()
{
if (recorder != null)
closeRecorder();
// evaluationInfo.agentType = agent.getClass().getSimpleName();
// evaluationInfo.agentName = agent.getName();
evaluationInfo.marioStatus = levelScene.getMarioStatus();
evaluationInfo.flowersDevoured = Mario.flowersDevoured;
evaluationInfo.distancePassedPhys = (int) levelScene.mario.x;
evaluationInfo.distancePassedCells = levelScene.mario.mapX;
// evaluationInfo.totalLengthOfLevelCells = levelScene.level.getWidthCells();
// evaluationInfo.totalLengthOfLevelPhys = levelScene.level.getWidthPhys();
evaluationInfo.timeSpent = levelScene.getTimeSpent();
evaluationInfo.timeLeft = levelScene.getTimeLeft();
evaluationInfo.coinsGained = Mario.coins;
evaluationInfo.totalNumberOfCoins = levelScene.level.counters.coinsCount;
evaluationInfo.totalNumberOfHiddenBlocks = levelScene.level.counters.hiddenBlocksCount;
evaluationInfo.totalNumberOfFlowers = levelScene.level.counters.flowers;
evaluationInfo.totalNumberOfMushrooms = levelScene.level.counters.mushrooms;
evaluationInfo.totalNumberOfCreatures = levelScene.level.counters.creatures;
evaluationInfo.marioMode = levelScene.getMarioMode();
evaluationInfo.mushroomsDevoured = Mario.mushroomsDevoured;
evaluationInfo.killsTotal = levelScene.getKillsTotal();
evaluationInfo.killsByStomp = levelScene.getKillsByStomp();
evaluationInfo.killsByFire = levelScene.getKillsByFire();
evaluationInfo.killsByShell = levelScene.getKillsByShell();
evaluationInfo.hiddenBlocksFound = Mario.hiddenBlocksFound;
evaluationInfo.collisionsWithCreatures = Mario.collisionsWithCreatures;
evaluationInfo.Memo = levelScene.memo;
evaluationInfo.levelLength = levelScene.level.length;
evaluationInfo.marioTraceFileName = marioTraceFile;
evaluationInfo.marioTrace = levelScene.level.marioTrace;
}
public void setAgent(Agent agent)
{
this.agent = agent;
}
public float getIntermediateReward()
{
// TODO: reward for coins, killed creatures, cleared dead-ends, bypassed gaps, hidden blocks found
return intermediateReward;
}
public int[] getMarioEgoPos()
{
return marioEgoPos;
}
public void closeRecorder()
{
if (recorder != null)
{
try
{
// recorder.closeFile();
recorder.closeRecorder(false, getTimeSpent());
recorder = null;
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public int getTimeSpent()
{
return levelScene.getTimeSpent();
}
public void setReplayer(Replayer replayer)
{
levelScene.setReplayer(replayer);
}
//public void setRecording(boolean isRecording)
// this.isRecording = isRecording;
}
|
package com.alphabetbloc.clinic.services;
import java.util.Iterator;
import java.util.List;
import org.odk.clinic.android.activities.DashboardActivity;
import org.odk.clinic.android.activities.DownloadPatientActivity;
import org.odk.clinic.android.activities.ListPatientActivity;
import org.odk.clinic.android.database.ClinicAdapter;
import android.app.ActivityManager;
import android.app.Service;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
*
* @author Louis Fazen (louis.fazen@gmail.com) (excerpts from curioustechizen
* from stackoverflow)
*
* This checks the signal strength, data connectivity and user activity
* before refreshing the patient list as background service.
*/
public class SignalStrengthService extends Service {
private ActivityManager mActivityManager;
private TelephonyManager mTelephonyManager;
private PhoneStateListener mPhoneStateListener;
private static final String TAG = "SignalStrengthService";
@Override
public IBinder onBind(Intent intent) {
// We don't want to bind; return null.
return null;
}
@Override
public void onCreate() {
Log.e(TAG, "SignalStrengthService Created");
mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
mPhoneStateListener = new PhoneStateListener() {
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
int asu = signalStrength.getGsmSignalStrength();
// if (asu >= 8 && asu < 32) {
// TODO: bring this back in with the ASU
// TODO: change the activity that is started...
Log.e(TAG, "asu=" + asu);
if (networkAvailable()) {
Log.e(TAG, "network available");
if (refreshClientsNow()) {
Log.e(TAG, "refresh now okay");
Intent id = new Intent(getApplicationContext(), DownloadPatientActivity.class);
id.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(id);
}
}
super.onSignalStrengthsChanged(signalStrength);
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
// do something
Log.d("louis.fazen", "Service State changed! New state = " + serviceState.getState());
super.onServiceStateChanged(serviceState);
}
};
super.onCreate();
}
/*
* int iconLevel = -1; if (asu <= 2 || asu == 99) iconLevel = 0; // 0 or 99
* = no signal else if (asu >= 12) iconLevel = 4; // very good signal else
* if (asu >= 8) iconLevel = 3; // good signal else if (asu >= 5) iconLevel
* = 2; // poor signal else iconLevel = 1; // <5 is very poor signal
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "SignalStrengthService Started");
boolean max = intent.getBooleanExtra("maximum", false);
Log.e(TAG, "boolean extra =" + max);
// Register the listener, which effectively starts the service
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS | PhoneStateListener.LISTEN_SERVICE_STATE);
return super.onStartCommand(intent, flags, startId);
}
private boolean networkAvailable() {
boolean dataNetwork = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null)
dataNetwork = true;
return dataNetwork;
}
private void updateService() {
// if 2G, then update to 3G?
int nt = mTelephonyManager.getNetworkType();
if (nt < 3)
Log.d(TAG, "network type =" + nt);
/*
* switch (nt) { case 1: return GPRS; case 2: return EDGE; case 3:
* return UMTS; case 8: return HSDPA; case 9: return HSUPA; case 10:
* return HSPA; default: return UNKNOWN; }
*/
}
@Override
public void onDestroy() {
Log.d(TAG, "Shutting down the Service" + TAG);
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
super.onDestroy();
}
private boolean refreshClientsNow() {
RunningAppProcessInfo info = null;
boolean refreshClients = true;
String collectPackage = "org.odk.collect.android";
String clinicPackage = "org.odk.clinic.android";
String createPatientClass = "org.odk.clinic.android.activities.CreatePatientActivity";
String listPatientClass = "org.odk.clinic.android.activities.ListPatientActivity";
if (mActivityManager == null)
mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
Iterator<RunningAppProcessInfo> i = l.iterator();
while (i.hasNext()) {
info = i.next();
// If Collect is visible, set refreshClients to false
if (info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (info.processName.equals(collectPackage))
refreshClients = false;
if (info.processName.equals(clinicPackage)) {
ComponentName foreGround = getActivityForApp(info);
// if (isStillActive(info, foreGround)) {
if (foreGround != null) {
if (foreGround.getClassName().equals(createPatientClass))
refreshClients = false;
else if (foreGround.getClassName().equals(listPatientClass) && ListPatientActivity.mListType == DashboardActivity.LIST_SIMILAR_CLIENTS)
refreshClients = false;
}
}
}
}
return refreshClients;
}
private RunningAppProcessInfo getForegroundApp() {
RunningAppProcessInfo result = null, info = null;
if (mActivityManager == null)
mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
// mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
Iterator<RunningAppProcessInfo> i = l.iterator();
while (i.hasNext()) {
info = i.next();
if (info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
result = info;
break;
}
}
return result;
}
private ComponentName getActivityForApp(RunningAppProcessInfo target) {
ComponentName result = null;
ActivityManager.RunningTaskInfo info;
if (target == null)
return null;
if (mActivityManager == null)
mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
// mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> l = mActivityManager.getRunningTasks(9999);
Iterator<ActivityManager.RunningTaskInfo> i = l.iterator();
while (i.hasNext()) {
info = i.next();
if (info.baseActivity.getPackageName().equals(target.processName)) {
result = info.topActivity;
break;
}
}
return result;
}
private boolean isStillActive(RunningAppProcessInfo process, ComponentName activity) {
// activity can be null in cases, where one app starts another. for
// example, astro
// starting rock player when a move file was clicked. we dont have an
// activity then,
// but the package exits as soon as back is hit. so we can ignore the
// activity
// in this case
if (process == null)
return false;
RunningAppProcessInfo currentFg = getForegroundApp();
ComponentName currentActivity = getActivityForApp(currentFg);
if (currentFg != null && currentFg.processName.equals(process.processName) && (activity == null || currentActivity.compareTo(activity) == 0))
return true;
Log.i("RefreshClientServive", "isStillActive returns false - CallerProcess: " + process.processName + " CurrentProcess: " + (currentFg == null ? "null" : currentFg.processName) + " CallerActivity:" + (activity == null ? "null" : activity.toString())
+ " CurrentActivity: " + (currentActivity == null ? "null" : currentActivity.toString()));
return false;
}
private boolean isRunningService(String processname) {
// if(processname==null || processname.isEmpty())
if (processname == null || processname.length() < 1)
return false;
RunningServiceInfo service;
if (mActivityManager == null)
mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
// mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> l = mActivityManager.getRunningServices(9999);
Iterator<RunningServiceInfo> i = l.iterator();
while (i.hasNext()) {
service = i.next();
if (service.process.equals(processname))
return true;
}
return false;
}
}
|
package org.languagetool.rules.de;
import de.danielnaber.jwordsplitter.GermanWordSplitter;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.language.German;
import org.languagetool.rules.Example;
import org.languagetool.rules.spelling.hunspell.CompoundAwareHunspellRule;
import org.languagetool.rules.spelling.morfologik.MorfologikMultiSpeller;
import org.languagetool.synthesis.Synthesizer;
import org.languagetool.tagging.Tagger;
import org.languagetool.tokenizers.de.GermanCompoundTokenizer;
import org.languagetool.tools.StringTools;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class GermanSpellerRule extends CompoundAwareHunspellRule {
public static final String RULE_ID = "GERMAN_SPELLER_RULE";
private static final Pattern ENDINGS_NEEDING_FUGENS = Pattern.compile(".*(tum|ling|ion|tät|keit|schaft|sicht|ung|en)");
private static final int MAX_EDIT_DISTANCE = 2;
// some exceptions for changes to the spelling in 2017 - just a workaround so we don't have to touch the binary dict:
private static final Pattern PREVENT_SUGGESTION = Pattern.compile(
".*(?i:Majonäse|Bravur|Anschovis|Belkanto|Campagne|Frotté|Grisli|Jokei|Joga|Kalvinismus|Kanossa|Kargo|Ketschup|" +
"Kollier|Kommunikee|Masurka|Negligee|Nessessär|Poulard|Varietee|Wandalismus|kalvinist).*");
private final LineExpander lineExpander = new LineExpander();
private final GermanCompoundTokenizer compoundTokenizer;
private final GermanWordSplitter splitter;
private final Synthesizer synthesizer;
private final Tagger tagger;
public GermanSpellerRule(ResourceBundle messages, German language) {
super(messages, language, language.getNonStrictCompoundSplitter(), getSpeller(language));
addExamplePair(Example.wrong("LanguageTool kann mehr als eine <marker>nromale</marker> Rechtschreibprüfung."),
Example.fixed("LanguageTool kann mehr als eine <marker>normale</marker> Rechtschreibprüfung."));
compoundTokenizer = language.getStrictCompoundTokenizer();
tagger = language.getTagger();
synthesizer = language.getSynthesizer();
try {
splitter = new GermanWordSplitter(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void init() throws IOException {
super.init();
String pattern = "(" + nonWordPattern.pattern() + "|(?<=\\d)-|-(?=\\d+))";
nonWordPattern = Pattern.compile(pattern);
needsInit = false;
}
@Override
public String getId() {
return RULE_ID;
}
@Override
public List<String> getCandidates(String word) {
List<List<String>> partList = splitter.getAllSplits(word);
List<String> candidates = new ArrayList<>();
for (List<String> parts : partList) {
candidates.addAll(super.getCandidates(parts));
if (parts.size() == 2 && !parts.get(0).endsWith("s")) {
// so we get e.g. Einzahlungschein -> Einzahlungsschein
candidates.add(parts.get(0) + "s" + parts.get(1));
}
if (parts.size() == 2 && parts.get(1).startsWith("s")) {
String firstPart = parts.get(0);
String secondPart = parts.get(1);
candidates.addAll(super.getCandidates(Arrays.asList(firstPart + "s", secondPart.substring(1))));
}
}
return candidates;
}
@Override
protected boolean isProhibited(String word) {
return word.startsWith("Standart-") || super.isProhibited(word);
}
@Override
protected void addIgnoreWords(String origLine) {
String line;
if (language.getShortCodeWithCountryAndVariant().equals("de-CH")) {
line = origLine.replace("ß", "ss");
} else {
line = origLine;
}
List<String> words = expandLine(line);
for (String word : words) {
super.addIgnoreWords(word);
}
}
@Override
protected List<String> expandLine(String line) {
return lineExpander.expandLine(line);
}
/*
* @since 3.6
*/
@Override
public List<String> getSuggestions(String word) throws IOException {
List<String> suggestions = super.getSuggestions(word);
suggestions = suggestions.stream().filter(k -> !PREVENT_SUGGESTION.matcher(k).matches() && !k.endsWith("roulett")).collect(Collectors.toList());
if (word.endsWith(".")) {
// To avoid losing the "." of "word" if it is at the end of a sentence.
suggestions.replaceAll(s -> s.endsWith(".") ? s : s + ".");
}
return suggestions;
}
@Nullable
private static MorfologikMultiSpeller getSpeller(Language language) {
if (!language.getShortCode().equals(Locale.GERMAN.getLanguage())) {
throw new RuntimeException("Language is not a variant of German: " + language);
}
try {
String morfoFile = "/de/hunspell/de_" + language.getCountries()[0] + ".dict";
if (JLanguageTool.getDataBroker().resourceExists(morfoFile)) {
// spell data will not exist in LibreOffice/OpenOffice context
try (InputStream stream = JLanguageTool.getDataBroker().getFromResourceDirAsStream("/de/hunspell/spelling.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "utf-8"))) {
return new MorfologikMultiSpeller(morfoFile, new ExpandingReader(br), MAX_EDIT_DISTANCE);
}
} else {
return null;
}
} catch (IOException e) {
throw new RuntimeException("Could not set up morfologik spell checker", e);
}
}
@Override
protected void filterForLanguage(List<String> suggestions) {
if (language.getShortCodeWithCountryAndVariant().equals("de-CH")) {
for (int i = 0; i < suggestions.size(); i++) {
String s = suggestions.get(i);
suggestions.set(i, s.replace("ß", "ss"));
}
}
// Remove suggestions like "Mafiosi s" and "Mafiosi s.":
suggestions.removeIf(s -> Arrays.stream(s.split(" ")).anyMatch(k -> k.matches("\\w\\p{Punct}?")));
// This is not quite correct as it might remove valid suggestions that start with "-",
// but without this we get too many strange suggestions that start with "-" for no apparent reason
// (e.g. for "Gratifikationskrisem" -> "-Gratifikationskrisen"):
suggestions.removeIf(s -> s.length() > 1 && s.startsWith("-"));
}
@Override
protected List<String> sortSuggestionByQuality(String misspelling, List<String> suggestions) {
List<String> result = new ArrayList<>();
for (String suggestion : suggestions) {
if (misspelling.equalsIgnoreCase(suggestion)) {
// this should be preferred - only case differs:
result.add(0, suggestion);
} else if (suggestion.contains(" ")) {
// prefer e.g. "vor allem":
result.add(0, suggestion);
} else {
result.add(suggestion);
}
}
return result;
}
@Override
protected boolean ignoreWord(List<String> words, int idx) throws IOException {
boolean ignore = super.ignoreWord(words, idx);
boolean ignoreUncapitalizedWord = !ignore && idx == 0 && super.ignoreWord(StringUtils.uncapitalize(words.get(0)));
boolean ignoreByHyphen = false, ignoreHyphenatedCompound = false;
if (!ignore && !ignoreUncapitalizedWord) {
if (words.get(idx).contains("-")) {
ignoreByHyphen = words.get(idx).endsWith("-") && ignoreByHangingHyphen(words, idx);
}
ignoreHyphenatedCompound = !ignoreByHyphen && ignoreCompoundWithIgnoredWord(words.get(idx));
}
return ignore || ignoreUncapitalizedWord || ignoreByHyphen || ignoreHyphenatedCompound;
}
@Override
protected List<String> getAdditionalTopSuggestions(List<String> suggestions, String word) throws IOException {
String w = StringUtils.removeEnd(word, ".");
String suggestion;
if ("WIFI".equals(word) || "wifi".equals(word)) {
return Collections.singletonList("Wi-Fi");
} else if ("ausversehen".equals(word)) {
return Collections.singletonList("aus Versehen");
} else if ("getz".equals(word)) {
return Arrays.asList("jetzt", "geht's");
} else if ("Trons".equals(word)) {
return Collections.singletonList("Trance");
} else if (word.matches("desweitere[nm]")) {
return Collections.singletonList("des Weiteren");
} else if (word.matches("einzigste[mnrs]?")) {
return Collections.singletonList(word.replaceFirst("^einzigst", "einzig"));
} else if (word.endsWith("standart")) {
suggestion = word.replaceFirst("standart$", "standard");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.endsWith("standarts")) {
suggestion = word.replaceFirst("standarts$", "standards");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.endsWith("parties")) {
suggestion = word.replaceFirst("parties$", "partys");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.endsWith("derbies")) {
suggestion = word.replaceFirst("derbies$", "derbys");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.endsWith("stories")) {
suggestion = word.replaceFirst("stories$", "storys");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.endsWith("tip")) {
suggestion = word.replaceFirst("tip$", "tipp");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.endsWith("tips")) {
suggestion = word.replaceFirst("tips$", "tipps");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.endsWith("oullie")) {
suggestion = word.replaceFirst("oullie$", "ouille");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.startsWith("Bundstift")) {
suggestion = word.replaceFirst("^Bundstift", "Buntstift");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.matches(".*[mM]ajonäse.*")) {
suggestion = word.replaceFirst("ajonäse", "ayonnaise");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.matches(".*[lL]aborants$")) {
suggestion = word.replaceFirst("ts$", "ten");
if (!hunspellDict.misspelled(suggestion)) {
return Collections.singletonList(suggestion);
}
} else if (word.matches("interkurell(e[nmrs]?)?")) {
suggestion = word.replaceFirst("ku", "kultu");
return Collections.singletonList(suggestion);
} else if (word.equals("wolt")) {
return Collections.singletonList("wollt");
} else if (word.equals("angepreist")) {
return Collections.singletonList("angepriesen");
} else if (word.equals("halo")) {
return Collections.singletonList("hallo");
} else if (word.equals("zuende")) {
return Collections.singletonList("zu Ende");
} else if (word.equals("zumindestens")) {
return Collections.singletonList("zumindest");
} else if (word.equals("ca")) {
return Collections.singletonList("ca.");
} else if (word.equals("Jezt")) {
return Collections.singletonList("Jetzt");
} else if (word.equals("Rolladen")) {
return Collections.singletonList("Rollladen");
} else if (word.equals("Maßname")) {
return Collections.singletonList("Maßnahme");
} else if (word.equals("Maßnamen")) {
return Collections.singletonList("Maßnahmen");
} else if (word.equals("nanten")) {
return Collections.singletonList("nannten");
} else if (word.equals("Stories")) {
return Collections.singletonList("Storys");
} else if (word.equals("Lobbies")) {
return Collections.singletonList("Lobbys");
} else if (word.equals("Hobbies")) {
return Collections.singletonList("Hobbys");
} else if (word.equals("Parties")) {
return Collections.singletonList("Partys");
} else if (word.equals("Babies")) {
return Collections.singletonList("Babys");
} else if (word.equals("Ladies")) {
return Collections.singletonList("Ladys");
} else if (word.equals("Hallochen")) {
return Arrays.asList("Hallöchen", "hallöchen");
} else if (word.equals("hallochen")) {
return Collections.singletonList("hallöchen");
} else if (word.matches("[mM]issionarie?sie?rung")) {
return Collections.singletonList("Missionierung");
} else if (word.matches("[sS]chee?selonge?")) {
return Collections.singletonList("Chaiselongue");
} else if (word.matches("Re[kc]amiere")) {
return Collections.singletonList("Récamière");
} else if (word.matches("legen[td]lich")) {
return Collections.singletonList("lediglich");
} else if (word.matches("[mM]illion(en)?mal")) {
suggestion = word.replaceFirst("^million", "Million");
suggestion = suggestion.replaceFirst("mal$", "");
return Collections.singletonList(suggestion + " Mal");
} else if (word.equals("ok")) {
return Arrays.asList("okay", "O.\u202fK."); // Duden-like suggestion with no-break space
} else if (word.equals("Germanistiker")) {
return Arrays.asList("Germanist", "Germanisten");
} else if (word.matches("Germanistiker[ns]")) {
return Collections.singletonList("Germanisten");
} else if (word.matches("Germanistikerin(nen)?")) {
return Collections.singletonList(word.replaceFirst("Germanistiker", "Germanist"));
} else if (word.matches("[eE]rhöherung")) {
return Collections.singletonList("Erhöhung");
} else if (word.matches("[eE]rhöherungen")) {
return Collections.singletonList("Erhöhungen");
} else if (word.matches("[aA]ufjedenfall")) {
suggestion = word.replaceFirst("jedenfall$", "");
return Collections.singletonList(suggestion + " jeden Fall");
} else if (word.matches("^funk?z[ou]nier.+")) {
suggestion = word.replaceFirst("funk?z[ou]nier", "funktionier");
return Collections.singletonList(suggestion);
} else if (word.equals("Wöruber")) {
return Collections.singletonList("Worüber");
} else if (word.equals("par")) {
return Collections.singletonList("paar");
} else if (word.equals("vllt")) {
return Collections.singletonList("vielleicht");
} else if (word.equals("iwie")) {
return Collections.singletonList("irgendwie");
} else if (word.equals("sry")) {
return Collections.singletonList("sorry");
} else if (word.equals("Zynik")) {
return Collections.singletonList("Zynismus");
} else if (word.matches("[aA]wa")) {
return Arrays.asList("AWA", "ach was", "aber");
} else if (word.equals("ch")) {
return Collections.singletonList("ich");
} else if (word.matches("aufgehangen(e[mnrs]?)?$")) {
return Collections.singletonList(word.replaceFirst("hangen", "hängt"));
} else if (word.matches("rosane[mnrs]?$")) {
return Arrays.asList("rosa", word.replaceFirst("^rosan", "rosafarben"));
} else if (word.matches("geupdate[dt]$")) {
return Collections.singletonList("upgedatet");
} else if (word.matches("näste[mnrs]?$")) {
return Collections.singletonList(word.replaceFirst("^näs", "nächs"));
} else if (word.matches("Erdogans?$")) {
return Collections.singletonList(word.replaceFirst("^Erdogan", "Erdoğan"));
} else if (word.matches("Email[a-zäöü]{5,}")) {
String suffix = word.substring(5);
if (hunspellDict.misspelled(suffix)) {
List<String> suffixSuggestions = hunspellDict.suggest(suffix);
suffix = suffixSuggestions.isEmpty() ? suffix : suffixSuggestions.get(0);
}
return Collections.singletonList("E-Mail-"+Character.toUpperCase(suffix.charAt(0))+suffix.substring(1));
} else if (word.equals("wiederspiegeln")) {
return Collections.singletonList("widerspiegeln");
} else if (!StringTools.startsWithUppercase(word)) {
String ucWord = StringTools.uppercaseFirstChar(word);
if (!suggestions.contains(ucWord) && !hunspellDict.misspelled(ucWord)) {
// Hunspell doesn't always automatically offer the most obvious suggestion for compounds:
return Collections.singletonList(ucWord);
}
}
String verbSuggestion = getPastTenseVerbSuggestion(word);
if (verbSuggestion != null) {
return Collections.singletonList(verbSuggestion);
}
String participleSuggestion = getParticipleSuggestion(word);
if (participleSuggestion != null) {
return Collections.singletonList(participleSuggestion);
}
// hyphenated compounds words (e.g., "Netflix-Flm")
if (suggestions.isEmpty() && word.contains("-")) {
String[] words = word.split("-");
if (words.length > 1) {
List<List<String>> suggestionLists = new ArrayList<>(words.length);
int startAt = 0, stopAt = words.length;
if (super.ignoreWord(words[0] + "-" + words[1])) { // "Au-pair-Agentr"
startAt = 2;
suggestionLists.add(Collections.singletonList(words[0] + "-" + words[1]));
}
if (super.ignoreWord(words[words.length-2] + "-" + words[words.length-1])) { // "Seniren-Au-pair"
stopAt = words.length-2;
}
for (int idx = startAt; idx < stopAt; idx++) {
if (super.ignoreWord(words[idx])) {
suggestionLists.add(Collections.singletonList(words[idx]));
} else if (hunspellDict.misspelled(words[idx])) {
List<String> list = sortSuggestionByQuality(words[idx], super.getSuggestions(words[idx]));
suggestionLists.add(list);
} else {
suggestionLists.add(Collections.singletonList(words[idx]));
}
}
if (stopAt < words.length-1) {
suggestionLists.add(Collections.singletonList(words[words.length-2] + "-" + words[words.length-1]));
}
if (suggestionLists.size() <= 3) { // avoid OOM on words like "free-and-open-source-and-cross-platform"
List<String> additionalSuggestions = suggestionLists.get(0);
for (int idx = 1; idx < suggestionLists.size(); idx++) {
List<String> suggestionList = suggestionLists.get(idx);
List<String> newList = new ArrayList<>(additionalSuggestions.size() * suggestionList.size());
for (String additionalSuggestion : additionalSuggestions) {
for (String aSuggestionList : suggestionList) {
newList.add(additionalSuggestion + "-" + aSuggestionList);
}
}
additionalSuggestions = newList;
}
return additionalSuggestions;
}
}
}
return Collections.emptyList();
}
// Get a correct suggestion for invalid words like greifte, denkte, gehte: useful for
// non-native speakers and cannot be found by just looking for similar words.
@Nullable
private String getPastTenseVerbSuggestion(String word) {
if (word.endsWith("e")) {
// strip trailing "e"
String wordStem = word.substring(0, word.length()-1);
try {
String lemma = baseForThirdPersonSingularVerb(wordStem);
if (lemma != null) {
AnalyzedToken token = new AnalyzedToken(lemma, null, lemma);
String[] forms = synthesizer.synthesize(token, "VER:3:SIN:PRT:.*", true);
if (forms.length > 0) {
return forms[0];
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
@Nullable
private String baseForThirdPersonSingularVerb(String word) throws IOException {
List<AnalyzedTokenReadings> readings = tagger.tag(Collections.singletonList(word));
for (AnalyzedTokenReadings reading : readings) {
if (reading.hasPartialPosTag("VER:3:SIN:")) {
return reading.getReadings().get(0).getLemma();
}
}
return null;
}
// Get a correct suggestion for invalid words like geschwimmt, geruft: useful for
// non-native speakers and cannot be found by just looking for similar words.
@Nullable
private String getParticipleSuggestion(String word) {
if (word.startsWith("ge") && word.endsWith("t")) {
// strip leading "ge" and replace trailing "t" with "en":
String baseform = word.substring(2, word.length()-1) + "en";
try {
String participle = getParticipleForBaseform(baseform);
if (participle != null) {
return participle;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
@Nullable
private String getParticipleForBaseform(String baseform) throws IOException {
AnalyzedToken token = new AnalyzedToken(baseform, null, baseform);
String[] forms = synthesizer.synthesize(token, "VER:PA2:.*", true);
if (forms.length > 0 && !hunspellDict.misspelled(forms[0])) {
return forms[0];
}
return null;
}
private boolean ignoreByHangingHyphen(List<String> words, int idx) {
String word = words.get(idx);
String nextWord = getWordAfterEnumerationOrNull(words, idx+1);
if (nextWord != null) {
nextWord = StringUtils.removeEnd(nextWord, ".");
}
boolean isCompound = nextWord != null && compoundTokenizer.tokenize(nextWord).size() > 1;
if (isCompound) {
return !hunspellDict.misspelled(StringUtils.removeEnd(word, "-"));
}
return false;
}
@Nullable
private String getWordAfterEnumerationOrNull(List<String> words, int idx) {
for (int i = idx; i < words.size(); i++) {
String word = words.get(i);
boolean inEnumeration = ",".equals(word) || "und".equals(word) || "oder".equals(word) || word.trim().isEmpty() || word.endsWith("-");
if (!inEnumeration) {
return word;
}
}
return null;
}
// check whether a <code>word<code> is a valid compound (e.g., "Feynmandiagramm" or "Feynman-Diagramm")
// that contains an ignored word from spelling.txt (e.g., "Feynman")
private boolean ignoreCompoundWithIgnoredWord(String word) throws IOException{
if (!StringTools.startsWithUppercase(word) && !word.matches("(nord|ost|süd|west).*")) {
// otherwise stuff like "rumfangreichen" gets accepted
return false;
}
String[] words = word.split("-");
if (words.length < 2) {
// non-hyphenated compound (e.g., "Feynmandiagramm"):
// only search for compounds that start(!) with a word from spelling.txt
int end = super.startsWithIgnoredWord(word, true);
if (end < 3) {
// to accept sentences such as
if (word.startsWith("ost") || word.startsWith("süd")) {
end = 3;
} else if (word.startsWith("west") || word.startsWith("nord")) {
end = 4;
} else {
return false;
}
}
String ignoredWord = word.substring(0, end);
String partialWord = word.substring(end);
boolean needFugenS = ENDINGS_NEEDING_FUGENS.matcher(ignoredWord).matches();
if (!needFugenS && partialWord.length() > 1) {
return !hunspellDict.misspelled(partialWord) || !hunspellDict.misspelled(StringUtils.capitalize(partialWord));
} else if (needFugenS && partialWord.length() > 2) {
partialWord = partialWord.startsWith("s") ? partialWord.substring(1) : partialWord;
return !hunspellDict.misspelled(partialWord) || !hunspellDict.misspelled(StringUtils.capitalize(partialWord));
}
return false;
}
// hyphenated compound (e.g., "Feynman-Diagramm"):
boolean hasIgnoredWord = false;
List<String> toSpellCheck = new ArrayList<>(3);
String stripFirst = word.substring(words[0].length()+1); // everything after the first "-"
String stripLast = word.substring(0, word.length()-words[words.length-1].length()-1); // everything up to the last "-"
if (super.ignoreWord(stripFirst)) { // e.g., "Senioren-Au-pair"
hasIgnoredWord = true;
if (!super.ignoreWord(words[0])) {
toSpellCheck.add(words[0]);
}
} else if (super.ignoreWord(stripLast)) { // e.g., "Au-pair-Agentur"
hasIgnoredWord = true;
if (!super.ignoreWord(words[words.length-1])){
toSpellCheck.add(words[words.length-1]);
}
} else {
for (String word1 : words) {
if (super.ignoreWord(word1)) {
hasIgnoredWord = true;
} else {
toSpellCheck.add(word1);
}
}
}
if (hasIgnoredWord) {
for (String w : toSpellCheck) {
if (hunspellDict.misspelled(w)) {
return false;
}
}
}
return hasIgnoredWord;
}
static class ExpandingReader extends BufferedReader {
private final List<String> buffer = new ArrayList<>();
private final LineExpander lineExpander = new LineExpander();
ExpandingReader(Reader in) {
super(in);
}
@Override
public String readLine() throws IOException {
if (buffer.size() > 0) {
return buffer.remove(0);
} else {
String line = super.readLine();
if (line == null) {
return null;
}
buffer.addAll(lineExpander.expandLine(line));
return buffer.remove(0);
}
}
}
}
|
package lcm.lcm;
import java.io.*;
public final class LCMDataOutputStream implements DataOutput
{
byte buf[];
int pos;
public LCMDataOutputStream()
{
this(512);
}
public LCMDataOutputStream(int sz)
{
this.buf = new byte[sz];
}
public LCMDataOutputStream(byte buf[])
{
this.buf = buf;
}
public void reset()
{
pos = 0;
}
void ensureSpace(int needed)
{
if (pos+needed >= buf.length) {
// compute new power-of-two capacity
int newlen = buf.length;
while (newlen < pos+needed)
newlen *= 2;
byte buf2[] = new byte[newlen];
System.arraycopy(buf, 0, buf2, 0, pos);
buf = buf2;
}
}
public void write(byte b[])
{
ensureSpace(b.length);
System.arraycopy(b, 0, buf, pos, b.length);
pos += b.length;
}
public void write(byte b[], int off, int len)
{
ensureSpace(len);
System.arraycopy(b, off, buf, pos, len);
pos += len;
}
public void write(int b)
{
ensureSpace(1);
buf[pos++] = (byte) b;
}
public void writeBoolean(boolean v)
{
ensureSpace(1);
buf[pos++] = v ? (byte) 1 : (byte) 0;
}
public void writeByte(int v)
{
ensureSpace(1);
buf[pos++] = (byte) v;
}
public void writeBytes(String s)
{
ensureSpace(s.length());
for (int i = 0; i < s.length(); i++) {
buf[pos++] = (byte) s.charAt(i);
}
}
public void writeChar(int v)
{
writeShort(v);
}
public void writeChars(String s)
{
ensureSpace(2*s.length());
for (int i = 0; i < s.length(); i++) {
int v = s.charAt(i);
buf[pos++] = (byte) (v>>>8);
buf[pos++] = (byte) (v>>>0);
}
}
/** Write a zero-terminated string consisting of 8 bit characters. **/
public void writeStringZ(String s)
{
ensureSpace(s.length()+1);
for (int i = 0; i < s.length(); i++) {
buf[pos++] = (byte) s.charAt(i);
}
buf[pos++] = 0;
}
public void writeDouble(double v)
{
writeLong(Double.doubleToLongBits(v));
}
public void writeFloat(float v)
{
writeInt(Float.floatToIntBits(v));
}
public void writeInt(int v)
{
ensureSpace(4);
buf[pos++] = (byte) (v>>>24);
buf[pos++] = (byte) (v>>>16);
buf[pos++] = (byte) (v>>>8);
buf[pos++] = (byte) (v>>>0);
}
public void writeLong(long v)
{
ensureSpace(8);
buf[pos++] = (byte) (v>>>56);
buf[pos++] = (byte) (v>>>48);
buf[pos++] = (byte) (v>>>40);
buf[pos++] = (byte) (v>>>32);
buf[pos++] = (byte) (v>>>24);
buf[pos++] = (byte) (v>>>16);
buf[pos++] = (byte) (v>>>8);
buf[pos++] = (byte) (v>>>0);
}
public void writeShort(int v)
{
ensureSpace(2);
buf[pos++] = (byte) (v>>>8);
buf[pos++] = (byte) (v>>>0);
}
public void writeUTF(String s)
{
assert(false);
}
/** Makes a copy of the internal buffer. **/
public byte[] toByteArray()
{
byte b[] = new byte[pos];
System.arraycopy(buf, 0, b, 0, pos);
return b;
}
/** Returns the internal buffer, which may be longer than the
* buffer that has been written to so far.
**/
public byte[] getBuffer()
{
return buf;
}
/** Get the number of bytes that have been written to the buffer. **/
public int size()
{
return pos;
}
}
|
package com.daveme.intellij.organizephpimports;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.php.codeInsight.PhpCodeInsightUtil;
import com.jetbrains.php.lang.psi.PhpFile;
import com.jetbrains.php.lang.psi.elements.PhpNamespace;
import com.jetbrains.php.lang.psi.elements.PhpPsiElement;
import com.jetbrains.php.lang.psi.elements.PhpUse;
import com.jetbrains.php.lang.psi.elements.PhpUseList;
import com.jetbrains.php.lang.psi.elements.impl.PhpNamespaceImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class OrganizeImports extends AnAction {
@Override
public void update(AnActionEvent e) {
super.update(e);
Object psiFile = e.getData(CommonDataKeys.PSI_FILE);
boolean enabled = psiFile instanceof PhpFile;
e.getPresentation().setVisible(enabled);
e.getPresentation().setEnabled(enabled);
}
@Override
public void actionPerformed(AnActionEvent e) {
Object psiFile = e.getData(CommonDataKeys.PSI_FILE);
final PhpFile file = (PhpFile)psiFile;
final Editor editor = e.getData(CommonDataKeys.EDITOR);
if (editor == null || psiFile == null) {
return;
}
new WriteCommandAction.Simple(file.getProject(), file) {
@Override
protected void run() throws Throwable {
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
if (element == null) {
return;
}
PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(element);
if (scopeForUseOperator == null) {
return;
}
List imports = PhpCodeInsightUtil.collectImports(scopeForUseOperator);
Integer startingOffset = removeUseStatements(imports, editor);
PsiElement namespaceParent = PsiTreeUtil.findFirstParent(element, PhpNamespace.INSTANCEOF);
boolean indentExtraLevel = false;
if (namespaceParent != null) {
PhpNamespaceImpl parent = (PhpNamespaceImpl)namespaceParent;
indentExtraLevel = parent.isBraced();
}
if (startingOffset != null) {
StringBuilder useStatements = generateUseStatements(imports, indentExtraLevel);
editor.getDocument().insertString(startingOffset, useStatements);
}
}
}.execute();
}
@Nullable
private Integer removeUseStatements(List imports, Editor editor) {
int modifyOffset = 0;
Integer startingOffset = null;
for (Object useListObject : imports) {
PhpUseList useList = (PhpUseList)useListObject;
TextRange textRange = useList.getTextRange();
if (startingOffset == null) {
startingOffset = textRange.getStartOffset();
}
// get the newline character after this use statement if there is one:
PsiElement subsequentElement = useList.getNextSibling();
modifyOffset = removeRange(modifyOffset, textRange, editor);
if (subsequentElement instanceof PsiWhiteSpace) {
PsiElement nextElement = subsequentElement.getNextSibling();
if (nextElement instanceof PhpUseList) {
modifyOffset = removeRange(modifyOffset, subsequentElement.getTextRange(), editor);
} else {
modifyOffset = removeUpToNextNewLine(modifyOffset, subsequentElement.getTextRange(), editor);
}
}
}
return startingOffset;
}
@NotNull
private StringBuilder generateUseStatements(List imports, boolean indentExtraLevel) {
// replace the use statements:
StringBuilder useStatements = new StringBuilder();
useStatements.append("use ");
int totalUses = 0;
for (Object useListObject : imports) {
PhpUseList useList = (PhpUseList)useListObject;
for (PhpUse use : useList.getDeclarations()) {
if (totalUses > 0) {
useStatements.append(",\n\t");
if (indentExtraLevel) {
useStatements.append("\t");
}
}
useStatements.append(use.getFQN());
totalUses++;
}
}
useStatements.append(";\n");
return useStatements;
}
private int removeRange(int modifyOffset, TextRange textRange, Editor editor) {
editor.getDocument().deleteString(textRange.getStartOffset() - modifyOffset,
textRange.getEndOffset() - modifyOffset);
return modifyOffset + textRange.getEndOffset() - textRange.getStartOffset();
}
private int removeUpToNextNewLine(int modifyOffset, TextRange textRange, Editor editor) {
TextRange modifiedRange = new TextRange(textRange.getStartOffset() - modifyOffset,
textRange.getEndOffset() - modifyOffset);
String text = editor.getDocument().getText(modifiedRange);
char[] chars = text.toCharArray();
int textLength = 0;
for (char aChar : chars) {
textLength += 1;
if (aChar == '\n') {
break;
}
}
TextRange newRange = new TextRange(textRange.getStartOffset(), textRange.getStartOffset() + textLength);
return removeRange(modifyOffset, newRange, editor);
}
}
|
package com.dmdirc.addons.ui_swing.dialogs.serverlist;
import com.dmdirc.addons.ui_swing.components.vetoable.VetoableComboBoxModel;
import com.dmdirc.config.Identity;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.serverlists.ServerGroupItem;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import net.miginfocom.swing.MigLayout;
/**
* Profile selection field for an associated server group item.
*/
public class Profiles extends JPanel implements ServerListListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 2;
/** Server list model. */
private final ServerListModel model;
/** Combo boxes. */
private final Map<ServerGroupItem, JComboBox> combos =
new HashMap<ServerGroupItem, JComboBox>();
/** Info label. */
private final JLabel label;
/**
* Creates a new profile panel backed by the specified model.
*
* @param model Backing server list model
*/
public Profiles(final ServerListModel model) {
super();
this.model = model;
label = new JLabel("Use this profile on this network: ");
setBorder(BorderFactory.createTitledBorder(UIManager.getBorder(
"TitledBorder.border"), "Default profile"));
addListeners();
setLayout(new MigLayout("fill"));
add(label);
add(getComboBox(model.getSelectedItem()), "grow, push");
}
/**
* Adds required listeners.
*/
private void addListeners() {
model.addServerListListener(this);
}
/** {@inheritDoc} */
@Override
public void serverGroupChanged(final ServerGroupItem item) {
setVisible(false);
removeAll();
add(label);
add(getComboBox(item), "grow, push");
setVisible(true);
}
/**
* Gets or creates a combo box for selecting performs for the specified
* server group item.
*
* @param item Server group item requiring the profile selection
*
* @return The server group item's associated profile selection box
*/
private JComboBox getComboBox(final ServerGroupItem item) {
if (!combos.containsKey(item)) {
final DefaultComboBoxModel comboModel = new VetoableComboBoxModel();
final List<Identity> profiles = IdentityManager.getCustomIdentities(
"profile");
Identity selectedItem = null;
comboModel.addElement(null);
for (Identity profile : profiles) {
comboModel.addElement(profile);
if (item != null && profile.getName().equals(
item.getProfile())) {
selectedItem = profile;
}
}
comboModel.setSelectedItem(selectedItem);
combos.put(item, new JComboBox(comboModel));
}
return combos.get(item);
}
/** {@inheritDoc} */
@Override
public void dialogClosed(final boolean save) {
if (save) {
for (Entry<ServerGroupItem, JComboBox> entry : combos.entrySet()) {
if (entry.getKey() != null) {
if (entry.getValue().getSelectedItem() == null) {
entry.getKey().setProfile(null);
} else {
entry.getKey().setProfile(((Identity) entry.getValue().
getSelectedItem()).getName());
}
}
}
}
}
/** {@inheritDoc} */
@Override
public void serverGroupAdded(final ServerGroupItem parent,
final ServerGroupItem group) {
//Ignore
}
/** {@inheritDoc} */
@Override
public void serverGroupRemoved(final ServerGroupItem parent,
final ServerGroupItem group) {
//Ignore
}
}
|
package com.github.pixelrunstudios.ChemHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class EquationBalancer{
private static final boolean DEBUG = true;
public static void print(Object o){
if(DEBUG){
System.out.print(o);
}
}
public static void println(Object o){
if(DEBUG){
System.out.println(o);
}
}
public static void println(){
if(DEBUG){
System.out.println();
}
}
public static void main(String[] args){
/*Map<ChemistryUnit, Integer> map1 = new LinkedHashMap<ChemistryUnit, Integer>();
map1.put(ChemistryUnit.mk("Fe"), 1);
map1.put(ChemistryUnit.mk("Br"), 3);
ChemistryUnit c1 = ChemistryUnit.mk(map1);
Map<ChemistryUnit, Integer> map2 = new LinkedHashMap<ChemistryUnit, Integer>();
map2.put(ChemistryUnit.mk("H"), 2);
map2.put(ChemistryUnit.mk("S"), 1);
map2.put(ChemistryUnit.mk("O"), 4);
ChemistryUnit c2 = ChemistryUnit.mk(map2);
ChemistryUnit in = ChemistryUnit.mk(Pair.make(c1, 1), Pair.make(c2, 1));
println(in);
Map<ChemistryUnit, Integer> map3 = new LinkedHashMap<ChemistryUnit, Integer>();
map3.put(ChemistryUnit.mk("Fe"), 2);
map3.put(ChemistryUnit.mk("S"), 3);
map3.put(ChemistryUnit.mk("O"), 12);
ChemistryUnit c3 = ChemistryUnit.mk(map3);
Map<ChemistryUnit, Integer> map4 = new LinkedHashMap<ChemistryUnit, Integer>();
map4.put(ChemistryUnit.mk("H"), 1);
map4.put(ChemistryUnit.mk("Br"), 1);
ChemistryUnit c4 = ChemistryUnit.mk(map4);
ChemistryUnit out = ChemistryUnit.mk(Pair.make(c3, 1), Pair.make(c4, 1));
println(out);*/
Map<ChemistryUnit, Integer> map1 = new LinkedHashMap<ChemistryUnit, Integer>();
map1.put(ChemistryUnit.mk("C"), 8);
map1.put(ChemistryUnit.mk("H"), 18);
ChemistryUnit c1 = ChemistryUnit.mk(map1);
Map<ChemistryUnit, Integer> map2 = new LinkedHashMap<ChemistryUnit, Integer>();
map2.put(ChemistryUnit.mk("O"), 2);
ChemistryUnit c2 = ChemistryUnit.mk(map2);
ChemistryUnit in = ChemistryUnit.mk(Pair.make(c1, 1), Pair.make(c2, 1));
println(in);
Map<ChemistryUnit, Integer> map3 = new LinkedHashMap<ChemistryUnit, Integer>();
map3.put(ChemistryUnit.mk("H"), 2);
map3.put(ChemistryUnit.mk("O"), 1);
ChemistryUnit c3 = ChemistryUnit.mk(map3);
Map<ChemistryUnit, Integer> map4 = new LinkedHashMap<ChemistryUnit, Integer>();
map4.put(ChemistryUnit.mk("C"), 1);
map4.put(ChemistryUnit.mk("O"), 2);
ChemistryUnit c4 = ChemistryUnit.mk(map4);
ChemistryUnit out = ChemistryUnit.mk(Pair.make(c3, 1), Pair.make(c4, 1));
println(out);
balance(in,out);
}
public static Pair<ChemistryUnit, ChemistryUnit>
balance(ChemistryUnit inX, ChemistryUnit outX){
return balance(inX, outX, false);
}
public static Pair<ChemistryUnit, ChemistryUnit>
balance(ChemistryUnit inX, ChemistryUnit outX, boolean apart){
if(apart){
inX = apart(inX);
outX = apart(outX);
}
BigFraction.setAutoSimplify(true);
/*
* Complexity of thing
*
*/
//{Fe=1,Br=3}, {H=2,S=1,O=4} -> {Fe=2,S=3,O=12} + {H=1,Br=1}
// Map1 Map2 Map3 Map4
// Br 3 0 0 1
// Fe 1 2 2 0
// S 0 1 3 0
// H 0 2 0 1
// O 0 4 12 0
// Final: 2, 3, 1, 6
ArrayList<ChemistryUnit> elements = new ArrayList<ChemistryUnit>();
int mapNum = 0;
int numOfEle = 0;
for(Map.Entry<ChemistryUnit, Integer> map : inX.getUnits().entrySet()){
for(Map.Entry<ChemistryUnit, Integer> entry : map.getKey().getUnits().entrySet()){
boolean yesEle = false;
for(int i = 0; i<elements.size();i++){
if(elements.get(i).equals(entry.getKey())){
yesEle = true;
break;
}
}
if(!yesEle){
println("hi");
elements.add(entry.getKey());
}
}
}
for(int i = 0; i<elements.size();i++){
println(elements.get(i));
}
println();
mapNum = inX.getSubUnits().size() + outX.getSubUnits().size();
numOfEle = elements.size();
println(numOfEle + " " + mapNum);
int[][] system = new int[numOfEle][mapNum];
int newArrayRow = numOfEle-(numOfEle-mapNum+1);
int counter = add(true, inX, elements, system, 0);
add(false, outX, elements, system, counter);
println("newArrayRow: "+newArrayRow);
BigFraction[] finale = new BigFraction[mapNum];
//boolean[] finalePut = new boolean[mapNum];
finale[0] = new BigFraction(1, 1);
//finalePut[0] = true;
//boolean finalePutFull = false;
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < elements.size(); i++){
set.add(i);
}
Set<Set<Integer>> is = SubsetHelper.subsets(set);
Set<Set<Integer>> ins = new HashSet<Set<Integer>>();
for(Set<Integer> s : is){
if(!(!(s.size() == newArrayRow) || !s.contains(1))){
println(s);
ins.add(s);
}
}
for(Set<Integer> s : ins){
Integer[] ia = new Integer[newArrayRow];
int ooo = 0;
for(Integer i : s){
ia[ooo] = i;
ooo++;
}
Pair<Integer[], BigFraction[][]> pair = solve(ia, newArrayRow, mapNum, system, numOfEle);
if(pair == null){
continue;
}
BigFraction[][] systemX = pair.getValueTwo();
int i = 0;
for(BigFraction[] sa : systemX){
finale[i+1] = sa[0];
i++;
}
/*Integer[] mX = pair.getValueOne();
BigFraction[][] systemX = pair.getValueTwo();
int i = 0;
BigFraction multiplicant = new BigFraction(1, 1);
boolean mset = false;
for(BigFraction[] sa : systemX){
if(sa[0].compareTo(new BigFraction(0, 1)) < 0){
i++;
continue;
}
println("hax: " + mX[i]);
if(finalePut[mX[i]] == true && !mset){
mset = true;
//multiplicant = finale[mX[i]].divide(sa[0]);
}
//else{
finale[mX[i]] = sa[0].multiply(multiplicant);
finalePut[mX[i]] = true;
//}
i++;
}
finalePutFull = true;
int finaleCounter = 0;
for(boolean b : finalePut){
if(!b){
finalePutFull = false;
}
else{
finaleCounter++;
}
}
println("WHoos");
print("HO ");
for(BigFraction bf : finale){
print(bf + " ");
}
println();
println(finaleCounter);*/
}
for(BigFraction bf : finale){
println("
}
int finDenProd = 1;
for(BigFraction bf : finale){
if(bf == null){
//if(apart){
return null;
//else{
//println("ModeSwitch");
// return balance(inX, outX, true);
}
finDenProd *= bf.getDenominator();
}
for(int i = 0; i < finale.length; i++){
finale[i] = finale[i].multiply(new BigFraction(finDenProd, 1));
}
for(BigFraction bf : finale){
println("
}
int[] finalOutOne = new int[finale.length];
for(int i = 0; i < finale.length; i++){
finalOutOne[i] = (int) finale[i].getNumerator();
}
int gcdX = gcd(finalOutOne);
for(int i = 0; i < finale.length; i++){
finalOutOne[i] = finalOutOne[i] / gcdX;
}
for(int i : finalOutOne){
println("
}
int finalOutX = 0;
Map<ChemistryUnit, Integer> mapOfIn = new HashMap<ChemistryUnit, Integer>();
for(Map.Entry<ChemistryUnit, Integer> map : inX.getUnits().entrySet()){
mapOfIn.put(map.getKey(), finalOutOne[finalOutX]);
finalOutX++;
}
Map<ChemistryUnit, Integer> mapOfOut = new HashMap<ChemistryUnit, Integer>();
for(Map.Entry<ChemistryUnit, Integer> map : outX.getUnits().entrySet()){
mapOfOut.put(map.getKey(), finalOutOne[finalOutX]);
finalOutX++;
}
ChemistryUnit inRet = ChemistryUnit.mk(mapOfIn);
ChemistryUnit outRet = ChemistryUnit.mk(mapOfOut);
return new Pair<ChemistryUnit,
ChemistryUnit>(inRet, outRet);
}
protected static ChemistryUnit apart(ChemistryUnit inX){
ChemistryUnit inNew = new ChemistryUnit();
return apart(inX, inNew).getValueOne();
}
private static Pair<ChemistryUnit, Boolean> apart(ChemistryUnit inX, ChemistryUnit inNew){
if(inX.getType() == ChemistryUnit.TYPE_BASE){
return Pair.make(inX, true);
}
else{
for(Map.Entry<ChemistryUnit, Integer> pair : inX.getUnits().entrySet()){
Pair<ChemistryUnit, Boolean> pcb = apart(pair.getKey(), inNew);
ChemistryUnit v1 = pcb.getValueOne();
if(v1.getType() == ChemistryUnit.TYPE_BASE){
inNew.putUnit(v1, pair.getValue());
}
}
return Pair.make(inNew, false);
}
}
private static int gcd(int a, int b){
while(b > 0){
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}
private static int gcd(int[] ia){
int r = ia[0];
for(int i = 1; i < ia.length; i++){
r = gcd(r, ia[i]);
}
return r;
}
public static Pair<Integer[], BigFraction[][]> solve(Integer[] randomY, int newArrayRow, int mapNum, int[][] system, int numOfEle){
int[][] system2 = new int[newArrayRow][mapNum];
int[][] system3 = new int[newArrayRow][mapNum-1];
Pair<Integer[], int[][]> px = pickRandom(randomY, system, newArrayRow, mapNum);
system2 = px.getValueTwo();
for(int i = 0; i<newArrayRow;i++){
for(int j = 0; j<mapNum-1;j++){
system3[i][j] = system2[i][j+1];
}
}
/*int[][] numOfNonZero = new int[mapNum-1][2];
for(int i = 0; i<newArrayRow;i++){
for(int j = 0; j<mapNum-1;j++){
if(system3[i][j] != 0){
numOfNonZero[i][0] = i;
numOfNonZero[i][1]++;
}
}
}
List<int[]> list = Arrays.asList(numOfNonZero);
list.sort(new EquationComparator());
numOfNonZero = list.toArray(numOfNonZero);*/
int[] target = new int[mapNum-1];
Integer[] ia = new Integer[newArrayRow];
for(int i = 0; i < ia.length; i++){
ia[i] = i;
}
Set<List<Integer>> sli = CombinatoricHelper.permutations(
Arrays.asList(ia), ia.length);
boolean broken = false;
printArray(system3);
for(List<Integer> li : sli){
boolean fail = false;
for(int i = 0; i < target.length; i++){
target[i] = -1;
}
superFor: for(int i = 0; i < mapNum - 1; i++){
outerFor: for(int lx : li){
if(system3[lx][i] != 0){
for(int k = 0; k<mapNum-1;k++){
if(target[k] == lx){
continue outerFor;
}
}
target[i] = lx;
continue superFor;
}
}
if(target[i] == -1){
fail = true;
break;
}
}
if(!fail){
broken = true;
break;
}
}
if(!broken){
return null;
}
BigFraction[][] system4 = new BigFraction[newArrayRow][mapNum];
for(int i = 0; i<newArrayRow;i++){
for(int j = 0; j<mapNum;j++){
print(system2[i][j] + " ");
system4[i][j] = new BigFraction(system2[target[i]][j], 1);
}
println();
}
for(int i = 0;i<newArrayRow;i++){
for(int j = 0; j<mapNum;j++){
print(system4[i][j] + " ");
}
println();
}
for(int i = 0; i<newArrayRow;i++){
for(int j = i+1; j<newArrayRow; j++){
BigFraction temp = system4[j][i+1];
for(int k = 0; k<mapNum;k++){
system4[j][k] = system4[j][k].subtract(temp.multiply(
system4[i][k].divide(system4[i][i+1])));
}
}
}
println();
for(int i = 0;i<newArrayRow;i++){
for(int j = 0; j<mapNum;j++){
print(system4[i][j] + " ");
}
println();
}
println();
int counter2 = 0;
for(int i = newArrayRow-1; i>=0;i
system4[i][0] = system4[i][0].divide(system4[i][mapNum-1-counter2]);
system4[i][mapNum-1-counter2] = system4[i][mapNum-1-counter2].divide(system4[i][mapNum-1-counter2]);
for(int j = i-1; j>=0; j
system4[j][0] = system4[j][0].subtract(system4[j][mapNum-1-counter2].multiply(system4[i][0]));
system4[j][mapNum-1-counter2] = system4[j][mapNum-1-counter2].subtract(system4[j][mapNum-1-counter2].multiply(system4[i][mapNum-1-counter2]));
}
counter2++;
}
println();
for(int i = 0;i<newArrayRow;i++){
for(int j = 0; j<mapNum;j++){
print(system4[i][j] + " ");
}
println();
}
println();
check(newArrayRow, mapNum, target, system3);
Integer[] iax = px.getValueOne();
Integer[] outIax = new Integer[iax.length];
int i = 0;
for(Integer inx : iax){
outIax[target[i]] = inx;
println(inx);
i++;
}
for(Integer inx : outIax){
println(inx);
}
/*for(int i = 0;i<numOfEle;i++){
print(elements.get(i)+" ");
for(int j = 0; j<mapNum;j++){
print(system[i][j] + " ");
}
println();
}
println();
for(int i = 0;i<newArrayRow;i++){
for(int j = 0; j<mapNum;j++){
print(system2[i][j] + " ");
}
println();
}
println();
for(int i = 0;i<newArrayRow;i++){
for(int j = 0; j<mapNum-1;j++){
print(system3[i][j] + " ");
}
println();
}
println();
for(int i = 0;i<mapNum-1;i++){
for(int j = 0; j<2;j++){
print(numOfNonZero[i][j] + " ");
}
println();
}
println();
for(int i = 0; i<mapNum-1;i++){
print(target[i] + " ");
}
println();*/
//TODO
return new Pair<Integer[], BigFraction[][]>(outIax, system4);
}
private static Pair<Integer[], int[][]> pickRandom(Integer[] randomY, int[][] system, int newArrayRow, int mapNum){
if(randomY == null){
Integer[] randomX = new Integer[newArrayRow - 1];
for(int i = 0; i < randomX.length; i++){
randomX[i] = i + 2;
}
List<Integer> ia = Arrays.<Integer>asList(randomX);
Collections.shuffle(ia);
randomX = ia.toArray(randomX);
randomY = new Integer[newArrayRow];
System.arraycopy(randomX, 0, randomY, 1, randomX.length);
randomY[0] = 1;
}
println(Arrays.asList(randomY));
int[][] system2 = new int[newArrayRow][mapNum];
for(int i = 0; i<newArrayRow;i++){
system2[i] = system[randomY[i]];
}
Integer[] outX = new Integer[newArrayRow];
System.arraycopy(randomY, 0, outX, 0, newArrayRow);
return new Pair<Integer[], int[][]>(outX, system2);
}
public static int add(boolean b, ChemistryUnit inX, ArrayList<ChemistryUnit> elements, int[][] system, int initCounter){
int counter = initCounter;
for(Map.Entry<ChemistryUnit, Integer> map : inX.getUnits().entrySet()){
for(Map.Entry<ChemistryUnit, Integer> entry : map.getKey().getUnits().entrySet()){
int temp = 0;
for(int i = 0; i<elements.size();i++){
if(elements.get(i).equals(entry.getKey())){
temp = i;
}
}
system[temp][counter] = counter != 0 && b ? -entry.getValue() : entry.getValue();
}
counter++;
}
return counter;
}
public static boolean check(int newArrayRow, int mapNum, int[] target, int[][] system3){
boolean done = false;
boolean onTarget = false;
int zeroes = 0;
int rowDone = 0;
outerFor: for(int i = 0; i<newArrayRow;i++){
onTarget = false;
zeroes = 0;
for(int j = 0; j<mapNum-1;j++){
if(j != target[i]){
if(system3[i][j] !=0){
break outerFor;
}else{
zeroes++;
}
}else{
if(target[i] !=1){
break outerFor;
}else{
onTarget = true;
}
}
}
if(zeroes == mapNum-2 && onTarget){
rowDone++;
}
}
if(rowDone == newArrayRow){
done = true;
}else{
done = false;
}
return done;
}
private static void printArray(int[][] arr){
for(int[] ia : arr){
for(int i : ia){
print(i + " ");
}
println();
}
println();
}
public static class EquationComparator implements Comparator<int[]>{
@Override
public int compare(int[] o1, int[] o2){
return Integer.compare(o1[1], o2[1]);
}
}
}
|
package com.hp.hpl.jena.util.iterator.test;
/**
test the WrappedIterator class. TODO: test _remove_, which means having
some fake base iterator to do the checking, and _close_, ditto.
*/
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.graph.test.GraphTestBase;
import com.hp.hpl.jena.util.iterator.*;
import java.util.*;
import junit.framework.*;
public class TestWrappedIterator extends GraphTestBase
{
public static TestSuite suite()
{ return new TestSuite( TestWrappedIterator.class ); }
public TestWrappedIterator(String name)
{ super(name); }
public void testWrappedIterator()
{
Iterator i = Arrays.asList( new String [] {"bill", "and", "ben"} ).iterator();
ExtendedIterator e = WrappedIterator.create( i );
assertTrue( "wrapper has at least one element", e.hasNext() );
assertEquals( "", "bill", e.next() );
assertTrue( "wrapper has at least two elements", e.hasNext() );
assertEquals( "", "and", e.next() );
assertTrue( "wrapper has at least three elements", e.hasNext() );
assertEquals( "", "ben", e.next() );
assertFalse( "wrapper is now empty", e.hasNext() );
}
public void testUnwrapExtendedIterator()
{
ExtendedIterator i = graphWith( "a R b" ).find( Triple.ANY );
assertSame( i, WrappedIterator.create( i ) );
}
public void testWrappedNoRemove()
{
Iterator base = nodeSet( "a b c" ).iterator();
base.next();
base.remove();
ExtendedIterator wrapped = WrappedIterator.createNoRemove( base );
wrapped.next();
try { wrapped.remove(); fail( "wrapped-no-remove iterator should deny .remove()" ); }
catch (UnsupportedOperationException e) { pass(); }
}
}
|
package com.redhat.ceylon.compiler.analyzer;
import java.util.Stack;
import com.redhat.ceylon.compiler.model.Class;
import com.redhat.ceylon.compiler.model.CompilationUnit;
import com.redhat.ceylon.compiler.model.Declaration;
import com.redhat.ceylon.compiler.model.Getter;
import com.redhat.ceylon.compiler.model.Interface;
import com.redhat.ceylon.compiler.model.Method;
import com.redhat.ceylon.compiler.model.Parameter;
import com.redhat.ceylon.compiler.model.Scope;
import com.redhat.ceylon.compiler.model.SimpleValue;
import com.redhat.ceylon.compiler.tree.Tree;
import com.redhat.ceylon.compiler.tree.Tree.ParameterName;
import com.redhat.ceylon.compiler.tree.Visitor;
import com.redhat.ceylon.compiler.model.Package;
public class DeclarationVisitor extends Visitor {
Stack<Scope<Declaration>> declarationScopes = new Stack<Scope<Declaration>>();
CompilationUnit compilationUnit;
public DeclarationVisitor(Package p) {
declarationScopes.push(p);
}
public void visit(Tree.CompilationUnit that) {
compilationUnit = new CompilationUnit();
super.visit(that);
}
@Override
public void visit(Tree.ClassDeclaration that) {
Class c = new Class();
c.setCompilationUnit(compilationUnit);
c.setName(that.getTypeName().getText());
Scope<Declaration> scope = declarationScopes.peek();
c.setContainer(scope);
scope.getMembers().add(c);
declarationScopes.push(c);
super.visit(that);
declarationScopes.pop();
}
@Override
public void visit(Tree.InterfaceDeclaration that) {
Interface i = new Interface();
i.setCompilationUnit(compilationUnit);
i.setName(that.getTypeName().getText());
Scope<Declaration> scope = declarationScopes.peek();
i.setContainer(scope);
scope.getMembers().add(i);
declarationScopes.push(i);
super.visit(that);
declarationScopes.pop();
}
@Override
public void visit(Tree.MethodDeclaration that) {
Method m = new Method();
m.setCompilationUnit(compilationUnit);
m.setName(that.getMemberName().getText());
Scope<Declaration> scope = declarationScopes.peek();
m.setContainer(scope);
scope.getMembers().add(m);
declarationScopes.push(m);
super.visit(that);
declarationScopes.pop();
}
@Override
public void visit(Tree.AttributeDeclaration that) {
SimpleValue v = new SimpleValue();
v.setCompilationUnit(compilationUnit);
v.setName(that.getMemberName().getText());
Scope<Declaration> scope = declarationScopes.peek();
v.setContainer(scope);
scope.getMembers().add(v);
super.visit(that);
}
@Override
public void visit(Tree.AttributeGetter that) {
Getter g = new Getter();
g.setCompilationUnit(compilationUnit);
g.setName(that.getMemberName().getText());
Scope<Declaration> scope = declarationScopes.peek();
g.setContainer(scope);
scope.getMembers().add(g);
declarationScopes.push(g);
super.visit(that);
declarationScopes.pop();
}
@Override
public void visit(Tree.Parameter that) {
Parameter p = new Parameter();
p.setCompilationUnit(compilationUnit);
ParameterName parameterName = that.getParameterName();
if (parameterName==null) {
p.setName("this");
}
else {
p.setName(parameterName.getText());
}
Scope<Declaration> scope = declarationScopes.peek();
p.setContainer(scope);
scope.getMembers().add(p);
declarationScopes.push(p);
super.visit(that);
declarationScopes.pop();
}
//TODO: variables in try, catch, if, for, while blocks
@Override
public void visit(Tree.ControlClause that) {
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// 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 DAVID J. PEARCE 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 wyrl.io;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.*;
import wyautl.core.Automaton;
import wyautl.io.BinaryAutomataReader;
import wyautl.util.BigRational;
import wybs.io.BinaryInputStream;
import wybs.io.BinaryOutputStream;
import wyrl.core.Attribute;
import wyrl.core.Expr;
import wyrl.core.Pattern;
import wyrl.core.SpecFile;
import wyrl.core.Type;
import wyrl.core.Types;
import wyrl.core.SpecFile.RuleDecl;
import wyrl.util.*;
import static wyrl.core.Attribute.*;
import static wyrl.core.SpecFile.*;
public class NewJavaFileWriter {
private PrintWriter out;
public NewJavaFileWriter(Writer os) {
this.out = new PrintWriter(os);
}
public NewJavaFileWriter(OutputStream os) {
this.out = new PrintWriter(os);
}
public void write(SpecFile spec) throws IOException {
reset();
translate(spec, spec);
}
private void translate(SpecFile spec, SpecFile root) throws IOException {
PrintWriter saved = out;
if (root == spec) {
if (!spec.pkg.equals("")) {
myOut("package " + spec.pkg + ";");
myOut("");
}
writeImports();
myOut("public final class " + spec.name + " {");
}
for (Decl d : spec.declarations) {
if (d instanceof IncludeDecl) {
IncludeDecl id = (IncludeDecl) d;
SpecFile file = id.file;
translate(file, root);
} else if (d instanceof TermDecl) {
translate((TermDecl) d);
} else if (d instanceof RewriteDecl) {
translate((RewriteDecl) d, root);
}
}
if (root == spec) {
writeSchema(spec);
writeTypeTests();
writePatterns(spec);
writeRuleArrays(spec);
writeMainMethod();
}
if (root == spec) {
myOut("}");
out.close();
}
out = saved;
}
/**
* Reset all global information before proceeding to write out another file.
*/
protected void reset() {
termCounter = 0;
reductionCounter = 0;
inferenceCounter = 0;
}
protected void writeImports() {
myOut("import java.io.*;");
myOut("import java.util.*;");
myOut("import java.math.BigInteger;");
myOut("import wyautl.util.BigRational;");
myOut("import wyautl.io.*;");
myOut("import wyautl.core.*;");
myOut("import wyautl.rw.*;");
myOut("import wyrl.core.*;");
myOut("import wyrl.util.Runtime;");
myOut("import wyrl.util.AbstractRewriteRule;");
myOut("import wyrl.util.Pair;");
myOut();
}
public void translate(TermDecl decl) {
myOut(1, "// term " + decl.type);
String name = decl.type.name();
myOut(1, "public final static int K_" + name + " = " + termCounter++
+ ";");
if (decl.type.element() == null) {
myOut(1, "public final static Automaton.Term " + name
+ " = new Automaton.Term(K_" + name + ");");
} else {
Type.Ref data = decl.type.element();
Type element = data.element();
if (element instanceof Type.Collection) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, int... r0) {");
if (element instanceof Type.Set) {
myOut(2, "int r1 = automaton.add(new Automaton.Set(r0));");
} else if (element instanceof Type.Bag) {
myOut(2, "int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2, "int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, List<Integer> r0) {");
if (element instanceof Type.Set) {
myOut(2, "int r1 = automaton.add(new Automaton.Set(r0));");
} else if (element instanceof Type.Bag) {
myOut(2, "int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2, "int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else if (element instanceof Type.Int) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, long r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, BigInteger r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else if (element instanceof Type.Real) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, long r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Real(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, BigRational r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Real(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else if (element instanceof Type.Strung) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, String r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Strung(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else {
myOut(1, "public final static int " + name
+ "(Automaton automaton, " + type2JavaType(data)
+ " r0) {");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r0));");
myOut(1, "}");
}
}
myOut();
}
private int termCounter = 0;
private int reductionCounter = 0;
private int inferenceCounter = 0;
public void translate(RewriteDecl decl, SpecFile file) {
register(decl.pattern);
boolean isReduction = decl instanceof ReduceDecl;
Type param = decl.pattern.attribute(Attribute.Type.class).type;
myOut(1, "// " + decl.pattern);
if (isReduction) {
myOut(1, "private final static class Reduction_" + reductionCounter
+ " extends AbstractRewriteRule implements ReductionRule {");
} else {
myOut(1, "private final static class Inference_" + inferenceCounter
+ " extends AbstractRewriteRule implements InferenceRule {");
}
// Constructor
myOut();
if (isReduction) {
myOut(2, "public Reduction_" + reductionCounter++
+ "(Pattern pattern) { super(pattern,SCHEMA); }");
} else {
myOut(2, "public Inference_" + inferenceCounter++
+ "(Pattern pattern) { super(pattern,SCHEMA); }");
}
// Probe
myOut();
myOut(2,
"public final void probe(Automaton automaton, int root, List<Activation> activations) {");
Environment environment = new Environment();
int thus = environment.allocate(param, "this");
myOut(3, "int r" + thus + " = root;");
int level = translatePatternMatch(3, decl.pattern, thus, environment);
// Add the appropriate activation
indent(level);
out.print("int[] state = {");
for (int i = 0; i != environment.size(); ++i) {
Pair<Type, String> t = environment.get(i);
if (t.first() == Type.T_VOID()) {
// In this case, we have allocated a temporary variable which
// should not be loaded into the activation state.
continue;
}
if (i != 0) {
out.print(", ");
}
out.print("r" + i);
}
out.println("};");
myOut(level, "activations.add(new Activation(this,null,state));");
// close the pattern match
while (level > 2) {
myOut(--level, "}");
}
// Apply
myOut();
myOut(2,
"public final boolean apply(Automaton automaton, Object _state) {");
myOut(3, "int[] state = (int[]) _state;");
// first, unpack the state
myOut(3, "int thus = state[0];");
environment = new Environment();
thus = environment.allocate(param, "this");
translateStateUnpack(3, decl.pattern, thus, environment);
// second, translate the individual rules
for (RuleDecl rd : decl.rules) {
translate(3, rd, isReduction, new Environment(), file);
}
myOut(3, "return false;");
myOut(2, "}");
myOut(1, "}"); // end class
}
/**
* Translate the test to see whether a pattern is accepted or not. A key
* requirement of this translation procedure is that it does not allocate
* *any* memory during the process.
*
* @param pattern
* The pattern being translated
* @param freeRegister
* The next available free register.
* @return The next available free register after this translation.
*/
protected int translatePatternMatch(int level, Pattern pattern, int source,
Environment environment) {
if (pattern instanceof Pattern.Leaf) {
return translatePatternMatch(level, (Pattern.Leaf) pattern, source,
environment);
} else if (pattern instanceof Pattern.Term) {
return translatePatternMatch(level, (Pattern.Term) pattern, source,
environment);
} else if (pattern instanceof Pattern.BagOrSet) {
return translatePatternMatch(level, (Pattern.BagOrSet) pattern,
source, environment);
} else {
return translatePatternMatch(level, (Pattern.List) pattern, source,
environment);
}
}
public int translatePatternMatch(int level, Pattern.Leaf pattern,
int source, Environment environment) {
Type element = pattern.type().element();
if (element == Type.T_ANY()) {
// In this very special case, we don't need to do anything.
return level;
} else {
int typeIndex = register(pattern.type);
myOut(level++, "if(Runtime.accepts(type" + typeIndex
+ ",automaton,automaton.get(r" + source + "), SCHEMA)) {");
return level;
}
}
public int translatePatternMatch(int level, Pattern.Term pattern,
int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
myOut(level++, "if(s" + source + ".kind == K_" + pattern.name + ") {");
myOut(level, "Automaton.Term t" + source + " = (Automaton.Term) s"
+ source + ";");
if (pattern.data != null) {
int target = environment.allocate(Type.T_ANY(), pattern.variable);
myOut(level, "int r" + target + " = t" + source + ".contents;");
return translatePatternMatch(level, pattern.data, target,
environment);
} else {
return level;
}
}
public int translatePatternMatch(int level, Pattern.List pattern,
int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
myOut(level++, "if(s" + source + " instanceof Automaton.List) {");
myOut(level, "Automaton.List l" + source + " = (Automaton.List) s"
+ source + ";");
Pair<Pattern, String>[] elements = pattern.elements;
for (int i = 0; i != elements.length; ++i) {
Pair<Pattern, String> p = elements[i];
Pattern pat = p.first();
if (pattern.unbounded && (i + 1) == elements.length) {
int element = environment.allocate(Type.T_VOID());
String idx = "i" + source;
myOut(level, "boolean m" + source + " = true;");
myOut(level++, "for(int " + idx + "=" + i + "; " + idx + " < l"
+ source + ".size(); " + idx + "++) {");
myOut(level, "int r" + element + " = l" + source + ".get("
+ idx + ");");
int myLevel = level;
level = translatePatternMatch(level, pat, element, environment);
if (myLevel != level) {
myOut(level, "continue;");
myOut(--level, "} else { m" + source + "=false; break; }");
}
while (level >= myLevel) {
myOut(--level, "}");
}
myOut(level++, "if(m" + source + ") {");
} else {
int element = environment.allocate(Type.T_ANY());
myOut(level, "int r" + element + " = l" + source + ".get(" + i
+ ");");
level = translatePatternMatch(level, pat, element, environment);
}
}
return level;
}
public int translatePatternMatch(int level, Pattern.BagOrSet pattern,
int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
if (pattern instanceof Pattern.Bag) {
myOut(level++, "if(s" + source + " instanceof Automaton.Bag) {");
} else {
myOut(level++, "if(s" + source + " instanceof Automaton.Set) {");
}
myOut(level, "Automaton.Collection c" + source
+ " = (Automaton.Collection) s" + source + ";");
// What we do here is construct a series of nested for-loops (one for
// each pattern element) which goes through each element of the source
// collection and attempts to match the element. In doing this, we must
// ensure that no previously matched elements are matched again.
// Furthermore, in the case of an unbounded match (i.e. where the
// pattern has a generic match against all remaining elements), then we
// simply go through all unmatched elements making sure they match the
// required pattern.
Pair<Pattern, String>[] elements = pattern.elements;
int[] indices = new int[elements.length];
for (int i = 0; i != elements.length; ++i) {
boolean isUnbounded = pattern.unbounded
&& (i + 1) == elements.length;
Pair<Pattern, String> p = elements[i];
Pattern pat = p.first();
int index = environment.allocate(isUnbounded ? Type.T_VOID() : Type
.T_ANY());
String idx = "i" + index;
indices[i] = index;
if (isUnbounded) {
myOut(level, "boolean m" + i + " = true;");
}
// TODO: at some point here, we want to check whether or not it's
// actually worth having a loop in the unbounded case. Specifically,
// when the type being matched is any then we can just drop the loop
// altogether.
// Construct the for-loop for this element
myOut(level++, "for(int " + idx + "=0;" + idx + "!=c" + source
+ ".size();++" + idx + ") {");
// Check that the current element from the source collection is not
// already matched. If this is the first pattern element (i.e. i ==
// 0), then we don't need to do anything since nothing could have
// been matched yet.
if (i != 0) {
indent(level);
out.print("if(");
// check against earlier indices
for (int j = 0; j < i; ++j) {
if (j != 0) {
out.print(" || ");
}
out.print(idx + " == i" + indices[j]);
}
out.println(") { continue; }");
}
myOut(level, "int r" + index + " = c" + source + ".get(" + idx
+ ");");
int myLevel = level;
level = translatePatternMatch(level, pat, index, environment);
// In the case that pattern is unbounded, we match all non-matched
// items against the last pattern element. This time, we construct a
// loop which sets a flag if it finds one that doesn't match and
// exits early.
if (isUnbounded) {
if (myLevel != level) {
myOut(level, "continue;");
myOut(--level, "} else { m" + i + "=false; break; }");
}
while (level >= myLevel) {
myOut(--level, "}");
}
myOut(level++, "if(m" + source + ") {");
}
}
// Done.
return level;
}
/**
* Here, we simply read out all of the registers from the state. We also
* assign named variables so they can be used subsequently.
*
* @param level
* @param pattern
* @param environment
*/
protected void translateStateUnpack(int level, Pattern pattern, int source,
Environment environment) {
if (pattern instanceof Pattern.Leaf) {
translateStateUnpack(level, (Pattern.Leaf) pattern, source,
environment);
} else if (pattern instanceof Pattern.Term) {
translateStateUnpack(level, (Pattern.Term) pattern, source,
environment);
} else if (pattern instanceof Pattern.BagOrSet) {
translateStateUnpack(level, (Pattern.BagOrSet) pattern, source,
environment);
} else {
translateStateUnpack(level, (Pattern.List) pattern, source,
environment);
}
}
protected void translateStateUnpack(int level, Pattern.Leaf pattern, int source,
Environment environment) {
// Don't need to do anything!!
}
protected void translateStateUnpack(int level, Pattern.Term pattern,
int source, Environment environment) {
if (pattern.data != null) {
int target = environment.allocate(Type.T_ANY());
if (pattern.variable != null) {
myOut(level, "int " + pattern.variable + " = state[" + target
+ "];");
}
translateStateUnpack(level, pattern.data, target, environment);
}
}
protected void translateStateUnpack(int level, Pattern.BagOrSet pattern,
int source, Environment environment) {
Pair<Pattern, String>[] elements = pattern.elements;
int[] indices = new int[elements.length];
for (int i = 0; i != elements.length; ++i) {
Pair<Pattern, String> p = elements[i];
String p_name = p.second();
if (pattern.unbounded && (i + 1) == elements.length) {
if (p_name != null) {
String src = "__s" + source;
myOut(level, "Automaton.Collection " + src
+ " = (Automaton.Collection) automaton.get(state["
+ source + "]);");
String array = src + "children";
myOut(level, "int[] " + array + " = new int[" + src
+ ".size() - " + i + "];");
String idx = "__s" + source + "i";
String jdx = "__s" + source + "j";
String tmp = "__s" + source + "t";
myOut(level, "for(int " + idx + "=0, " + jdx + "=0; " + idx + " != " + src
+ ".size();++" + idx + ") {");
myOut(level+1,"int " + tmp + " = " + src + ".get(" + idx + ");");
if (i != 0) {
indent(level+1);out.print("if(");
for (int j = 0; j < i; ++j) {
if (j != 0) {
out.print(" || ");
}
out.print(tmp + " == state[" + indices[j] + "]");
}
out.println(") { continue; }");
}
myOut(level+1,array + "[" + jdx + "++] = " + tmp + ";");
myOut(level, "}");
if (pattern instanceof Pattern.Set) {
myOut(level, "Automaton.Set " + p_name
+ " = new Automaton.Set(" + array + ");");
} else {
myOut(level, "Automaton.Bag " + p_name
+ " = new Automaton.Bag(" + array + ");");
}
}
// NOTE: calling translate unpack here is strictly unnecessary
// because we cannot map an unbounded pattern to a single
// variable name.
} else {
int target = environment.allocate(Type.T_ANY());
indices[i] = target;
if (p_name != null) {
myOut(level, "int " + p_name + " = state[" + target
+ "];");
}
translateStateUnpack(level, p.first(), target, environment);
}
}
}
protected void translateStateUnpack(int level, Pattern.List pattern,
int source, Environment environment) {
Pair<Pattern, String>[] elements = pattern.elements;
for (int i = 0; i != elements.length; ++i) {
Pair<Pattern, String> p = elements[i];
String p_name = p.second();
if (pattern.unbounded && (i + 1) == elements.length) {
if (p_name != null) {
myOut(level, "Automaton.List " + p_name
+ " = ((Automaton.List) automaton.get(state["
+ source + "])).sublist(" + i + ");");
}
// NOTE: calling translate unpack here is strictly unnecessary
// because we cannot map an unbounded pattern to a single
// variable name.
} else {
int target = environment.allocate(Type.T_ANY());
if (p_name != null) {
myOut(level, "int " + p_name + " = state[" + target
+ "];");
}
translateStateUnpack(level, p.first(), target, environment);
}
}
}
public void register(Pattern p) {
if (p instanceof Pattern.Leaf) {
Pattern.Leaf pl = (Pattern.Leaf) p;
int typeIndex = register(pl.type);
} else if (p instanceof Pattern.Term) {
Pattern.Term pt = (Pattern.Term) p;
if (pt.data != null) {
register(pt.data);
}
} else if (p instanceof Pattern.Collection) {
Pattern.Collection pc = (Pattern.Collection) p;
for (Pair<Pattern, String> e : pc.elements) {
register(e.first());
}
}
}
public void translate(int level, RuleDecl decl, boolean isReduce,
Environment environment, SpecFile file) {
// TODO: can optimise this by translating lets within the conditionals
// in the case that the conditionals don't refer to those lets. This
// will then prevent unnecessary object creation.
for (Pair<String, Expr> let : decl.lets) {
String letVar = let.first();
Expr letExpr = let.second();
int result = translate(level, letExpr, environment, file);
environment.put(result, letVar);
}
if (decl.condition != null) {
int condition = translate(level, decl.condition, environment, file);
myOut(level++, "if(r" + condition + ") {");
}
int result = translate(level, decl.result, environment, file);
result = coerceFromValue(level, decl.result, result, environment);
myOut(level, "if(thus != r" + result + ") {");
myOut(level + 1, "automaton.rewrite(thus, r" + result + ");");
myOut(level + 1, "return true;");
myOut(level, "}");
if (decl.condition != null) {
myOut(--level, "}");
}
}
public void writeSchema(SpecFile spec) {
myOut(1,
"
myOut(1, "// Schema");
myOut(1,
"
myOut();
myOut(1,
"public static final Schema SCHEMA = new Schema(new Schema.Term[]{");
boolean firstTime = true;
for (TermDecl td : extractDecls(TermDecl.class, spec)) {
if (!firstTime) {
myOut(",");
}
firstTime = false;
myOut(2, "// " + td.type.toString());
indent(2);
writeSchema(td.type);
}
myOut();
myOut(1, "});");
myOut();
}
public void writeRuleArrays(SpecFile spec) {
myOut(1,
"
myOut(1, "// rules");
myOut(1,
"
myOut();
myOut(1,
"public static final InferenceRule[] inferences = new InferenceRule[]{");
int patternCounter = 0;
int inferCounter = 0;
for (Decl d : spec.declarations) {
if (d instanceof InferDecl) {
indent(2);
if (inferCounter != 0) {
out.println(",");
}
out.print("new Inference_" + inferCounter + "(pattern"
+ patternCounter + ")");
inferCounter++;
}
if (d instanceof RewriteDecl) {
patternCounter++;
}
}
myOut();
myOut(1, "};");
myOut(1,
"public static final ReductionRule[] reductions = new ReductionRule[]{");
patternCounter = 0;
int reduceCounter = 0;
for (Decl d : spec.declarations) {
if (d instanceof ReduceDecl) {
indent(2);
if (reduceCounter != 0) {
out.println(",");
}
out.print("new Reduction_" + reduceCounter + "(pattern"
+ patternCounter + ")");
reduceCounter++;
}
if (d instanceof RewriteDecl) {
patternCounter++;
}
}
myOut();
myOut(1, "};");
myOut();
}
protected void writeTypeTests() throws IOException {
myOut(1,
"
myOut(1, "// Types");
myOut(1,
"
myOut();
for (int i = 0; i != typeRegister.size(); ++i) {
Type t = typeRegister.get(i);
JavaIdentifierOutputStream jout = new JavaIdentifierOutputStream();
BinaryOutputStream bout = new BinaryOutputStream(jout);
bout.write(t.toBytes());
bout.close();
// FIXME: strip out nominal types (and any other unneeded types).
myOut(1, "
myOut(1, "private static Type type" + i + " = Runtime.Type(\""
+ jout.toString() + "\");");
}
myOut();
}
protected void writePatterns(SpecFile spec) throws IOException {
myOut(1,
"
myOut(1, "// Patterns");
myOut(1,
"
myOut();
int counter = 0;
for (Decl d : spec.declarations) {
if (d instanceof RewriteDecl) {
RewriteDecl rd = (RewriteDecl) d;
indent(1);
out.print("private final static Pattern pattern" + counter++
+ " = ");
translate(2, rd.pattern);
myOut(";");
}
}
}
public void translate(int level, Pattern p) {
if (p instanceof Pattern.Leaf) {
Pattern.Leaf pl = (Pattern.Leaf) p;
int typeIndex = register(pl.type);
out.print("new Pattern.Leaf(type" + typeIndex + ")");
} else if (p instanceof Pattern.Term) {
Pattern.Term pt = (Pattern.Term) p;
out.print("new Pattern.Term(\"" + pt.name + "\",");
if (pt.data != null) {
myOut();
indent(level);
translate(level + 1, pt.data);
out.println(",");
indent(level);
} else {
out.print("null,");
}
if (pt.variable != null) {
out.print("\"" + pt.variable + "\")");
} else {
out.print("null)");
}
} else if (p instanceof Pattern.Collection) {
Pattern.Collection pc = (Pattern.Collection) p;
String kind;
if (p instanceof Pattern.Set) {
kind = "Set";
} else if (p instanceof Pattern.Bag) {
kind = "Bag";
} else {
kind = "List";
}
out.print("new Pattern." + kind + "(" + pc.unbounded
+ ", new Pair[]{");
for (int i = 0; i != pc.elements.length; ++i) {
Pair<Pattern, String> e = pc.elements[i];
Pattern ep = e.first();
String es = e.second();
if (i != 0) {
out.println(", ");
} else {
out.println();
}
indent(level);
out.print("new Pair(");
translate(level + 1, ep);
if (es == null) {
out.print(",null)");
} else {
out.print(", \"" + es + "\")");
}
}
out.print("})");
}
}
private void writeSchema(Type.Term tt) {
Automaton automaton = tt.automaton();
BitSet visited = new BitSet(automaton.nStates());
writeSchema(automaton.getRoot(0), automaton, visited);
}
private void writeSchema(int node, Automaton automaton, BitSet visited) {
if (node < 0) {
// bypass virtual node
} else if (visited.get(node)) {
out.print("Schema.Any");
return;
} else {
visited.set(node);
}
// you can scratch your head over why this is guaranteed ;)
Automaton.Term state = (Automaton.Term) automaton.get(node);
switch (state.kind) {
case wyrl.core.Types.K_Void:
out.print("Schema.Void");
break;
case wyrl.core.Types.K_Any:
out.print("Schema.Any");
break;
case wyrl.core.Types.K_Bool:
out.print("Schema.Bool");
break;
case wyrl.core.Types.K_Int:
out.print("Schema.Int");
break;
case wyrl.core.Types.K_Real:
out.print("Schema.Real");
break;
case wyrl.core.Types.K_String:
out.print("Schema.String");
break;
case wyrl.core.Types.K_Not:
out.print("Schema.Not(");
writeSchema(state.contents, automaton, visited);
out.print(")");
break;
case wyrl.core.Types.K_Ref:
writeSchema(state.contents, automaton, visited);
break;
case wyrl.core.Types.K_Meta:
out.print("Schema.Meta(");
writeSchema(state.contents, automaton, visited);
out.print(")");
break;
case wyrl.core.Types.K_Nominal: {
// bypass the nominal marker
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
writeSchema(list.get(1), automaton, visited);
break;
}
case wyrl.core.Types.K_Or: {
out.print("Schema.Or(");
Automaton.Set set = (Automaton.Set) automaton.get(state.contents);
for (int i = 0; i != set.size(); ++i) {
if (i != 0) {
out.print(", ");
}
writeSchema(set.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Set: {
out.print("Schema.Set(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.Bag set = (Automaton.Bag) automaton.get(list.get(1));
for (int i = 0; i != set.size(); ++i) {
out.print(",");
writeSchema(set.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Bag: {
out.print("Schema.Bag(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.Bag bag = (Automaton.Bag) automaton.get(list.get(1));
for (int i = 0; i != bag.size(); ++i) {
out.print(",");
writeSchema(bag.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_List: {
out.print("Schema.List(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.List list2 = (Automaton.List) automaton.get(list.get(1));
for (int i = 0; i != list2.size(); ++i) {
out.print(",");
writeSchema(list2.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Term: {
out.print("Schema.Term(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
Automaton.Strung str = (Automaton.Strung) automaton
.get(list.get(0));
out.print("\"" + str.value + "\"");
if (list.size() > 1) {
out.print(",");
writeSchema(list.get(1), automaton, visited);
}
out.print(")");
break;
}
default:
throw new RuntimeException("Unknown kind encountered: "
+ state.kind);
}
}
private <T extends Decl> ArrayList<T> extractDecls(Class<T> kind,
SpecFile spec) {
ArrayList r = new ArrayList();
extractDecls(kind, spec, r);
return r;
}
private <T extends Decl> void extractDecls(Class<T> kind, SpecFile spec,
ArrayList<T> decls) {
for (Decl d : spec.declarations) {
if (kind.isInstance(d)) {
decls.add((T) d);
} else if (d instanceof IncludeDecl) {
IncludeDecl id = (IncludeDecl) d;
extractDecls(kind, id.file, decls);
}
}
}
public int translate(int level, Expr code, Environment environment,
SpecFile file) {
if (code instanceof Expr.Constant) {
return translate(level, (Expr.Constant) code, environment, file);
} else if (code instanceof Expr.UnOp) {
return translate(level, (Expr.UnOp) code, environment, file);
} else if (code instanceof Expr.BinOp) {
return translate(level, (Expr.BinOp) code, environment, file);
} else if (code instanceof Expr.NaryOp) {
return translate(level, (Expr.NaryOp) code, environment, file);
} else if (code instanceof Expr.Constructor) {
return translate(level, (Expr.Constructor) code, environment, file);
} else if (code instanceof Expr.ListAccess) {
return translate(level, (Expr.ListAccess) code, environment, file);
} else if (code instanceof Expr.ListUpdate) {
return translate(level, (Expr.ListUpdate) code, environment, file);
} else if (code instanceof Expr.Variable) {
return translate(level, (Expr.Variable) code, environment, file);
} else if (code instanceof Expr.Substitute) {
return translate(level, (Expr.Substitute) code, environment, file);
} else if (code instanceof Expr.Comprehension) {
return translate(level, (Expr.Comprehension) code, environment,
file);
} else if (code instanceof Expr.TermAccess) {
return translate(level, (Expr.TermAccess) code, environment, file);
} else if (code instanceof Expr.Cast) {
return translate(level, (Expr.Cast) code, environment, file);
} else {
throw new RuntimeException("unknown expression encountered - "
+ code);
}
}
public int translate(int level, Expr.Cast code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first translate src expression, and coerce to a value
int src = translate(level, code.src, environment, file);
src = coerceFromRef(level, code.src, src, environment);
// TODO: currently we only support casting from integer to real!!
String body = "new Automaton.Real(r" + src + ".value)";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Constant code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
Object v = code.value;
String rhs;
if (v instanceof Boolean) {
rhs = v.toString();
} else if (v instanceof BigInteger) {
BigInteger bi = (BigInteger) v;
if (bi.bitLength() <= 64) {
rhs = "new Automaton.Int(" + bi.longValue() + ")";
} else {
rhs = "new Automaton.Int(\"" + bi.toString() + "\")";
}
} else if (v instanceof BigRational) {
BigRational br = (BigRational) v;
rhs = "new Automaton.Real(\"" + br.toString() + "\")";
if (br.isInteger()) {
long lv = br.longValue();
if (BigRational.valueOf(lv).equals(br)) {
// Yes, this will fit in a long value. Therefore, inline a
// long constant as this is faster.
rhs = "new Automaton.Real(" + lv + ")";
}
}
} else if (v instanceof String) {
rhs = "new Automaton.Strung(\"" + v + "\")";
} else {
throw new RuntimeException("unknown constant encountered (" + v
+ ")");
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + rhs + ";",
code.toString()));
return target;
}
public int translate(int level, Expr.UnOp code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int rhs = translate(level, code.mhs, environment, file);
rhs = coerceFromRef(level, code.mhs, rhs, environment);
String body;
switch (code.op) {
case LENGTHOF:
body = "r" + rhs + ".lengthOf()";
break;
case NUMERATOR:
body = "r" + rhs + ".numerator()";
break;
case DENOMINATOR:
body = "r" + rhs + ".denominator()";
break;
case NEG:
body = "r" + rhs + ".negate()";
break;
case NOT:
body = "!r" + rhs;
break;
default:
throw new RuntimeException("unknown unary expression encountered");
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.BinOp code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
Type lhs_t = code.lhs.attribute(Attribute.Type.class).type;
Type rhs_t = code.rhs.attribute(Attribute.Type.class).type;
int lhs = translate(level, code.lhs, environment, file);
String body;
if (code.op == Expr.BOp.IS && code.rhs instanceof Expr.Constant) {
// special case for runtime type tests
Expr.Constant c = (Expr.Constant) code.rhs;
Type test = (Type) c.value;
int typeIndex = register(test);
body = "Runtime.accepts(type" + typeIndex + ", automaton, r" + lhs
+ ", SCHEMA)";
} else if (code.op == Expr.BOp.AND) {
// special case to ensure short-circuiting of AND.
lhs = coerceFromRef(level, code.lhs, lhs, environment);
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + false
+ ";", code.toString()));
myOut(level++, "if(r" + lhs + ") {");
int rhs = translate(level, code.rhs, environment, file);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
myOut(level, "r" + target + " = r" + rhs + ";");
myOut(--level, "}");
return target;
} else {
int rhs = translate(level, code.rhs, environment, file);
// First, convert operands into values (where appropriate)
switch (code.op) {
case EQ:
case NEQ:
if (lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
// OK to do nothing here...
} else {
lhs = coerceFromRef(level, code.lhs, lhs, environment);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
}
break;
case APPEND:
// append is a tricky case as we have support the non-symmetic
// cases
// for adding a single element to the end or the beginning of a
// list.
lhs_t = Type.unbox(lhs_t);
rhs_t = Type.unbox(rhs_t);
if (lhs_t instanceof Type.Collection) {
lhs = coerceFromRef(level, code.lhs, lhs, environment);
} else {
lhs = coerceFromValue(level, code.lhs, lhs, environment);
}
if (rhs_t instanceof Type.Collection) {
rhs = coerceFromRef(level, code.rhs, rhs, environment);
} else {
rhs = coerceFromValue(level, code.rhs, rhs, environment);
}
break;
case IN:
lhs = coerceFromValue(level, code.lhs, lhs, environment);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
break;
default:
lhs = coerceFromRef(level, code.lhs, lhs, environment);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
}
// Second, construct the body of the computation
switch (code.op) {
case ADD:
body = "r" + lhs + ".add(r" + rhs + ")";
break;
case SUB:
body = "r" + lhs + ".subtract(r" + rhs + ")";
break;
case MUL:
body = "r" + lhs + ".multiply(r" + rhs + ")";
break;
case DIV:
body = "r" + lhs + ".divide(r" + rhs + ")";
break;
case OR:
body = "r" + lhs + " || r" + rhs;
break;
case EQ:
if (lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
body = "r" + lhs + " == r" + rhs;
} else {
body = "r" + lhs + ".equals(r" + rhs + ")";
}
break;
case NEQ:
if (lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
body = "r" + lhs + " != r" + rhs;
} else {
body = "!r" + lhs + ".equals(r" + rhs + ")";
}
break;
case LT:
body = "r" + lhs + ".compareTo(r" + rhs + ")<0";
break;
case LTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")<=0";
break;
case GT:
body = "r" + lhs + ".compareTo(r" + rhs + ")>0";
break;
case GTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")>=0";
break;
case APPEND:
if (lhs_t instanceof Type.Collection) {
body = "r" + lhs + ".append(r" + rhs + ")";
} else {
body = "r" + rhs + ".appendFront(r" + lhs + ")";
}
break;
case DIFFERENCE:
body = "r" + lhs + ".removeAll(r" + rhs + ")";
break;
case IN:
body = "r" + rhs + ".contains(r" + lhs + ")";
break;
case RANGE:
body = "Runtime.rangeOf(automaton,r" + lhs + ",r" + rhs + ")";
break;
default:
throw new RuntimeException(
"unknown binary operator encountered: " + code);
}
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.NaryOp code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
String body = "new Automaton.";
if (code.op == Expr.NOp.LISTGEN) {
body += "List(";
} else if (code.op == Expr.NOp.BAGGEN) {
body += "Bag(";
} else {
body += "Set(";
}
List<Expr> arguments = code.arguments;
for (int i = 0; i != arguments.size(); ++i) {
if (i != 0) {
body += ", ";
}
Expr argument = arguments.get(i);
int reg = translate(level, argument, environment, file);
reg = coerceFromValue(level, argument, reg, environment);
body += "r" + reg;
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ");", code.toString()));
return target;
}
public int translate(int level, Expr.ListAccess code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int src = translate(level, code.src, environment, file);
int idx = translate(level, code.index, environment, file);
src = coerceFromRef(level, code.src, src, environment);
idx = coerceFromRef(level, code.index, idx, environment);
String body = "r" + src + ".indexOf(r" + idx + ")";
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.ListUpdate code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int src = translate(level, code.src, environment, file);
int idx = translate(level, code.index, environment, file);
int value = translate(level, code.value, environment, file);
src = coerceFromRef(level, code.src, src, environment);
idx = coerceFromRef(level, code.index, idx, environment);
value = coerceFromValue(level, code.value, value, environment);
String body = "r" + src + ".update(r" + idx + ", r" + value + ")";
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.Constructor code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
String body;
if (code.argument == null) {
body = code.name;
} else {
int arg = translate(level, code.argument, environment, file);
if (code.external) {
body = file.name + "$native." + code.name + "(automaton, r"
+ arg + ")";
} else {
arg = coerceFromValue(level, code.argument, arg, environment);
body = "new Automaton.Term(K_" + code.name + ",r" + arg + ")";
}
}
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Variable code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + code.var
+ ";");
return target;
}
public int translate(int level, Expr.Substitute code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first, translate all subexpressions and make sure they are
// references.
int src = translate(level, code.src, environment, file);
src = coerceFromValue(level, code.src, src, environment);
int original = translate(level, code.original, environment, file);
original = coerceFromValue(level, code.original, original, environment);
int replacement = translate(level, code.replacement, environment, file);
replacement = coerceFromValue(level, code.replacement, replacement,
environment);
// second, put in place the substitution
String body = "automaton.substitute(r" + src + ", r" + original + ", r"
+ replacement + ")";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.TermAccess code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first translate src expression, and coerce to a value
int src = translate(level, code.src, environment, file);
src = coerceFromRef(level, code.src, src, environment);
String body = "r" + src + ".contents";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Comprehension expr,
Environment environment, SpecFile file) {
Type type = expr.attribute(Attribute.Type.class).type;
int target = environment.allocate(type);
// first, translate all source expressions
int[] sources = new int[expr.sources.size()];
for (int i = 0; i != sources.length; ++i) {
Pair<Expr.Variable, Expr> p = expr.sources.get(i);
int operand = translate(level, p.second(), environment, file);
operand = coerceFromRef(level, p.second(), operand, environment);
sources[i] = operand;
}
// TODO: initialise result set
myOut(level, "Automaton.List t" + target + " = new Automaton.List();");
int startLevel = level;
// initialise result register if needed
switch (expr.cop) {
case NONE:
myOut(level, type2JavaType(type) + " r" + target + " = true;");
myOut(level, "outer:");
break;
case SOME:
myOut(level, type2JavaType(type) + " r" + target + " = false;");
myOut(level, "outer:");
break;
}
// second, generate all the for loops
for (int i = 0; i != sources.length; ++i) {
Pair<Expr.Variable, Expr> p = expr.sources.get(i);
Expr.Variable variable = p.first();
Expr source = p.second();
Type.Collection sourceType = (Type.Collection) source
.attribute(Attribute.Type.class).type;
Type elementType = variable.attribute(Attribute.Type.class).type;
int index = environment.allocate(elementType, variable.var);
myOut(level++, "for(int i" + index + "=0;i" + index + "<r"
+ sources[i] + ".size();i" + index + "++) {");
String rhs = "r" + sources[i] + ".get(i" + index + ")";
// FIXME: need a more general test for a reference type
if (!(elementType instanceof Type.Ref)) {
rhs = "automaton.get(" + rhs + ");";
}
myOut(level, type2JavaType(elementType) + " r" + index + " = ("
+ type2JavaType(elementType) + ") " + rhs + ";");
}
if (expr.condition != null) {
int condition = translate(level, expr.condition, environment, file);
myOut(level++, "if(r" + condition + ") {");
}
switch (expr.cop) {
case SETCOMP:
case BAGCOMP:
case LISTCOMP:
int result = translate(level, expr.value, environment, file);
result = coerceFromValue(level, expr.value, result, environment);
myOut(level, "t" + target + ".add(r" + result + ");");
break;
case NONE:
myOut(level, "r" + target + " = false;");
myOut(level, "break outer;");
break;
case SOME:
myOut(level, "r" + target + " = true;");
myOut(level, "break outer;");
break;
}
// finally, terminate all the for loops
while (level > startLevel) {
myOut(--level, "}");
}
switch (expr.cop) {
case SETCOMP:
myOut(level, type2JavaType(type) + " r" + target
+ " = new Automaton.Set(t" + target + ".toArray());");
break;
case BAGCOMP:
myOut(level, type2JavaType(type) + " r" + target
+ " = new Automaton.Bag(t" + target + ".toArray());");
break;
case LISTCOMP:
myOut(level, type2JavaType(type) + " r" + target + " = t" + target
+ ";");
break;
}
return target;
}
protected void writeMainMethod() {
myOut();
myOut(1,
"
myOut(1, "// Main Method");
myOut(1,
"
myOut();
myOut(1, "public static void main(String[] args) throws IOException {");
myOut(2, "try {");
myOut(3,
"PrettyAutomataReader reader = new PrettyAutomataReader(System.in,SCHEMA);");
myOut(3,
"PrettyAutomataWriter writer = new PrettyAutomataWriter(System.out,SCHEMA);");
myOut(3, "Automaton automaton = reader.read();");
myOut(3, "System.out.print(\"PARSED: \");");
myOut(3, "print(automaton);");
myOut(3, "new SimpleRewriter(inferences,reductions).apply(automaton);");
myOut(3, "System.out.print(\"REWROTE: \");");
myOut(3, "print(automaton);");
// myOut(3,
// "System.out.println(\"(Reductions=\" + numReductions + \", Inferences=\" + numInferences + \", Misinferences=\" + numMisinferences + \", steps = \" + numSteps + \")\");");
myOut(2, "} catch(PrettyAutomataReader.SyntaxError ex) {");
myOut(3, "System.err.println(ex.getMessage());");
myOut(2, "}");
myOut(1, "}");
myOut(1, "");
myOut(1, "static void print(Automaton automaton) {");
myOut(2, "try {");
myOut(3,
"PrettyAutomataWriter writer = new PrettyAutomataWriter(System.out,SCHEMA);");
myOut(3, "writer.write(automaton);");
myOut(3, "writer.flush();");
myOut(3, "System.out.println();");
myOut(2,
"} catch(IOException e) { System.err.println(\"I/O error printing automaton\"); }");
myOut(1, "}");
}
public String comment(String code, String comment) {
int nspaces = 30 - code.length();
String r = "";
for (int i = 0; i < nspaces; ++i) {
r += " ";
}
return code + r + " // " + comment;
}
/**
* Convert a Wyrl type into its equivalent Java type.
*
* @param type
* @return
*/
public String type2JavaType(Type type) {
return type2JavaType(type, true);
}
/**
* Convert a Wyrl type into its equivalent Java type. The user specifies
* whether primitive types are allowed or not. If not then, for example,
* <code>Type.Int</code> becomes <code>int</code>; otherwise, it becomes
* <code>Integer</code>.
*
* @param type
* @return
*/
public String type2JavaType(Type type, boolean primitives) {
if (type instanceof Type.Any) {
return "Object";
} else if (type instanceof Type.Int) {
return "Automaton.Int";
} else if (type instanceof Type.Real) {
return "Automaton.Real";
} else if (type instanceof Type.Bool) {
return "boolean";
} else if (type instanceof Type.Strung) {
return "Automaton.Strung";
} else if (type instanceof Type.Term) {
return "Automaton.Term";
} else if (type instanceof Type.Ref) {
if (primitives) {
return "int";
} else {
return "Integer";
}
} else if (type instanceof Type.Nominal) {
Type.Nominal nom = (Type.Nominal) type;
return type2JavaType(nom.element(), primitives);
} else if (type instanceof Type.Or) {
return "Object";
} else if (type instanceof Type.List) {
return "Automaton.List";
} else if (type instanceof Type.Bag) {
return "Automaton.Bag";
} else if (type instanceof Type.Set) {
return "Automaton.Set";
}
throw new RuntimeException("unknown type encountered: " + type);
}
public int coerceFromValue(int level, Expr expr, int register,
Environment environment) {
Type type = expr.attribute(Attribute.Type.class).type;
if (type instanceof Type.Ref) {
return register;
} else {
Type.Ref refType = Type.T_REF(type);
int result = environment.allocate(refType);
String src = "r" + register;
if (refType.element() instanceof Type.Bool) {
// special thing needed for bools
src = src + " ? Automaton.TRUE : Automaton.FALSE";
}
myOut(level, type2JavaType(refType) + " r" + result
+ " = automaton.add(" + src + ");");
return result;
}
}
public int coerceFromRef(int level, SyntacticElement elem, int register,
Environment environment) {
Type type = elem.attribute(Attribute.Type.class).type;
if (type instanceof Type.Ref) {
Type.Ref refType = (Type.Ref) type;
Type element = refType.element();
int result = environment.allocate(element);
String cast = type2JavaType(element);
String body = "automaton.get(r" + register + ")";
// special case needed for booleans
if (element instanceof Type.Bool) {
body = "((Automaton.Bool)" + body + ").value";
} else {
body = "(" + cast + ") " + body;
}
myOut(level, cast + " r" + result + " = " + body + ";");
return result;
} else {
return register;
}
}
protected void myOut() {
myOut(0, "");
}
protected void myOut(int level) {
myOut(level, "");
}
protected void myOut(String line) {
myOut(0, line);
}
protected void myOut(int level, String line) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
out.println(line);
}
protected void indent(int level) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
}
private HashMap<Type, Integer> registeredTypes = new HashMap<Type, Integer>();
private ArrayList<Type> typeRegister = new ArrayList<Type>();
private int register(Type t) {
t.automaton().canonicalise();
// Types.reduce(t.automaton());
Integer i = registeredTypes.get(t);
if (i == null) {
int r = typeRegister.size();
registeredTypes.put(t, r);
typeRegister.add(t);
return r;
} else {
return i;
}
}
private static final class Environment {
private final HashMap<String, Integer> var2idx;
private final ArrayList<Pair<Type, String>> idx2var;
public Environment() {
this.var2idx = new HashMap<String, Integer>();
this.idx2var = new ArrayList<Pair<Type, String>>();
}
private Environment(HashMap<String, Integer> var2idx,
ArrayList<Pair<Type, String>> idx2var) {
this.var2idx = var2idx;
this.idx2var = idx2var;
}
public int size() {
return idx2var.size();
}
public int allocate(Type t) {
int idx = idx2var.size();
idx2var.add(new Pair<Type, String>(t, null));
return idx;
}
public int allocate(Type t, String v) {
int idx = idx2var.size();
idx2var.add(new Pair<Type, String>(t, v));
var2idx.put(v, idx);
return idx;
}
public Integer get(String v) {
return var2idx.get(v);
}
public Pair<Type, String> get(int idx) {
return idx2var.get(idx);
}
public void put(int idx, String v) {
var2idx.put(v, idx);
idx2var.set(idx,
new Pair<Type, String>(idx2var.get(idx).first(), v));
}
public Environment clone() {
return new Environment((HashMap) var2idx.clone(),
(ArrayList) idx2var.clone());
}
public String toString() {
return var2idx.toString();
}
}
}
|
package org.jeffpiazza.derby;
import jssc.*;
import java.io.*;
import java.util.ArrayList;
// TODO: UNFINISHED!!!!!!!!!!!!!!!!!!!!!
// scan for timer. If not found, repeat.
// send HELLO; keep trying until successful
// do forever:
// poll (HEARTBEAT) until a STARTED
// keep polling
// start timer
// poll timer until results in.
// send FINISHED
// Two threads: one for timer, one for heartbeat
// Meanwhile, timer thread takes a device plug-in, and polls timer continuously.
// On HEAT-READY, arm the timer
// On gate open, send STARTED message, and (Champ) if timer armed, start internal timer to abort after 10 seconds.
// (Maybe just send heartbeat with gate state if not racing?)
// On gate close, send heartbeat
// On timer result, if racing send FINISHED
// On 10-second elapsed, force race finish, send FINISHED
public class TimerMain {
private HttpTask task;
private TimerMain(HttpTask task) {
this.task = task;
}
public static void usage() {
System.err.println("Usage: [-u <user>] [-p <password>] [-l <nlanes>] [-t] [-th] [-r] <base-url>");
System.err.println(" -u, -p: Specify username and password for authenticating to web server");
System.err.println(" -l: Specify number of lanes to report to web server");
System.err.println(" -t: Trace non-heartbeat messages sent");
System.err.println(" -th: Trace heartbeat messages sent");
System.err.println(" -r: Show responses to traced messages");
}
private static Class[] knownTimerDeviceClasses = { FastTrackDevice.class, ChampDevice.class };
public static void main(String[] args) {
String username = "RaceCoordinator";
String password = "doyourbest";
int nlanes = 3;
StdoutMessageTrace traceMessages = null;
StdoutMessageTrace traceHeartbeats = null;
boolean traceResponses = false;
int consumed_args = 0;
while (consumed_args + 1 < args.length) {
if (args[consumed_args].equals("-u") && consumed_args + 2 < args.length) {
username = args[consumed_args + 1];
consumed_args += 2;
} else if (args[consumed_args].equals("-p") && consumed_args + 2 < args.length) {
password = args[consumed_args + 1];
consumed_args += 2;
} else if (args[consumed_args].equals("-l") && consumed_args + 2 < args.length) {
try {
nlanes = Integer.parseInt(args[consumed_args + 1]);
} catch (Throwable t) {
t.printStackTrace();
}
} else if (args[consumed_args].equals("-t")) {
traceMessages = new StdoutMessageTrace();
++consumed_args;
} else if (args[consumed_args].equals("-th")) {
traceHeartbeats = new StdoutMessageTrace();
++consumed_args;
} else if (args[consumed_args].equals("-r")) {
traceResponses = true;
++consumed_args;
} else {
usage();
System.exit(1);
}
}
if (consumed_args + 1 != args.length) {
usage();
System.exit(1);
}
if (traceMessages != null) {
traceMessages.traceResponses = traceResponses;
}
if (traceHeartbeats != null) {
traceHeartbeats.traceResponses = traceResponses;
}
String base_url = args[consumed_args];
try {
// (new TimerMain(new HttpTask(base_url, username, password,
// traceMessages, traceHeartbeats)))
// .runTest(nlanes);
} catch (Throwable t) {
t.printStackTrace();
}
}
private static TimerDevice identifyDevice(SerialPortWrapper wrapper) throws SerialPortException {
while (true) {
for (Class deviceClass : knownTimerDeviceClasses) {
try {
System.out.println("Trying " + deviceClass.getName());
TimerDevice device =
(TimerDevice) deviceClass.getConstructor(SerialPortWrapper.class).newInstance(wrapper);
if (device.probe()) {
return device;
}
} catch (Throwable t) {
t.printStackTrace();
}
}
try {
Thread.sleep(10000); // Wait 10 seconds before trying again
} catch (Throwable t) {}
}
}
public static void experiment(String base_url, String username, String password,
SerialPort port) throws Exception {
SerialPortWrapper wrapper = new SerialPortWrapper(port);
final TimerDevice device = identifyDevice(wrapper);
int nlanes = device.getNumberOfLanes();
final TimerDeviceTask deviceTask = new TimerDeviceTask(device);
final HttpTask httpTask = new HttpTask(base_url, username, password);
(new Thread(deviceTask)).start();
// (new Thread(httpTask)).start();
httpTask.registerHeatReadyCallback(new HttpTask.HeatReadyCallback() {
public void heatReady(int laneMask) {
try {
device.prepareHeat(laneMask);
} catch (Throwable t) {
// TODO: details
try {
httpTask.send(new Message.Malfunction("Can't ready timer."));
} catch (Throwable tt) {
}
}
}
});
device.registerRaceFinishedCallback(new TimerDevice.RaceFinishedCallback() {
public void raceFinished(Message.LaneResult[] results) {
// Rely on recipient to ignore if not expecting any results
try {
httpTask.send(new Message.Finished(results));
} catch (Throwable t) {
}
}
});
device.registerStartingGateCallback(new TimerDevice.StartingGateCallback() {
public void startGateChange(boolean isOpen) {
try {
if (isOpen /* && timer armed? */) {
httpTask.send(new Message.Started());
} else {
httpTask.send(new Message.Heartbeat());
}
} catch (Throwable t) {
}
}
});
// TODO: handler for ABORT message: device.abortHeat();
boolean sentHello = false;
while (!sentHello) {
try {
httpTask.send(new Message.Hello(nlanes));
sentHello = true;
} catch (Throwable t) {
t.printStackTrace();
}
}
httpTask.run();
}
}
|
package de.uni.freiburg.iig.telematik.swat.workbench;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.ScrollPane;
import java.awt.Toolkit;
import java.util.Calendar;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import de.uni.freiburg.iig.telematik.swat.logs.LogFileViewer;
import de.uni.freiburg.iig.telematik.swat.lukas.pattern_analysis_component.logic.AnalysisController;
import de.uni.freiburg.iig.telematik.swat.misc.errorhandling.ErrorStorage;
import de.uni.freiburg.iig.telematik.swat.workbench.SwatState.OperatingMode;
import de.uni.freiburg.iig.telematik.swat.workbench.dialog.MessageDialog;
import de.uni.freiburg.iig.telematik.swat.workbench.listener.SwatStateListener;
import de.uni.freiburg.iig.telematik.swat.workbench.listener.SwatTabViewListener;
import de.uni.freiburg.iig.telematik.swat.workbench.listener.SwatTreeViewListener;
import de.uni.freiburg.iig.telematik.wolfgang.editor.component.PNEditorComponent;
import de.uni.freiburg.iig.telematik.wolfgang.editor.component.ViewComponent;
public class Workbench extends JFrame implements SwatTreeViewListener, SwatTabViewListener, SwatStateListener {
private static final long serialVersionUID = 6109154620023481119L;
public static final Dimension PREFERRED_SIZE_WORKBENCH = new Dimension(1024,768);
private static final Dimension PREFERRED_SIZE_PROPERTIES_PANEL = new Dimension(200, 768);
private static final Dimension PREFERRED_SIZE_TREEVIEW_PANEL = new Dimension(250, 500);
private static final Dimension PREFERRED_SIZE_CONSOLE_PANEL = new Dimension(300,80);
private static final Dimension MINIMUM_SIZE_TAB_PANEL = new Dimension(300, 550);
// private MultiSplitPane splitPane = null;
private SwatToolbar toolbar = null;
private SwatTreeView treeView = null;
private SwatTabView tabView = null;
private SwatMenuBar menuBar = null;
private static JTabbedPane messagePanel = null;
private JPanel properties = null;
private JPanel content = null;
private static JTextArea console = null;
private static JTextArea errors = null;
private static Workbench myWorkbench;
private Workbench() {
super();
setLookAndFeel();
setUpGUI();
Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
int wdwLeft = (int) ((screenSize.width/2.0) - ((PREFERRED_SIZE_WORKBENCH.width + MessageDialog.PREFERRED_SIZE.width + 10)/2.0));
int wdwTop = screenSize.height / 2 - PREFERRED_SIZE_WORKBENCH.height / 2;
pack();
setLocation(wdwLeft, wdwTop);
SwatState.getInstance().setOperatingMode(Workbench.this, OperatingMode.EDIT_MODE);
SwatState.getInstance().addListener(this);
SwatComponents.getInstance().addSwatComponentListener(treeView);
}
public static Workbench getInstance() {
if (myWorkbench == null) {
myWorkbench = new Workbench();
}
return myWorkbench;
}
/** Changes Look and Feel if running on Linux **/
private void setLookAndFeel() {
if (System.getProperty("os.name").toLowerCase().contains("nux")) {
try {
setLocationByPlatform(true);
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
} catch (Exception e) {
MessageDialog.getInstance().addMessage("Could not set Look and Feel. Using standard");
}
} else if (System.getProperty("os.name").toLowerCase().contains("windows")) {
try {
UIManager
.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void setUpGUI(){
setTitle("SWAT 2.0");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(PREFERRED_SIZE_WORKBENCH);
setResizable(true);
setContentPane(getContent());
setJMenuBar(getSwatMenu());
pack();
setVisible(true);
}
private JComponent getContent(){
if(content == null){
content = new JPanel(new BorderLayout());
content.add(getSwatToolbar(), BorderLayout.NORTH);
//content.add(getTreeView(), BorderLayout.WEST);
//content.add(new JScrollPane(getPropertiesPanel(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
// JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.EAST);
content.add(getPropertiesPanel(), BorderLayout.EAST);
//content.add(propertieSplit, BorderLayout.EAST);
JSplitPane centerPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
centerPanel.add(getTabView());
centerPanel.add(getMessagePanel());
JSplitPane middlePanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
JScrollPane scrollPane = new JScrollPane(getTreeView(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setSize(PREFERRED_SIZE_TREEVIEW_PANEL);
middlePanel.add(scrollPane);
middlePanel.add(centerPanel);
//middlePanel.setMinimumSize(MINIMUM_SIZE_TAB_PANEL);
//middlePanel.add(propertieSplit);
//content.add(centerPanel, BorderLayout.CENTER);
//JSplitPane thirdSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
//thirdSplit.add(middlePanel);
//thirdSplit.add(getPropertiesPanel());
//thirdSplit.setSize(PREFERRED_SIZE_PROPERTIES_PANEL);
//thirdSplit.setPreferredSize(PREFERRED_SIZE_PROPERTIES_PANEL);
content.add(middlePanel, BorderLayout.CENTER);
centerPanel.setDividerLocation(0.8);
//content.add(thirdSplit, BorderLayout.CENTER);
}
return content;
}
public SwatToolbar getSwatToolbar() {
if(toolbar == null){
toolbar = new SwatToolbar(getTabView(), getTreeView());
}
return toolbar;
}
private JPanel getPropertiesPanel(){
if(properties == null){
properties = new JPanel(new BorderLayout());
properties.setPreferredSize(PREFERRED_SIZE_PROPERTIES_PANEL);
properties.setMinimumSize(PREFERRED_SIZE_PROPERTIES_PANEL);
properties.setSize(PREFERRED_SIZE_PROPERTIES_PANEL);
}
return properties;
}
public SwatTabView getTabView() {
if(tabView == null){
tabView = SwatTabView.getInstance();
tabView.setMinimumSize(MINIMUM_SIZE_TAB_PANEL);
tabView.setPreferredSize(MINIMUM_SIZE_TAB_PANEL);
tabView.addTabViewListener(this);
}
return tabView;
}
public SwatMenuBar getSwatMenu() {
if(menuBar == null){
menuBar = new SwatMenuBar(getTabView(), getTreeView());
}
return menuBar;
}
public SwatTreeView getTreeView() {
UIManager.put("Tree.rendererFillBackground", false);
if(treeView == null){
treeView = SwatTreeView.getInstance();
treeView.setMinimumSize(PREFERRED_SIZE_TREEVIEW_PANEL);
treeView.addTreeViewListener(this);
}
return treeView;
}
private static JComponent getMessagePanel() {
if(messagePanel == null){
messagePanel = new JTabbedPane();
messagePanel.add(getErrorArea(), "Errors");
messagePanel.add(getConsoleArea(), "Console");
messagePanel.setPreferredSize(PREFERRED_SIZE_CONSOLE_PANEL);
messagePanel.setMinimumSize(PREFERRED_SIZE_CONSOLE_PANEL);
messagePanel.setMaximumSize(PREFERRED_SIZE_CONSOLE_PANEL);
}
return messagePanel;
}
private static JTextArea getConsoleArea() {
if(console == null){
console = new JTextArea();
console.setEditable(false);
}
return console;
}
private static JTextArea getErrorArea() {
if(errors == null){
errors = new JTextArea();
errors.setEditable(false);
}
return errors;
}
public static void consoleMessage(String message) {
getConsoleArea().append(
Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":"
+ Calendar.getInstance().get(Calendar.SECOND) + " - ");
getConsoleArea().append(message);
getConsoleArea().append("\n\r");
try {
messagePanel.setSelectedIndex(1);
} catch (ArrayIndexOutOfBoundsException e) {
}
}
public static void errorMessage(String message, Exception e, boolean showPopup) {
String messageToShow = "";
if (!message.isEmpty())
messageToShow = message + " ";
if (e != null)
messageToShow += e.getMessage();
if (showPopup)
JOptionPane.showMessageDialog(myWorkbench, messageToShow);
errorMessage(messageToShow);
try {
ErrorStorage.getInstance().addMessage(message, e);
} catch (Exception ex) {
}
}
private static void errorMessageWithNotification(String message) {
JOptionPane.showMessageDialog(getInstance(), message);
errorMessage(message);
}
private static void errorMessage(String message) {
getConsoleArea().append(
Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":"
+ Calendar.getInstance().get(Calendar.SECOND) + " - ");
getConsoleArea().append(message);
getConsoleArea().append("\n\r");
try {
messagePanel.setSelectedIndex(0);
} catch (ArrayIndexOutOfBoundsException e) {
}
}
@Override
public void componentSelected(SwatTreeNode node) {
//Information from TreeView: New node activated -> relay to TabView
getTabView().componentSelected(node);
//Update Toolbar
updateToolbar();
}
@Override
public void componentActivated(SwatTreeNode node) {
if (getTabView().containsComponent(node))
return;
ViewComponent swatComponent = null;
// add SwatTreeNode to tab and get its swatComponent to make its propertyView
swatComponent = getTabView().addNewTab(node);
getPropertiesPanel().removeAll();
if (SwatState.getInstance().getOperatingMode() == OperatingMode.EDIT_MODE) {
getPropertiesPanel().add(new ScrollPane().add(swatComponent.getPropertiesView()));
}
else if (SwatState.getInstance().getOperatingMode() == OperatingMode.ANALYSIS_MODE) {
String name = node.getDisplayName();
if (swatComponent instanceof PNEditorComponent) {
if (node.getObjectType() == SwatComponentType.PETRI_NET_ANALYSIS) {
name = ((SwatTreeNode) node.getParent()).getDisplayName();
}
}
//Here: Analyze Panel is loaded
//getPropertiesPanel().add(AnalyzePanelController.getInstance().getAnalyzePanel(name, swatComponent).getContent());
getPropertiesPanel().add(getPropertiesPanel().add(AnalysisController.getInstance(swatComponent).getAnalyzePanel()));
}
getPropertiesPanel().validate();
getPropertiesPanel().repaint();
getPropertiesPanel().updateUI();
//Update Toolbar
updateToolbar();
}
// @SuppressWarnings("rawtypes")
// private WorkbenchComponent getWorkbenchComponent(SwatTreeNode node) {
// switch (node.getObjectType()) {
// case LABELING:
// // TODO:
// break;
// case PETRI_NET:
// AbstractGraphicalPN petriNet = (AbstractGraphicalPN) node.getUserObject();
// if(petriNet instanceof GraphicalPTNet){
// return new PTNetEditor((GraphicalPTNet) petriNet, SwatComponents.getInstance().getPetriNetFile(petriNet.getPetriNet().getName()));
// } else if(petriNet instanceof GraphicalCPN){
//// return new CPNEditor((GraphicalPTNet) petriNet, SwatComponents.getInstance().getFile(petriNet));
// } else if(petriNet instanceof GraphicalIFNet){
//// return new IFNetEditor((GraphicalPTNet) petriNet, SwatComponents.getInstance().getFile(petriNet));
// break;
//// case LOG_FILE:
//// // User Object is of type LogFileViewer
//// return (LogFileViewer) node.getUserObject();
// return null;
@Override
public void activeTabChanged(int index, ViewComponent component) {
if (index < 0)
return; //no tabs inside
// Update Properties Panel & Toolbar according to active tab
getPropertiesPanel().removeAll();
//pack();
if(SwatState.getInstance().getOperatingMode() == OperatingMode.EDIT_MODE) {
getPropertiesPanel().add(new ScrollPane().add(component.getPropertiesView()));
} else if (SwatState.getInstance().getOperatingMode() == OperatingMode.ANALYSIS_MODE) {
getPropertiesPanel().add(AnalysisController.getInstance(component).getAnalyzePanel());
}
getPropertiesPanel().repaint();
getPropertiesPanel().updateUI();
updateToolbar();
}
@Override
public void operatingModeChanged() {
try {
//Update Properties View & Toolbar
ViewComponent swatComponent = (ViewComponent) getTabView().getSelectedComponent();
getPropertiesPanel().removeAll();
if(SwatState.getInstance().getOperatingMode() == OperatingMode.EDIT_MODE) {
getPropertiesPanel().add(new ScrollPane().add(swatComponent.getPropertiesView()));
} else if (SwatState.getInstance().getOperatingMode() == OperatingMode.ANALYSIS_MODE) {
if(swatComponent instanceof PNEditorComponent){
getPropertiesPanel().add(AnalysisController.getInstance(swatComponent).getAnalyzePanel());
//((PNEditor)swatComponent).setEnabled(false);
}
if (swatComponent instanceof LogFileViewer)
getPropertiesPanel().add(AnalysisController.getInstance(swatComponent).getAnalyzePanel());
//getPropertiesPanel().add(((LogFileViewer) swatComponent).getPropertiesView());
}
//pack();
getPropertiesPanel().repaint();
getPropertiesPanel().updateUI();
//getPropertiesPanel().repaint();
updateToolbar();
} catch (NullPointerException e) {
//Can happens when Arista-Flow analysis is called with no active tabs
}
}
/** check if a PNEditor got activated and update Toolbar if needed **/
private void updateToolbar() {
if (getTabView().getSelectedComponent() instanceof PNEditorComponent) {
try {
PNEditorComponent editor = (PNEditorComponent) getTabView().getSelectedComponent();
getSwatToolbar().clear();
if (SwatState.getInstance().getOperatingMode() == OperatingMode.ANALYSIS_MODE) {
//getSwatToolbar().add(((AnalyzePanelPN)AnalyzePanelController.getInstance().getAnalyzePanel(getTabView().getSelectedComponent().getName(), (ViewComponent) editor)).getToolBar());
} else {
getSwatToolbar().add(editor.getEditorToolbar());
}
} catch (Exception e) {
}
} else {
//remove Toolbar-Addons
getSwatToolbar().clear();
}
getSwatToolbar().validate();
getSwatToolbar().repaint();
}
}
|
package edu.psu.compbio.seqcode.projects.naomi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.distribution.NormalDistribution;
import edu.psu.compbio.seqcode.deepseq.StrandedBaseCount;
import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager;
import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig;
import edu.psu.compbio.seqcode.deepseq.experiments.Sample;
import edu.psu.compbio.seqcode.genome.Genome;
import edu.psu.compbio.seqcode.genome.GenomeConfig;
import edu.psu.compbio.seqcode.genome.location.Region;
import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.ChromosomeGenerator;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.projects.seed.SEEDConfig;
/**
* DifferentialMSR:
*
* Methods refer to two papers
* Probabilistic Multiscale Image Segmentation, Vincken et al. IEEE (1997)
*
* @author naomi yamada
*
**/
public class DifferentialMSR {
protected GenomeConfig gconfig;
protected ExptConfig econfig;
protected SEEDConfig sconfig;
protected int threePrimReadExt = 200;
protected int binWidth = 1;
//Map<chrm, Map<scale space, Set<segmentation>>>
protected Map<Region, Map<Integer,Set<Integer>>> segmentationTree;
public DifferentialMSR(GenomeConfig gcon, ExptConfig econ, SEEDConfig scon){
gconfig = gcon;
econfig = econ;
sconfig = scon;
}
public void buildMSR(){
/*********************
* Gaussian scale space and window parameters
*/
// arbitrary number of scale
int numScale= 5;
double DELTA_TAU = 0.5*Math.log(2);
// I have to determine P_MIN value carefully because P_MIN will substantially affect Gaussian window size
double P_MIN = Math.pow(10,-3);
double K_MIN = 1/Math.sqrt(1-Math.exp(-2*DELTA_TAU));
double K_N = Math.ceil(K_MIN);
/*********************
* Linkage parameters
*/
double WEIGHT_I = 1.00;
double WEIGHT_G = 0.0000001;
double WEIGHT_M = 1000;
/*********************
* Matrices parameters
*/
double sigma = 1;
double radius[] = new double[numScale];
for (int i = 0; i<numScale;i++){
radius[i] = 1;
}
ExperimentManager manager = new ExperimentManager(econfig);
Genome genome = gconfig.getGenome();
//test to print whole chromosomes
System.out.println(genome.getChromList());
System.out.println("before: "+binWidth+"\t"+threePrimReadExt);
//fix here to get parameters only if they are specified
binWidth = sconfig.getBinWidth();
threePrimReadExt = sconfig.getTag3PrimeExtension();
//test to print binWidth and threePrimReadExt
System.out.println("binWidth is: "+binWidth);
System.out.println("threePrimReadExt is: "+threePrimReadExt);
Iterator<Region> chroms = new ChromosomeGenerator<Genome>().execute(genome);
//iterating each chromosome (each chromosome is a region).
while (chroms.hasNext()) {
Region currChrom = chroms.next();
//previously it was below. but I don't think I need +1 here
//int currchromSize= currChrom.getWidth()+1
int currchromSize = currChrom.getWidth();
int currchromBinSize = (int) Math.ceil(currchromSize/binWidth);
//primitive matrix to store signal and the subsequent convolved signals
//its index correspond to the coordinates
float[][] GaussianBlur = new float[currchromBinSize][2];
for (int i = 0;i<currchromBinSize;i++){
for (int j = 0; j<2;j++)
GaussianBlur[i][j] = 0;
}
//get StrandedBaseCount list for each chromosome
Map<Sample, List<StrandedBaseCount>> sampleCountsMap = new HashMap<Sample, List<StrandedBaseCount>>();
for (Sample sample : manager.getSamples())
sampleCountsMap.put(sample,sample.getBases(currChrom));
//StrandedBasedCount object contains positive and negative strand separately
//store all base counts indexed by positions at column[1]
//extend reads to 3' end and bin according to bin size
for (Sample sample : manager.getSamples()){
List<StrandedBaseCount> currentCounts = sampleCountsMap.get(sample);
for (StrandedBaseCount hits: currentCounts){
for (int i = 0; i<threePrimReadExt+1; i++){
if (hits.getStrand()=='+' && hits.getCoordinate()+i<currchromSize){
GaussianBlur[(int) Math.ceil((hits.getCoordinate()+i)/binWidth)][1]+=hits.getCount();
}else if (hits.getStrand()=='+' && hits.getCoordinate()-i >=0){
GaussianBlur[(int) Math.ceil((hits.getCoordinate()-i)/binWidth)][1]+=hits.getCount();
}
}
}
currentCounts = null;
}
//testing
if (currchromSize > 200000000){
System.out.println("current Chrom is: "+currChrom.getChrom());
for (int i = 0; i< 100;i++)
System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]);
}
/*********************
* Starting nodes
*/
//linkageMap contains index of kids and parents
HashMap <Integer, Integer> linkageMap = new HashMap<Integer, Integer>();
//adding starting nodes; to qualify for the starting nodes the signal intensity needs to be different from the subsequent signal intensity
//adding the starting and end positions in the kids at start and end positions
//setting max & min signal intensity
float DImax = 0;
float DImin = (float) Integer.MAX_VALUE;
List <Integer> nonzeroList = new ArrayList<Integer>();
linkageMap.put(0,0);
for (int i = 0 ; i< GaussianBlur.length-1; i++){ //should I start
if (GaussianBlur[i][1] != GaussianBlur[i+1][1])
linkageMap.put(i,0);
if (GaussianBlur[i][1] > DImax)
DImax = GaussianBlur[i][1];
if (GaussianBlur[i][1] < DImin)
DImin = GaussianBlur[i][1];
if (GaussianBlur[i][1]!=0)
nonzeroList.add(i);
}
linkageMap.put(GaussianBlur.length-1,0);
//copy to segmentation tree
Map<Integer,Set<Integer>> currScale =new HashMap<Integer,Set<Integer>>();
currScale.put(1, linkageMap.keySet());
//determine the first nonzero and last nonzero from signal
//check here
int trailingZero = 0;
int zeroEnd = 0;
if (!nonzeroList.isEmpty()){
trailingZero = Collections.min(nonzeroList)-1;
zeroEnd = Collections.max(nonzeroList)+1;
}
if (trailingZero == -1)
trailingZero = 0;
System.out.println("DImax is: "+DImax+"\t"+"DImin is: "+DImin+
"\t"+"trailingZero: "+trailingZero+"\t"+"zeroEnd"+"\t"+zeroEnd);
for (int n = 2;n < numScale+1; n++){
/*********************
* Gaussian scale space
*/
double polyCoeffi[] = new double [currchromBinSize];
//first copy from column[1] to column[0];this procedure need to be repeated for each iteration of scale
//also copy from column[1] to array to store polynomial coefficient
for (int i = 0 ; i<currchromBinSize; i++){
GaussianBlur[i][0]=GaussianBlur[i][1];
polyCoeffi[i]=GaussianBlur[i][1];
}
//sigma calculation
sigma = Math.exp((n-1)*DELTA_TAU);
// create normal distribution with mean zero and sigma[n]
NormalDistribution normDistribution = new NormalDistribution(0.00,sigma);
//take inverse CDF based on the normal distribution using probability
double inverseCDF = normDistribution.inverseCumulativeProbability(P_MIN);
int windowSize = (int) (-Math.round(inverseCDF)*2+1);
//window calculation based on Gaussian(normal) distribution with sigma, mean=zero,x=X[i]
double window[] = new double[windowSize];
double windowSum = 0;
for (int i = 0;i<windowSize;i++){
window[i] = normDistribution.density(Math.round(inverseCDF)+i);
windowSum = windowSum+window[i];
}
double normalizedWindow[]=new double[windowSize];
for (int i = 0;i<windowSize;i++)
normalizedWindow[i] = window[i]/windowSum;
//test
System.out.println("delta_tau is: "+DELTA_TAU+"\t"+"sigma is: "+sigma+"\t"+"inverseCDF is: "+inverseCDF+"windowSize is: "+windowSize);
System.out.println("normalized window is: ");
for (int i = 0; i<windowSize; i++)
System.out.println(normalizedWindow[i]);
//multiplying by polynomial ; I have to test to see how this works
PolynomialFunction poly1 = new PolynomialFunction(polyCoeffi);
PolynomialFunction poly2 = new PolynomialFunction(normalizedWindow);
PolynomialFunction polyMultiplication=poly1.multiply(poly2);
double coefficients[]= polyMultiplication.getCoefficients();
//taking mid point of polynomial coefficients
int polyMid = (int) Math.floor(coefficients.length/2);
System.out.println("coefficients length is: "+coefficients.length+"polyMid is: "+polyMid);
//copy Gaussian blur results to the column[1]
// I should check to make sure that it's not off by 1
// for (int i = 0; i<currchromBinSize;i++){
// if (currchromBinSize % 2 ==0 && coefficients.length/2 == 1)
// GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i+1];
// else
// GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i];
//testing
// if (currchromSize > 200000000){
// System.out.println("current Chrom is: "+currChrom.getChrom());
// for (int i = 0; i< 100;i++)
// System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][0]+" : "+GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]);
/***********
* Over kids
//I haven't understood this part from the matlab code
}
//for each scaleNum, add the parents to the segmentationTree
currScale.put(n, GvParents.keySet());
*/
}//end of scale space iteration
// segmentationTree.put(currChrom, currScale);
GaussianBlur = null;
}// end of chromosome iteration
manager.close();
}
public static void main(String[] args) {
GenomeConfig gconf = new GenomeConfig(args);
ExptConfig econf = new ExptConfig(gconf.getGenome(), args);
SEEDConfig sconf = new SEEDConfig(gconf, args);
DifferentialMSR profile = new DifferentialMSR (gconf, econf, sconf);
profile.buildMSR();
}
}
|
package org.sagebionetworks.repo.model.dbo.v2.dao;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ATTACHMENT_RESERVATION_FILE_HANDLE_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ATTACHMENT_RESERVATION_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ETAG;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_ATTACHMENT_ID_LIST;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_MODIFIED_BY;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_MODIFIED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_VERSION;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_VERSION_NUM;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_TITLE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ONWERS_OBJECT_TYPE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ONWERS_OWNER_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ONWERS_ROOT_WIKI_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_PARENT_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ROOT_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_TITLE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_TABLE_WIKI_ATTACHMENT_RESERVATION;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_TABLE_WIKI_MARKDOWN;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_TABLE_WIKI_OWNERS;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_TABLE_WIKI_PAGE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_FILE_HANDLE_ID;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.sagebionetworks.downloadtools.FileUtils;
import org.sagebionetworks.ids.IdGenerator;
import org.sagebionetworks.ids.IdGenerator.TYPE;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.NameConflictException;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.dao.FileHandleDao;
import org.sagebionetworks.repo.model.dao.WikiPageKey;
import org.sagebionetworks.repo.model.dbo.DBOBasicDao;
import org.sagebionetworks.repo.model.dbo.TableMapping;
import org.sagebionetworks.repo.model.dbo.V2WikiTranslationUtils;
import org.sagebionetworks.repo.model.dbo.v2.persistence.V2DBOWikiAttachmentReservation;
import org.sagebionetworks.repo.model.dbo.v2.persistence.V2DBOWikiMarkdown;
import org.sagebionetworks.repo.model.dbo.v2.persistence.V2DBOWikiOwner;
import org.sagebionetworks.repo.model.dbo.v2.persistence.V2DBOWikiPage;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.file.S3FileHandle;
import org.sagebionetworks.repo.model.jdo.KeyFactory;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.sagebionetworks.repo.model.message.TransactionalMessenger;
import org.sagebionetworks.repo.model.v2.dao.V2WikiPageDao;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiMarkdownVersion;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;
import org.sagebionetworks.repo.web.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
/**
* The basic implementation of the V2WikiPageDao.
* (Derived from org.sagebionetworks.repo.model.dbo.dao.DBOWikiPageDaoImpl)
*
* @author hso
*
*/
public class V2DBOWikiPageDaoImpl implements V2WikiPageDao {
@Autowired
private IdGenerator idGenerator;
@Autowired
private TransactionalMessenger transactionalMessenger;
@Autowired
private DBOBasicDao basicDao;
@Autowired
private SimpleJdbcTemplate simpleJdbcTemplate;
@Autowired
private AmazonS3Client s3Client;
@Autowired
private FileHandleDao fileMetadataDao;
/**
* Used to detect if a wiki object already exists.
*/
private static final String SQL_LOOKUP_WIKI_PAGE_KEY = "SELECT WO."+V2_COL_WIKI_ONWERS_OWNER_ID+", WO."+V2_COL_WIKI_ONWERS_OBJECT_TYPE+", WP."+V2_COL_WIKI_ID+" FROM "+V2_TABLE_WIKI_PAGE+" WP, "+V2_TABLE_WIKI_OWNERS+" WO WHERE WP."+V2_COL_WIKI_ROOT_ID+" = WO."+V2_COL_WIKI_ONWERS_ROOT_WIKI_ID+" AND WP."+V2_COL_WIKI_ID+" = ?";
private static final String SQL_DOES_EXIST = "SELECT "+V2_COL_WIKI_ID+" FROM "+V2_TABLE_WIKI_PAGE+" WHERE "+V2_COL_WIKI_ID+" = ?";
private static final String SQL_SELECT_WIKI_ROOT_USING_OWNER_ID_AND_TYPE = "SELECT "+V2_COL_WIKI_ONWERS_ROOT_WIKI_ID+" FROM "+V2_TABLE_WIKI_OWNERS+" WHERE "+V2_COL_WIKI_ONWERS_OWNER_ID+" = ? AND "+V2_COL_WIKI_ONWERS_OBJECT_TYPE+" = ?";
private static final String SQL_SELECT_WIKI_USING_ID_AND_ROOT = "SELECT * FROM "+V2_TABLE_WIKI_PAGE+" WHERE "+V2_COL_WIKI_ID+" = ? AND "+V2_COL_WIKI_ROOT_ID+" = ?";
private static final String SQL_SELECT_WIKI_VERSION_USING_ID_AND_ROOT = "SELECT "+V2_COL_WIKI_MARKDOWN_VERSION+" FROM "+V2_TABLE_WIKI_PAGE+" WHERE "+V2_COL_WIKI_ID+" = ? AND "+V2_COL_WIKI_ROOT_ID+" = ?";
private static final String SQL_SELECT_WIKI_ATTACHMENT = "SELECT * FROM "+V2_TABLE_WIKI_ATTACHMENT_RESERVATION+" WHERE "+V2_COL_WIKI_ATTACHMENT_RESERVATION_ID+" = ? AND "+V2_COL_WIKI_ATTACHMENT_RESERVATION_FILE_HANDLE_ID+" = ?";
private static final String SQL_GET_WIKI_MARKDOWN_ATTACHMENT_ID_LIST = "SELECT WM."+V2_COL_WIKI_MARKDOWN_ATTACHMENT_ID_LIST+" FROM "+V2_TABLE_WIKI_MARKDOWN+" WM, "+V2_TABLE_WIKI_PAGE+" WP WHERE WP."+V2_COL_WIKI_ID+" = ? AND WM."+V2_COL_WIKI_MARKDOWN_ID+" = WP."+V2_COL_WIKI_ID+" AND WP."+V2_COL_WIKI_MARKDOWN_VERSION+" = WM."+V2_COL_WIKI_MARKDOWN_VERSION_NUM;
private static final String SQL_DELETE_USING_ID_AND_ROOT = "DELETE FROM "+V2_TABLE_WIKI_PAGE+" WHERE "+V2_COL_WIKI_ID+" = ? AND "+V2_COL_WIKI_ROOT_ID+" = ?";
private static final String WIKI_HEADER_SELECT = V2_COL_WIKI_ID+", "+V2_COL_WIKI_TITLE+", "+V2_COL_WIKI_PARENT_ID;
private static final String SQL_SELECT_CHILDREN_HEADERS = "SELECT "+WIKI_HEADER_SELECT+" FROM "+V2_TABLE_WIKI_PAGE+" WHERE "+V2_COL_WIKI_ROOT_ID+" = ? ORDER BY "+V2_COL_WIKI_PARENT_ID+", "+V2_COL_WIKI_TITLE;
private static final String SQL_LOCK_FOR_UPDATE = "SELECT "+V2_COL_WIKI_ETAG+" FROM "+V2_TABLE_WIKI_PAGE+" WHERE "+V2_COL_WIKI_ID+" = ? FOR UPDATE";
private static final String SQL_COUNT_ALL_WIKIPAGES = "SELECT COUNT(*) FROM "+V2_TABLE_WIKI_PAGE;
private static final String SQL_SELECT_WIKI_MARKDOWN_USING_ID_AND_VERSION = "SELECT * FROM "+V2_TABLE_WIKI_MARKDOWN+" WHERE "+V2_COL_WIKI_MARKDOWN_ID+" = ? AND "+V2_COL_WIKI_MARKDOWN_VERSION_NUM+" = ?";
private static final String SQL_GET_RESERVATION_OF_ATTACHMENT_IDS = "SELECT "+V2_COL_WIKI_ATTACHMENT_RESERVATION_FILE_HANDLE_ID+" FROM "+V2_TABLE_WIKI_ATTACHMENT_RESERVATION+" WHERE "+V2_COL_WIKI_ATTACHMENT_RESERVATION_ID+" = ?";
private static final String SQL_GET_WIKI_HISTORY = "SELECT WM."+V2_COL_WIKI_MARKDOWN_VERSION_NUM+", WM."+V2_COL_WIKI_MARKDOWN_MODIFIED_ON+", WM."+V2_COL_WIKI_MARKDOWN_MODIFIED_BY+" FROM "+V2_TABLE_WIKI_MARKDOWN+" WM WHERE WM."+V2_COL_WIKI_MARKDOWN_ID+" = ? ORDER BY "+V2_COL_WIKI_MARKDOWN_VERSION_NUM+" DESC LIMIT ?, ?";
private static final String SQL_GET_MARKDOWN_IDS = "SELECT DISTINCT "+V2_COL_WIKI_MARKDOWN_FILE_HANDLE_ID+" FROM "+V2_TABLE_WIKI_MARKDOWN+" WHERE "+V2_COL_WIKI_MARKDOWN_ID+" = ?";
private static final String SQL_GET_CONTENT_FOR_VERSION = "SELECT "+V2_COL_WIKI_MARKDOWN_VERSION_NUM+", "+V2_COL_WIKI_MARKDOWN_TITLE+", "+V2_COL_WIKI_MARKDOWN_ATTACHMENT_ID_LIST+", "+V2_COL_WIKI_MARKDOWN_FILE_HANDLE_ID+" FROM "+V2_TABLE_WIKI_MARKDOWN+" WHERE "+V2_COL_WIKI_MARKDOWN_ID+" = ? AND "+V2_COL_WIKI_MARKDOWN_VERSION_NUM+" = ?";
private static final TableMapping<V2DBOWikiAttachmentReservation> ATTACHMENT_ROW_MAPPER = new V2DBOWikiAttachmentReservation().getTableMapping();
private static final TableMapping<V2DBOWikiMarkdown> WIKI_MARKDOWN_ROW_MAPPER = new V2DBOWikiMarkdown().getTableMapping();
private static final TableMapping<V2DBOWikiPage> WIKI_PAGE_ROW_MAPPER = new V2DBOWikiPage().getTableMapping();
/**
* Maps to a simple wiki header.
*/
private static final RowMapper<V2WikiHeader> WIKI_HEADER_ROW_MAPPER = new RowMapper<V2WikiHeader>() {
@Override
public V2WikiHeader mapRow(ResultSet rs, int rowNum) throws SQLException {
V2WikiHeader header = new V2WikiHeader();
header.setId(""+rs.getLong(V2_COL_WIKI_ID));
header.setTitle(rs.getString(V2_COL_WIKI_TITLE));
header.setParentId(rs.getString(V2_COL_WIKI_PARENT_ID));
return header;
}
};
/**
* Maps to a version/row of a wiki's history
*/
private static final RowMapper<V2WikiHistorySnapshot> WIKI_HISTORY_SNAPSHOT_MAPPER = new RowMapper<V2WikiHistorySnapshot>() {
@Override
public V2WikiHistorySnapshot mapRow(ResultSet rs, int rowNum) throws SQLException {
V2WikiHistorySnapshot snapshot = new V2WikiHistorySnapshot();
snapshot.setVersion("" + rs.getLong(V2_COL_WIKI_MARKDOWN_VERSION_NUM));
snapshot.setModifiedOn(new Date(rs.getLong(V2_COL_WIKI_MARKDOWN_MODIFIED_ON)));
snapshot.setModifiedBy("" + rs.getLong(V2_COL_WIKI_MARKDOWN_MODIFIED_BY));
return snapshot;
}
};
/**
* Maps to the content (title/markdown id/attachment list) of a wiki's version
*/
private static final RowMapper<V2WikiMarkdownVersion> WIKI_MARKDOWN_VERSION_MAPPER = new RowMapper<V2WikiMarkdownVersion>() {
@Override
public V2WikiMarkdownVersion mapRow(ResultSet rs, int rowNum) throws SQLException {
V2WikiMarkdownVersion versionOfMarkdown = new V2WikiMarkdownVersion();
versionOfMarkdown.setVersion("" + rs.getLong(V2_COL_WIKI_MARKDOWN_VERSION_NUM));
versionOfMarkdown.setMarkdownFileHandleId(rs.getString(V2_COL_WIKI_MARKDOWN_FILE_HANDLE_ID));
versionOfMarkdown.setTitle(rs.getString(V2_COL_WIKI_MARKDOWN_TITLE));
// Extract the attachment list in byte[] state
java.sql.Blob blob = rs.getBlob(V2_COL_WIKI_MARKDOWN_ATTACHMENT_ID_LIST);
if(blob != null){
String listAsString = V2WikiTranslationUtils.getStringFromByteArray(blob.getBytes(1, (int) blob.length()));
List<String> fileHandleIds = V2WikiTranslationUtils.createFileHandleListFromString(listAsString);
versionOfMarkdown.setAttachmentFileHandleIds(fileHandleIds);
} else {
versionOfMarkdown.setAttachmentFileHandleIds(null);
}
return versionOfMarkdown;
}
};
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public V2WikiPage create(V2WikiPage wikiPage, Map<String, FileHandle> fileNameToFileHandleMap, String ownerId, ObjectType ownerType, List<String> newFileHandleIds) throws NotFoundException {
if(wikiPage == null) throw new IllegalArgumentException("wikiPage cannot be null");
if(fileNameToFileHandleMap == null) throw new IllegalArgumentException("fileNameToFileIdMap cannot be null");
if(ownerId == null) throw new IllegalArgumentException("ownerId cannot be null");
if(ownerType == null) throw new IllegalArgumentException("ownerType cannot be null");
// Convert to a DBO
V2DBOWikiPage dbo = V2WikiTranslationUtils.createDBOFromDTO(wikiPage);
long currentTime = System.currentTimeMillis();
dbo.setCreatedOn(currentTime);
dbo.setModifiedOn(dbo.getCreatedOn());
// We're creating a new wiki page so it has the first version of the markdown
dbo.setMarkdownVersion(new Long(0));
if(wikiPage.getId() == null) {
dbo.setId(idGenerator.generateNewId(TYPE.WIKI_ID));
} else {
// If an id was provided then it must not exist
if(doesExist(wikiPage.getId())) throw new IllegalArgumentException("A wiki page already exists with ID: "+wikiPage.getId());
// Make sure the ID generator has reserved this ID.
idGenerator.reserveId(new Long(wikiPage.getId()), TYPE.WIKI_ID);
}
// Check for parent cycle
if(wikiPage.getParentWikiId() != null) {
if(checkForParentCycle(new WikiPageKey(ownerId, ownerType, wikiPage.getParentWikiId()), wikiPage.getId())) {
throw new IllegalArgumentException("There will be a cycle if this wiki is updated. Put in valid parentId");
}
}
// When we migrate we keep the original etag. When it is null we set it.
if(dbo.getEtag() == null) {
dbo.setEtag(UUID.randomUUID().toString());
}
Long ownerIdLong = KeyFactory.stringToKey(ownerId);
dbo = create(ownerType, dbo, ownerIdLong);
// Create the attachments
long timeStamp = (currentTime/1000)*1000;
List<V2DBOWikiAttachmentReservation> attachments = V2WikiTranslationUtils.createDBOAttachmentReservationFromDTO(newFileHandleIds, dbo.getId(), timeStamp);
// Save them to the attachments archive
if(attachments.size() > 0){
basicDao.createBatch(attachments);
}
// Create the markdown snapshot
Long markdownFileHandleId = Long.parseLong(wikiPage.getMarkdownFileHandleId());
V2DBOWikiMarkdown markdownDbo = V2WikiTranslationUtils.createDBOWikiMarkdownFromDTO(fileNameToFileHandleMap, dbo.getId(), markdownFileHandleId, wikiPage.getTitle());
markdownDbo.setMarkdownVersion(new Long(0));
markdownDbo.setModifiedOn(currentTime);
markdownDbo.setModifiedBy(dbo.getModifiedBy());
// Save this new version to the markdown DB
basicDao.createNew(markdownDbo);
// Send the create message
transactionalMessenger.sendMessageAfterCommit(dbo, ChangeType.CREATE);
try {
return get(new WikiPageKey(ownerId, ownerType, dbo.getId().toString()), null);
} catch (NotFoundException e) {
// This should not occur.
throw new RuntimeException(e);
}
}
private V2DBOWikiPage create(ObjectType ownerType, V2DBOWikiPage dbo,
Long ownerIdLong) throws NotFoundException {
// If the parentID is null then this is a root wiki
setRoot(ownerIdLong, ownerType, dbo);
// Save it to the DB
dbo = basicDao.createNew(dbo);
// If the parentID is null then this must be a root.
if(dbo.getParentId() == null){
// Set the root entry.
createRootOwnerEntry(ownerIdLong, ownerType, dbo.getId());
}
return dbo;
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public V2WikiPage updateWikiPage(V2WikiPage wikiPage,
Map<String, FileHandle> fileNameToFileHandleMap, String ownerId,
ObjectType ownerType, List<String> newFileHandleIds) throws NotFoundException {
if(wikiPage == null) throw new IllegalArgumentException("wikiPage cannot be null");
if(fileNameToFileHandleMap == null) throw new IllegalArgumentException("fileNameToFileHandleMap cannot be null");
if(ownerId == null) throw new IllegalArgumentException("ownerId cannot be null");
if(ownerType == null) throw new IllegalArgumentException("ownerType cannot be null");
if(wikiPage.getId() == null) throw new IllegalArgumentException("wikiPage.getID() cannot be null");
Long ownerIdLong = KeyFactory.stringToKey(ownerId);
// Does this page exist?
if(!doesExist(wikiPage.getId())) throw new NotFoundException("No WikiPage exists with id: "+wikiPage.getId());
Long wikiId = new Long(wikiPage.getId());
// Check for parent cycle
if(wikiPage.getParentWikiId() != null) {
if(checkForParentCycle(new WikiPageKey(ownerId, ownerType, wikiPage.getParentWikiId()), wikiPage.getId())) {
throw new IllegalArgumentException("There will be a cycle if this wiki is updated. Put in valid parentId");
}
}
long currentTime = System.currentTimeMillis();
V2DBOWikiPage oldDbo = getWikiPageDBO(ownerId, ownerType, wikiPage.getId());
Long incrementedVersion = oldDbo.getMarkdownVersion() + 1;
// Update this wiki's entry in the WikiPage database (update version)
V2DBOWikiPage newDbo = V2WikiTranslationUtils.createDBOFromDTO(wikiPage);
// Set the modifiedon to current.
newDbo.setModifiedOn(currentTime);
newDbo.setMarkdownVersion(incrementedVersion);
update(ownerType, ownerIdLong, newDbo);
// Create a new markdown snapshot/version
Long markdownFileHandleId = Long.parseLong(wikiPage.getMarkdownFileHandleId());
V2DBOWikiMarkdown markdownDbo = V2WikiTranslationUtils.createDBOWikiMarkdownFromDTO(fileNameToFileHandleMap, newDbo.getId(), markdownFileHandleId, wikiPage.getTitle());
markdownDbo.setMarkdownVersion(incrementedVersion);
markdownDbo.setModifiedOn(currentTime);
markdownDbo.setModifiedBy(newDbo.getModifiedBy());
// Save this as a new entry of the markdown DB
basicDao.createNew(markdownDbo);
// Create the attachments
long timeStamp = (currentTime/1000)*1000;
List<V2DBOWikiAttachmentReservation> attachmentsToInsert = V2WikiTranslationUtils.createDBOAttachmentReservationFromDTO(newFileHandleIds, wikiId, timeStamp);
// Insert only unique/new attachments into the reservation
// Save them to the attachments archive
if(attachmentsToInsert.size() > 0) {
basicDao.createBatch(attachmentsToInsert);
}
// Send the change message
transactionalMessenger.sendMessageAfterCommit(newDbo, ChangeType.UPDATE);
// Return the results.
return get(new WikiPageKey(ownerId, ownerType, wikiPage.getId().toString()), null);
}
private void update(ObjectType ownerType, Long ownerIdLong,
V2DBOWikiPage newDBO) throws NotFoundException {
// Set the root
setRoot(ownerIdLong, ownerType, newDBO);
// Update
basicDao.update(newDBO);
}
private boolean checkForParentCycle(WikiPageKey parentKey, String childId) throws NotFoundException {
if(parentKey == null) {
return false;
} else if(parentKey.getWikiPageId().equals(childId)) {
return true;
} else {
V2WikiPage parent = get(parentKey, null);
WikiPageKey nextParentKey;
if(parent.getParentWikiId() == null) {
nextParentKey = null;
} else {
nextParentKey = new WikiPageKey(parentKey.getOwnerObjectId(), parentKey.getOwnerObjectType(), parent.getParentWikiId());
}
return checkForParentCycle(nextParentKey, childId);
}
}
@Override
public List<Long> getFileHandleReservationForWiki(WikiPageKey key) {
return simpleJdbcTemplate.query(SQL_GET_RESERVATION_OF_ATTACHMENT_IDS, new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
Long id = rs.getLong(V2_COL_WIKI_ATTACHMENT_RESERVATION_FILE_HANDLE_ID);
return id;
}
}, key.getWikiPageId());
}
@Override
public List<Long> getMarkdownFileHandleIdsForWiki(WikiPageKey key) {
return simpleJdbcTemplate.query(SQL_GET_MARKDOWN_IDS, new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
Long id = rs.getLong(V2_COL_WIKI_MARKDOWN_FILE_HANDLE_ID);
return id;
}
}, key.getWikiPageId());
}
/**
* Validate the owner and the root. An owner can only have one root.
* @param ownerId
* @param ownerType
* @param dbo
* @throws NotFoundException
*/
private void setRoot(Long ownerId, ObjectType ownerType, V2DBOWikiPage dbo) throws NotFoundException {
// If a parent ID was provide then this is not a root.
if(dbo.getParentId() == null){
// This wiki is the root
dbo.setRootId(dbo.getId());
}else{
// Look up the root
Long rootWikiId = getRootWiki(ownerId, ownerType);
dbo.setRootId(rootWikiId);
}
}
/**
* Lookup the root wiki for a given type.
* @param ownerId
* @param ownerType
* @throws NotFoundException
*/
private Long getRootWiki(Long ownerId, ObjectType ownerType) throws NotFoundException {
try{
return simpleJdbcTemplate.queryForLong(SQL_SELECT_WIKI_ROOT_USING_OWNER_ID_AND_TYPE, ownerId, ownerType.name());
}catch(DataAccessException e){
throw new NotFoundException("A root wiki does not exist for ownerId: "+ownerId+" and ownerType: "+ownerType);
}
}
private void createRootOwnerEntry(Long ownerId, ObjectType ownerType, Long rootWikiId){
// Create the root owner entry
V2DBOWikiOwner ownerEntry = new V2DBOWikiOwner();
ownerEntry.setOwnerId(new Long(ownerId));
ownerEntry.setOwnerTypeEnum(ownerType);
ownerEntry.setRootWikiId(rootWikiId);
try{
basicDao.createNew(ownerEntry);
} catch (DatastoreException e) {
throw new IllegalArgumentException("A root wiki already exists for ownerId: "+ownerId+" and ownerType: "+ownerType);
} catch (DuplicateKeyException e) {
throw new NameConflictException("An owner already exists with the ownerId: " + ownerId + " and ownerType: " + ownerType);
}
}
@Override
public V2WikiPage get(WikiPageKey key, Long version) throws NotFoundException {
// Get the Wikipage DBO.
V2DBOWikiPage dbo = getWikiPageDBO(key);
// Now get the markdown
V2DBOWikiMarkdown markdownDbo;
if(version == null) {
markdownDbo = getWikiMarkdownDBO(dbo.getId(), dbo.getMarkdownVersion());
} else {
markdownDbo = getWikiMarkdownDBO(dbo.getId(), version);
}
String listToString = V2WikiTranslationUtils.getStringFromByteArray(markdownDbo.getAttachmentIdList());
List<String> fileHandleIds = V2WikiTranslationUtils.createFileHandleListFromString(listToString);
return V2WikiTranslationUtils.createDTOfromDBO(dbo, fileHandleIds, markdownDbo);
}
@Override
public String getMarkdown(WikiPageKey key, Long version) throws IOException, NotFoundException {
V2WikiPage wiki = get(key, version);
S3FileHandle markdownHandle = (S3FileHandle) fileMetadataDao.get(wiki.getMarkdownFileHandleId());
File markdownTemp = File.createTempFile(wiki.getId()+ "_markdown", ".tmp");
try {
// Retrieve uploaded markdown
s3Client.getObject(new GetObjectRequest(markdownHandle.getBucketName(),
markdownHandle.getKey()), markdownTemp);
// Read the file as a string
String markdownString = FileUtils.readCompressedFileAsString(markdownTemp);
return markdownString;
} finally {
if (markdownTemp != null) {
markdownTemp.delete();
}
}
}
@Override
public String getMarkdownHandleId(WikiPageKey key, Long version) throws NotFoundException {
if(key == null) throw new IllegalArgumentException("Key cannot be null");
if(version == null) {
// Get the markdown file handle id of the wiki's current version
version = getCurrentWikiVersion(key.getOwnerObjectId(), key.getOwnerObjectType(), key.getWikiPageId());
}
// Lookup the version of the markdown
V2DBOWikiMarkdown markdownDbo = getWikiMarkdownDBO(Long.parseLong(key.getWikiPageId()), version);
return String.valueOf(markdownDbo.getFileHandleId());
}
@Override
public V2WikiMarkdownVersion getVersionOfWikiContent(WikiPageKey key, Long version) throws NotFoundException {
if(key == null) throw new IllegalArgumentException("Key cannot be null");
if(version == null) {
// Get the current version number
version = getCurrentWikiVersion(key.getOwnerObjectId(), key.getOwnerObjectType(), key.getWikiPageId());
}
String wikiId = key.getWikiPageId();
List<V2WikiMarkdownVersion> versionOfContent = simpleJdbcTemplate.query(SQL_GET_CONTENT_FOR_VERSION, WIKI_MARKDOWN_VERSION_MAPPER, wikiId, version);
if(versionOfContent.size() > 1) throw new DatastoreException("More than one Wiki page found with the id: " + wikiId + " and version: " + version);
if(versionOfContent.size() < 1) throw new NotFoundException("No wiki page found with id: " + wikiId + " and version: " + version);
return versionOfContent.get(0);
}
/**
* Return the current version of the wiki's markdown/attachments with the given id
* @param ownerId
* @param ownerType
* @param wikiId
* @return
* @throws NotFoundException
*/
private Long getCurrentWikiVersion(String ownerId, ObjectType ownerType, String wikiId) throws NotFoundException {
Long root = getRootWiki(ownerId, ownerType);
try{
return simpleJdbcTemplate.queryForLong(SQL_SELECT_WIKI_VERSION_USING_ID_AND_ROOT, new Long(wikiId), root);
}catch(DataAccessException e){
throw new NotFoundException("A wiki does not exist for id: "+wikiId);
}
}
/**
* Get the DBOWikiPage using its key.
* @param key
* @throws NotFoundException
*/
private V2DBOWikiPage getWikiPageDBO(WikiPageKey key) throws NotFoundException{
if(key == null) throw new IllegalArgumentException("Key cannot be null");
return getWikiPageDBO(key.getOwnerObjectId(), key.getOwnerObjectType(), key.getWikiPageId());
}
/**
* Get the DBOWikiPage using ownerId, ownerType, and wikiId.
* @param ownerId
* @param ownerType
* @param wikiId
* @throws NotFoundException
*/
private V2DBOWikiPage getWikiPageDBO(String ownerId, ObjectType ownerType, String wikiId) throws NotFoundException {
// In order to access a wiki you must know its owner.
// If the root does not exist then the wiki does not exist.
Long root = getRootWiki(ownerId, ownerType);
// We use the root in addition to the primary key (id) to enforce they are not out of sych.
List<V2DBOWikiPage> list = simpleJdbcTemplate.query(SQL_SELECT_WIKI_USING_ID_AND_ROOT, WIKI_PAGE_ROW_MAPPER, new Long(wikiId), root);
if(list.size() > 1) throw new DatastoreException("More than one Wiki page found with the id: " + wikiId);
if(list.size() < 1) throw new NotFoundException("No wiki page found with id: " + wikiId);
return list.get(0);
}
/**
* Get the DBOWikiMarkdown using the wiki id and specific version.
* @param wikiId
* @param version
* @throws NotFoundException
*/
private V2DBOWikiMarkdown getWikiMarkdownDBO(Long wikiId, Long version) throws NotFoundException {
if(wikiId == null) throw new IllegalArgumentException("Wiki id cannot be null");
if(version == null) throw new IllegalArgumentException("Markdown version cannot be null");
List<V2DBOWikiMarkdown> list = simpleJdbcTemplate.query(SQL_SELECT_WIKI_MARKDOWN_USING_ID_AND_VERSION, WIKI_MARKDOWN_ROW_MAPPER, wikiId, version);
if(list.size() > 1) throw new DatastoreException("Wiki page has multiple versions of number: " + version);
if(list.size() < 1) throw new NotFoundException("Wiki page of id: " + wikiId + " was not found with version: " + version);
return list.get(0);
}
@Override
public List<V2WikiHistorySnapshot> getWikiHistory(WikiPageKey key, Long limit, Long offset) throws DatastoreException, NotFoundException {
if(key == null) throw new IllegalArgumentException("WikiPage key cannot be null");
if(doesExist(key.getWikiPageId())) {
// Get all versions of a wiki page
List<V2WikiHistorySnapshot> history = simpleJdbcTemplate.query(SQL_GET_WIKI_HISTORY, WIKI_HISTORY_SNAPSHOT_MAPPER, key.getWikiPageId(), offset, limit);
if(history.size() < 1) throw new DatastoreException("No history is found for a wiki page of id: " + key.getWikiPageId());
return history;
} else {
throw new NotFoundException("Wiki page with id: " + key.getWikiPageId() + " does not exist.");
}
}
@Override
public Long getRootWiki(String ownerId, ObjectType ownerType)
throws NotFoundException {
return getRootWiki(KeyFactory.stringToKey(ownerId), ownerType);
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public void delete(WikiPageKey key) {
if(key == null) throw new IllegalArgumentException("Key cannot be null");
// In order to access a wiki you must know its owner.
// If the root does not exist then the wiki does not exist.
try{
Long rootId = getRootWiki(key.getOwnerObjectId(), key.getOwnerObjectType());
// Delete the wiki using both the root and the id
simpleJdbcTemplate.update(SQL_DELETE_USING_ID_AND_ROOT, new Long(key.getWikiPageId()), rootId);
}catch(NotFoundException e){
// Nothing to do if the wiki does not exist.
}
}
@Override
public List<V2WikiHeader> getHeaderTree(String ownerId, ObjectType ownerType)
throws DatastoreException, NotFoundException {
// First look up the root for this owner
Long root = getRootWiki(ownerId, ownerType);
// Now use the root to the the full tree
return simpleJdbcTemplate.query(SQL_SELECT_CHILDREN_HEADERS, WIKI_HEADER_ROW_MAPPER, root);
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public String lockForUpdate(String wikiId) {
// Lock the wiki row and return current Etag.
return simpleJdbcTemplate.queryForObject(SQL_LOCK_FOR_UPDATE, String.class, new Long(wikiId));
}
/**
* Retrieves the attachments list for the given wiki
* @param key
* @return
*/
private String getAttachmentsListFromMarkdownTable(WikiPageKey key) {
if(key == null) throw new IllegalArgumentException("Key cannot be null");
List<String> attachmentsList = simpleJdbcTemplate.query(SQL_GET_WIKI_MARKDOWN_ATTACHMENT_ID_LIST, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
// Extract the attachment list in byte[] state
java.sql.Blob blob = rs.getBlob(V2_COL_WIKI_MARKDOWN_ATTACHMENT_ID_LIST);
if(blob != null){
return V2WikiTranslationUtils.getStringFromByteArray(blob.getBytes(1, (int) blob.length()));
}
return null;
}
}, key.getWikiPageId());
return attachmentsList.get(0);
}
@Override
public List<String> getWikiFileHandleIds(WikiPageKey key, Long version) throws NotFoundException {
if(key == null) throw new IllegalArgumentException("Key cannot be null");
String listToString;
if(version == null) {
// Get the attachments for the current wiki
listToString = getAttachmentsListFromMarkdownTable(key);
} else {
// Lookup the attachments for another version of the wiki
V2DBOWikiMarkdown markdownDbo = getWikiMarkdownDBO(Long.parseLong(key.getWikiPageId()), version);
listToString = V2WikiTranslationUtils.getStringFromByteArray(markdownDbo.getAttachmentIdList());
}
return V2WikiTranslationUtils.createFileHandleListFromString(listToString);
}
@Override
public String getWikiAttachmentFileHandleForFileName(WikiPageKey key,
String fileName, Long version) throws NotFoundException {
if(key == null) throw new IllegalArgumentException("Key cannot be null");
if(fileName == null) throw new IllegalArgumentException("fileName cannot be null");
String attachmentsList;
if(version == null) {
attachmentsList = getAttachmentsListFromMarkdownTable(key);
} else {
// Lookup the attachments for another version of the wiki
V2DBOWikiMarkdown markdownDbo = getWikiMarkdownDBO(Long.parseLong(key.getWikiPageId()), version);
attachmentsList = V2WikiTranslationUtils.getStringFromByteArray(markdownDbo.getAttachmentIdList());
}
if(attachmentsList != null) {
// Process the list of attachments into a map for easy searching
Map<String, String> fileNameToIdMap = V2WikiTranslationUtils.getFileNameAndHandleIdPairs(attachmentsList);
// Return the associated file handle id if filename exists
String fileHandleId = fileNameToIdMap.get(fileName);
if(fileHandleId != null) {
return fileHandleId;
}
}
// No attachment with the file name exists for this wiki page
throw new NotFoundException("Cannot find a wiki attachment for OwnerID: "+key.getOwnerObjectId()+", ObjectType: "+key.getOwnerObjectType()+", WikiPageId: "+key.getWikiPageId()+", fileName: "+fileName);
}
@Override
public WikiPageKey lookupWikiKey(String wikiId) throws NotFoundException {
if(wikiId == null) throw new IllegalArgumentException("wikiId cannot be null");
long id = Long.parseLong(wikiId);
try{
return this.simpleJdbcTemplate.queryForObject(SQL_LOOKUP_WIKI_PAGE_KEY, new RowMapper<WikiPageKey>() {
@Override
public WikiPageKey mapRow(ResultSet rs, int rowNum) throws SQLException {
String owner = rs.getString(V2_COL_WIKI_ONWERS_OWNER_ID);
ObjectType type = ObjectType.valueOf(rs.getString(V2_COL_WIKI_ONWERS_OBJECT_TYPE));
if(ObjectType.ENTITY == type){
owner = KeyFactory.keyToString(Long.parseLong(owner));
}
String wikiId = rs.getString(V2_COL_WIKI_ID);
return new WikiPageKey(owner, type, wikiId);
}
}, id);
}catch(EmptyResultDataAccessException e){
throw new NotFoundException("Cannot find a wiki page with id: "+wikiId);
}
}
@Override
public long getCount() throws DatastoreException {
return simpleJdbcTemplate.queryForLong(SQL_COUNT_ALL_WIKIPAGES);
}
/**
* Get a list of attachment DBOs for a given wiki
* @param wikiId
* @param key
* @return
* @throws NotFoundException
*/
private List<V2DBOWikiAttachmentReservation> getAttachmentDbos(Long wikiId, String attachmentList) throws NotFoundException{
if(attachmentList == null) throw new IllegalArgumentException("The WikiPageKey cannot be null");
// Process which file handle ids this wiki needs
Map<String, String> fileNameToIdMap = V2WikiTranslationUtils.getFileNameAndHandleIdPairs(attachmentList);
List<V2DBOWikiAttachmentReservation> results = new ArrayList<V2DBOWikiAttachmentReservation>();
// For each file handle id, query the attachment archive with the wiki id and file handle id
for(String fileName: fileNameToIdMap.keySet()) {
String fileHandleId = fileNameToIdMap.get(fileName);
List<V2DBOWikiAttachmentReservation> attachment = simpleJdbcTemplate.query(SQL_SELECT_WIKI_ATTACHMENT, ATTACHMENT_ROW_MAPPER, wikiId, fileHandleId);
if(attachment.size() > 1) throw new DatastoreException("More than one attachment was found with the file handle id: " + fileHandleId + ", for the wiki page id: " + wikiId);
if(attachment.size() < 1) throw new NotFoundException("No attachment was found for the file handle id: " + fileHandleId + ", for the wiki page id: " + wikiId);
results.add(attachment.get(0));
}
return results;
}
private boolean doesExist(String id) {
if(id == null) throw new IllegalArgumentException("Id cannot be null");
try{
// Is this in the database.
simpleJdbcTemplate.queryForLong(SQL_DOES_EXIST, id);
return true;
}catch(EmptyResultDataAccessException e){
return false;
}
}
}
|
package ragnardb.runtime;
import gw.lang.reflect.IType;
import gw.lang.reflect.features.PropertyReference;
import gw.util.GosuExceptionUtil;
import ragnardb.plugin.SQLColumnPropertyInfo;
import java.sql.SQLException;
import java.util.*;
public class SQLQuery<T> implements Iterable<T>{
protected IType _rootType;
private SQLConstraint _whereExpr;
private SQLConstraint _joinExpr;
private SQLConstraint _onExpr;
private String _select;
private SQLQuery _parent;
private PropertyReference _singlePick;
protected ITypeToSQLMetadata _metadata;
public SQLQuery( ITypeToSQLMetadata md, IType rootType )
{
_metadata = md;
_rootType = rootType;
_select = _metadata.getTableForType( getRoot()._rootType ) + ".* ";
}
public SQLQuery( ITypeToSQLMetadata md, IType rootType, PropertyReference p)
{
_metadata = md;
_rootType = rootType;
_select = _metadata.getTableForType( getRoot()._rootType ) + ".* ";
}
public SQLQuery<T> where(SQLConstraint constraint) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._whereExpr = constraint;
newQuery._joinExpr = this._joinExpr; //Carrying data over
newQuery._onExpr = this._onExpr; //Carrying data over
return newQuery;
}
public SQLQuery<T> crossJoin( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "CROSS JOIN");
return newQuery;
}
public SQLQuery<T> join( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "JOIN");
return newQuery;
}
public SQLQuery<T> innerJoin( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "INNER JOIN");
return newQuery;
}
public SQLQuery<T> leftOuterJoin( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "LEFT OUTER JOIN");
return newQuery;
}
public SQLQuery<T> rightOuterJoin( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "RIGHT OUTER JOIN");
return newQuery;
}
public SQLQuery<T> rightJoin( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "RIGHT JOIN");
return newQuery;
}
public SQLQuery<T> leftJoin( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "LEFT JOIN");
return newQuery;
}
public SQLQuery<T> naturalJoin( IType type) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._joinExpr = SQLConstraint.join(type , "NATURAL JOIN");
return newQuery;
}
public SQLQuery<T> on( SQLConstraint constraint) {
SQLQuery<T> newQuery = new SQLQuery<T>( _metadata, _rootType );
newQuery._onExpr = SQLConstraint.on(constraint);
newQuery._joinExpr = this._joinExpr;
return newQuery;
}
public SQLQuery<T> pick( PropertyReference ref){
SQLQuery base = this;
this._select = ((SQLColumnPropertyInfo) ref.getPropertyInfo()).getColumnName();
this._singlePick = ref;
return new SQLQuery(_metadata,_rootType){
public Iterator<T> iterator()
{
List col = new ArrayList<>();
for ( Object s : base){
col.add(((SQLRecord) s).getRawValue(_select));
}
return col.iterator();
}
public List<Object> getArgs(){
return base.getArgs();
}
public String getSQLString() {
return base.getSQLString();
}
};
}
public Iterator<T> iterator()
{
return execQuery().iterator();
}
private SQLQuery getRoot() {
if(_parent != null) {
return _parent.getRoot();
} else {
return this;
}
}
public String getSQLString() {
String select = "SELECT " + _select;
String from = "FROM " + _metadata.getTableForType( getRoot()._rootType );
String join = _joinExpr == null ? "" : _joinExpr.getSQL( _metadata);
String on = _onExpr == null ? "" : _onExpr.getSQL( _metadata);
String where = _whereExpr == null ? "" : "WHERE " + _whereExpr.getSQL( _metadata );
return select + " " + from + " " + join + on + " " + " " + where;
}
public List<Object> getArgs()
{
List answer = new ArrayList();
if(_joinExpr!=null) {
answer.addAll(_joinExpr.getArgs());
}
if(_onExpr!=null) {
answer.addAll(_onExpr.getArgs());
}
if(_whereExpr!=null) {
answer.addAll(_whereExpr.getArgs());
}
return answer;
}
private Iterable<T> execQuery()
{
try
{
return SQLRecord.select( getSQLString(), getArgs(), _rootType );
}
catch( SQLException e )
{
throw GosuExceptionUtil.forceThrow( e );
}
}
}
|
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
Stack<TreeNode> leftStack = new Stack<TreeNode>();
Stack<TreeNode> rightStack = new Stack<TreeNode>();
leftStack.add(root.left);
rightStack.add(root.right);
while (!leftStack.isEmpty() && !rightStack.isEmpty()) {
TreeNode a = leftStack.pop();
TreeNode b = rightStack.pop();
if (a == null && b == null) continue;
if (a == null || b == null) return false;
if (a.val != b.val) return false;
leftStack.push(a.left);
leftStack.push(a.right);
rightStack.push(b.right);
rightStack.push(b.left);
}
return true;
}
}
// recursive
public class Solution2 {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
return symmetricTest(root.left, root.right);
}
public static boolean symmetricTest(TreeNode leftNode, TreeNode rightNode) {
if (leftNode == null && rightNode == null) return true;
if (leftNode == null || rightNode == null) return false;
if (leftNode.val != rightNode.val) return false;
return symmetricTest(leftNode.left, rightNode.right) && symmetricTest(leftNode.right, rightNode.left);
}
}
|
package org.libreplan.web.planner.company;
import static org.libreplan.web.I18nHelper._;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.Validate;
import org.joda.time.LocalDate;
import org.libreplan.business.common.entities.ProgressType;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.planner.entities.TaskElement;
import org.libreplan.business.users.daos.IUserDAO;
import org.libreplan.business.users.entities.User;
import org.libreplan.business.users.entities.UserRole;
import org.libreplan.web.common.components.bandboxsearch.BandboxMultipleSearch;
import org.libreplan.web.common.components.finders.FilterPair;
import org.libreplan.web.common.components.finders.TaskGroupFilterEnum;
import org.libreplan.web.planner.TaskGroupPredicate;
import org.libreplan.web.planner.tabs.MultipleTabsPlannerController;
import org.libreplan.web.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.zkoss.ganttz.Planner;
import org.zkoss.ganttz.extensions.ICommandOnTask;
import org.zkoss.ganttz.timetracker.zoom.ZoomLevel;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Vbox;
/**
* Controller for company planning view. Representation of company orders in the
* planner.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@org.springframework.stereotype.Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class CompanyPlanningController implements Composer {
@Autowired
private ICompanyPlanningModel model;
@Autowired
private IUserDAO userDAO;
private List<ICommandOnTask<TaskElement>> additional = new ArrayList<ICommandOnTask<TaskElement>>();
private Planner planner;
private Vbox orderFilter;
private Datebox filterStartDate;
private Datebox filterFinishDate;
private BandboxMultipleSearch bdFilters;
private Checkbox checkIncludeOrderElements;
private ICommandOnTask<TaskElement> doubleClickCommand;
private Map<String, String[]> parameters;
private MultipleTabsPlannerController tabsController;
public CompanyPlanningController() {
}
private Combobox cbProgressTypes;
private Button btnShowAdvances;
@Override
public void doAfterCompose(org.zkoss.zk.ui.Component comp) {
planner = (Planner) comp;
String zoomLevelParameter = null;
if ((parameters != null) && (parameters.get("zoom") != null)
&& !(parameters.isEmpty())) {
zoomLevelParameter = parameters.get("zoom")[0];
}
ZoomLevel sessionZoom = (ZoomLevel) Sessions.getCurrent().getAttribute(
"zoomLevel");
if (sessionZoom != null) {
zoomLevelParameter = sessionZoom.getInternalName();
}
if (zoomLevelParameter != null) {
planner.setInitialZoomLevel(ZoomLevel
.getFromString(zoomLevelParameter));
}
planner.setAreContainersExpandedByDefault(Planner
.guessContainersExpandedByDefault(parameters));
initializeListboxProgressTypes();
planner.setAreShownAdvancesByDefault(Planner
.guessShowAdvancesByDefault(parameters));
planner.setAreShownReportedHoursByDefault(Planner
.guessShowReportedHoursByDefault(parameters));
planner.setAreShownMoneyCostBarByDefault(Planner
.guessShowMoneyCostBarByDefault(parameters));
orderFilter = (Vbox) planner.getFellow("orderFilter");
// Configuration of the order filter
Component filterComponent = Executions.createComponents(
"/orders/_orderFilter.zul", orderFilter,
new HashMap<String, String>());
filterComponent.setVariable("orderFilterController", this, true);
filterStartDate = (Datebox) filterComponent
.getFellow("filterStartDate");
filterFinishDate = (Datebox) filterComponent
.getFellow("filterFinishDate");
bdFilters = (BandboxMultipleSearch) filterComponent
.getFellow("bdFilters");
bdFilters.setFinder("taskGroupsMultipleFiltersFinder");
loadPredefinedBandboxFilter();
checkIncludeOrderElements = (Checkbox) filterComponent
.getFellow("checkIncludeOrderElements");
filterComponent.setVisible(true);
checkCreationPermissions();
}
private void loadPredefinedBandboxFilter() {
List<FilterPair> sessionFilterPairs = (List<FilterPair>) Sessions
.getCurrent().getAttribute("companyFilterLabel");
if (sessionFilterPairs != null && !sessionFilterPairs.isEmpty()) {
bdFilters.clear();
for (FilterPair filterPair : sessionFilterPairs) {
bdFilters.addSelectedElement(filterPair);
}
return;
}
User user;
try {
user = this.userDAO.findByLoginName(SecurityUtils
.getSessionUserLoginName());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
// Calculate filter based on user preferences
if ((user != null) && (user.getProjectsFilterLabel() != null)) {
bdFilters.clear();
bdFilters.addSelectedElement(new FilterPair(
TaskGroupFilterEnum.Label, user.getProjectsFilterLabel()
.getFinderPattern(), user
.getProjectsFilterLabel()));
}
// Calculate filter based on user preferences
if (user != null) {
if (filterStartDate.getValue() == null
&& (user.getProjectsFilterPeriodSince() != null)) {
filterStartDate.setValue(new LocalDate()
.minusMonths(user.getProjectsFilterPeriodSince())
.toDateTimeAtStartOfDay().toDate());
}
if (filterFinishDate.getValue() == null
&& (user.getProjectsFilterPeriodTo() != null)) {
filterFinishDate.setValue(new LocalDate()
.plusMonths(user.getProjectsFilterPeriodTo())
.toDateMidnight().toDate());
}
}
}
private void checkCreationPermissions() {
if (!SecurityUtils
.isSuperuserOrUserInRoles(UserRole.ROLE_CREATE_PROJECTS)) {
Button createOrderButton = (Button) planner.getPage().getFellow(
"createOrderButton");
if (createOrderButton != null) {
createOrderButton.setDisabled(true);
}
}
}
private void initializeListboxProgressTypes() {
if (cbProgressTypes == null) {
cbProgressTypes = (Combobox) planner.getFellow("cbProgressTypes");
}
if (btnShowAdvances == null) {
btnShowAdvances = (Button) planner.getFellow("showAdvances");
}
cbProgressTypes.setModel(new ListModelList(ProgressType.getAll()));
cbProgressTypes.setItemRenderer(new ProgressTypeRenderer());
// Update completion of tasks on selecting new progress type
cbProgressTypes.addEventListener(Events.ON_SELECT, new EventListener() {
@Override
public void onEvent(Event event) {
planner.forcedShowAdvances();
planner.updateCompletion(getSelectedProgressType().toString());
}
private ProgressType getSelectedProgressType() {
return (ProgressType) cbProgressTypes.getSelectedItem().getValue();
}
});
cbProgressTypes.setVisible(true);
ProgressType progressType = getProgressTypeFromConfiguration();
if (progressType != null) {
planner.updateCompletion(progressType.toString());
}
}
private class ProgressTypeRenderer implements ComboitemRenderer {
@Override
public void render(Comboitem item, Object data) {
final ProgressType progressType = (ProgressType) data;
item.setValue(progressType);
item.setLabel(_(progressType.getValue()));
ProgressType configuredProgressType = getProgressTypeFromConfiguration();
if ((configuredProgressType != null)
&& configuredProgressType.equals(progressType)) {
cbProgressTypes.setSelectedItem(item);
}
}
}
public ProgressType getProgressTypeFromConfiguration() {
return model.getProgressTypeFromConfiguration();
}
public void setConfigurationForPlanner() {
// Added predicate
model
.setConfigurationToPlanner(planner, additional,
doubleClickCommand, createPredicate());
model.setTabsController(tabsController);
planner.updateSelectedZoomLevel();
planner.invalidate();
}
public void setAdditional(List<ICommandOnTask<TaskElement>> additional) {
Validate.notNull(additional);
Validate.noNullElements(additional);
this.additional = additional;
}
public void setDoubleClickCommand(
ICommandOnTask<TaskElement> doubleClickCommand) {
this.doubleClickCommand = doubleClickCommand;
}
public void setURLParameters(Map<String, String[]> parameters) {
this.parameters = parameters;
}
/**
* Operations to filter the tasks by multiple filters
*/
public Constraint checkConstraintFinishDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date finishDate = (Date) value;
if ((finishDate != null)
&& (filterStartDate.getRawValue() != null)
&& (finishDate.compareTo((Date)
filterStartDate.getRawValue()) < 0)) {
filterFinishDate.setValue(null);
throw new WrongValueException(comp,
_("must be after start date"));
}
}
};
}
public Constraint checkConstraintStartDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date startDate = (Date) value;
if ((startDate != null)
&& (filterFinishDate.getRawValue() != null)
&& (startDate.compareTo((Date)
filterFinishDate.getRawValue()) > 0)) {
filterStartDate.setValue(null);
throw new WrongValueException(comp,
_("must be lower than end date"));
}
}
};
}
public void readSessionVariables() {
filterStartDate.setValue((Date) Sessions.getCurrent().getAttribute(
"companyFilterStartDate"));
filterFinishDate.setValue((Date) Sessions.getCurrent().getAttribute(
"companyFilterFinishDate"));
loadPredefinedBandboxFilter();
}
public void onApplyFilter() {
Sessions.getCurrent().setAttribute("companyFilterStartDate",
filterStartDate.getValue());
Sessions.getCurrent().setAttribute("companyFilterFinishDate",
filterFinishDate.getValue());
Sessions.getCurrent().setAttribute("companyFilterLabel",
bdFilters.getSelectedElements());
Sessions.getCurrent().setAttribute("companyFilterChanged", true);
filterByPredicate(createPredicate());
}
private TaskGroupPredicate createPredicate() {
List<FilterPair> listFilters = (List<FilterPair>) bdFilters
.getSelectedElements();
Date startDate = filterStartDate.getValue();
Date finishDate = filterFinishDate.getValue();
Boolean includeOrderElements = checkIncludeOrderElements.isChecked();
if (startDate == null && finishDate == null) {
TaskGroupPredicate predicate = model
.getDefaultPredicate(includeOrderElements);
//show filter dates calculated by default on screen
if(model.getFilterStartDate() != null) {
filterStartDate.setValue(model.getFilterStartDate());
}
if(model.getFilterFinishDate() != null) {
filterFinishDate.setValue(model.getFilterFinishDate());
}
predicate.setFilters(listFilters);
return predicate;
}
return new TaskGroupPredicate(listFilters, startDate, finishDate,
includeOrderElements);
}
private void filterByPredicate(TaskGroupPredicate predicate) {
// Recalculate predicate
model.setConfigurationToPlanner(planner, additional,
doubleClickCommand, predicate);
planner.updateSelectedZoomLevel();
planner.invalidate();
}
public void setTabsController(MultipleTabsPlannerController tabsController) {
this.tabsController = tabsController;
}
}
|
package com.pg85.otg.forge.materials;
import com.pg85.otg.OTG;
import com.pg85.otg.logging.LogMarker;
import net.minecraft.block.AnvilBlock;
import net.minecraft.block.BannerBlock;
import net.minecraft.block.BedBlock;
import net.minecraft.block.BeetrootBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.BrewingStandBlock;
import net.minecraft.block.CactusBlock;
import net.minecraft.block.CakeBlock;
import net.minecraft.block.CarrotBlock;
import net.minecraft.block.CarvedPumpkinBlock;
import net.minecraft.block.CauldronBlock;
import net.minecraft.block.ChestBlock;
import net.minecraft.block.CocoaBlock;
import net.minecraft.block.ComparatorBlock;
import net.minecraft.block.CropsBlock;
import net.minecraft.block.DaylightDetectorBlock;
import net.minecraft.block.DetectorRailBlock;
import net.minecraft.block.DispenserBlock;
import net.minecraft.block.DoorBlock;
import net.minecraft.block.DropperBlock;
import net.minecraft.block.EndPortalFrameBlock;
import net.minecraft.block.EndRodBlock;
import net.minecraft.block.EnderChestBlock;
import net.minecraft.block.FarmlandBlock;
import net.minecraft.block.FenceGateBlock;
import net.minecraft.block.FireBlock;
import net.minecraft.block.FurnaceBlock;
import net.minecraft.block.GlazedTerracottaBlock;
import net.minecraft.block.HayBlock;
import net.minecraft.block.HopperBlock;
import net.minecraft.block.HugeMushroomBlock;
import net.minecraft.block.JukeboxBlock;
import net.minecraft.block.LadderBlock;
import net.minecraft.block.LeavesBlock;
import net.minecraft.block.LeverBlock;
import net.minecraft.block.NetherPortalBlock;
import net.minecraft.block.NetherWartBlock;
import net.minecraft.block.ObserverBlock;
import net.minecraft.block.PistonBlock;
import net.minecraft.block.PistonHeadBlock;
import net.minecraft.block.PotatoBlock;
import net.minecraft.block.PoweredRailBlock;
import net.minecraft.block.PressurePlateBlock;
import net.minecraft.block.RailBlock;
import net.minecraft.block.RedstoneLampBlock;
import net.minecraft.block.RedstoneWallTorchBlock;
import net.minecraft.block.RedstoneWireBlock;
import net.minecraft.block.RepeaterBlock;
import net.minecraft.block.RotatedPillarBlock;
import net.minecraft.block.ShulkerBoxBlock;
import net.minecraft.block.SlabBlock;
import net.minecraft.block.SnowBlock;
import net.minecraft.block.StairsBlock;
import net.minecraft.block.StandingSignBlock;
import net.minecraft.block.StemBlock;
import net.minecraft.block.StoneButtonBlock;
import net.minecraft.block.StructureBlock;
import net.minecraft.block.SugarCaneBlock;
import net.minecraft.block.TrapDoorBlock;
import net.minecraft.block.TrappedChestBlock;
import net.minecraft.block.TripWireBlock;
import net.minecraft.block.TripWireHookBlock;
import net.minecraft.block.VineBlock;
import net.minecraft.block.WallBannerBlock;
import net.minecraft.block.WallSignBlock;
import net.minecraft.block.WallTorchBlock;
import net.minecraft.block.WeightedPressurePlateBlock;
import net.minecraft.block.WoodButtonBlock;
import net.minecraft.state.properties.AttachFace;
import net.minecraft.state.properties.BedPart;
import net.minecraft.state.properties.ComparatorMode;
import net.minecraft.state.properties.DoorHingeSide;
import net.minecraft.state.properties.DoubleBlockHalf;
import net.minecraft.state.properties.Half;
import net.minecraft.state.properties.PistonType;
import net.minecraft.state.properties.RailShape;
import net.minecraft.state.properties.SlabType;
import net.minecraft.state.properties.StructureMode;
import net.minecraft.util.Direction;
// Converts any (1.12.2 or lower) legacy block names/ids + data to the new (1.16) format.
// TODO: Can probably use some Forge method to convert data to the new format, don't do it all manually?
// ^ At least this way we have full control and can accommodate for any legacy OTG names/data/aliases etc.
// Block.getStateById() says //Forge: Do not use, use GameRegistry. GameRegistry doesn't appear to provide what we need though(?)
class LegacyMaterials
{
// TODO: Don't need any names here that match 1.16's
static BlockState fromLegacyBlockName(String oldBlockName)
{
switch(oldBlockName)
{
case "stationary_water":
return Blocks.WATER.getDefaultState();
case "stationary_lava":
return Blocks.LAVA.getDefaultState();
case "stained_clay":
return Blocks.WHITE_TERRACOTTA.getDefaultState();
case "hard_clay":
return Blocks.TERRACOTTA.getDefaultState();
case "step":
return Blocks.STONE_SLAB.getDefaultState();
case "sugar_cane_block":
return Blocks.SUGAR_CANE.getDefaultState();
case "melon_block":
return Blocks.MELON.getDefaultState();
case "water_lily":
return Blocks.LILY_PAD.getDefaultState();
case "soil":
return Blocks.FARMLAND.getDefaultState();
case "grass":
return Blocks.GRASS_BLOCK.getDefaultState();
case "long_grass":
return Blocks.TALL_GRASS.getDefaultState();
case "mycel":
return Blocks.MYCELIUM.getDefaultState();
case "snow_layer":
return Blocks.SNOW.getDefaultState();
case "leaves":
return Blocks.OAK_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
case "leaves_2":
return Blocks.ACACIA_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
case "red_rose":
return Blocks.ROSE_BUSH.getDefaultState();
// TODO: This only spawns the bottom half?
case "double_plant":
return Blocks.SUNFLOWER.getDefaultState();
case "wood_stairs":
case "oak_stairs":
return Blocks.OAK_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "birch_wood_stairs":
case "birch_stairs":
return Blocks.BIRCH_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "spruce_wood_stairs":
case "spruce_stairs":
return Blocks.SPRUCE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "jungle_wood_stairs":
case "jungle_stairs":
return Blocks.JUNGLE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "cobblestone_stairs":
return Blocks.COBBLESTONE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "stone_stairs":
return Blocks.STONE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "brick_stairs":
return Blocks.BRICK_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "nether_brick_stairs":
return Blocks.NETHER_BRICK_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "sandstone_stairs":
return Blocks.SANDSTONE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "quartz_stairs":
return Blocks.QUARTZ_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "acacia_stairs":
return Blocks.ACACIA_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "dark_oak_stairs":
return Blocks.DARK_OAK_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "red_sandstone_stairs":
return Blocks.RED_SANDSTONE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "purpur_stairs":
return Blocks.PURPUR_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "stone_brick_stairs":
return Blocks.COBBLESTONE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
// TODO: Stone stairs didn't exist in 1.12? OTG had a smooth_stairs DefaultMaterial tho :/
case "smooth_stairs":
return Blocks.STONE_STAIRS.getDefaultState().with(StairsBlock.FACING, Direction.EAST);
case "yellow_flower":
return Blocks.DANDELION.getDefaultState();
case "web":
return Blocks.COBWEB.getDefaultState();
case "wall_banner":
return Blocks.WHITE_WALL_BANNER.getDefaultState();
case "redstone_lamp_on":
return Blocks.REDSTONE_LAMP.getDefaultState().with(RedstoneLampBlock.LIT, true);
case "redstone_lamp_off":
return Blocks.REDSTONE_LAMP.getDefaultState().with(RedstoneLampBlock.LIT, false);
case "wool":
return Blocks.WHITE_WOOL.getDefaultState();
case "log":
case "wood":
return Blocks.OAK_LOG.getDefaultState();
case "log_2":
return Blocks.ACACIA_LOG.getDefaultState();
case "magma":
return Blocks.MAGMA_BLOCK.getDefaultState();
case "tallgrass":
return Blocks.GRASS.getDefaultState();
case "cobble_wall":
return Blocks.COBBLESTONE_WALL.getDefaultState();
case "iron_fence":
return Blocks.IRON_BARS.getDefaultState();
case "workbench":
return Blocks.CRAFTING_TABLE.getDefaultState();
case "mob_spawner":
return Blocks.INFESTED_STONE.getDefaultState();
case "double_step":
return Blocks.SMOOTH_STONE.getDefaultState();
case "smooth_brick":
return Blocks.STONE_BRICKS.getDefaultState();
case "rails":
return Blocks.RAIL.getDefaultState();
case "fence":
return Blocks.OAK_FENCE.getDefaultState();
case "wood_step":
return Blocks.OAK_SLAB.getDefaultState();
case "thin_glass":
return Blocks.GLASS_PANE.getDefaultState();
case "stone_plate":
return Blocks.STONE_PRESSURE_PLATE.getDefaultState();
case "wood_plate":
return Blocks.OAK_PRESSURE_PLATE.getDefaultState();
case "wood_double_step":
return Blocks.OAK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case "brick":
return Blocks.BRICKS.getDefaultState();
case "iron_door_block":
return Blocks.IRON_DOOR.getDefaultState();
case "carpet":
return Blocks.WHITE_CARPET.getDefaultState();
case "carrot":
return Blocks.CARROTS.getDefaultState();
case "skull":
return Blocks.SKELETON_SKULL.getDefaultState();
case "mcpitman":
return Blocks.CREEPER_HEAD.getDefaultState();
case "pg85":
return Blocks.ZOMBIE_HEAD.getDefaultState();
case "supercoder":
return Blocks.CAKE.getDefaultState();
case "authvin":
return Blocks.WET_SPONGE.getDefaultState();
case "josh":
return Blocks.BARREL.getDefaultState();
case "wahrheit":
return Blocks.LECTERN.getDefaultState();
case "lordsmellypants":
return Blocks.FLOWER_POT.getDefaultState();
default:
return null;
}
}
static String blockNameFromLegacyBlockId(int id)
{
switch(id)
{
case 0:
return "air";
case 1:
return "stone";
case 2:
return "grass_block";
case 3:
return "dirt";
case 4:
return "cobblestone";
case 5:
return "oak_planks";
case 6:
return "oak_sapling";
case 7:
return "bedrock";
case 8:
return "water";
case 9:
return "water";
case 10:
return "lava";
case 11:
return "lava";
case 12:
return "sand";
case 13:
return "gravel";
case 14:
return "gold_ore";
case 15:
return "iron_ore";
case 16:
return "coal_ore";
case 17:
return "oak_log";
case 18:
return "oak_leaves";
case 19:
return "sponge";
case 20:
return "glass";
case 21:
return "lapis_ore";
case 22:
return "lapis_block";
case 23:
return "dispenser";
case 24:
return "sandstone";
case 25:
return "note_block";
case 26:
return "white_bed";
case 27:
return "powered_rail";
case 28:
return "detector_rail";
case 29:
return "sticky_piston";
case 30:
return "cobweb";
case 31:
return "tall_grass";
case 32:
return "dead_bush";
case 33:
return "piston";
case 34:
return "piston_head";
case 35:
return "white_wool";
case 36:
return "piston_extension";
case 37:
return "dandelion";
case 38:
return "rose_bush";
case 39:
return "brown_mushroom";
case 40:
return "red_mushroom";
case 41:
return "gold_block";
case 42:
return "iron_block";
case 43:
return "smooth_stone"; // Double-slab
case 44:
return "stone_slab";
case 45:
return "bricks";
case 46:
return "tnt";
case 47:
return "bookshelf";
case 48:
return "mossy_cobblestone";
case 49:
return "obsidian";
case 50:
return "torch";
case 51:
return "fire";
case 52:
return "spawner";
case 53:
return "oak_stairs";
case 54:
return "chest";
case 55:
return "redstone_wire";
case 56:
return "diamond_ore";
case 57:
return "diamond_block";
case 58:
return "crafting_table";
case 59:
return "wheat";
case 60:
return "farmland";
case 61:
return "furnace";
case 62:
return "furnace"; // TODO: Should be lit
case 63:
return "oak_sign";
case 64:
return "oak_door";
case 65:
return "ladder";
case 66:
return "rail";
case 67:
return "stone_stairs";
case 68:
return "oak_wall_sign";
case 69:
return "lever";
case 70:
return "stone_pressure_plate";
case 71:
return "iron_door";
case 72:
return "oak_pressure_plate";
case 73:
return "redstone_ore";
case 74:
return "redstone_ore"; // TODO: Should be lit
case 75:
return "redstone_torch"; // TODO: Should be unlit
case 76:
return "redstone_torch"; // TODO: Should be lit
case 77:
return "stone_button";
case 78:
return "snow";
case 79:
return "ice";
case 80:
return "snow_block";
case 81:
return "cactus";
case 82:
return "clay";
case 83:
return "sugar_cane";
case 84:
return "jukebox";
case 85:
return "oak_fence";
case 86:
return "pumpkin";
case 87:
return "netherrack";
case 88:
return "soul_sand";
case 89:
return "glowstone";
case 90:
return "nether_portal";
case 91:
return "jack_o_lantern";
case 92:
return "cake";
case 93:
return "unpowered_repeater";
case 94:
return "powered_repeater";
case 95:
return "white_stained_glass";
case 96:
return "oak_trapdoor";
case 97:
return "infested_stone";
case 98:
return "stone_bricks";
case 99:
return "brown_mushroom_block";
case 100:
return "red_mushroom_block";
case 101:
return "iron_bars";
case 102:
return "glass_pane";
case 103:
return "melon";
case 104:
return "pumpkin_stem";
case 105:
return "melon_stem";
case 106:
return "vine";
case 107:
return "oak_fence_gate";
case 108:
return "brick_stairs";
case 109:
return "stone_brick_stairs";
case 110:
return "mycelium";
case 111:
return "lily_pad";
case 112:
return "nether_bricks";
case 113:
return "nether_brick_fence";
case 114:
return "nether_brick_stairs";
case 115:
return "nether_wart";
case 116:
return "enchanting_table";
case 117:
return "brewing_stand";
case 118:
return "cauldron";
case 119:
return "end_portal";
case 120:
return "end_portal_frame";
case 121:
return "end_stone";
case 122:
return "dragon_egg";
case 123:
return "redstone_lamp";
case 124:
return "redstone_lamp"; // TODO: Should be lit
case 125:
return "oak_planks"; // Double-slab
case 126:
return "oak_slab";
case 127:
return "cocoa";
case 128:
return "sandstone_stairs";
case 129:
return "emerald_ore";
case 130:
return "ender_chest";
case 131:
return "tripwire_hook";
case 132:
return "tripwire";
case 133:
return "emerald_block";
case 134:
return "spruce_stairs";
case 135:
return "birch_stairs";
case 136:
return "jungle_stairs";
case 137:
return "command_block";
case 138:
return "beacon";
case 139:
return "cobblestone_wall";
case 140:
return "flower_pot";
case 141:
return "carrots";
case 142:
return "potatoes";
case 143:
return "oak_button";
case 144:
return "skeleton_skull";
case 145:
return "anvil";
case 146:
return "trapped_chest";
case 147:
return "light_weighted_pressure_plate";
case 148:
return "heavy_weighted_pressure_plate";
case 149:
return "comparator"; // TODO: Should be unpowered
case 150:
return "comparator"; // TODO: Should be powered
case 151:
return "daylight_detector";
case 152:
return "redstone_block";
case 153:
return "nether_quartz_ore";
case 154:
return "hopper";
case 155:
return "quartz_block";
case 156:
return "quartz_stairs";
case 157:
return "activator_rail";
case 158:
return "dropper";
case 159:
return "white_terracotta";
case 160:
return "white_stained_glass_pane";
case 161:
return "acacia_leaves";
case 162:
return "acacia_log";
case 163:
return "acacia_stairs";
case 164:
return "dark_oak_stairs";
case 165:
return "slime_block";
case 166:
return "barrier";
case 167:
return "iron_trapdoor";
case 168:
return "prismarine";
case 169:
return "sea_lantern";
case 170:
return "hay_block";
case 171:
return "white_carpet";
case 172:
return "white_terracotta";
case 173:
return "coal_block";
case 174:
return "packed_ice";
case 175:
return "sunflower";
case 176:
return "standing_banner";
case 177:
return "wall_banner";
case 178:
return "daylight_detector_inverted";
case 179:
return "red_sandstone";
case 180:
return "red_sandstone_stairs";
case 181:
return "red_sandstone"; // Double-slab
case 182:
return "red_sandstone_slab";
case 183:
return "spruce_fence_gate";
case 184:
return "birch_fence_gate";
case 185:
return "jungle_fence_gate";
case 186:
return "dark_oak_fence_gate";
case 187:
return "acacia_fence_gate";
case 188:
return "spruce_fence";
case 189:
return "birch_fence";
case 190:
return "jungle_fence";
case 191:
return "dark_oak_fence";
case 192:
return "acacia_fence";
case 193:
return "spruce_door";
case 194:
return "birch_door";
case 195:
return "jungle_door";
case 196:
return "acacia_door";
case 197:
return "dark_oak_door";
case 198:
return "end_rod";
case 199:
return "chorus_plant";
case 200:
return "chorus_flower";
case 201:
return "purpur_block";
case 202:
return "purpur_pillar";
case 203:
return "purpur_stairs";
case 204:
return "purpur_double_slab";
case 205:
return "purpur_slab";
case 206:
return "end_stone_bricks";
case 207:
return "beetroots";
case 208:
return "grass_path";
case 209:
return "end_gateway";
case 210:
return "repeating_command_block";
case 211:
return "chain_command_block";
case 212:
return "frosted_ice";
case 213:
return "magma_block";
case 214:
return "nether_wart_block";
case 215:
return "red_nether_bricks";
case 216:
return "bone_block";
case 217:
return "structure_void";
case 218:
return "observer";
case 219:
return "white_shulker_box";
case 220:
return "orange_shulker_box";
case 221:
return "magenta_shulker_box";
case 222:
return "light_blue_shulker_box";
case 223:
return "yellow_shulker_box";
case 224:
return "lime_shulker_box";
case 225:
return "pink_shulker_box";
case 226:
return "gray_shulker_box";
case 227:
return "light_gray_shulker_box";
case 228:
return "cyan_shulker_box";
case 229:
return "purple_shulker_box";
case 230:
return "blue_shulker_box";
case 231:
return "brown_shulker_box";
case 232:
return "green_shulker_box";
case 233:
return "red_shulker_box";
case 234:
return "black_shulker_box";
case 235:
return "white_glazed_terracotta";
case 236:
return "orange_glazed_terracotta";
case 237:
return "magenta_glazed_terracotta";
case 238:
return "light_blue_glazed_terracotta";
case 239:
return "yellow_glazed_terracotta";
case 240:
return "lime_glazed_terracotta";
case 241:
return "pink_glazed_terracotta";
case 242:
return "gray_glazed_terracotta";
case 243:
return "light_gray_glazed_terracotta";
case 244:
return "cyan_glazed_terracotta";
case 245:
return "purple_glazed_terracotta";
case 246:
return "blue_glazed_terracotta";
case 247:
return "brown_glazed_terracotta";
case 248:
return "green_glazed_terracotta";
case 249:
return "red_glazed_terracotta";
case 250:
return "black_glazed_terracotta";
case 251:
return "white_concrete";
case 252:
return "white_concrete_powder";
case 255:
return "structure_block";
case 342:
return "chest_minecart";
case 343:
return "furnace_minecart";
case 397:
return "skeleton_skull";
case 404:
return "comparator";
case 405:
return "nether_bricks";
case 427:
return "spruce_door";
case 428:
return "birch_door";
case 429:
return "jungle_door";
case 430:
return "acacia_door";
case 431:
return "dark_oak_door";
default:
return null;
}
}
static BlockState fromLegacyBlockNameOrIdWithData(String blockName, int data)
{
if(blockName == null || blockName.trim().isEmpty())
{
return null;
}
try
{
int blockId = Integer.parseInt(blockName);
blockName = blockNameFromLegacyBlockId(blockId);
if(blockName == null)
{
return null;
}
} catch(NumberFormatException ex) { }
try
{
switch(blockName)
{
// Support "GRASS:0" here, or it will be misinterpreted as the new grass (plant)
case "grass":
switch(data)
{
case 0:
return Blocks.GRASS_BLOCK.getDefaultState();
}
// Legacy blocks with block data that are now their own block
case "banner":
case "white_banner":
switch(data)
{
case 0:
default:
return Blocks.BLACK_BANNER.getDefaultState();
case 1:
return Blocks.RED_BANNER.getDefaultState();
case 2:
return Blocks.GREEN_BANNER.getDefaultState();
case 3:
return Blocks.BROWN_BANNER.getDefaultState();
case 4:
return Blocks.BLUE_BANNER.getDefaultState();
case 5:
return Blocks.PURPLE_BANNER.getDefaultState();
case 6:
return Blocks.CYAN_BANNER.getDefaultState();
case 7:
return Blocks.LIGHT_GRAY_BANNER.getDefaultState();
case 8:
return Blocks.GRAY_BANNER.getDefaultState();
case 9:
return Blocks.PINK_BANNER.getDefaultState();
case 10:
return Blocks.LIME_BANNER.getDefaultState();
case 11:
return Blocks.YELLOW_BANNER.getDefaultState();
case 12:
return Blocks.LIGHT_BLUE_BANNER.getDefaultState();
case 13:
return Blocks.MAGENTA_BANNER.getDefaultState();
case 14:
return Blocks.ORANGE_BANNER.getDefaultState();
case 15:
return Blocks.WHITE_BANNER.getDefaultState();
}
// TODO: How does facing for bed blocks in bo's work for 1.12.2, can only specify color via data?
case "bed":
case "white_bed":
switch(data)
{
case 0:
default:
return Blocks.WHITE_BED.getDefaultState();
case 1:
return Blocks.ORANGE_BED.getDefaultState();
case 2:
return Blocks.MAGENTA_BED.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_BED.getDefaultState();
case 4:
return Blocks.YELLOW_BED.getDefaultState();
case 5:
return Blocks.LIME_BED.getDefaultState();
case 6:
return Blocks.PINK_BED.getDefaultState();
case 7:
return Blocks.GRAY_BED.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_BED.getDefaultState();
case 9:
return Blocks.CYAN_BED.getDefaultState();
case 10:
return Blocks.PURPLE_BED.getDefaultState();
case 11:
return Blocks.BLUE_BED.getDefaultState();
case 12:
return Blocks.BROWN_BED.getDefaultState();
case 13:
return Blocks.GREEN_BED.getDefaultState();
case 14:
return Blocks.RED_BED.getDefaultState();
case 15:
return Blocks.BLACK_BED.getDefaultState();
}
case "carpet":
case "white_carpet":
switch(data)
{
case 0:
default:
return Blocks.WHITE_CARPET.getDefaultState();
case 1:
return Blocks.ORANGE_CARPET.getDefaultState();
case 2:
return Blocks.MAGENTA_CARPET.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_CARPET.getDefaultState();
case 4:
return Blocks.YELLOW_CARPET.getDefaultState();
case 5:
return Blocks.LIME_CARPET.getDefaultState();
case 6:
return Blocks.PINK_CARPET.getDefaultState();
case 7:
return Blocks.GRAY_CARPET.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_CARPET.getDefaultState();
case 9:
return Blocks.CYAN_CARPET.getDefaultState();
case 10:
return Blocks.PURPLE_CARPET.getDefaultState();
case 11:
return Blocks.BLUE_CARPET.getDefaultState();
case 12:
return Blocks.BROWN_CARPET.getDefaultState();
case 13:
return Blocks.GREEN_CARPET.getDefaultState();
case 14:
return Blocks.RED_CARPET.getDefaultState();
case 15:
return Blocks.BLACK_CARPET.getDefaultState();
}
case "cobblestone_wall":
case "cobble_wall":
switch(data)
{
case 0:
default:
return Blocks.COBBLESTONE_WALL.getDefaultState();
case 1:
return Blocks.MOSSY_COBBLESTONE_WALL.getDefaultState();
}
case "concrete":
case "white_concrete":
switch(data)
{
case 0:
default:
return Blocks.WHITE_CONCRETE.getDefaultState();
case 1:
return Blocks.ORANGE_CONCRETE.getDefaultState();
case 2:
return Blocks.MAGENTA_CONCRETE.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_CONCRETE.getDefaultState();
case 4:
return Blocks.YELLOW_CONCRETE.getDefaultState();
case 5:
return Blocks.LIME_CONCRETE.getDefaultState();
case 6:
return Blocks.PINK_CONCRETE.getDefaultState();
case 7:
return Blocks.GRAY_CONCRETE.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_CONCRETE.getDefaultState();
case 9:
return Blocks.CYAN_CONCRETE.getDefaultState();
case 10:
return Blocks.PURPLE_CONCRETE.getDefaultState();
case 11:
return Blocks.BLUE_CONCRETE.getDefaultState();
case 12:
return Blocks.BROWN_CONCRETE.getDefaultState();
case 13:
return Blocks.GREEN_CONCRETE.getDefaultState();
case 14:
return Blocks.RED_CONCRETE.getDefaultState();
case 15:
return Blocks.BLACK_CONCRETE.getDefaultState();
}
case "concrete_powder":
case "white_concrete_powder":
switch(data)
{
case 0:
default:
return Blocks.WHITE_CONCRETE_POWDER.getDefaultState();
case 1:
return Blocks.ORANGE_CONCRETE_POWDER.getDefaultState();
case 2:
return Blocks.MAGENTA_CONCRETE_POWDER.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_CONCRETE_POWDER.getDefaultState();
case 4:
return Blocks.YELLOW_CONCRETE_POWDER.getDefaultState();
case 5:
return Blocks.LIME_CONCRETE_POWDER.getDefaultState();
case 6:
return Blocks.PINK_CONCRETE_POWDER.getDefaultState();
case 7:
return Blocks.GRAY_CONCRETE_POWDER.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_CONCRETE_POWDER.getDefaultState();
case 9:
return Blocks.CYAN_CONCRETE_POWDER.getDefaultState();
case 10:
return Blocks.PURPLE_CONCRETE_POWDER.getDefaultState();
case 11:
return Blocks.BLUE_CONCRETE_POWDER.getDefaultState();
case 12:
return Blocks.BROWN_CONCRETE_POWDER.getDefaultState();
case 13:
return Blocks.GREEN_CONCRETE_POWDER.getDefaultState();
case 14:
return Blocks.RED_CONCRETE_POWDER.getDefaultState();
case 15:
return Blocks.BLACK_CONCRETE_POWDER.getDefaultState();
}
case "dirt":
switch(data)
{
case 0:
default:
return Blocks.DIRT.getDefaultState();
case 1:
return Blocks.COARSE_DIRT.getDefaultState();
case 2:
return Blocks.PODZOL.getDefaultState();
}
// TODO: This only spawns the bottom half?
case "double_plant":
case "sunflower":
case "rose_bush":
case "tall_grass":
switch(data)
{
case 0:
default:
return Blocks.SUNFLOWER.getDefaultState();
case 1:
return Blocks.LILAC.getDefaultState();
case 2:
return Blocks.TALL_GRASS.getDefaultState();
case 3:
return Blocks.LARGE_FERN.getDefaultState();
case 4:
return Blocks.ROSE_BUSH.getDefaultState();
case 5:
return Blocks.PEONY.getDefaultState();
}
case "double_stone_slab":
case "smooth_stone":
switch(data)
{
case 0:
default:
return Blocks.STONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 1:
return Blocks.SANDSTONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
//case 2:
case 3:
return Blocks.COBBLESTONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 4:
return Blocks.BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 5:
return Blocks.STONE_BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 6:
return Blocks.NETHER_BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 7:
return Blocks.QUARTZ_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
}
// TODO: Did this even exist for 1.12.2?
case "double_wooden_slab":
case "wood_double_step":
switch(data)
{
case 0:
default:
return Blocks.OAK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 1:
return Blocks.SPRUCE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 2:
return Blocks.BIRCH_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 3:
return Blocks.JUNGLE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 4:
return Blocks.ACACIA_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
case 5:
return Blocks.DARK_OAK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.DOUBLE);
}
case "leaves":
case "oak_leaves":
switch(data)
{
case 0:
case 4:
case 8:
case 12:
default:
return Blocks.OAK_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
case 1:
case 5:
case 9:
case 13:
return Blocks.SPRUCE_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
case 2:
case 6:
case 10:
case 14:
return Blocks.BIRCH_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
case 3:
case 7:
case 11:
case 15:
return Blocks.JUNGLE_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
}
case "leaves2":
case "leaves_2":
case "acacia_leaves":
switch(data)
{
case 0:
case 4:
case 8:
case 12:
default:
return Blocks.ACACIA_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
case 1:
case 5:
case 9:
case 13:
return Blocks.DARK_OAK_LEAVES.getDefaultState().with(LeavesBlock.DISTANCE, 1);
}
case "monster_egg":
case "monster_eggs":
case "infested_stone":
switch(data)
{
case 0:
default:
return Blocks.INFESTED_STONE.getDefaultState();
case 1:
return Blocks.INFESTED_COBBLESTONE.getDefaultState();
case 2:
return Blocks.INFESTED_STONE_BRICKS.getDefaultState();
case 3:
return Blocks.INFESTED_MOSSY_STONE_BRICKS.getDefaultState();
case 4:
return Blocks.INFESTED_CRACKED_STONE_BRICKS.getDefaultState();
case 5:
return Blocks.INFESTED_CHISELED_STONE_BRICKS.getDefaultState();
}
case "planks":
case "oak_planks":
switch(data)
{
case 0:
default:
return Blocks.OAK_PLANKS.getDefaultState();
case 1:
return Blocks.SPRUCE_PLANKS.getDefaultState();
case 2:
return Blocks.BIRCH_PLANKS.getDefaultState();
case 3:
return Blocks.JUNGLE_PLANKS.getDefaultState();
case 4:
return Blocks.ACACIA_PLANKS.getDefaultState();
case 5:
return Blocks.DARK_OAK_PLANKS.getDefaultState();
}
case "prismarine":
switch(data)
{
// TODO: Docs contradict each other about whether 2 or 3 is bricks/dark, test this.
case 0:
default:
return Blocks.PRISMARINE.getDefaultState();
case 1:
return Blocks.PRISMARINE_BRICKS.getDefaultState();
case 2:
return Blocks.DARK_PRISMARINE.getDefaultState();
}
case "purpur_slab":
return Blocks.PURPUR_SLAB.getDefaultState()
.with(SlabBlock.TYPE, data == 2 ? SlabType.BOTTOM : data == 10 ? SlabType.TOP : SlabType.BOTTOM);
case "red_flower":
switch(data)
{
case 0:
default:
return Blocks.POPPY.getDefaultState();
case 1:
return Blocks.BLUE_ORCHID.getDefaultState();
case 2:
return Blocks.ALLIUM.getDefaultState();
case 3:
return Blocks.AZURE_BLUET.getDefaultState();
case 4:
return Blocks.RED_TULIP.getDefaultState();
case 5:
return Blocks.ORANGE_TULIP.getDefaultState();
case 6:
return Blocks.WHITE_TULIP.getDefaultState();
case 7:
return Blocks.PINK_TULIP.getDefaultState();
case 8:
return Blocks.OXEYE_DAISY.getDefaultState();
}
case "red_sandstone":
switch(data)
{
case 0:
default:
return Blocks.RED_SANDSTONE.getDefaultState();
case 1:
return Blocks.CHISELED_RED_SANDSTONE.getDefaultState();
case 2:
return Blocks.SMOOTH_RED_SANDSTONE.getDefaultState();
}
case "red_sandstone_slab":
case "stone_slab2":
switch(data)
{
case 0:
default:
return Blocks.RED_SANDSTONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 8:
return Blocks.CHISELED_RED_SANDSTONE.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
}
case "sand":
switch(data)
{
case 0:
default:
return Blocks.SAND.getDefaultState();
case 1:
return Blocks.RED_SAND.getDefaultState();
}
case "sandstone":
switch(data)
{
case 0:
default:
return Blocks.SANDSTONE.getDefaultState();
case 1:
return Blocks.CHISELED_SANDSTONE.getDefaultState();
case 2:
return Blocks.SMOOTH_SANDSTONE.getDefaultState();
}
case "sapling":
case "oak_sapling":
switch(data)
{
case 0:
default:
return Blocks.OAK_SAPLING.getDefaultState();
case 1:
return Blocks.SPRUCE_SAPLING.getDefaultState();
case 2:
return Blocks.BIRCH_SAPLING.getDefaultState();
case 3:
return Blocks.JUNGLE_SAPLING.getDefaultState();
case 4:
return Blocks.ACACIA_SAPLING.getDefaultState();
case 5:
return Blocks.DARK_OAK_SAPLING.getDefaultState();
}
case "skull":
case "skeleton_skull":
switch(data)
{
case 0:
default:
return Blocks.SKELETON_SKULL.getDefaultState();
case 1:
return Blocks.WITHER_SKELETON_SKULL.getDefaultState();
case 2:
return Blocks.ZOMBIE_HEAD.getDefaultState();
case 3:
return Blocks.PLAYER_HEAD.getDefaultState();
case 4:
return Blocks.CREEPER_HEAD.getDefaultState();
case 5:
return Blocks.DRAGON_HEAD.getDefaultState();
}
case "sponge":
switch(data)
{
case 0:
default:
return Blocks.SPONGE.getDefaultState();
case 1:
return Blocks.WET_SPONGE.getDefaultState();
}
case "stained_glass":
case "white_stained_glass":
switch(data)
{
case 0:
default:
return Blocks.WHITE_STAINED_GLASS.getDefaultState();
case 1:
return Blocks.ORANGE_STAINED_GLASS.getDefaultState();
case 2:
return Blocks.MAGENTA_STAINED_GLASS.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_STAINED_GLASS.getDefaultState();
case 4:
return Blocks.YELLOW_STAINED_GLASS.getDefaultState();
case 5:
return Blocks.LIME_STAINED_GLASS.getDefaultState();
case 6:
return Blocks.PINK_STAINED_GLASS.getDefaultState();
case 7:
return Blocks.GRAY_STAINED_GLASS.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_STAINED_GLASS.getDefaultState();
case 9:
return Blocks.CYAN_STAINED_GLASS.getDefaultState();
case 10:
return Blocks.PURPLE_STAINED_GLASS.getDefaultState();
case 11:
return Blocks.BLUE_STAINED_GLASS.getDefaultState();
case 12:
return Blocks.BROWN_STAINED_GLASS.getDefaultState();
case 13:
return Blocks.GREEN_STAINED_GLASS.getDefaultState();
case 14:
return Blocks.RED_STAINED_GLASS.getDefaultState();
case 15:
return Blocks.BLACK_STAINED_GLASS.getDefaultState();
}
case "stained_glass_pane":
case "white_stained_glass_pane":
case "thing_glass":
switch(data)
{
case 0:
default:
return Blocks.WHITE_STAINED_GLASS_PANE.getDefaultState();
case 1:
return Blocks.ORANGE_STAINED_GLASS_PANE.getDefaultState();
case 2:
return Blocks.MAGENTA_STAINED_GLASS_PANE.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_STAINED_GLASS_PANE.getDefaultState();
case 4:
return Blocks.YELLOW_STAINED_GLASS_PANE.getDefaultState();
case 5:
return Blocks.LIME_STAINED_GLASS_PANE.getDefaultState();
case 6:
return Blocks.PINK_STAINED_GLASS_PANE.getDefaultState();
case 7:
return Blocks.GRAY_STAINED_GLASS_PANE.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_STAINED_GLASS_PANE.getDefaultState();
case 9:
return Blocks.CYAN_STAINED_GLASS_PANE.getDefaultState();
case 10:
return Blocks.PURPLE_STAINED_GLASS_PANE.getDefaultState();
case 11:
return Blocks.BLUE_STAINED_GLASS_PANE.getDefaultState();
case 12:
return Blocks.BROWN_STAINED_GLASS_PANE.getDefaultState();
case 13:
return Blocks.GREEN_STAINED_GLASS_PANE.getDefaultState();
case 14:
return Blocks.RED_STAINED_GLASS_PANE.getDefaultState();
case 15:
return Blocks.BLACK_STAINED_GLASS_PANE.getDefaultState();
}
case "stained_hardened_clay":
case "stained_clay":
case "hard_clay":
case "white_terracotta":
switch(data)
{
case 0:
default:
return Blocks.WHITE_TERRACOTTA.getDefaultState();
case 1:
return Blocks.ORANGE_TERRACOTTA.getDefaultState();
case 2:
return Blocks.MAGENTA_TERRACOTTA.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_TERRACOTTA.getDefaultState();
case 4:
return Blocks.YELLOW_TERRACOTTA.getDefaultState();
case 5:
return Blocks.LIME_TERRACOTTA.getDefaultState();
case 6:
return Blocks.PINK_TERRACOTTA.getDefaultState();
case 7:
return Blocks.GRAY_TERRACOTTA.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_TERRACOTTA.getDefaultState();
case 9:
return Blocks.CYAN_TERRACOTTA.getDefaultState();
case 10:
return Blocks.PURPLE_TERRACOTTA.getDefaultState();
case 11:
return Blocks.BLUE_TERRACOTTA.getDefaultState();
case 12:
return Blocks.BROWN_TERRACOTTA.getDefaultState();
case 13:
return Blocks.GREEN_TERRACOTTA.getDefaultState();
case 14:
return Blocks.RED_TERRACOTTA.getDefaultState();
case 15:
return Blocks.BLACK_TERRACOTTA.getDefaultState();
}
case "stone":
switch(data)
{
case 0:
default:
return Blocks.STONE.getDefaultState();
case 1:
return Blocks.GRANITE.getDefaultState();
case 2:
return Blocks.POLISHED_GRANITE.getDefaultState();
case 3:
return Blocks.DIORITE.getDefaultState();
case 4:
return Blocks.POLISHED_DIORITE.getDefaultState();
case 5:
return Blocks.ANDESITE.getDefaultState();
case 6:
return Blocks.POLISHED_ANDESITE.getDefaultState();
}
case "stone_slab":
case "step":
switch(data)
{
case 0:
default:
return Blocks.STONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 1:
return Blocks.SANDSTONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
//case 2:
case 3:
return Blocks.COBBLESTONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 4:
return Blocks.BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 5:
return Blocks.STONE_BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 6:
return Blocks.NETHER_BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 7:
return Blocks.QUARTZ_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 8:
return Blocks.STONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 9:
return Blocks.SANDSTONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
//case 10:
case 11:
return Blocks.COBBLESTONE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 12:
return Blocks.BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 13:
return Blocks.STONE_BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 14:
return Blocks.NETHER_BRICK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 15:
return Blocks.QUARTZ_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
}
case "stonebrick":
case "stone_bricks":
case "smooth_brick":
switch(data)
{
case 0:
default:
return Blocks.STONE_BRICKS.getDefaultState();
case 1:
return Blocks.MOSSY_STONE_BRICKS.getDefaultState();
case 2:
return Blocks.CRACKED_STONE_BRICKS.getDefaultState();
case 3:
return Blocks.CHISELED_STONE_BRICKS.getDefaultState();
}
case "tallgrass":
case "long_grass":
switch(data)
{
case 1:
default:
return Blocks.GRASS.getDefaultState();
case 2:
return Blocks.FERN.getDefaultState();
}
case "wooden_slab":
case "wood_step":
case "oak_slab":
switch(data)
{
case 0:
default:
return Blocks.OAK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 1:
return Blocks.SPRUCE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 2:
return Blocks.BIRCH_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 3:
return Blocks.JUNGLE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 4:
return Blocks.ACACIA_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 5:
return Blocks.DARK_OAK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.BOTTOM);
case 8:
return Blocks.OAK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 9:
return Blocks.SPRUCE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 10:
return Blocks.BIRCH_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 11:
return Blocks.JUNGLE_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 12:
return Blocks.ACACIA_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
case 13:
return Blocks.DARK_OAK_SLAB.getDefaultState().with(SlabBlock.TYPE, SlabType.TOP);
}
case "wool":
case "white_wool":
switch(data)
{
case 0:
default:
return Blocks.WHITE_WOOL.getDefaultState();
case 1:
return Blocks.ORANGE_WOOL.getDefaultState();
case 2:
return Blocks.MAGENTA_WOOL.getDefaultState();
case 3:
return Blocks.LIGHT_BLUE_WOOL.getDefaultState();
case 4:
return Blocks.YELLOW_WOOL.getDefaultState();
case 5:
return Blocks.LIME_WOOL.getDefaultState();
case 6:
return Blocks.PINK_WOOL.getDefaultState();
case 7:
return Blocks.GRAY_WOOL.getDefaultState();
case 8:
return Blocks.LIGHT_GRAY_WOOL.getDefaultState();
case 9:
return Blocks.CYAN_WOOL.getDefaultState();
case 10:
return Blocks.PURPLE_WOOL.getDefaultState();
case 11:
return Blocks.BLUE_WOOL.getDefaultState();
case 12:
return Blocks.BROWN_WOOL.getDefaultState();
case 13:
return Blocks.GREEN_WOOL.getDefaultState();
case 14:
return Blocks.RED_WOOL.getDefaultState();
case 15:
return Blocks.BLACK_WOOL.getDefaultState();
}
// Blocks with data
case "fire":
return Blocks.FIRE.getDefaultState().with(FireBlock.AGE, data);
case "cake":
case "cake_block":
return Blocks.CAKE.getDefaultState().with(CakeBlock.BITES, data);
case "stone_pressure_plate":
case "stone_plate":
return Blocks.STONE_PRESSURE_PLATE.getDefaultState().with(PressurePlateBlock.POWERED, getBit(data, 0) == 1);
case "wooden_pressure_plate":
case "wood_plate":
return Blocks.OAK_PRESSURE_PLATE.getDefaultState().with(PressurePlateBlock.POWERED, getBit(data, 0) == 1);
case "light_weighted_pressure_plate":
return Blocks.LIGHT_WEIGHTED_PRESSURE_PLATE.getDefaultState().with(WeightedPressurePlateBlock.POWER, data);
case "heavy_weighted_pressure_plate":
return Blocks.HEAVY_WEIGHTED_PRESSURE_PLATE.getDefaultState().with(WeightedPressurePlateBlock.POWER, data);
case "snow_layer":
return Blocks.SNOW.getDefaultState().with(SnowBlock.LAYERS, data);
case "cactus":
return Blocks.CACTUS.getDefaultState().with(CactusBlock.AGE, data);
case "reeds":
return Blocks.SUGAR_CANE.getDefaultState().with(SugarCaneBlock.AGE, data);
case "jukebox":
return Blocks.JUKEBOX.getDefaultState().with(JukeboxBlock.HAS_RECORD, data == 1);
case "wheat":
case "crops":
return Blocks.WHEAT.getDefaultState().with(CropsBlock.AGE, data);
case "carrot":
return Blocks.CARROTS.getDefaultState().with(CarrotBlock.AGE, data);
case "potato":
return Blocks.POTATOES.getDefaultState().with(PotatoBlock.AGE, data);
case "beetroot":
return Blocks.BEETROOTS.getDefaultState().with(BeetrootBlock.BEETROOT_AGE, data);
case "farmland":
case "soil":
return Blocks.FARMLAND.getDefaultState().with(FarmlandBlock.MOISTURE, data);
case "anvil":
return getAnvilWithData(0, data);
case "log":
case "wood":
case "oak_log":
return getLogWithData(data);
case "log_2":
case "acacia_log":
return getLog2WithData(data);
case "quartz_block":
return getQuartzBlockWithData(data);
case "torch":
return getTorchWithData(0, data);
case "redstone_torch_off":
case "redstone_torch":
return getTorchWithData(1, data);
case "redstone_torch_on":
return getTorchWithData(2, data);
case "rails":
return Blocks.RAIL.getDefaultState().with(RailBlock.SHAPE, getRailShape(data));
case "powered_rail":
case "golden_rail":
return getRailsWithData(0, data);
case "detector_rail":
return getRailsWithData(1, data);
case "activator_rail":
return getRailsWithData(2, data);
case "hay_block":
return Blocks.HAY_BLOCK.getDefaultState().with(HayBlock.AXIS, getAxisXYZ(data));
case "bone_block":
return Blocks.BONE_BLOCK.getDefaultState().with(RotatedPillarBlock.AXIS, getAxisXYZ(data));
case "wood_stairs":
case "oak_stairs":
return getStairsWithData(0, data);
case "birch_wood_stairs":
case "birch_stairs":
return getStairsWithData(1, data);
case "spruce_wood_stairs":
case "spruce_stairs":
return getStairsWithData(2, data);
case "jungle_wood_stairs":
case "jungle_stairs":
return getStairsWithData(3, data);
case "cobblestone_stairs":
case "stone_stairs":
return getStairsWithData(4, data);
case "brick_stairs":
return getStairsWithData(5, data);
// TODO: Stone stairs didn't exist in 1.12? OTG had a smooth_stairs DefaultMaterial tho :/
case "smooth_stairs":
return getStairsWithData(6, data);
case "nether_brick_stairs":
return getStairsWithData(7, data);
case "sandstone_stairs":
return getStairsWithData(8, data);
case "quartz_stairs":
return getStairsWithData(9, data);
case "acacia_stairs":
return getStairsWithData(10, data);
case "dark_oak_stairs":
return getStairsWithData(11, data);
case "red_sandstone_stairs":
return getStairsWithData(12, data);
case "purpur_stairs":
return getStairsWithData(13, data);
case "stone_brick_stairs":
return getStairsWithData(14, data);
case "lever":
return getLeverOrButtonWithData(0, data);
case "stone_button":
return getLeverOrButtonWithData(1, data);
case "wood_button":
case "wooden_button":
return getLeverOrButtonWithData(2, data);
case "wooden_door":
case "oak_door":
return getDoorWithData(0, data);
case "iron_door_block":
case "iron_door":
return getDoorWithData(1, data);
case "spruce_door":
return getDoorWithData(2, data);
case "birch_door":
return getDoorWithData(3, data);
case "jungle_door":
return getDoorWithData(4, data);
case "acacia_door":
return getDoorWithData(5, data);
case "dark_oak_door":
return getDoorWithData(6, data);
case "sign_post":
case "sign": // TODO: This will also pick up wall signs
return getSignPostWithData(data);
case "standing_banner":
return Blocks.BLACK_BANNER.getDefaultState().with(BannerBlock.ROTATION, data);
case "wall_banner":
return Blocks.WHITE_WALL_BANNER.getDefaultState().with(WallBannerBlock.HORIZONTAL_FACING, getFacingNorthSouthWestEast(data));
case "end_rod":
return Blocks.END_ROD.getDefaultState().with(EndRodBlock.FACING, getFacingDownUpNorthSouthWestEast(data));
case "daylight_detector":
return Blocks.DAYLIGHT_DETECTOR.getDefaultState().with(DaylightDetectorBlock.POWER, data);
case "command":
case "command_block":
return getCommandBlockWithData(0, data);
case "command_repeating":
case "repeating_command_block":
return getCommandBlockWithData(1, data);
case "command_chain":
case "chain_command_block":
return getCommandBlockWithData(2, data);
case "white_shulker_box":
return getShulkerBoxWithData(0, data);
case "orange_shulker_box":
return getShulkerBoxWithData(1, data);
case "magenta_shulker_box":
return getShulkerBoxWithData(2, data);
case "light_blue_shulker_box":
return getShulkerBoxWithData(3, data);
case "yellow_shulker_box":
return getShulkerBoxWithData(4, data);
case "lime_shulker_box":
return getShulkerBoxWithData(5, data);
case "pink_shulker_box":
return getShulkerBoxWithData(6, data);
case "gray_shulker_box":
return getShulkerBoxWithData(7, data);
case "silver_shulker_box":
return getShulkerBoxWithData(8, data);
case "cyan_shulker_box":
return getShulkerBoxWithData(9, data);
case "purple_shulker_box":
return getShulkerBoxWithData(10, data);
case "blue_shulker_box":
return getShulkerBoxWithData(11, data);
case "brown_shulker_box":
return getShulkerBoxWithData(12, data);
case "green_shulker_box":
return getShulkerBoxWithData(13, data);
case "red_shulker_box":
return getShulkerBoxWithData(14, data);
case "black_shulker_box":
return getShulkerBoxWithData(15, data);
case "ladder":
return getLadderChestOrFurnaceWithData(0, data);
case "chest":
return getLadderChestOrFurnaceWithData(1, data);
case "ender_chest":
return getLadderChestOrFurnaceWithData(2, data);
case "trapped_chest":
return getLadderChestOrFurnaceWithData(3, data);
case "furnace":
return getLadderChestOrFurnaceWithData(4, data);
case "burning_furnace":
return getLadderChestOrFurnaceWithData(5, data);
case "wall_sign":
return getWallSignWithData(data);
case "observer":
return getObserverWithData(data);
case "dispenser":
return getDispenserHopperDropperWithData(0, data);
case "dropper":
return getDispenserHopperDropperWithData(1, data);
case "hopper":
return getDispenserHopperDropperWithData(2, data);
case "pumpkin_stem":
// TODO: Hopefully this auto-updates to ATTACHED_PUMPKIN_STEM when placed next to a pumpkin block..
return Blocks.PUMPKIN_STEM.getDefaultState().with(StemBlock.AGE, data);
case "melon_stem":
// TODO: Hopefully this auto-updates to ATTACHED_MELON_STEM when placed next to a melon block..
return Blocks.MELON_STEM.getDefaultState().with(StemBlock.AGE, data);
case "carved_pumpkin":
return getJackOLanternOrPumpkinWithData(0, data);
case "jack_o_lantern":
case "lit_pumpkin":
return getJackOLanternOrPumpkinWithData(1, data);
case "diode_block_off":
case "repeater":
return getRepeaterWithData(0, data);
case "diode_block_on":
return getRepeaterWithData(1, data);
case "redstone":
case "redstone_wire":
return Blocks.REDSTONE_WIRE.getDefaultState().with(RedstoneWireBlock.POWER, data);
case "redstone_comparator_off":
case "comparator":
return getComparatorWithData(0, data);
case "redstone_comparator_on":
return getComparatorWithData(1, data);
// TODO: How does facing for bed blocks in bo's work for 1.12.2, can only specify color via data?
case "bed_block":
return getBedBlockWithData(data);
case "trap_door":
case "trapdoor":
case "oak_trapdoor":
return getTrapDoorBlockWithData(0, data);
case "iron_trapdoor":
return getTrapDoorBlockWithData(1, data);
case "piston_base":
case "piston":
return getPistonWithData(0, data);
case "piston_sticky_base":
case "sticky_piston":
return getPistonWithData(1, data);
case "piston_extension":
case "piston_head":
return getPistonHeadWithData(data);
case "huge_mushroom_1":
case "brown_mushroom_block":
return getHugeMushroomWithData(0, data);
case "huge_mushroom_2":
case "red_mushroom_block":
return getHugeMushroomWithData(1, data);
case "vine":
return getVineWithData(data);
case "fence_gate":
return getFenceGateWithData(0, data);
case "spruce_fence_gate":
return getFenceGateWithData(1, data);
case "birch_fence_gate":
return getFenceGateWithData(2, data);
case "jungle_fence_gate":
return getFenceGateWithData(3, data);
case "dark_oak_fence_gate":
return getFenceGateWithData(4, data);
case "acacia_fence_gate":
return getFenceGateWithData(5, data);
case "cocoa":
return getCocoaWithData(data);
// What about trip-wire (the wire itself)?
case "tripwire_hook":
return getTripWireHookWithData(data);
case "tripwire":
return getTripWireWithData(data);
case "purpur_pillar":
return Blocks.PURPUR_PILLAR.getDefaultState().with(RotatedPillarBlock.AXIS, getAxisXYZ(data));
case "nether_wart":
return Blocks.NETHER_WART.getDefaultState().with(NetherWartBlock.AGE, data);
case "brewing_stand":
return Blocks.BREWING_STAND.getDefaultState()
.with(BrewingStandBlock.HAS_BOTTLE[0], Boolean.valueOf(getBit(data, 0) == 1))
.with(BrewingStandBlock.HAS_BOTTLE[1], Boolean.valueOf(getBit(data, 1) == 1))
.with(BrewingStandBlock.HAS_BOTTLE[2], Boolean.valueOf(getBit(data, 2) == 1))
;
case "cauldron":
return Blocks.CAULDRON.getDefaultState().with(CauldronBlock.LEVEL, data);
case "portal":
return Blocks.NETHER_PORTAL.getDefaultState().with(NetherPortalBlock.AXIS, getAxisXZ(data));
case "end_portal_frame":
return getEndPortalFrameWithData(data);
case "structure_block":
return getStructureBlockWithData(data);
case "black_glazed_terracotta":
return getGlazedTerracottaWithData(0, data);
case "blue_glazed_terracotta":
return getGlazedTerracottaWithData(1, data);
case "brown_glazed_terracotta":
return getGlazedTerracottaWithData(2, data);
case "cyan_glazed_terracotta":
return getGlazedTerracottaWithData(3, data);
case "gray_glazed_terracotta":
return getGlazedTerracottaWithData(4, data);
case "green_glazed_terracotta":
return getGlazedTerracottaWithData(5, data);
case "light_blue_glazed_terracotta":
return getGlazedTerracottaWithData(6, data);
case "lime_glazed_terracotta":
return getGlazedTerracottaWithData(7, data);
case "magenta_glazed_terracotta":
return getGlazedTerracottaWithData(8, data);
case "orange_glazed_terracotta":
return getGlazedTerracottaWithData(9, data);
case "pink_glazed_terracotta":
return getGlazedTerracottaWithData(10, data);
case "purple_glazed_terracotta":
return getGlazedTerracottaWithData(11, data);
case "red_glazed_terracotta":
return getGlazedTerracottaWithData(12, data);
case "silver_glazed_terracotta":
return getGlazedTerracottaWithData(13, data);
case "white_glazed_terracotta":
return getGlazedTerracottaWithData(14, data);
case "yellow_glazed_terracotta":
return getGlazedTerracottaWithData(15, data);
default:
return null;
}
} catch(IllegalArgumentException ex) {
OTG.log(LogMarker.INFO, "Could not parse block with data, illegal data: " + blockName + ":" + data + ". Exception: " + ex.getMessage());
}
return null;
}
private static BlockState getAnvilWithData(int material, int data)
{
Direction orientation = getBit(data, 0) == 0 ? Direction.NORTH : Direction.WEST;
switch(material)
{
case 0:
// 0x4 0x8 state: regular (0x4 & 0x8 = 0), slightly damaged (0x4 = 1), very damaged (0x8 = 1)
if((getBit(data, 2) & getBit(data, 3)) == 0)
{
return Blocks.ANVIL.getDefaultState().with(AnvilBlock.FACING, orientation);
}
else if(getBit(data, 2) == 1)
{
return Blocks.CHIPPED_ANVIL.getDefaultState().with(AnvilBlock.FACING, orientation);
}
else if(getBit(data, 3) == 1)
{
return Blocks.DAMAGED_ANVIL.getDefaultState().with(AnvilBlock.FACING, orientation);
}
case 1:
return Blocks.CHIPPED_ANVIL.getDefaultState().with(AnvilBlock.FACING, orientation);
case 2:
return Blocks.DAMAGED_ANVIL.getDefaultState().with(AnvilBlock.FACING, orientation);
default:
return null;
}
}
private static BlockState getLogWithData(int data)
{
int material = getBits(data, 0, 2);
int orientation = getBits(data, 2, 2);
Direction.Axis axisDirection = orientation == 0 ? Direction.Axis.Y : orientation == 1 ? Direction.Axis.X : orientation == 2 ? Direction.Axis.Z : Direction.Axis.Y;
switch(material)
{
case 0:
return Blocks.OAK_LOG.getDefaultState().with(RotatedPillarBlock.AXIS, axisDirection);
case 1:
return Blocks.SPRUCE_LOG.getDefaultState().with(RotatedPillarBlock.AXIS, axisDirection);
case 2:
return Blocks.BIRCH_LOG.getDefaultState().with(RotatedPillarBlock.AXIS, axisDirection);
case 3:
return Blocks.JUNGLE_LOG.getDefaultState().with(RotatedPillarBlock.AXIS, axisDirection);
default:
return Blocks.OAK_LOG.getDefaultState();
}
}
private static BlockState getLog2WithData(int data)
{
int material = getBits(data, 0, 2);
int orientation = getBits(data, 2, 2);
Direction.Axis axisDirection = orientation == 0 ? Direction.Axis.Y : orientation == 1 ? Direction.Axis.X : orientation == 2 ? Direction.Axis.Z : Direction.Axis.Y;
switch(material)
{
case 0:
return Blocks.ACACIA_LOG.getDefaultState().with(RotatedPillarBlock.AXIS, axisDirection);
case 1:
return Blocks.DARK_OAK_LOG.getDefaultState().with(RotatedPillarBlock.AXIS, axisDirection);
default:
return Blocks.ACACIA_LOG.getDefaultState();
}
}
private static BlockState getQuartzBlockWithData(int data)
{
switch(data)
{
case 0:
default:
return Blocks.QUARTZ_BLOCK.getDefaultState();
case 1:
return Blocks.CHISELED_QUARTZ_BLOCK.getDefaultState();
case 2:
return Blocks.QUARTZ_PILLAR.getDefaultState().with(RotatedPillarBlock.AXIS, Direction.Axis.Y);
case 3:
return Blocks.QUARTZ_PILLAR.getDefaultState().with(RotatedPillarBlock.AXIS, Direction.Axis.X);
case 4:
return Blocks.QUARTZ_PILLAR.getDefaultState().with(RotatedPillarBlock.AXIS, Direction.Axis.Z);
}
}
private static BlockState getTorchWithData(int material, int data)
{
switch(material)
{
case 0:
switch(data)
{
case 0:
case 5:
default:
return Blocks.TORCH.getDefaultState();
case 1:
return Blocks.WALL_TORCH.getDefaultState().with(WallTorchBlock.HORIZONTAL_FACING, Direction.EAST);
case 2:
return Blocks.WALL_TORCH.getDefaultState().with(WallTorchBlock.HORIZONTAL_FACING, Direction.WEST);
case 3:
return Blocks.WALL_TORCH.getDefaultState().with(WallTorchBlock.HORIZONTAL_FACING, Direction.SOUTH);
case 4:
return Blocks.WALL_TORCH.getDefaultState().with(WallTorchBlock.HORIZONTAL_FACING, Direction.NORTH);
}
case 1:
switch(data)
{
case 0:
case 5:
default:
return Blocks.TORCH.getDefaultState();
case 1:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, false).with(RedstoneWallTorchBlock.FACING, Direction.EAST);
case 2:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, false).with(RedstoneWallTorchBlock.FACING, Direction.WEST);
case 3:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, false).with(RedstoneWallTorchBlock.FACING, Direction.SOUTH);
case 4:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, false).with(RedstoneWallTorchBlock.FACING, Direction.NORTH);
}
case 2:
switch(data)
{
case 0:
case 5:
default:
return Blocks.TORCH.getDefaultState();
case 1:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, true).with(RedstoneWallTorchBlock.FACING, Direction.EAST);
case 2:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, true).with(RedstoneWallTorchBlock.FACING, Direction.WEST);
case 3:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, true).with(RedstoneWallTorchBlock.FACING, Direction.SOUTH);
case 4:
return Blocks.REDSTONE_WALL_TORCH.getDefaultState().with(RedstoneWallTorchBlock.REDSTONE_TORCH_LIT, true).with(RedstoneWallTorchBlock.FACING, Direction.NORTH);
}
default:
return null;
}
}
private static BlockState getRailsWithData(int material, int data)
{
int shape = getBits(data, 0, 3);
int active = getBit(data, 3);
switch(material)
{
case 0:
return Blocks.POWERED_RAIL.getDefaultState().with(PoweredRailBlock.SHAPE, getRailShape(shape)).with(PoweredRailBlock.POWERED, active == 1);
case 1:
return Blocks.DETECTOR_RAIL.getDefaultState().with(DetectorRailBlock.SHAPE, getRailShape(shape)).with(DetectorRailBlock.POWERED, active == 1);
case 2:
return Blocks.ACTIVATOR_RAIL.getDefaultState().with(PoweredRailBlock.SHAPE, getRailShape(shape)).with(PoweredRailBlock.POWERED, active == 1);
default:
return null;
}
}
private static BlockState getStairsWithData(int material, int data)
{
int facing = getBits(data, 0, 2);
int half = getBit(data, 2);
BlockState output = null;
switch(material)
{
case 0:
output = Blocks.OAK_STAIRS.getDefaultState();
break;
case 1:
output = Blocks.BIRCH_STAIRS.getDefaultState();
break;
case 2:
output = Blocks.SPRUCE_STAIRS.getDefaultState();
break;
case 3:
output = Blocks.JUNGLE_STAIRS.getDefaultState();
break;
case 4:
output = Blocks.COBBLESTONE_STAIRS.getDefaultState();
break;
case 5:
output = Blocks.BRICK_STAIRS.getDefaultState();
break;
case 6:
output = Blocks.STONE_STAIRS.getDefaultState();
break;
case 7:
output = Blocks.NETHER_BRICK_STAIRS.getDefaultState();
break;
case 8:
output = Blocks.SANDSTONE_STAIRS.getDefaultState();
break;
case 9:
output = Blocks.QUARTZ_STAIRS.getDefaultState();
break;
case 10:
output = Blocks.ACACIA_STAIRS.getDefaultState();
break;
case 11:
output = Blocks.DARK_OAK_STAIRS.getDefaultState();
break;
case 12:
output = Blocks.RED_SANDSTONE_STAIRS.getDefaultState();
break;
case 13:
output = Blocks.PURPUR_STAIRS.getDefaultState();
break;
case 14:
output = Blocks.STONE_BRICK_STAIRS.getDefaultState();
break;
default:
return null;
}
return output
.with(StairsBlock.FACING, getFacingEastWestSouthNorth(facing))
.with(StairsBlock.HALF, half == 0 ? Half.BOTTOM : Half.TOP);
}
private static BlockState getLeverOrButtonWithData(int material, int data)
{
int facing = getBits(data, 0, 3);
int powered = getBit(data, 3);
AttachFace face = facing == 0 || facing == 7 ? AttachFace.CEILING : facing == 1 || facing == 2 || facing == 3 || facing == 4 ? AttachFace.WALL : facing == 5 || facing == 6 ? AttachFace.FLOOR : AttachFace.FLOOR;
switch(material)
{
case 0:
return Blocks.LEVER.getDefaultState().with(LeverBlock.FACE, face).with(LeverBlock.HORIZONTAL_FACING, getFacingLever(facing)).with(LeverBlock.POWERED, powered == 1);
case 1:
return Blocks.STONE_BUTTON.getDefaultState().with(StoneButtonBlock.FACE, face).with(StoneButtonBlock.HORIZONTAL_FACING, getFacingButton(facing)).with(StoneButtonBlock.POWERED, powered == 1);
case 2:
return Blocks.OAK_BUTTON.getDefaultState().with(WoodButtonBlock.FACE, face).with(WoodButtonBlock.HORIZONTAL_FACING, getFacingButton(facing)).with(WoodButtonBlock.POWERED, powered == 1);
default:
return null;
}
}
private static BlockState getDoorWithData(int material, int data)
{
// 0x8 Half
// Top half of door:
// 0x1 Hinge side
// 0x2 powered
// Bottom half of door:
// 0x1 0x2 facing
// 0x4 closed/open
int half = getBit(data, 3);
int hinge = getBit(data, 0);
int powered = getBit(data, 1);
int facing = getBits(data, 0, 2);
int open = getBit(data, 2);
BlockState blockState;
switch(material)
{
case 0:
blockState = Blocks.OAK_DOOR.getDefaultState();
break;
case 1:
blockState = Blocks.IRON_DOOR.getDefaultState();
break;
case 2:
blockState = Blocks.SPRUCE_DOOR.getDefaultState();
break;
case 3:
blockState = Blocks.BIRCH_DOOR.getDefaultState();
break;
case 4:
blockState = Blocks.JUNGLE_DOOR.getDefaultState();
break;
case 5:
blockState = Blocks.ACACIA_DOOR.getDefaultState();
break;
case 6:
blockState = Blocks.DARK_OAK_DOOR.getDefaultState();
break;
default:
return null;
}
return half == 0 ?
blockState
.with(DoorBlock.HALF, DoubleBlockHalf.LOWER)
.with(DoorBlock.FACING, getFacingEastSouthWestNorth(facing))
.with(DoorBlock.OPEN, open == 1)
: blockState
.with(DoorBlock.HALF, DoubleBlockHalf.UPPER)
.with(DoorBlock.HINGE, hinge == 0 ? DoorHingeSide.LEFT : DoorHingeSide.RIGHT)
.with(DoorBlock.POWERED, powered == 1)
;
}
private static BlockState getSignPostWithData(int data)
{
int rotation = getBits(data, 0, 4);
// TODO: Hopefully rotation is still mapped to the same int values as 1.12..
return Blocks.OAK_SIGN.getDefaultState().with(StandingSignBlock.ROTATION, rotation);
}
private static BlockState getWallSignWithData(int data)
{
int facing = getBits(data, 0, 3);
return Blocks.OAK_WALL_SIGN.getDefaultState().with(WallSignBlock.FACING, getFacingNorthSouthWestEast(facing));
}
// TODO: Can't find information on 1.12 command block block data, what about facing?
private static BlockState getCommandBlockWithData(int material, int data)
{
BlockState blockState;
switch(material)
{
case 0:
blockState = Blocks.COMMAND_BLOCK.getDefaultState();
break;
case 1:
blockState = Blocks.REPEATING_COMMAND_BLOCK.getDefaultState();
break;
case 2:
blockState = Blocks.CHAIN_COMMAND_BLOCK.getDefaultState();
break;
default:
return null;
}
return blockState;
}
// TODO: Can't find information on 1.12 command block block data, what about facing?
private static BlockState getShulkerBoxWithData(int material, int data)
{
BlockState blockState;
switch(material)
{
case 0:
blockState = Blocks.WHITE_SHULKER_BOX.getDefaultState();
break;
case 1:
blockState = Blocks.ORANGE_SHULKER_BOX.getDefaultState();
break;
case 2:
blockState = Blocks.MAGENTA_SHULKER_BOX.getDefaultState();
break;
case 3:
blockState = Blocks.LIGHT_BLUE_SHULKER_BOX.getDefaultState();;
break;
case 4:
blockState = Blocks.YELLOW_SHULKER_BOX.getDefaultState();
break;
case 5:
blockState = Blocks.YELLOW_SHULKER_BOX.getDefaultState();
break;
case 6:
blockState = Blocks.LIME_SHULKER_BOX.getDefaultState();
break;
case 7:
blockState = Blocks.PINK_SHULKER_BOX.getDefaultState();
break;
case 8:
blockState = Blocks.GRAY_SHULKER_BOX.getDefaultState();
break;
case 9:
blockState = Blocks.SHULKER_BOX.getDefaultState();
break;
case 10:
blockState = Blocks.CYAN_SHULKER_BOX.getDefaultState();
break;
case 11:
blockState = Blocks.PURPLE_SHULKER_BOX.getDefaultState();
break;
case 12:
blockState = Blocks.BLUE_SHULKER_BOX.getDefaultState();
break;
case 13:
blockState = Blocks.BROWN_SHULKER_BOX.getDefaultState();
break;
case 14:
blockState = Blocks.GREEN_SHULKER_BOX.getDefaultState();
break;
case 15:
blockState = Blocks.RED_SHULKER_BOX.getDefaultState();
break;
case 16:
blockState = Blocks.BLACK_SHULKER_BOX.getDefaultState();
break;
default:
return null;
}
return blockState.with(ShulkerBoxBlock.FACING, getFacingDownEastNorthSouthUpWest(data));
}
private static BlockState getLadderChestOrFurnaceWithData(int material, int data)
{
int facing = getBits(data, 0, 3);
switch(material)
{
case 0:
return Blocks.LADDER.getDefaultState().with(LadderBlock.FACING, getFacingNorthSouthWestEast(facing));
case 1:
return Blocks.CHEST.getDefaultState().with(ChestBlock.FACING, getFacingNorthSouthWestEast(facing));
case 2:
return Blocks.ENDER_CHEST.getDefaultState().with(EnderChestBlock.FACING, getFacingNorthSouthWestEast(facing));
case 3:
return Blocks.TRAPPED_CHEST.getDefaultState().with(TrappedChestBlock.FACING, getFacingNorthSouthWestEast(facing));
case 4:
return Blocks.FURNACE.getDefaultState().with(FurnaceBlock.FACING, getFacingNorthSouthWestEast(facing)).with(FurnaceBlock.LIT, false);
case 5:
return Blocks.FURNACE.getDefaultState().with(FurnaceBlock.FACING, getFacingNorthSouthWestEast(facing)).with(FurnaceBlock.LIT, true);
default:
return null;
}
}
private static BlockState getDispenserHopperDropperWithData(int material, int data)
{
int facing = getBits(data, 0, 3);
int active = getBit(data, 3);
switch(material)
{
case 0:
return Blocks.DISPENSER.getDefaultState().with(DispenserBlock.FACING, getFacingDownUpNorthSouthWestEast(facing)).with(DispenserBlock.TRIGGERED, active == 1);
case 1:
return Blocks.DROPPER.getDefaultState().with(DropperBlock.FACING, getFacingDownUpNorthSouthWestEast(facing)).with(DropperBlock.TRIGGERED, active == 1);
case 2:
return Blocks.HOPPER.getDefaultState().with(HopperBlock.FACING, getFacingDownUpNorthSouthWestEast(facing)).with(HopperBlock.ENABLED, active == 1);
default:
return null;
}
}
private static BlockState getJackOLanternOrPumpkinWithData(int material, int data)
{
int facing = getBits(data, 0, 2);
switch(material)
{
case 0:
return Blocks.CARVED_PUMPKIN.getDefaultState().with(CarvedPumpkinBlock.FACING, getFacingSouthWestNorthEast(facing));
case 1:
return Blocks.JACK_O_LANTERN.getDefaultState().with(CarvedPumpkinBlock.FACING, getFacingSouthWestNorthEast(facing));
default:
return null;
}
}
private static BlockState getObserverWithData(int data)
{
int facing = getBits(data, 0, 3);
int powered = getBit(data, 3);
return Blocks.OBSERVER.getDefaultState().with(ObserverBlock.FACING, getFacingDownUpNorthSouthWestEast(facing)).with(ObserverBlock.POWERED, powered == 1);
}
private static BlockState getRepeaterWithData(int material, int data)
{
int facing = getBits(data, 0, 2);
int delay = getBits(data, 2, 2) + 1;
BlockState blockState;
switch(material)
{
case 0:
blockState = Blocks.REPEATER.getDefaultState().with(RepeaterBlock.POWERED, false);
break;
case 1:
blockState = Blocks.REPEATER.getDefaultState().with(RepeaterBlock.POWERED, true);
break;
default:
return null;
}
return blockState
.with(RepeaterBlock.DELAY, delay)
.with(RepeaterBlock.HORIZONTAL_FACING, getFacingNorthEastSouthWest(facing))
;
}
private static BlockState getComparatorWithData(int material, int data)
{
int facing = getBits(data, 0, 2);
int mode = getBit(data, 2);
int powered = material == 1 ? 1 : getBit(data, 3);
return Blocks.COMPARATOR.getDefaultState()
.with(ComparatorBlock.HORIZONTAL_FACING, getFacingNorthEastSouthWest(facing))
.with(ComparatorBlock.MODE, mode == 0 ? ComparatorMode.COMPARE : ComparatorMode.SUBTRACT)
.with(ComparatorBlock.POWERED, powered == 1)
;
}
private static BlockState getBedBlockWithData(int data)
{
int facing = getBits(data, 0, 2);
int occupied = getBit(data, 2);
int part = getBit(data, 3);
return Blocks.WHITE_BED.getDefaultState()
.with(BedBlock.HORIZONTAL_FACING, getFacingSouthWestNorthEast(facing))
.with(BedBlock.OCCUPIED, occupied == 1)
.with(BedBlock.PART, part == 0 ? BedPart.FOOT : BedPart.HEAD)
;
}
private static BlockState getTrapDoorBlockWithData(int material, int data)
{
int facing = getBits(data, 0, 2);
int open = getBit(data, 2);
int half = getBit(data, 3);
BlockState blockState;
switch(material)
{
case 0:
blockState = Blocks.OAK_TRAPDOOR.getDefaultState();
break;
case 1:
blockState = Blocks.IRON_TRAPDOOR.getDefaultState();
break;
default:
return null;
}
return blockState
.with(TrapDoorBlock.HORIZONTAL_FACING, getFacingSouthNorthEastWest(facing))
.with(TrapDoorBlock.HALF, half == 0 ? Half.BOTTOM : Half.TOP)
.with(TrapDoorBlock.OPEN, open == 1)
;
}
private static BlockState getPistonWithData(int material, int data)
{
int facing = getBits(data, 0, 3);
int extended = getBit(data, 3);
switch(material)
{
case 0:
return Blocks.PISTON.getDefaultState().with(PistonBlock.EXTENDED, extended == 1).with(PistonBlock.FACING, getFacingDownUpNorthSouthWestEast(facing));
case 1:
return Blocks.STICKY_PISTON.getDefaultState().with(PistonBlock.EXTENDED, extended == 1).with(PistonBlock.FACING, getFacingDownUpNorthSouthWestEast(facing));
default:
return null;
}
}
private static BlockState getPistonHeadWithData(int data)
{
int facing = getBits(data, 0, 3);
int type = getBit(data, 3);
return Blocks.PISTON_HEAD.getDefaultState()
.with(PistonHeadBlock.FACING, getFacingDownUpNorthSouthWestEast(facing))
.with(PistonHeadBlock.TYPE, type == 0 ? PistonType.DEFAULT : PistonType.STICKY)
;
}
private static BlockState getHugeMushroomWithData(int material, int data)
{
boolean down = data == 14 || data == 15;
boolean up = data == 1 || data == 2 || data == 3 || data == 4 || data == 5 || data == 6 || data == 7 || data == 8 || data == 9 || data == 14 || data == 15;
boolean north = data == 1 || data == 2 || data == 3 || data == 10 || data == 14 || data == 15;
boolean east = data == 3 || data == 6 || data == 9 || data == 10 || data == 14 || data == 15;
boolean south = data == 7 || data == 8 || data == 9 || data == 10 || data == 14 || data == 15;
boolean west = data == 1 || data == 4 || data == 7 || data == 10 || data == 14 || data == 15;
BlockState blockState;
if(data == 10 || data == 15)
{
blockState = Blocks.MUSHROOM_STEM.getDefaultState();
} else {
switch(material)
{
case 0:
blockState = Blocks.BROWN_MUSHROOM_BLOCK.getDefaultState();
break;
case 1:
blockState = Blocks.RED_MUSHROOM_BLOCK.getDefaultState();
break;
default:
return null;
}
}
return blockState
.with(HugeMushroomBlock.DOWN, down)
.with(HugeMushroomBlock.UP, up)
.with(HugeMushroomBlock.NORTH, north)
.with(HugeMushroomBlock.EAST, east)
.with(HugeMushroomBlock.SOUTH, south)
.with(HugeMushroomBlock.WEST, west)
;
}
private static BlockState getVineWithData(int data)
{
int south = getBit(data, 0);
int west = getBit(data, 1);
int north = getBit(data, 2);
int east = getBit(data, 3);
int up = data == 0 ? 1 : 0; // TODO: Should also be true if there's a block above, test if this is done dynamically.
return Blocks.VINE.getDefaultState()
.with(VineBlock.EAST, east == 1)
.with(VineBlock.NORTH, north == 1)
.with(VineBlock.SOUTH, south == 1)
.with(VineBlock.WEST, west == 1)
.with(VineBlock.UP, up == 1)
;
}
private static BlockState getFenceGateWithData(int material, int data)
{
int facing = getBits(data, 0, 2);
int open = getBit(data, 2);
BlockState blockState;
switch(material)
{
case 0:
blockState = Blocks.BIRCH_FENCE_GATE.getDefaultState();
break;
case 1:
blockState = Blocks.OAK_FENCE_GATE.getDefaultState();
break;
case 2:
blockState = Blocks.SPRUCE_FENCE_GATE.getDefaultState();
break;
case 3:
blockState = Blocks.JUNGLE_FENCE_GATE.getDefaultState();
break;
case 4:
blockState = Blocks.DARK_OAK_FENCE_GATE.getDefaultState();
break;
case 5:
blockState = Blocks.ACACIA_FENCE_GATE.getDefaultState();
break;
default:
return null;
}
return blockState
.with(FenceGateBlock.HORIZONTAL_FACING, getFacingSouthWestNorthEast(facing))
.with(FenceGateBlock.OPEN, open == 1)
;
}
private static BlockState getCocoaWithData(int data)
{
int facing = getBits(data, 0, 2);
int age = getBits(data, 2, 2);
return Blocks.COCOA.getDefaultState().with(CocoaBlock.HORIZONTAL_FACING, getFacingNorthEastSouthWest(facing)).with(CocoaBlock.AGE, age);
}
private static BlockState getTripWireHookWithData(int data)
{
int facing = getBits(data, 0, 2);
int attached = getBit(data, 2);
int powered = getBit(data, 3);
return Blocks.TRIPWIRE_HOOK.getDefaultState()
.with(TripWireHookBlock.ATTACHED, attached == 1)
.with(TripWireHookBlock.FACING, getFacingSouthWestNorthEast(facing))
.with(TripWireHookBlock.POWERED, powered == 1)
;
}
private static BlockState getEndPortalFrameWithData(int data)
{
int facing = getBits(data, 0, 2);
int eye = getBit(data, 2);
return Blocks.END_PORTAL_FRAME.getDefaultState().with(EndPortalFrameBlock.EYE, eye == 1).with(EndPortalFrameBlock.FACING, getFacingSouthWestNorthEast(facing));
}
private static BlockState getStructureBlockWithData(int data)
{
StructureMode structureBlockMode = data == 0 ? StructureMode.DATA : data == 1 ? StructureMode.SAVE : data == 2 ? StructureMode.LOAD : data == 3 ? StructureMode.LOAD : StructureMode.DATA;
return Blocks.STRUCTURE_BLOCK.getDefaultState().with(StructureBlock.MODE, structureBlockMode);
}
private static BlockState getGlazedTerracottaWithData(int material, int data)
{
int facing = getBits(data, 0, 2);
BlockState blockState;
switch(material)
{
case 0:
blockState = Blocks.BLACK_GLAZED_TERRACOTTA.getDefaultState();
break;
case 1:
blockState = Blocks.BLUE_GLAZED_TERRACOTTA.getDefaultState();
break;
case 2:
blockState = Blocks.BROWN_GLAZED_TERRACOTTA.getDefaultState();
break;
case 3:
blockState = Blocks.CYAN_GLAZED_TERRACOTTA.getDefaultState();
break;
case 4:
blockState = Blocks.GRAY_GLAZED_TERRACOTTA.getDefaultState();
break;
case 5:
blockState = Blocks.GREEN_GLAZED_TERRACOTTA.getDefaultState();
break;
case 6:
blockState = Blocks.LIGHT_BLUE_GLAZED_TERRACOTTA.getDefaultState();
break;
case 7:
blockState = Blocks.LIME_GLAZED_TERRACOTTA.getDefaultState();
break;
case 8:
blockState = Blocks.MAGENTA_GLAZED_TERRACOTTA.getDefaultState();
break;
case 9:
blockState = Blocks.ORANGE_GLAZED_TERRACOTTA.getDefaultState();
break;
case 10:
blockState = Blocks.PINK_GLAZED_TERRACOTTA.getDefaultState();
break;
case 11:
blockState = Blocks.PURPLE_GLAZED_TERRACOTTA.getDefaultState();
break;
case 12:
blockState = Blocks.RED_GLAZED_TERRACOTTA.getDefaultState();
break;
case 13:
blockState = Blocks.LIGHT_GRAY_GLAZED_TERRACOTTA.getDefaultState();
break;
case 14:
blockState = Blocks.WHITE_GLAZED_TERRACOTTA.getDefaultState();
break;
case 15:
blockState = Blocks.YELLOW_GLAZED_TERRACOTTA.getDefaultState();
break;
default:
return Blocks.BLACK_GLAZED_TERRACOTTA.getDefaultState();
}
return blockState.with(GlazedTerracottaBlock.HORIZONTAL_FACING, getFacingSouthWestNorthEast(facing));
}
private static BlockState getTripWireWithData(int data)
{
int active = getBit(data, 0);
int attached = getBit(data, 2);
int disarmed = getBit(data, 3);
return Blocks.TRIPWIRE.getDefaultState()
.with(TripWireBlock.POWERED, active == 1)
.with(TripWireBlock.ATTACHED, attached == 1)
.with(TripWireBlock.DISARMED, disarmed == 1)
;
}
private static Direction.Axis getAxisXYZ(int data)
{
switch(data)
{
case 0:
return Direction.Axis.X;
case 1:
return Direction.Axis.Y;
case 2:
return Direction.Axis.Z;
default:
return Direction.Axis.Y;
}
}
private static Direction.Axis getAxisXZ(int data)
{
switch(data)
{
case 1:
return Direction.Axis.X;
case 2:
return Direction.Axis.Z;
default:
return Direction.Axis.X;
}
}
private static Direction getFacingSouthWestNorthEast(int data)
{
switch(data)
{
case 0:
return Direction.SOUTH;
case 1:
return Direction.WEST;
case 2:
return Direction.NORTH;
case 3:
return Direction.EAST;
default:
return Direction.SOUTH;
}
}
private static Direction getFacingNorthSouthWestEast(int data)
{
switch(data)
{
case 2:
return Direction.NORTH;
case 3:
return Direction.SOUTH;
case 4:
return Direction.WEST;
case 5:
return Direction.EAST;
default:
return Direction.NORTH;
}
}
private static Direction getFacingNorthEastSouthWest(int data)
{
switch(data)
{
case 0:
return Direction.NORTH;
case 1:
return Direction.EAST;
case 2:
return Direction.SOUTH;
case 3:
return Direction.WEST;
default:
return Direction.NORTH;
}
}
private static Direction getFacingDownUpNorthSouthWestEast(int data)
{
switch(data)
{
case 0:
return Direction.DOWN;
case 1:
return Direction.UP;
case 2:
return Direction.NORTH;
case 3:
return Direction.SOUTH;
case 4:
return Direction.WEST;
case 5:
return Direction.EAST;
default:
return Direction.DOWN;
}
}
private static Direction getFacingSouthNorthEastWest(int data)
{
switch(data)
{
case 0:
return Direction.SOUTH;
case 1:
return Direction.NORTH;
case 2:
return Direction.EAST;
case 3:
return Direction.WEST;
default:
return Direction.SOUTH;
}
}
private static Direction getFacingEastSouthWestNorth(int data)
{
switch(data)
{
case 0:
return Direction.EAST;
case 1:
return Direction.SOUTH;
case 2:
return Direction.WEST;
case 3:
return Direction.NORTH;
default:
return Direction.EAST;
}
}
private static Direction getFacingEastWestSouthNorth(int data)
{
switch(data)
{
case 0:
return Direction.EAST;
case 1:
return Direction.WEST;
case 2:
return Direction.SOUTH;
case 3:
return Direction.NORTH;
default:
return Direction.EAST;
}
}
// TODO: Couldn't find docs for 1.12.2 shulker box
// data values, these rotations may be incorrect.
private static Direction getFacingDownEastNorthSouthUpWest(int data)
{
switch(data)
{
case 0:
return Direction.DOWN;
case 1:
return Direction.EAST;
case 2:
return Direction.NORTH;
case 3:
return Direction.SOUTH;
case 4:
return Direction.UP;
case 5:
return Direction.WEST;
default:
return Direction.UP;
}
}
// TODO: Test this
private static Direction getFacingLever(int data)
{
switch(data)
{
case 0:
case 1:
case 6:
return Direction.EAST;
case 2:
return Direction.WEST;
case 3:
case 5:
case 7:
return Direction.SOUTH;
case 4:
return Direction.NORTH;
default:
return Direction.EAST;
}
}
private static Direction getFacingButton(int data)
{
switch(data)
{
case 1:
return Direction.EAST;
case 2:
return Direction.WEST;
case 3:
return Direction.SOUTH;
case 4:
return Direction.NORTH;
default:
return Direction.EAST;
}
}
private static RailShape getRailShape(int shape)
{
switch (shape)
{
case 0:
return RailShape.NORTH_SOUTH;
case 1:
return RailShape.EAST_WEST;
case 2:
return RailShape.ASCENDING_EAST;
case 3:
return RailShape.ASCENDING_WEST;
case 4:
return RailShape.ASCENDING_NORTH;
case 5:
return RailShape.ASCENDING_SOUTH;
case 6:
return RailShape.SOUTH_EAST;
case 7:
return RailShape.SOUTH_WEST;
case 8:
return RailShape.NORTH_WEST;
case 9:
return RailShape.NORTH_EAST;
default:
return RailShape.NORTH_SOUTH;
}
}
private static int getBits(int source, int index, int length)
{
int bits = 0;
for(int i = 0; i < length; i++)
{
bits = bits | (getBit(source, index + i) << i);
}
return bits;
}
private static int getBit(int source, int index)
{
return ((source & (1 << index)) >> index);
}
}
|
package org.rakam.collection.mapper.geoip;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.Country;
import org.apache.avro.generic.GenericRecord;
import org.rakam.collection.Event;
import org.rakam.collection.FieldType;
import org.rakam.collection.SchemaField;
import org.rakam.collection.event.FieldDependencyBuilder;
import org.rakam.plugin.EventMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class GeoIPEventMapper implements EventMapper {
final static Logger LOGGER = LoggerFactory.getLogger(GeoIPEventMapper.class);
private final static List<String> ATTRIBUTES = ImmutableList.of("country","countryCode","region","city","latitude","longitude","timezone");
DatabaseReader lookup;
String[] attributes;
public GeoIPEventMapper(GeoIPModuleConfig config) throws IOException {
Preconditions.checkNotNull(config, "config is null");
InputStream database;
if(config.getDatabase() != null) {
database = new FileInputStream(config.getDatabase());
}else {
URL resource = getClass().getClassLoader().getResource("data/GeoLite2-Country.mmdb");
if(resource == null) {
throw new IllegalStateException("GeoIP module is enabled but database location is not set. Please set plugin.geoip.database.");
}
database = resource.openStream();
}
lookup = new DatabaseReader.Builder(database).build();
if(config.getAttributes() != null) {
for (String attr : config.getAttributes()) {
if(!ATTRIBUTES.contains(attr)) {
throw new IllegalArgumentException("Attribute "+attr+" is not exist. Available attributes: " +
Joiner.on(", ").join(ATTRIBUTES));
}
}
attributes = config.getAttributes().stream().toArray(String[]::new);
} else {
attributes = ATTRIBUTES.toArray(new String[ATTRIBUTES.size()]);
}
}
@Override
public void map(Event event) {
GenericRecord properties = event.properties();
Object IP = properties.get("ip");
InetAddress ipAddress;
try {
if(!(IP instanceof String)) {
return;
}
ipAddress = InetAddress.getByName((String) IP);
if(ipAddress == null) {
return;
}
} catch (UnknownHostException e) {
return;
}
// TODO: lazy initialization
CityResponse response;
try {
response = lookup.city(ipAddress);
} catch (IOException e) {
LOGGER.error("Error while search for location information. ", e);
return;
} catch (GeoIp2Exception e) {
return;
}
Country country = response.getCountry();
for (String attribute : attributes) {
switch (attribute) {
case "country":
properties.put("country", country.getName());
break;
case "countryCode":
properties.put("countryCode", country.getIsoCode());
break;
case "region":
properties.put("region", response.getContinent());
break;
case "city":
properties.put("city", response.getCity().getName());
break;
case "latitude":
properties.put("latitude", response.getLocation().getLatitude());
break;
case "longitude":
properties.put("longitude", response.getLocation().getLongitude());
break;
case "timezone":
properties.put("timezone", response.getLocation().getTimeZone());
break;
}
}
}
@Override
public void addFieldDependency(FieldDependencyBuilder builder) {
builder.addFields("ip", Arrays.stream(attributes)
.map(attr -> new SchemaField(attr, FieldType.STRING, true))
.collect(Collectors.toList()));
}
}
|
package org.eclipse.birt.report.model.command;
import org.eclipse.birt.report.model.activity.AbstractElementCommand;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.command.StyleException;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.birt.report.model.core.DesignElement;
import org.eclipse.birt.report.model.core.Module;
import org.eclipse.birt.report.model.core.StyledElement;
import org.eclipse.birt.report.model.elements.Theme;
import org.eclipse.birt.report.model.elements.interfaces.IStyledElementModel;
import org.eclipse.birt.report.model.metadata.ElementPropertyDefn;
import org.eclipse.birt.report.model.metadata.ElementRefValue;
/**
* Sets the style property of an element.
*
*/
public class StyleCommand extends AbstractElementCommand
{
/**
* Constructor.
*
* @param module
* the root of <code>obj</code>
* @param obj
* the element to modify.
*/
public StyleCommand( Module module, DesignElement obj )
{
super( module, obj );
}
/**
* Sets the style of an element.
*
* @param name
* the name of the style to set.
* @throws StyleException
* if the element can not have style or the style is not found.
*/
public void setStyle( String name ) throws StyleException
{
name = StringUtil.trimString( name );
// Ensure that the element can have a style.
if ( !element.getDefn( ).hasStyle( ) )
throw new StyleException( element, name,
StyleException.DESIGN_EXCEPTION_FORBIDDEN );
StyledElement obj = (StyledElement) element;
// Ensure that the style exists.
ElementPropertyDefn propDefn = obj
.getPropertyDefn( IStyledElementModel.STYLE_PROP );
if ( name == null && obj.getStyleName( ) == null )
return;
Object retValue = null;
try
{
retValue = propDefn.validateValue( module, name );
}
catch ( PropertyValueException e )
{
assert false;
}
// Make the change.
doSetStyleRefValue( (ElementRefValue) retValue );
}
/**
* Sets the style of an element given the style itself.
*
* @param style
* the style element to set.
* @throws StyleException
* if the element can not have style or the style is not found.
*/
public void setStyleElement( DesignElement style ) throws StyleException
{
// Make the change starting with the name. This will handle the
// case where the application is trying to set a style that is
// not part of the design.
String name = null;
if ( style != null )
name = style.getName( );
setStyle( name );
}
/**
* Sets the extends attribute for an element given the new parent element.
*
* @param parent
* the new parent element.
* @throws StyleException
* if the element can not be extended or the base element is not
* on component slot, or the base element has no name.
*/
public void setStyleElement( StyleHandle parent ) throws StyleException
{
if ( parent == null )
{
setStyle( null );
return;
}
setStyle( parent.getName( ) );
}
/**
* Sets the theme with the given element reference value. Call this method
* when the theme name or theme element has been validated. Otherwise, uses
* {@link #setStyle(String)} or {@link #setStyleElement(Theme)}.
*
* @param refValue
* the validated reference value
* @throws StyleException
* if the style is not found.
*/
protected void setStyleRefValue( ElementRefValue refValue )
throws StyleException
{
if ( refValue == null )
{
if ( ( element instanceof StyledElement )
&& ( ( (StyledElement) element ).getStyleName( ) == null ) )
{
return;
}
}
doSetStyleRefValue( refValue );
}
/**
* Does the work to set the new style with the given
* <code>newStyleValue</code>.
*
* @param newStyleValue
* the validated <code>ElementRefValue</code>
*/
private void doSetStyleRefValue( ElementRefValue newStyleValue )
throws StyleException
{
if ( newStyleValue != null && !newStyleValue.isResolved( ) )
throw new StyleException( element, newStyleValue.getName( ),
StyleException.DESIGN_EXCEPTION_NOT_FOUND );
if ( newStyleValue != null && newStyleValue.isResolved( )
&& newStyleValue.getElement( ) == element.getStyle( ) )
return;
// Make the change.
StyledElement obj = (StyledElement) element;
StyleRecord record = new StyleRecord( obj, newStyleValue );
getActivityStack( ).execute( record );
}
}
|
package name.abuchen.portfolio.ui.views.dashboard;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Optional;
import java.util.function.Supplier;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.money.ExchangeRate;
import name.abuchen.portfolio.money.ExchangeRateTimeSeries;
import name.abuchen.portfolio.money.Values;
import name.abuchen.portfolio.snapshot.ReportingPeriod;
import name.abuchen.portfolio.ui.Messages;
import name.abuchen.portfolio.ui.util.InfoToolTip;
import name.abuchen.portfolio.util.TextUtil;
public class ExchangeRateWidget extends WidgetDelegate<Object>
{
private DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.withZone(ZoneId.systemDefault());
private Label title;
private Label indicator;
public ExchangeRateWidget(Widget widget, DashboardData dashboardData)
{
super(widget, dashboardData);
addConfig(new ExchangeRateSeriesConfig(this));
addConfig(new ReportingPeriodConfig(this));
}
@Override
public Composite createControl(Composite parent, DashboardResources resources)
{
Composite container = new Composite(parent, SWT.NONE);
container.setBackground(parent.getBackground());
GridLayoutFactory.fillDefaults().numColumns(1).margins(5, 5).applyTo(container);
title = new Label(container, SWT.NONE);
title.setText(TextUtil.tooltip(getWidget().getLabel()));
title.setBackground(container.getBackground());
GridDataFactory.fillDefaults().grab(true, false).applyTo(title);
indicator = new Label(container, SWT.NONE);
indicator.setFont(resources.getKpiFont());
indicator.setBackground(container.getBackground());
indicator.setText(""); //$NON-NLS-1$
GridDataFactory.fillDefaults().grab(true, false).applyTo(indicator);
InfoToolTip.attach(indicator, () -> {
ReportingPeriod period = get(ReportingPeriodConfig.class).getReportingPeriod();
ExchangeRateTimeSeries series = get(ExchangeRateSeriesConfig.class).getSeries();
Optional<ExchangeRate> rate = series.lookupRate(period.toInterval(LocalDate.now()).getEnd());
return rate.isPresent() ? MessageFormat.format(Messages.TooltipDateOfExchangeRate,
formatter.format(rate.get().getTime())) : ""; //$NON-NLS-1$
});
update(null);
return container;
}
@Override
public Control getTitleControl()
{
return title;
}
@Override
public Supplier<Object> getUpdateTask()
{
return () -> null;
}
@Override
public void update(Object data)
{
this.title.setText(TextUtil.tooltip(getWidget().getLabel()));
ReportingPeriod period = get(ReportingPeriodConfig.class).getReportingPeriod();
ExchangeRateTimeSeries series = get(ExchangeRateSeriesConfig.class).getSeries();
Optional<ExchangeRate> rate = series.lookupRate(period.toInterval(LocalDate.now()).getEnd());
this.indicator.setText(series.getBaseCurrency() + '/' + series.getTermCurrency() + ' '
+ (rate.isPresent() ? Values.ExchangeRate.format(rate.get().getValue()) : '-'));
}
}
|
package org.navalplanner.business.orders.entities;
import static org.navalplanner.business.i18n.I18nHelper._;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.Validate;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.Valid;
import org.joda.time.LocalDate;
import org.navalplanner.business.advance.entities.AdvanceAssignment;
import org.navalplanner.business.advance.entities.AdvanceType;
import org.navalplanner.business.advance.entities.DirectAdvanceAssignment;
import org.navalplanner.business.advance.entities.IndirectAdvanceAssignment;
import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException;
import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException;
import org.navalplanner.business.common.BaseEntity;
import org.navalplanner.business.labels.entities.Label;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.orders.entities.SchedulingState.ITypeChangedListener;
import org.navalplanner.business.orders.entities.SchedulingState.Type;
import org.navalplanner.business.orders.entities.TaskSource.TaskSourceSynchronization;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.business.planner.entities.TaskElement;
import org.navalplanner.business.requirements.entities.CriterionRequirement;
import org.navalplanner.business.requirements.entities.DirectCriterionRequirement;
import org.navalplanner.business.requirements.entities.IndirectCriterionRequirement;
import org.navalplanner.business.resources.entities.Criterion;
public abstract class OrderElement extends BaseEntity {
@NotEmpty(message = "name not specified")
private String name;
private Date initDate;
private Date deadline;
private Boolean mandatoryInit = false;
private Boolean mandatoryEnd = false;
private String description;
protected Set<DirectAdvanceAssignment> directAdvanceAssignments = new HashSet<DirectAdvanceAssignment>();
protected Set<MaterialAssignment> materialAssignments = new HashSet<MaterialAssignment>();
private Set<Label> labels = new HashSet<Label>();
@NotEmpty(message = "code not specified")
private String code;
private Set<CriterionRequirement> criterionRequirements = new HashSet<CriterionRequirement>();
protected OrderLineGroup parent;
protected CriterionRequirementHandler criterionRequirementHandler = CriterionRequirementHandler
.getInstance();
private SchedulingState.Type schedulingStateType = Type.NO_SCHEDULED;
/**
* This field is transient
*/
private SchedulingState schedulingState = null;
private TaskSource taskSource;
public SchedulingState getSchedulingState() {
if (schedulingState == null) {
schedulingState = createSchedulingState();
}
return schedulingState;
}
private SchedulingState createSchedulingState() {
List<SchedulingState> childrenStates = getChildrenStates();
SchedulingState result = childrenStates.isEmpty() ? new SchedulingState(
getSchedulingStateType())
: new SchedulingState(schedulingStateType, childrenStates);
schedulingStateType = result.getType();
result.addTypeChangeListener(new ITypeChangedListener() {
@Override
public void typeChanged(Type newType) {
schedulingStateType = newType;
}
});
return result;
}
private List<SchedulingState> getChildrenStates() {
List<SchedulingState> result = new ArrayList<SchedulingState>();
for (OrderElement each : getChildren()) {
result.add(each.getSchedulingState());
}
return result;
}
public List<TaskSourceSynchronization> calculateSynchronizationsNeeded() {
List<TaskSourceSynchronization> result = new ArrayList<TaskSourceSynchronization>();
if (isSchedulingPoint()) {
result.add(synchronizationForSchedulingPoint());
} else if (isSuperElementPartialOrCompletelyScheduled()) {
removeUnscheduled(result);
result.add(synchronizationForSuperelement());
} else if (schedulingState.isNoScheduled()) {
removeTaskSource(result);
}
return result;
}
private TaskSourceSynchronization synchronizationForSuperelement() {
List<TaskSourceSynchronization> childrenSynchronizations = childrenSynchronizations();
if (thereIsNoTaskSource()) {
taskSource = TaskSource.createForGroup(this);
return TaskSource
.mustAddGroup(taskSource,
childrenSynchronizations);
} else {
return taskSource.modifyGroup(childrenSynchronizations);
}
}
private List<TaskSourceSynchronization> childrenSynchronizations() {
List<TaskSourceSynchronization> childrenOfGroup = new ArrayList<TaskSourceSynchronization>();
for (OrderElement orderElement : getSomewhatScheduledOrderElements()) {
childrenOfGroup.addAll(orderElement
.calculateSynchronizationsNeeded());
}
return childrenOfGroup;
}
private void removeUnscheduled(List<TaskSourceSynchronization> result) {
for (OrderElement orderElement : getNoScheduledOrderElements()) {
orderElement.removeTaskSource(result);
}
}
private TaskSourceSynchronization synchronizationForSchedulingPoint() {
if (thereIsNoTaskSource()) {
taskSource = TaskSource.create(this, getHoursGroups());
return TaskSource.mustAdd(taskSource);
} else {
if (taskSource.getTask().isLeaf()) {
return taskSource.withCurrentHoursGroup(getHoursGroups());
} else {
List<TaskSource> toBeRemoved = getTaskSourcesFromBottomToTop();
taskSource = TaskSource.create(this, getHoursGroups());
return TaskSource.mustReplace(toBeRemoved, taskSource);
}
}
}
private boolean thereIsNoTaskSource() {
return taskSource == null;
}
private List<OrderElement> getSomewhatScheduledOrderElements() {
List<OrderElement> result = new ArrayList<OrderElement>();
for (OrderElement orderElement : getChildren()) {
if (orderElement.getSchedulingStateType().isSomewhatScheduled()) {
result.add(orderElement);
}
}
return result;
}
private List<OrderElement> getNoScheduledOrderElements() {
List<OrderElement> result = new ArrayList<OrderElement>();
for (OrderElement orderElement : getChildren()) {
if (orderElement.getSchedulingState().isNoScheduled()) {
result.add(orderElement);
}
}
return result;
}
private void removeTaskSource(List<TaskSourceSynchronization> result) {
removeChildrenTaskSource(result);
if (taskSource != null) {
result.add(TaskSource.mustRemove(taskSource));
taskSource = null;
}
}
private void removeChildrenTaskSource(List<TaskSourceSynchronization> result) {
List<OrderElement> children = getChildren();
for (OrderElement each : children) {
each.removeTaskSource(result);
}
}
private boolean isSuperElementPartialOrCompletelyScheduled() {
return getSchedulingState().isSomewhatScheduled();
}
private boolean isSchedulingPoint() {
return getSchedulingState().getType() == Type.SCHEDULING_POINT;
}
public OrderLineGroup getParent() {
return parent;
}
public TaskElement getAssociatedTaskElement() {
if (taskSource == null) {
return null;
} else {
return taskSource.getTask();
}
}
protected void setParent(OrderLineGroup parent) {
this.parent = parent;
}
public abstract Integer getWorkHours();
public abstract List<HoursGroup> getHoursGroups();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract boolean isLeaf();
public abstract List<OrderElement> getChildren();
private static Date copy(Date date) {
return date != null ? new Date(date.getTime()) : date;
}
public Date getInitDate() {
return copy(initDate);
}
public void setInitDate(Date initDate) {
this.initDate = initDate;
}
public Date getDeadline() {
return copy(deadline);
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
public void setMandatoryInit(Boolean mandatoryInit) {
this.mandatoryInit = mandatoryInit;
}
public Boolean isMandatoryInit() {
return mandatoryInit;
}
public void setMandatoryEnd(Boolean mandatoryEnd) {
this.mandatoryEnd = mandatoryEnd;
}
public Boolean isMandatoryEnd() {
return mandatoryEnd;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public abstract OrderLine toLeaf();
public abstract OrderLineGroup toContainer();
public boolean isScheduled() {
return taskSource != null;
}
public boolean checkAtLeastOneHoursGroup() {
return (getHoursGroups().size() > 0);
}
public boolean isFormatCodeValid(String code) {
if (code.contains("_")) {
return false;
}
if (code.equals("")) {
return false;
}
return true;
}
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public abstract DirectAdvanceAssignment getReportGlobalAdvanceAssignment();
public Set<DirectAdvanceAssignment> getDirectAdvanceAssignments() {
return Collections.unmodifiableSet(directAdvanceAssignments);
}
protected abstract Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments();
protected abstract Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments(
AdvanceType advanceType);
protected abstract Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignmentsReportGlobal();
public void removeAdvanceAssignment(AdvanceAssignment advanceAssignment) {
directAdvanceAssignments.remove(advanceAssignment);
if (this.getParent() != null) {
this.getParent().removeIndirectAdvanceAssignment(advanceAssignment
.getAdvanceType());
}
}
public Set<Label> getLabels() {
return Collections.unmodifiableSet(labels);
}
public void setLabels(Set<Label> labels) {
this.labels = labels;
}
public void addLabel(Label label) {
Validate.notNull(label);
labels.add(label);
}
public void removeLabel(Label label) {
labels.remove(label);
}
/**
* Validate if the advanceAssignment can be added to the order element.The
* list of advanceAssignments must be attached.
* @param advanceAssignment
* must be attached
* @throws DuplicateValueTrueReportGlobalAdvanceException
* @throws DuplicateAdvanceAssignmentForOrderElementException
*/
public void addAdvanceAssignment(
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
checkNoOtherGlobalAdvanceAssignment(newAdvanceAssignment);
checkAncestorsNoOtherAssignmentWithSameAdvanceType(this,
newAdvanceAssignment);
checkChildrenNoOtherAssignmentWithSameAdvanceType(this,
newAdvanceAssignment);
newAdvanceAssignment.setOrderElement(this);
this.directAdvanceAssignments.add(newAdvanceAssignment);
if (this.getParent() != null) {
IndirectAdvanceAssignment indirectAdvanceAssignment = IndirectAdvanceAssignment
.create();
indirectAdvanceAssignment.setAdvanceType(newAdvanceAssignment
.getAdvanceType());
indirectAdvanceAssignment.setOrderElement(this.getParent());
this.getParent().addIndirectAdvanceAssignment(indirectAdvanceAssignment);
}
}
protected void checkNoOtherGlobalAdvanceAssignment(
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException {
if (!newAdvanceAssignment.getReportGlobalAdvance()) {
return;
}
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if (directAdvanceAssignment.getReportGlobalAdvance()) {
throw new DuplicateValueTrueReportGlobalAdvanceException(
_("Duplicate Value True ReportGlobalAdvance For Order Element"),
this, OrderElement.class);
}
}
}
/**
* It checks there are no {@link DirectAdvanceAssignment} with the same type
* in {@link OrderElement} and ancestors
*
* @param orderElement
* @param newAdvanceAssignment
* @throws DuplicateAdvanceAssignmentForOrderElementException
*/
private void checkAncestorsNoOtherAssignmentWithSameAdvanceType(
OrderElement orderElement,
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateAdvanceAssignmentForOrderElementException {
for (DirectAdvanceAssignment directAdvanceAssignment : orderElement.directAdvanceAssignments) {
if (AdvanceType.equivalentInDB(directAdvanceAssignment
.getAdvanceType(), newAdvanceAssignment.getAdvanceType())) {
throw new DuplicateAdvanceAssignmentForOrderElementException(
_("Duplicate Advance Assignment For Order Element"),
this,
OrderElement.class);
}
}
if (orderElement.getParent() != null) {
checkAncestorsNoOtherAssignmentWithSameAdvanceType(orderElement
.getParent(), newAdvanceAssignment);
}
}
/**
* It checks there are no {@link AdvanceAssignment} with the same type in
* orderElement and its children
* @param orderElement
* @param newAdvanceAssignment
* @throws DuplicateAdvanceAssignmentForOrderElementException
*/
protected void checkChildrenNoOtherAssignmentWithSameAdvanceType(
OrderElement orderElement,
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateAdvanceAssignmentForOrderElementException {
for (DirectAdvanceAssignment directAdvanceAssignment : orderElement.directAdvanceAssignments) {
if (AdvanceType.equivalentInDB(directAdvanceAssignment
.getAdvanceType(), newAdvanceAssignment.getAdvanceType())) {
throw new DuplicateAdvanceAssignmentForOrderElementException(
_("Duplicate Advance Assignment For Order Element"),
this,
OrderElement.class);
}
}
if (!orderElement.getChildren().isEmpty()) {
for (OrderElement child : orderElement.getChildren()) {
checkChildrenNoOtherAssignmentWithSameAdvanceType(child,
newAdvanceAssignment);
}
}
}
public BigDecimal getAdvancePercentage() {
return getAdvancePercentage(null);
}
public abstract BigDecimal getAdvancePercentage(LocalDate date);
public List<OrderElement> getAllChildren() {
List<OrderElement> children = getChildren();
List<OrderElement> result = new ArrayList<OrderElement>(children);
for (OrderElement orderElement : children) {
result.addAll(orderElement.getAllChildren());
}
return result;
}
public void setCriterionRequirements(
Set<CriterionRequirement> criterionRequirements) {
this.criterionRequirements = criterionRequirements;
}
@Valid
public Set<CriterionRequirement> getCriterionRequirements() {
return Collections.unmodifiableSet(criterionRequirements);
}
protected Set<CriterionRequirement> myCriterionRequirements() {
return criterionRequirements;
}
/*
* Operations to manage the criterion requirements of a orderElement
* (remove, adding, update of the criterion requirement of the orderElement
* such as the descendent's criterion requirement)
*/
public void setValidCriterionRequirement(IndirectCriterionRequirement requirement,boolean valid){
requirement.setIsValid(valid);
criterionRequirementHandler.propagateValidCriterionRequirement(this,
requirement.getParent(), valid);
}
public void removeDirectCriterionRequirement(DirectCriterionRequirement criterionRequirement){
criterionRequirementHandler.propagateRemoveCriterionRequirement(this,
criterionRequirement);
removeCriterionRequirement(criterionRequirement);
}
protected void removeCriterionRequirement(CriterionRequirement requirement) {
criterionRequirements.remove(requirement);
if(requirement instanceof IndirectCriterionRequirement){
((IndirectCriterionRequirement)requirement).getParent().
getChildren().remove((IndirectCriterionRequirement)requirement);
}
}
public void addDirectCriterionRequirement(
CriterionRequirement newRequirement) {
if (criterionRequirementHandler.canAddCriterionRequirement(this,
newRequirement)) {
addCriterionRequirement(newRequirement);
criterionRequirementHandler
.propagateDirectCriterionRequirementAddition(this,
newRequirement);
} else {
Criterion criterion = newRequirement.getCriterion();
throw new IllegalStateException(_(
" The {0} already exist into other order element",
criterion
.getName()));
}
}
void addIndirectCriterionRequirement(
IndirectCriterionRequirement criterionRequirement) {
addCriterionRequirement(criterionRequirement);
}
protected void addCriterionRequirement(
CriterionRequirement criterionRequirement) {
criterionRequirement.setOrderElement(this);
this.criterionRequirements.add(criterionRequirement);
}
public void updateCriterionRequirements() {
updateMyCriterionRequirements();
criterionRequirementHandler.propagateUpdateCriterionRequirements(this);
}
void updateMyCriterionRequirements() {
OrderElement newParent = this.getParent();
Set<CriterionRequirement> requirementsParent = newParent
.getCriterionRequirements();
Set<IndirectCriterionRequirement> currentIndirects = criterionRequirementHandler
.getCurrentIndirectRequirements(
getIndirectCriterionRequirement(), requirementsParent);
criterionRequirementHandler.transformDirectToIndirectIfNeeded(this,
currentIndirects);
criterionRequirementHandler.removeOldIndirects(this, currentIndirects);
criterionRequirementHandler.addNewsIndirects(this, currentIndirects);
}
public boolean canAddCriterionRequirement(
DirectCriterionRequirement newRequirement) {
return criterionRequirementHandler.canAddCriterionRequirement(this,
newRequirement);
}
protected Set<IndirectCriterionRequirement> getIndirectCriterionRequirement() {
Set<IndirectCriterionRequirement> list = new HashSet<IndirectCriterionRequirement>();
for (CriterionRequirement criterionRequirement : criterionRequirements) {
if (criterionRequirement instanceof IndirectCriterionRequirement) {
list.add((IndirectCriterionRequirement) criterionRequirement);
}
}
return list;
}
public void applyStartConstraintIfNeededTo(Task task) {
if (getInitDate() != null) {
applyStartConstraintTo(task);
return;
}
OrderLineGroup parent = getParent();
if (parent != null) {
parent.applyStartConstraintIfNeededTo(task);
}
}
protected void applyStartConstraintTo(Task task) {
task.getStartConstraint().notEarlierThan(this.getInitDate());
}
public Set<DirectCriterionRequirement> getDirectCriterionRequirement() {
Set<DirectCriterionRequirement> list = new HashSet<DirectCriterionRequirement>();
for (CriterionRequirement criterionRequirement : criterionRequirements) {
if (criterionRequirement instanceof DirectCriterionRequirement) {
list.add((DirectCriterionRequirement) criterionRequirement);
}
}
return list;
}
public SchedulingState.Type getSchedulingStateType() {
if (schedulingStateType == null) {
schedulingStateType = Type.NO_SCHEDULED;
}
return schedulingStateType;
}
public TaskSource getTaskSource() {
return taskSource;
}
public Set<TaskElement> getTaskElements() {
if (taskSource == null) {
return Collections.emptySet();
}
return Collections.singleton(taskSource.getTask());
}
public List<TaskSource> getTaskSourcesFromBottomToTop() {
List<TaskSource> result = new ArrayList<TaskSource>();
taskSourcesFromBottomToTop(result);
return result;
}
private void taskSourcesFromBottomToTop(List<TaskSource> result) {
for (OrderElement each : getChildren()) {
each.taskSourcesFromBottomToTop(result);
}
if (taskSource != null) {
result.add(taskSource);
}
}
public Set<MaterialAssignment> getMaterialAssignments() {
return Collections.unmodifiableSet(materialAssignments);
}
public void addMaterialAssignment(MaterialAssignment materialAssignment) {
materialAssignments.add(materialAssignment);
materialAssignment.setOrderElement(this);
}
public void removeMaterialAssignment(MaterialAssignment materialAssignment) {
materialAssignments.remove(materialAssignment);
}
public double getTotalMaterialAssigmentUnits() {
double result = 0;
final Set<MaterialAssignment> materialAssigments = getMaterialAssignments();
for (MaterialAssignment each: materialAssigments) {
result += each.getUnits();
}
return result;
}
public BigDecimal getTotalMaterialAssigmentPrice() {
BigDecimal result = new BigDecimal(0);
final Set<MaterialAssignment> materialAssigments = getMaterialAssignments();
for (MaterialAssignment each: materialAssigments) {
result = result.add(each.getTotalPrice());
}
return result;
}
public Order getOrder() {
if (this instanceof Order) {
return (Order) this;
}
if (parent != null) {
return parent.getOrder();
}
return null;
}
}
|
package org.navalplanner.web.planner.order;
import static org.navalplanner.web.I18nHelper._;
import java.util.Date;
import java.util.List;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.externalcompanies.entities.ExternalCompany;
import org.navalplanner.business.planner.entities.SubcontractedTaskData;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.business.planner.entities.TaskElement;
import org.navalplanner.web.common.Util;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.zkoss.ganttz.extensions.IContextWithPlannerTask;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.api.Tabpanel;
/**
* Controller for subcontract a task.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@org.springframework.stereotype.Component("subcontractController")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class SubcontractController extends GenericForwardComposer {
private Tabpanel tabpanel;
private ISubcontractModel subcontractModel;
private IContextWithPlannerTask<TaskElement> context;
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
tabpanel = (Tabpanel) comp;
}
public void init(Task task,
IContextWithPlannerTask<TaskElement> context) {
this.context = context;
subcontractModel.init(task, context.getTask());
Util.reloadBindings(tabpanel);
}
public void accept() throws ValidationException {
int status = Messagebox.YES;
if (subcontractModel.hasResourceAllocations()
&& (subcontractModel.getSubcontractedTaskData() != null)) {
try {
status = Messagebox
.show(
_("As you are subcontracting this task, all the resource allocations related with this task will be removed.")
+ _("Are you sure?"), _("Confirm"),
Messagebox.YES | Messagebox.NO,
Messagebox.QUESTION);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if (status == Messagebox.YES) {
subcontractModel.confirm();
}
}
public void cancel() {
subcontractModel.cancel();
}
public List<ExternalCompany> getSubcontractorExternalCompanies() {
return subcontractModel.getSubcontractorExternalCompanies();
}
public SubcontractedTaskData getSubcontractedTaskData() {
return subcontractModel.getSubcontractedTaskData();
}
public void setExternalCompany(Comboitem comboitem) {
if (comboitem != null && comboitem.getValue() != null) {
ExternalCompany externalCompany = (ExternalCompany) comboitem
.getValue();
subcontractModel.setExternalCompany(externalCompany);
} else {
subcontractModel.setExternalCompany(null);
}
}
public Date getEndDate() {
return subcontractModel.getEndDate();
}
public void setEndDate(Date endDate) {
subcontractModel.setEndDate(endDate);
}
public void removeSubcontractedTaskData() {
subcontractModel.removeSubcontractedTaskData();
}
}
|
package org.navalplanner.web.users.services;
import static org.navalplanner.web.I18nHelper._;
import java.util.HashSet;
import java.util.Set;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.users.daos.IUserDAO;
import org.navalplanner.business.users.entities.Profile;
import org.navalplanner.business.users.entities.User;
import org.navalplanner.business.users.entities.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
/**
* Default implementation of Spring Security's <code>UserDetailsService</code>.
* The implementation retrieves the user's details from the database by using
* <code>IUserDAO</code>.
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
*/
public class DBUserDetailsService implements UserDetailsService {
@Autowired
private IUserDAO userDAO;
@Override
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String loginName)
throws UsernameNotFoundException, DataAccessException {
User user;
try {
user = userDAO.findByLoginNameNotDisabled(loginName);
} catch (InstanceNotFoundException e) {
throw new UsernameNotFoundException(_("User with login name " +
"'{0}': not found", loginName));
}
//Retrieve roles from the user and its profiles
Set<UserRole> allRoles = new HashSet<UserRole>();
allRoles.addAll(user.getRoles());
for(Profile eachProfile : user.getProfiles()) {
allRoles.addAll(eachProfile.getRoles());
}
if(allRoles.isEmpty()) {
//that user doesn't have any roles, so we forbid his login
throw new UsernameNotFoundException(_("User with login name " +
"'{0}': access forbidden", loginName));
}
return new org.springframework.security.userdetails.User(
user.getLoginName(),
user.getPassword(),
true, // enabled
true, // accountNonExpired
true, // credentialsNonExpired
true, // accountNonLocked
getGrantedAuthorities(allRoles));
}
private GrantedAuthority[] getGrantedAuthorities(Set<UserRole> roles) {
GrantedAuthority[] grantedAuthorities =
new GrantedAuthority[roles.size()];
int i = 0;
for (UserRole r : roles) {
grantedAuthorities[i++] = new GrantedAuthorityImpl(r.name());
}
return grantedAuthorities;
}
}
|
package org.eclipse.mylar.trac.tests;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.mylar.internal.trac.core.ITracClient;
import org.eclipse.mylar.internal.trac.core.TracException;
import org.eclipse.mylar.internal.trac.core.ITracClient.Version;
import org.eclipse.mylar.internal.trac.model.TracSearch;
import org.eclipse.mylar.internal.trac.model.TracTicket;
import org.eclipse.mylar.internal.trac.model.TracTicket.Key;
import org.eclipse.mylar.trac.tests.support.TestFixture;
import org.eclipse.mylar.trac.tests.support.XmlRpcServer.TestData;
import org.eclipse.mylar.trac.tests.support.XmlRpcServer.Ticket;
/**
* Test cases that validate search results for classes that implement
* {@link ITracClient}.
*
* @author Steffen Pingel
*/
public abstract class AbstractTracClientSearchTest extends AbstractTracClientTest {
protected List<Ticket> tickets;
public AbstractTracClientSearchTest(Version version) {
super(version);
}
protected void setUp() throws Exception {
super.setUp();
TestData data = TestFixture.init010();
tickets = data.tickets;
connect010();
}
protected void tearDown() throws Exception {
super.tearDown();
// TestFixture.cleanupRepository1();
}
protected void assertTicketEquals(Ticket ticket, TracTicket tracTicket) throws Exception {
assertTrue(tracTicket.isValid());
Map expectedValues = ticket.getValues();
Map<String, String> values = tracTicket.getValues();
for (String key : values.keySet()) {
assertEquals("Values for key '" + key + "' did not match", expectedValues.get(key), values.get(key));
}
}
public void testGetTicket() throws Exception {
TracTicket ticket = repository.getTicket(tickets.get(0).getId());
assertTicketEquals(tickets.get(0), ticket);
ticket = repository.getTicket(tickets.get(1).getId());
assertTicketEquals(tickets.get(1), ticket);
}
public void testGetTicketInvalidId() throws Exception {
try {
repository.getTicket(Integer.MAX_VALUE);
fail("Expected TracException");
} catch (TracException e) {
}
}
public void testSearchAll() throws Exception {
TracSearch search = new TracSearch();
// TODO figure out why search must be ordered when logged in (otherwise
// no results will be returned)
search.setOrderBy("id");
List<TracTicket> result = new ArrayList<TracTicket>();
repository.search(search, result);
assertEquals(tickets.size(), result.size());
}
public void testSearchEmpty() throws Exception {
TracSearch search = new TracSearch();
search.addFilter("milestone", "does not exist");
List<TracTicket> result = new ArrayList<TracTicket>();
repository.search(search, result);
assertEquals(0, result.size());
}
public void testSearchMilestone1() throws Exception {
TracSearch search = new TracSearch();
search.addFilter("milestone", "m1");
List<TracTicket> result = new ArrayList<TracTicket>();
repository.search(search, result);
assertEquals(1, result.size());
assertTicketEquals(tickets.get(0), result.get(0));
}
public void testSearchMilestone2() throws Exception {
TracSearch search = new TracSearch();
search.addFilter("milestone", "m1");
search.addFilter("milestone", "m2");
search.setOrderBy("id");
List<TracTicket> result = new ArrayList<TracTicket>();
repository.search(search, result);
assertEquals(3, result.size());
assertTicketEquals(tickets.get(0), result.get(0));
assertTicketEquals(tickets.get(1), result.get(1));
assertTicketEquals(tickets.get(2), result.get(2));
}
public void testSearchExactMatch() throws Exception {
TracSearch search = new TracSearch();
search.addFilter("milestone", "m1");
search.addFilter("summary", "summary1");
List<TracTicket> result = new ArrayList<TracTicket>();
repository.search(search, result);
assertEquals(1, result.size());
assertTicketEquals(tickets.get(0), result.get(0));
assertEquals("m1", result.get(0).getValue(Key.MILESTONE));
assertEquals("summary1", result.get(0).getValue(Key.SUMMARY));
}
}
|
package fr.lip6.jkernelmachines.example;
import java.util.List;
import fr.lip6.jkernelmachines.classifier.Classifier;
import fr.lip6.jkernelmachines.classifier.LaSVM;
import fr.lip6.jkernelmachines.classifier.LaSVMI;
import fr.lip6.jkernelmachines.classifier.NystromLSSVM;
import fr.lip6.jkernelmachines.classifier.SDCA;
import fr.lip6.jkernelmachines.classifier.SMOSVM;
import fr.lip6.jkernelmachines.evaluation.AccuracyEvaluator;
import fr.lip6.jkernelmachines.evaluation.RandomSplitCrossValidation;
import fr.lip6.jkernelmachines.io.ArffImporter;
import fr.lip6.jkernelmachines.io.LibSVMImporter;
import fr.lip6.jkernelmachines.kernel.Kernel;
import fr.lip6.jkernelmachines.kernel.typed.DoubleGaussL2;
import fr.lip6.jkernelmachines.kernel.typed.DoubleLinear;
import fr.lip6.jkernelmachines.projection.DoublePCA;
import fr.lip6.jkernelmachines.type.TrainingSample;
import fr.lip6.jkernelmachines.util.DebugPrinter;
/**
* <p>
* This is a more complex example of how to code with JKernelMachines than can
* be used as a stand-alone program.
* </p>
* <p>
* It reads data from an input file in the libsvm format, and performs a cross-validation evaluation.
* Optional parameters include the number of test to perform, the percentage of data to keep from training, the type of kernel, and the svm algorithm.
* Launch without argument to get the following help:<br/>
* <br />
* CrossValidationExample -f file [-p percent] [-n nbtests] [-k kernel] [-a algorithm] [-pca type] [-vvv]
* <ul>
* <li>-f file: the data file in libsvm format</li>
* <li>-p percent: the percent of data to keep for training</li>
* <li>-n nbtests: the number of test to perform during crossvalidation</li>
* <li>-k kernel: the type of kernel (linear or gauss, default gauss)</li>
* <li>-a algorithm: type of SVM algorithm(lasvm, lasvmi, smo, nlssvm default lasvm)</li>
* <li>-pca type: perform a PCA as preprocessing (no, yes, white, default no)</li>
* <li>-v: verbose (v few, vv lot, vvv insane, default none)</li>
* </ul>
* </p>
*
* @author David Picard
*
*/
public class CrossValidationExample {
/**
* @param args
*/
public static void main(String[] args) {
String file = "";
double percent = 0.8;
int nbtest = 10;
Kernel<double[]> kernel = null;
Classifier<double[]> svm = null;
int hasPCA = 0;
// parsing options
try {
for (int i = 0; i < args.length; i++) {
// parsing file
if (args[i].equalsIgnoreCase("-f")) {
i++;
file = args[i];
}
// split percent
else if (args[i].equalsIgnoreCase("-p")) {
i++;
percent = Double.parseDouble(args[i]);
}
// number of tests
else if (args[i].equalsIgnoreCase("-n")) {
i++;
nbtest = Integer.parseInt(args[i]);
}
// kernel type
else if (args[i].equalsIgnoreCase("-k")) {
i++;
if (args[i].equalsIgnoreCase("gauss")) {
kernel = new DoubleGaussL2();
} else {
kernel = new DoubleLinear();
}
}
// algorithm
else if (args[i].equalsIgnoreCase("-a")) {
i++;
if (args[i].equalsIgnoreCase("lasvmi")) {
svm = new LaSVMI<double[]>(kernel);
} else if (args[i].equalsIgnoreCase("sdca")) {
svm = new SDCA<double[]>(kernel);
} else if (args[i].equalsIgnoreCase("smo")) {
svm = new SMOSVM<double[]>(kernel);
} else if (args[i].equalsIgnoreCase("nlssvm")) {
NystromLSSVM<double[]> nlssvm = new NystromLSSVM<double[]>(kernel);
nlssvm.setPercent(0.1);
svm = nlssvm;
} else { // default lasvm
svm = new LaSVM<double[]>(kernel);
}
}
else if (args[i].equalsIgnoreCase("-pca")) {
i++;
if(args[i].equalsIgnoreCase("yes")) {
hasPCA = 1;
}
else if(args[i].equalsIgnoreCase("white")) {
hasPCA = 2;
}
}
// verbose
else if (args[i].equalsIgnoreCase("-v")) {
DebugPrinter.DEBUG_LEVEL = 2;
} else if (args[i].equalsIgnoreCase("-vv")) {
DebugPrinter.DEBUG_LEVEL = 3;
} else if (args[i].equalsIgnoreCase("-vvv")) {
DebugPrinter.DEBUG_LEVEL = 4;
}
}
} catch (Exception e) {
printHelp();
System.exit(-1);
}
// check option
if (file.equalsIgnoreCase("") || kernel == null || svm == null) {
printHelp();
System.exit(-1);
}
// read data
List<TrainingSample<double[]>> list = null;
try {
if(file.endsWith(".arff")) {
list = ArffImporter.importFromFile(file);
}
else {
list = LibSVMImporter.importFromFile(file);
}
} catch (Exception e) {
System.out.println("Wrong data file");
printHelp();
System.exit(-1);
}
if (list == null) {
System.out.println("Wrong data file");
printHelp();
System.exit(-1);
}
// perform PCA
if(hasPCA == 1) {
DoublePCA pca = new DoublePCA();
pca.train(list);
list = pca.projectList(list);
}
else if(hasPCA == 2) {
DoublePCA pca = new DoublePCA();
pca.train(list);
list = pca.projectList(list, true);
}
// initialize CV
AccuracyEvaluator<double[]> ev = new AccuracyEvaluator<double[]>();
RandomSplitCrossValidation<double[]> cv = new RandomSplitCrossValidation<double[]>(
svm, list, ev);
cv.setNbTest(nbtest);
cv.setTrainPercent(percent);
// do cv
cv.run();
// print result
System.out.println("Accuracy: " + cv.getAverageScore() + " +/- "
+ cv.getStdDevScore());
}
private static void printHelp() {
System.out
.println("CrossValidationExample -f file [-p percent] [-n nbtests] [-k kernel] [-a algorithm] [-vvv]");
System.out.println("\t-f file: the data file in libsvm format");
System.out
.println("\t-p percent: the percent of data to keep for training");
System.out
.println("\t-n nbtests: the number of test to perform during crossvalidation");
System.out
.println("\t-k kernel: the type of kernel (linear or gauss, default gauss)");
System.out
.println("\t-a algorithm: type of SVM algorithm(lasvm, lasvmi, smo, default lasvm)");
System.out
.println("\t-pca type: perform a PCA as preprocessing(no, yes, white, default no");
System.out
.println("\t-v: verbose (v few, vv lot, vvv insane, default none)");
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.ui;
import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory;
import gov.nih.nci.ncicb.cadsr.domain.PermissibleValue;
import gov.nih.nci.ncicb.cadsr.domain.ValueDomain;
import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeEvent;
import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeListener;
import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModule;
import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModuleListener;
import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode;
import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil;
import gov.nih.nci.ncicb.cadsr.loader.util.ConventionUtil;
import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class MapToExistingVDPanel extends JPanel
implements Editable, CadsrModuleListener
{
private JLabel vdPrefDefTitleLabel = new JLabel("VD Preferred Definition"),
vdLongNameLabel = new JLabel("VD Long Name"),
vdDatatypeTitleLabel = new JLabel("VD Datatype"),
vdCdIdTitleLabel = new JLabel("VD CD PublicId / Version"),
vdRepIdTitleLabel = new JLabel("Representation Term"),
vdCdLongNameTitleLabel = new JLabel("VD CD Long Name"),
vdCreatedByLabel = new JLabel("Created By"),
vdCreatedDateLabel = new JLabel("Created Date");
private JLabel vdDatatypeTitleLabelValue = new JLabel(),
vdLongNameLabelValue = new JLabel(),
vdTypeTitleLabelValue = new JLabel(),
vdCdIdTitleLabelValue = new JLabel(),
vdRepIdTitleLabelValue = new JLabel(),
vdCdLongNameTitleLabelValue = new JLabel(),
vdCreatedByLabelValue = new JLabel(),
vdCreatedDateLabelValue = new JLabel();
private JTextArea vdPrefDefValueTextField = new JTextArea();
private JButton searchButton;
private JButton clearButton;
private JButton lvdCadsrButton;
private CadsrDialog cadsrVDDialog;
private ValueDomain vd, tempVD;
private UMLNode umlNode;
private CadsrModule cadsrModule;
public boolean applied = false;
private boolean isInitialized = false;
private boolean isSearched = false;
private List<ElementChangeListener> changeListeners = new ArrayList<ElementChangeListener>();
private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>();
private Logger logger = Logger.getLogger(MapToExistingVDPanel.class.getName());
public MapToExistingVDPanel() {
if(!isInitialized)
initUI();
}
public void update(ValueDomain vd, UMLNode umlNode)
{
this.vd = vd;
this.umlNode = umlNode;
tempVD = DomainObjectFactory.newValueDomain();
tempVD.setConceptualDomain(vd.getConceptualDomain());
tempVD.setPreferredDefinition(vd.getPreferredDefinition());
tempVD.setRepresentation(vd.getRepresentation());
tempVD.setLongName(vd.getLongName());
tempVD.setDataType(vd.getDataType());
tempVD.setVdType(vd.getVdType());
tempVD.setPublicId(vd.getPublicId());
tempVD.setVersion(vd.getVersion());
tempVD.setAudit(vd.getAudit());
tempVD.setId(vd.getId());
if(!isInitialized)
initUI();
initValues();
}
private void initUI()
{
isInitialized = true;
applied = false;
this.setLayout(new BorderLayout());
JPanel mainPanel = new JPanel(new GridBagLayout());
vdPrefDefValueTextField.setLineWrap(true);
vdPrefDefValueTextField.setEnabled(false);
vdPrefDefValueTextField.setWrapStyleWord(true);
JScrollPane defScrollPane = new JScrollPane(vdPrefDefValueTextField);
defScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
defScrollPane.setPreferredSize(new Dimension(200, 100));
searchButton = new JButton("Search Value Domains");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cadsrVDDialog.setAlwaysOnTop(true);
cadsrVDDialog.setVisible(true);
ValueDomain _vd = (ValueDomain)cadsrVDDialog.getAdminComponent();
if(_vd != null){
tempVD.setPublicId(_vd.getPublicId());
tempVD.setConceptualDomain(_vd.getConceptualDomain());
tempVD.setPreferredDefinition(_vd.getPreferredDefinition());
tempVD.setRepresentation(_vd.getRepresentation());
tempVD.setLongName(_vd.getLongName());
tempVD.setDataType(_vd.getDataType());
tempVD.setVdType(_vd.getVdType());
tempVD.setVersion(_vd.getVersion());
tempVD.setAudit(_vd.getAudit());
tempVD.setId(_vd.getId());
setSearchedValues();
isSearched = true;
firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true));
}
}});
JPanel searchButtonPanel = new JPanel();
searchButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
searchButtonPanel.add(searchButton);
lvdCadsrButton = new JButton("<html>Compare<br>Values</html>");
lvdCadsrButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
List<PermissibleValue> cadsrPVs = cadsrModule.getPermissibleValues(tempVD);
List<PermissibleValue> localPVs = vd.getPermissibleValues();
PVCompareDialog pvCompareDialog = new PVCompareDialog(localPVs, cadsrPVs);
pvCompareDialog.setVisible(true);
pvCompareDialog.setAlwaysOnTop(true);
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}});
clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
vdPrefDefValueTextField.setText("");
vdLongNameLabelValue.setText("");
vdDatatypeTitleLabelValue.setText("");
vdTypeTitleLabelValue.setText("");
vdCdIdTitleLabelValue.setText("");
vdCdLongNameTitleLabelValue.setText("");
vdRepIdTitleLabelValue.setText("");
vdCreatedByLabelValue.setText("");
vdCreatedDateLabelValue.setText("");
lvdCadsrButton.setVisible(false);
tempVD.setConceptualDomain(null);
tempVD.setPreferredDefinition("");
tempVD.setRepresentation(null);
tempVD.setLongName("");
tempVD.setDataType("");
tempVD.setVdType(null);
tempVD.setPublicId(null);
tempVD.setId(null);
if(isSearched)
firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true));
isSearched = false;
}});
JPanel clearButtonPanel = new JPanel();
clearButtonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
clearButtonPanel.add(clearButton);
UIUtil.insertInBag(mainPanel, vdPrefDefTitleLabel, 0, 1);
UIUtil.insertInBag(mainPanel, defScrollPane, 1, 1, 3, 2);
UIUtil.insertInBag(mainPanel, lvdCadsrButton, 2, 1, 1, 10);
UIUtil.insertInBag(mainPanel, vdLongNameLabel, 0, 3);
UIUtil.insertInBag(mainPanel, vdLongNameLabelValue, 1, 3);
UIUtil.insertInBag(mainPanel, vdDatatypeTitleLabel, 0, 5);
UIUtil.insertInBag(mainPanel, vdDatatypeTitleLabelValue, 1, 5);
UIUtil.insertInBag(mainPanel, vdCdIdTitleLabel, 0, 6);
UIUtil.insertInBag(mainPanel, vdCdIdTitleLabelValue, 1, 6);
UIUtil.insertInBag(mainPanel, vdCdLongNameTitleLabel, 0, 7);
UIUtil.insertInBag(mainPanel, vdCdLongNameTitleLabelValue, 1, 7);
UIUtil.insertInBag(mainPanel, vdRepIdTitleLabel, 0, 8);
UIUtil.insertInBag(mainPanel, vdRepIdTitleLabelValue, 1, 8);
UIUtil.insertInBag(mainPanel, vdCreatedByLabel, 0, 9);
UIUtil.insertInBag(mainPanel, vdCreatedByLabelValue, 1, 9);
UIUtil.insertInBag(mainPanel, vdCreatedDateLabel, 0, 10);
UIUtil.insertInBag(mainPanel, vdCreatedDateLabelValue, 1, 10);
UIUtil.insertInBag(mainPanel, clearButtonPanel, 0, 11);
UIUtil.insertInBag(mainPanel, searchButtonPanel, 2, 11);
JScrollPane mainScrollPane = new JScrollPane(mainPanel);
mainScrollPane.getVerticalScrollBar().setUnitIncrement(30);
this.add(mainScrollPane, BorderLayout.CENTER);
}
private void initValues()
{
if(StringUtil.isEmpty(tempVD.getPublicId())) {
vdPrefDefValueTextField.setText("");
vdLongNameLabelValue.setText("");
vdDatatypeTitleLabelValue.setText("");
vdTypeTitleLabelValue.setText("");
vdCdIdTitleLabelValue.setText("");
vdCdLongNameTitleLabelValue.setText("");
vdRepIdTitleLabelValue.setText("");
vdCreatedByLabelValue.setText("");
vdCreatedDateLabelValue.setText("");
lvdCadsrButton.setVisible(false);
} else {
vdPrefDefValueTextField.setText(tempVD.getPreferredDefinition());
vdLongNameLabelValue.setText(tempVD.getLongName());
vdDatatypeTitleLabelValue.setText(tempVD.getDataType());
vdTypeTitleLabelValue.setText(tempVD.getVdType());
vdCdIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getConceptualDomain()));
vdCdLongNameTitleLabelValue.setText(tempVD.getConceptualDomain().getLongName());
vdRepIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getRepresentation()));
vdCreatedByLabelValue.setText(tempVD.getAudit().getCreatedBy());
vdCreatedDateLabelValue.setText(getFormatedDate(tempVD.getAudit().getCreationDate()));
lvdCadsrButton.setVisible(true);
}
}
private void setSearchedValues(){
if(tempVD != null){
if(tempVD.getConceptualDomain() != null){
vdPrefDefValueTextField.setText(tempVD.getPreferredDefinition());
vdCdIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getConceptualDomain()));
vdCdLongNameTitleLabelValue.setText(tempVD.getConceptualDomain().getLongName());
}
if(tempVD.getRepresentation() != null)
vdRepIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getRepresentation()));
if(tempVD.getLongName() != null &&
!tempVD.getLongName().equals("Unable to lookup CD Long Name"))
vdLongNameLabelValue.setText(tempVD.getLongName());
if(tempVD.getDataType() != null)
vdDatatypeTitleLabelValue.setText(tempVD.getDataType());
if(tempVD.getVdType() != null)
vdTypeTitleLabelValue.setText(tempVD.getVdType());
if(tempVD.getAudit() != null){
vdCreatedByLabelValue.setText(tempVD.getAudit().getCreatedBy());
vdCreatedDateLabelValue.setText(getFormatedDate(tempVD.getAudit().getCreationDate()));
}
lvdCadsrButton.setVisible(true);
}
}
public static void main(String args[])
{
// JFrame frame = new JFrame();
// ValueDomainViewPanel vdPanel = new ValueDomainViewPanel();
// vdPanel.setVisible(true);
// frame.add(vdPanel);
// frame.setVisible(true);
// frame.setSize(450, 350);
}
public void applyPressed() {
applied = true;
vd.setConceptualDomain(tempVD.getConceptualDomain());
vd.setRepresentation(tempVD.getRepresentation());
vd.setLongName(tempVD.getLongName());
vd.setDataType(tempVD.getDataType());
vd.setPreferredDefinition(tempVD.getPreferredDefinition());
vd.setVdType(tempVD.getVdType());
vd.setPublicId(tempVD.getPublicId());
vd.setVersion(tempVD.getVersion());
vd.setAudit(tempVD.getAudit());
vd.setId(tempVD.getId());
firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, false));
fireElementChangeEvent(new ElementChangeEvent((Object)umlNode));
}
public void setCadsrVDDialog(CadsrDialog cadsrVDDialog) {
this.cadsrVDDialog = cadsrVDDialog;
}
public void setCadsrModule(CadsrModule cadsrModule){
this.cadsrModule = cadsrModule;
}
public void addElementChangeListener(ElementChangeListener listener){
changeListeners.add(listener);
}
private void fireElementChangeEvent(ElementChangeEvent event) {
for(ElementChangeListener l : changeListeners)
l.elementChanged(event);
}
private void firePropertyChangeEvent(PropertyChangeEvent evt) {
for(PropertyChangeListener l : propChangeListeners)
l.propertyChange(evt);
}
private String getFormatedDate(java.util.Date date){
return DateFormat.getDateTimeInstance().format(date);
}
public String getPubId() {
return tempVD.getPublicId();
}
public boolean isApplied() {
return applied;
}
public void setApplied(boolean applied) {
this.applied = applied;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
super.addPropertyChangeListener(l);;
propChangeListeners.add(l);
}
}
|
// $Id: AnimationSequencer.java,v 1.17 2004/11/11 23:53:06 mdb Exp $
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media.animation;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import com.samskivert.util.StringUtil;
import com.threerings.media.Log;
/**
* An animation that provides facilities for adding a sequence of
* animations that are fired after a fixed time interval has elapsed or
* after previous animations in the sequence have completed. Facilities
* are also provided for running code upon the completion of animations in
* the sequence.
*/
public class AnimationSequencer extends Animation
{
/**
* Constructs an animation sequencer with the expectation that
* animations will be added via subsequent calls to {@link
* #addAnimation}.
*
* @param animmgr the animation manager to which to add our animations
* when they are ready to start.
*/
public AnimationSequencer (AnimationManager animmgr)
{
super(new Rectangle());
_animmgr = animmgr;
}
/**
* Adds the supplied animation to the sequence with the given
* parameters. Note that care should be taken if this is called after
* the animation sequence has begun firing animations. Do not add new
* animations after the final animation in the sequence has been
* started or you run the risk of attempting to add an animation to
* the sequence after it thinks that it has finished (in which case
* this method will fail).
*
* @param anim the animation to be sequenced, or null if the
* completion action should be run immediately when this "animation"
* is ready to fired.
* @param delta the number of milliseconds following the
* <em>start</em> of the previous animation in the queue that this
* animation should be started; 0 if it should be started
* simultaneously with its predecessor int the queue; -1 if it should
* be started when its predecessor has completed.
* @param completionAction a runnable to be executed when this
* animation completes.
*/
public void addAnimation (
Animation anim, long delta, Runnable completionAction)
{
// sanity check
if (_finished) {
throw new IllegalStateException(
"Animation added to finished sequencer");
}
// if this guy is triggering on a previous animation, grab that
// good fellow here
AnimRecord trigger = null;
if (delta == -1) {
if (_queued.size() > 0) {
// if there are queued animations we want the most
// recently queued animation
trigger = (AnimRecord)_queued.get(_queued.size()-1);
} else if (_running.size() > 0) {
// otherwise, if there are running animations, we want the
// last one in that list
trigger = (AnimRecord)_running.get(_running.size()-1);
}
// otherwise we have no trigger, we'll just start ASAP
}
AnimRecord arec = new AnimRecord(
anim, delta, trigger, completionAction);
// Log.info("Queued " + arec + ".");
_queued.add(arec);
}
/**
* Clears out the animations being managed by this sequencer.
*/
public void clear ()
{
_queued.clear();
_lastStamp = 0;
}
// documentation inherited
public void tick (long tickStamp)
{
if (_lastStamp == 0) {
_lastStamp = tickStamp;
}
// add all animations whose time has come
while (_queued.size() > 0) {
AnimRecord arec = (AnimRecord)_queued.get(0);
if (!arec.readyToFire(tickStamp, _lastStamp)) {
// if it's not time to add this animation, all subsequent
// animations must surely wait as well
break;
}
// remove it from queued and put it on the running list
_queued.remove(0);
_running.add(arec);
// note that we've advanced to the next animation
_lastStamp = tickStamp;
// fire in the hole!
arec.fire(tickStamp);
}
// we're done when both lists are empty
// boolean finished = _finished;
_finished = ((_queued.size() + _running.size()) == 0);
// if (!finished && _finished) {
// Log.info("Finishing sequence at " + (tickStamp%10000) + ".");
}
// documentation inherited
public void paint (Graphics2D gfx)
{
// don't care
}
// documentation inherited
public void fastForward (long timeDelta)
{
_lastStamp += timeDelta;
}
// documentation inherited
public void viewLocationDidChange (int dx, int dy)
{
super.viewLocationDidChange(dx, dy);
// track cumulative view location changes so that we can adjust our
// animations before we start them
_vdx += dx;
_vdy += dy;
}
/**
* Called when the time comes to start an animation. Derived classes
* may override this method and pass the animation on to their
* animation manager and do whatever else they need to do with
* operating animations. The default implementation simply adds them
* to the media panel supplied when we were constructed.
*
* @param anim the animation to be displayed.
* @param tickStamp the timestamp at which this animation was fired.
*/
protected void startAnimation (Animation anim, long tickStamp)
{
// account for any view scrolling that happened before this animation
// was actually added to the view
if (_vdx != 0 || _vdy != 0) {
anim.viewLocationDidChange(_vdx, _vdy);
}
_animmgr.registerAnimation(anim);
}
protected class AnimRecord extends AnimationAdapter
{
public AnimRecord (Animation anim, long delta, AnimRecord trigger,
Runnable completionAction) {
_anim = anim;
_delta = delta;
_trigger = trigger;
_completionAction = completionAction;
}
public boolean readyToFire (long now, long lastStamp)
{
if (_delta == -1) {
// if we have no trigger, that means we should start
// immediately, otherwise we wait until our trigger is no
// longer running (they are guaranteed not to be still
// queued at this point because readyToFire is only called
// on an animation after all animations previous in the
// queue have been started)
return (_trigger == null) ?
true : !_running.contains(_trigger);
} else {
return (lastStamp + _delta <= now);
}
}
public void fire (long when)
{
// Log.info("Firing " + this + " at " + (when%10000) + ".");
// if we have an animation, start it up and await its
// completion
if (_anim != null) {
startAnimation(_anim, when);
_anim.addAnimationObserver(this);
} else {
// since there's no animation, we need to fire our
// completion routine immediately
fireCompletion(when);
}
}
public void fireCompletion (long when)
{
// Log.info("Completing " + this + " at " + (when%10000) + ".");
// call the completion action, if there is one
if (_completionAction != null) {
try {
_completionAction.run();
} catch (Throwable t) {
Log.logStackTrace(t);
}
}
// make a note that this animation is complete
_running.remove(this);
// kids, don't try this at home; we call tick() immediately so
// that any animations triggered on the completion of previous
// animations can trigger on the completion of this animation
// rather than having to wait until the next tick to do so
tick(when);
}
public void animationCompleted (Animation anim, long when)
{
fireCompletion(when);
}
public String toString ()
{
return "[anim=" + StringUtil.shortClassName(_anim) +
((_anim == null) ? "" : ("/" + _anim.hashCode())) +
", action=" + _completionAction +
", delta=" + _delta + ", trig=" + (_trigger != null) + "]";
}
protected Animation _anim;
protected Runnable _completionAction;
protected long _delta;
protected AnimRecord _trigger;
}
/** The animation manager in which we run animations. */
protected AnimationManager _animmgr;
/** Animations that have not been fired. */
protected ArrayList _queued = new ArrayList();
/** Animations that are currently running. */
protected ArrayList _running = new ArrayList();
/** The timestamp at which we fired the last animation. */
protected long _lastStamp;
/** Used to track view scrolling while animations are in limbo. */
protected int _vdx, _vdy;
}
|
package edu.csus.ecs.moneybeets.narvaro.model;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import edu.csus.ecs.moneybeets.narvaro.database.DatabaseManager;
/**
* This class manages creation and storage of Narvaro data objects.
*
*/
public enum DataManager {
Narvaro,
;
private DataManager() {
}
private static final Logger LOG = Logger.getLogger(DataManager.class.getName());
private Connection con;
private ResultSet rs = null;
/*******************************************************************************************
* Selection queries
*/
/**
* Returns an integer > 0 if there is a record matching the <code>YearMonth</code> and park name.
*
* Input:
* 1) <code>YearMonth</code>
* 2) parkName
*
* Output:
* 1) An integer > 0 if there is already a record.
*/
private static final String selectDoesMonthDataExist = "SELECT data.id FROM data JOIN parks ON data.park = parks.id WHERE data.month = ? AND parks.name = ? LIMIT 1";
/**
* Gets database id of a park by name.
*
* Input:
* 1) parkName
*
* Output:
* 1) id
*/
private static final String selectParkIdByName = "SELECT id FROM parks WHERE parks.name = ?";
/**
* Gets the parkName of a park by id.
*
* Input:
* 1) id
*
* Output:
* 1) parkName
*/
private static final String selectParkNameById = "SELECT name FROM parks WHERE parks.id = ?";
/**
* Gets all park names.
*
* Input:
* none
*
* Output:
* 1) parkName
*/
private static final String selectAllParkNames = "SELECT name FROM parks";
/**
* Returns all column names from the `data` table of the schema.
*/
private static final String selectSchemaColumnNamesFromData = "SELECT `COLUMN_NAME` FROM "
+ "`INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = 'narvaro' AND `TABLE_NAME` = 'data'";
/**
* Gets all park id's and names.
*
* Input:
* none
*
* Output:
* 1) id
* 2) parkName
*/
private static final String selectAllParkNamesAndIds = "SELECT id, name FROM parks";
/**
* Gets all park id's and names that have data within the specified date range.
*
* Input:
* 1) starting date
* 2) ending date
*
* Output:
* 1) id
* 2) parkName
*/
private static final String selectAllParkNamesAndIdsExistInRange = "SELECT DISTINCT parks.id, parks.name FROM parks "
+ "JOIN data ON parks.id = data.park WHERE data.month >= ? AND data.month <= ?";
/**
* Selects a single 449 Form's filename using it's row ID as a lookup.
*
* Input:
* 1) row id
*
* Output:
* 1) Form filename
*/
private static final String selectForm449FileNameById = "SELECT forms.filename FROM forms WHERE forms.id = ?";
/**
* Gets all park data for the specified date range.
*
* Input:
* 1) starting date
* 2) ending date
*
* Output:
* 1) parkName
* 2) month
* 3) pduConversionFactor
* 4) pduTotals
* 5) pduSpecialEvents
* 6) pduAnnualDayUse
* 7) pduDayUse
* 8) pduSenior
* 9) pduDisabled
* 10) pduGoldenBear
* 11) pduDisabledVeteran
* 12) pduNonResOHVPass
* 13) pduAnnualPassSale
* 14) pduCamping
* 15) pduSeniorCamping
* 16) pduDisabledCamping
* 17) fduConversionFactor
* 18) fduTotals
* 19) fscTotalVehicles
* 20) fscTotalPeople
* 21) fscRatio
* 22) oMC
* 23) oATV
* 24) o4X4
* 25) oROV
* 26) oAQMA
* 27) oAllStarKarting
* 28) oHangTown
* 29) oOther
* 30) comment
* 31) formId
*/
private static final String selectAllMonthDataByRange = "SELECT parks.name, data.month, data.pduConversionFactor, "
+ "data.pduTotals, data.pduSpecialEvents, data.pduAnnualDayUse, data.pduDayUse, data.pduSenior, "
+ "data.pduDisabled, data.pduGoldenBear, data.pduDisabledVeteran, data.pduNonResOHVPass, "
+ "data.pduAnnualPassSale, data.pduCamping, data.pduSeniorCamping, data.pduDisabledCamping, "
+ "data.fduConversionFactor, data.fduTotals, data.fscTotalVehicles, data.fscTotalPeople, "
+ "data.fscRatio, data.oMC, data.oATV, data.o4X4, data.oROV, data.oAQMA, data.oAllStarKarting, "
+ "data.oHangtown, data.oOther, data.comment, forms.id "
+ "FROM data JOIN parks ON data.park = parks.id "
+ "JOIN forms ON data.form449 = forms.id "
+ "WHERE data.month >= ? AND data.month <= ?";
/**
* Gets all park data for the specified park by name.
*
* Input:
* 1) parkName
*
* Output:
* 1) parkName
* 2) month
* 3) pduConversionFactor
* 4) pduTotals
* 5) pduSpecialEvents
* 6) pduAnnualDayUse
* 7) pduDayUse
* 8) pduSenior
* 9) pduDisabled
* 10) pduGoldenBear
* 11) pduDisabledVeteran
* 12) pduNonResOHVPass
* 13) pduAnnualPassSale
* 14) pduCamping
* 15) pduSeniorCamping
* 16) pduDisabledCamping
* 17) fduConversionFactor
* 18) fduTotals
* 19) fscTotalVehicles
* 20) fscTotalPeople
* 21) fscRatio
* 22) oMC
* 23) oATV
* 24) o4X4
* 25) oROV
* 26) oAQMA
* 27) oAllStarKarting
* 28) oHangTown
* 29) oOther
* 30) comment
* 31) formId
*/
private static final String selectMonthDataByPark = "SELECT parks.name, data.month, data.pduConversionFactor, "
+ "data.pduTotals, data.pduSpecialEvents, data.pduAnnualDayUse, data.pduDayUse, data.pduSenior, "
+ "data.pduDisabled, data.pduGoldenBear, data.pduDisabledVeteran, data.pduNonResOHVPass, "
+ "data.pduAnnualPassSale, data.pduCamping, data.pduSeniorCamping, data.pduDisabledCamping, "
+ "data.fduConversionFactor, data.fduTotals, data.fscTotalVehicles, data.fscTotalPeople, "
+ "data.fscRatio, data.oMC, data.oATV, data.o4X4, data.oROV, data.oAQMA, data.oAllStarKarting, "
+ "data.oHangtown, data.oOther, data.comment, forms.id "
+ "FROM data JOIN parks ON data.park = parks.id "
+ "JOIN forms ON data.form449 = forms.id "
+ "WHERE parks.name = ?";
private static final String selectMonthDataByParkAndYearMonth = "SELECT parks.name, data.month, data.pduConversionFactor, "
+ "data.pduTotals, data.pduSpecialEvents, data.pduAnnualDayUse, data.pduDayUse, data.pduSenior, "
+ "data.pduDisabled, data.pduGoldenBear, data.pduDisabledVeteran, data.pduNonResOHVPass, "
+ "data.pduAnnualPassSale, data.pduCamping, data.pduSeniorCamping, data.pduDisabledCamping, "
+ "data.fduConversionFactor, data.fduTotals, data.fscTotalVehicles, data.fscTotalPeople, "
+ "data.fscRatio, data.oMC, data.oATV, data.o4X4, data.oROV, data.oAQMA, data.oAllStarKarting, "
+ "data.oHangtown, data.oOther, data.comment, forms.id "
+ "FROM data JOIN parks ON data.park = parks.id "
+ "JOIN forms ON data.form449 = forms.id "
+ "WHERE parks.name = ? AND data.month = ?";
private static final String selectMonthDataByParkNameAndRange = "SELECT parks.name, data.month, data.pduConversionFactor, "
+ "data.pduTotals, data.pduSpecialEvents, data.pduAnnualDayUse, data.pduDayUse, data.pduSenior, "
+ "data.pduDisabled, data.pduGoldenBear, data.pduDisabledVeteran, data.pduNonResOHVPass, "
+ "data.pduAnnualPassSale, data.pduCamping, data.pduSeniorCamping, data.pduDisabledCamping, "
+ "data.fduConversionFactor, data.fduTotals, data.fscTotalVehicles, data.fscTotalPeople, "
+ "data.fscRatio, data.oMC, data.oATV, data.o4X4, data.oROV, data.oAQMA, data.oAllStarKarting, "
+ "data.oHangtown, data.oOther, data.comment, forms.id "
+ "FROM data JOIN parks ON data.park = parks.id "
+ "JOIN forms ON data.form449 = forms.id "
+ "WHERE parks.name = ? AND data.month >= ? AND data.month <= ?";
/*******************************************************************************************
* Insertion queries
*/
/**
* Inserts a new park by name into the database.
*
* Input:
* 1) parkName
*
* Output:
* none
*/
private static final String insertPark = "INSERT INTO parks (name) VALUES(?)";
/**
* Inserts a new 449 Form into the database.
*
* Input:
* 1) filename
* 2) InputStream of file
*
* Output:
* none
*/
private static final String insertForm = "INSERT INTO forms (filename, form) VALUES(?, ?)";
/**
* Inserts park month data into database.
* (Must be run after inserting 449 Form to have valid formId)
*
* Input:
* 1) parkId
* 2) month
* 3) pduConversionFactor
* 4) pduTotals
* 5) pduSpecialEvents
* 6) pduAnnualDayUse
* 7) pduDayUse
* 8) pduSenior
* 9) pduDisabled
* 10) pduGoldenBear
* 11) pduDisabledVeteran
* 12) pduNonResOHVPass
* 13) pduAnnualPassSale
* 14) pduCamping
* 15) pduSeniorCamping
* 16) pduDisabledCamping
* 17) fduConversionFactor
* 18) fduTotals
* 19) fscTotalVehicles
* 20) fscTotalPeople
* 21) fscRatio
* 22) oMC
* 23) oATV
* 24) o4X4
* 25) oROV
* 26) oAQMA
* 27) oAllStarKarting
* 28) oHangTown
* 29) oOther
* 30) comment
* 31) formId (automagically gotten from last insert)
*
* Output:
* none
*/
private static final String insertMonthData = "INSERT INTO data (park, month, pduConversionFactor, pduTotals, "
+ "pduSpecialEvents, pduAnnualDayUse, pduDayUse, pduSenior, pduDisabled, pduGoldenBear, pduDisabledVeteran, "
+ "pduNonResOHVPass, pduAnnualPassSale, pduCamping, pduSeniorCamping, pduDisabledCamping, fduConversionFactor, "
+ "fduTotals, fscTotalVehicles, fscTotalPeople, fscRatio, oMC, oATV, o4X4, oROV, oAQMA, oAllStarKarting, oHangtown, "
+ "oOther, comment, form449) "
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, LAST_INSERT_ID())";
/*******************************************************************************************
* Update queries
*/
/**
* Updates park month data into database.
* (Must be run after inserting 449 Form to have valid formId)
*
* Input:
* 1) pduConversionFactor
* 2) pduTotals
* 3) pduSpecialEvents
* 4) pduAnnualDayUse
* 5) pduDayUse
* 6) pduSenior
* 7) pduDisabled
* 8) pduGoldenBear
* 9) pduDisabledVeteran
* 10) pduNonResOHVPass
* 11) pduAnnualPassSale
* 12) pduCamping
* 13) pduSeniorCamping
* 14) pduDisabledCamping
* 15) fduConversionFactor
* 16) fduTotals
* 17) fscTotalVehicles
* 18) fscTotalPeople
* 19) fscRatio
* 20) oMC
* 21) oATV
* 22) o4X4
* 23) oROV
* 24) oAQMA
* 25) oAllStarKarting
* 26) oHangTown
* 27) oOther
* 28) comment
* 29) YearMonth
* 30) parkId
*
* Output:
* none
*/
private static final String updateMonthData = "UPDATE data SET pduConversionFactor = ?, pduTotals = ?, pduSpecialEvents = ?, "
+ "pduAnnualDayUse = ?, pduDayUse = ?, pduSenior = ?, pduDisabled = ?, pduGoldenBear = ?, pduDisabledVeteran = ?, "
+ "pduNonResOHVPass = ?, pduAnnualPassSale = ?, pduCamping = ?, pduSeniorCamping = ?, pduDisabledCamping = ?, "
+ "fduConversionFactor = ?, fduTotals = ?, fscTotalVehicles = ?, fscTotalPeople = ?, fscRatio = ?, oMC = ?, oATV = ?, "
+ "o4X4 = ?, oROV = ?, oAQMA = ?, oAllStarKarting = ?, oHangtown = ?, oOther = ?, comment = ?, form449 = LAST_INSERT_ID() "
+ "WHERE data.month = ? AND data.park = ?";
/**
* Updates a 449 Form.
*
* Input:
* 1) filename
* 2) InputStream of file
* 3) form id (row in database)
*
* Output:
* none
*/
private static final String updateForm = "UPDATE forms SET filename = ?, form = ? WHERE id = ?";
/**
* Setup all prepared statements for later use
*/
// select statements
private PreparedStatement psSelectDoesMonthDataExist = null;
private PreparedStatement psSelectParkIdByName = null;
private PreparedStatement psSelectParkNameById = null;
private PreparedStatement psSelectAllParkNames = null;
private PreparedStatement psSelectSchemaColumnNamesFromData = null;
private PreparedStatement psSelectAllParkNamesAndIds = null;
private PreparedStatement psSelectAllParkNamesAndIdsExistInRange = null;
private PreparedStatement psSelectForm449FileNameById = null;
private PreparedStatement psSelectAllMonthDataByRange = null;
private PreparedStatement psSelectMonthDataByPark = null;
private PreparedStatement psSelectMonthDataByParkAndYearMonth = null;
private PreparedStatement psSelectMonthDataByParkNameAndRange = null;
// insert statements
private PreparedStatement psInsertPark = null;
private PreparedStatement psInsertForm = null;
private PreparedStatement psInsertMonthData = null;
// update statements
private PreparedStatement psUpdateMonthData = null;
private PreparedStatement psUpdateForm = null;
/**
* Starts the Data Manager by first obtaining a database connection
* and then registering all prepared statements.
*/
public void start() {
try {
// get a database connection
con = DatabaseManager.Narvaro.getConnection();
// register all prepared statements
psSelectDoesMonthDataExist = con.prepareStatement(selectDoesMonthDataExist);
psSelectParkIdByName = con.prepareStatement(selectParkIdByName);
psSelectParkNameById = con.prepareStatement(selectParkNameById);
psSelectAllParkNames = con.prepareStatement(selectAllParkNames);
psSelectSchemaColumnNamesFromData = con.prepareStatement(selectSchemaColumnNamesFromData);
psSelectAllParkNamesAndIds = con.prepareStatement(selectAllParkNamesAndIds);
psSelectAllParkNamesAndIdsExistInRange = con.prepareStatement(selectAllParkNamesAndIdsExistInRange);
psSelectForm449FileNameById = con.prepareStatement(selectForm449FileNameById);
psSelectAllMonthDataByRange = con.prepareStatement(selectAllMonthDataByRange);
psSelectMonthDataByPark = con.prepareStatement(selectMonthDataByPark);
psSelectMonthDataByParkAndYearMonth = con.prepareStatement(selectMonthDataByParkAndYearMonth);
psSelectMonthDataByParkNameAndRange = con.prepareStatement(selectMonthDataByParkNameAndRange);
psInsertPark = con.prepareStatement(insertPark);
psInsertForm = con.prepareStatement(insertForm);
psInsertMonthData = con.prepareStatement(insertMonthData);
psUpdateMonthData = con.prepareStatement(updateMonthData);
psUpdateForm = con.prepareStatement(updateForm);
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
}
}
/**
* Shuts down the Data manager by closing all prepared statements,
* result sets, and connections.
*/
public void shutdown() {
DatabaseManager.Narvaro.closeStatement(psSelectDoesMonthDataExist);
DatabaseManager.Narvaro.closeStatement(psSelectParkIdByName);
DatabaseManager.Narvaro.closeStatement(psSelectParkNameById);
DatabaseManager.Narvaro.closeStatement(psSelectAllParkNames);
DatabaseManager.Narvaro.closeStatement(psSelectSchemaColumnNamesFromData);
DatabaseManager.Narvaro.closeStatement(psSelectAllParkNamesAndIds);
DatabaseManager.Narvaro.closeStatement(psSelectAllParkNamesAndIdsExistInRange);
DatabaseManager.Narvaro.closeStatement(psSelectForm449FileNameById);
DatabaseManager.Narvaro.closeStatement(psSelectAllMonthDataByRange);
DatabaseManager.Narvaro.closeStatement(psSelectMonthDataByPark);
DatabaseManager.Narvaro.closeStatement(psSelectMonthDataByParkAndYearMonth);
DatabaseManager.Narvaro.closeStatement(psSelectMonthDataByParkNameAndRange);
DatabaseManager.Narvaro.closeStatement(psInsertPark);
DatabaseManager.Narvaro.closeStatement(psInsertForm);
DatabaseManager.Narvaro.closeStatement(psInsertMonthData);
DatabaseManager.Narvaro.closeStatement(psUpdateMonthData);
DatabaseManager.Narvaro.closeStatement(psUpdateForm);
DatabaseManager.Narvaro.closeResultSet(rs);
DatabaseManager.Narvaro.closeConnection(con);
}
/**
* Retrieves a <code>TimeSpan</code> which spans from
* <code>YearMonth start</code> to <code>YearMonth</code>, inclusive.
*
* @param start Starting <code>YearMonth</code>.
* @param end Ending <code>YearMonth</code>.
* @return <code>TimeSpan</code> spanning the requested range.
* @throws SQLException If an SQLException occurs.
*/
public final TimeSpan getTimeSpan(final YearMonth start, final YearMonth end) throws SQLException {
// create base timespan
TimeSpan timeSpan = new TimeSpan(start, end);
// discover valid park names that have data in the range
// and create base ParkMonths
try {
psSelectAllParkNamesAndIdsExistInRange.setDate(1, DataManager.yearMonthToDate(start));
psSelectAllParkNamesAndIdsExistInRange.setDate(2, DataManager.yearMonthToDate(end));
rs = psSelectAllParkNamesAndIdsExistInRange.executeQuery();
if (rs != null) {
while (rs.next()) {
// parkname is the second column in this result set
String parkName = rs.getString(2);
timeSpan.putParkMonth(parkName, new ParkMonth(parkName));
}
}
} catch (SQLException e) {
// log and then throw exception
LOG.error(e.getMessage(), e);
throw new SQLException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception ex) {
LOG.warn(ex.getMessage(), ex);
}
rs = null;
}
// fetch data from range and populate MonthDatas
try {
psSelectAllMonthDataByRange.setDate(1, DataManager.yearMonthToDate(start));
psSelectAllMonthDataByRange.setDate(2, DataManager.yearMonthToDate(end));
rs = psSelectAllMonthDataByRange.executeQuery();
if (rs != null) {
while (rs.next()) {
// create a base month data
MonthData md = new MonthData(dateToYearMonth(rs.getDate(2)), rs.getBigDecimal(3),
rs.getLong(4), rs.getLong(5), rs.getLong(6), rs.getLong(7), rs.getLong(8),
rs.getLong(9), rs.getLong(10), rs.getLong(11), rs.getLong(12), rs.getLong(13),
rs.getLong(14), rs.getLong(15), rs.getLong(16), rs.getBigDecimal(17), rs.getLong(18),
rs.getLong(19), rs.getLong(20), rs.getBigDecimal(21), rs.getLong(22), rs.getLong(23),
rs.getLong(24), rs.getLong(25), rs.getLong(26), rs.getLong(27), rs.getLong(28),
rs.getLong(29), rs.getString(30), rs.getLong(31), null);
// store it in the timepsan for the proper park
timeSpan.getParkMonth(rs.getString(1)).putMonthData(dateToYearMonth(rs.getDate(2)), md);
}
}
} catch (SQLException e) {
// log and then throw exception
LOG.error(e.getMessage(), e);
throw new SQLException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception ex) {
LOG.warn(ex.getMessage(), ex);
}
rs = null;
}
return timeSpan;
}
/**
* Returns a <code>MonthData</code> for the specified <code>YearMonth</code> and park name.
*
* @param ym The <code>YearMonth</code>.
* @param parkName The Park name.
* @return a <code>MonthData</code>.
* @throws SQLException if an SQLException occurs.
*/
public final MonthData getMonthDataForParkAndYearMonth(final YearMonth ym, final String parkName) throws SQLException {
psSelectMonthDataByParkAndYearMonth.setString(1, parkName);
psSelectMonthDataByParkAndYearMonth.setDate(2, yearMonthToDate(ym));
try {
rs = psSelectMonthDataByParkAndYearMonth.executeQuery();
// should only have 1 result
if (rs != null && rs.next()) {
return new MonthData(dateToYearMonth(rs.getDate(2)), rs.getBigDecimal(3),
rs.getLong(4), rs.getLong(5), rs.getLong(6), rs.getLong(7), rs.getLong(8),
rs.getLong(9), rs.getLong(10), rs.getLong(11), rs.getLong(12), rs.getLong(13),
rs.getLong(14), rs.getLong(15), rs.getLong(16), rs.getBigDecimal(17), rs.getLong(18),
rs.getLong(19), rs.getLong(20), rs.getBigDecimal(21), rs.getLong(22), rs.getLong(23),
rs.getLong(24), rs.getLong(25), rs.getLong(26), rs.getLong(27), rs.getLong(28),
rs.getLong(29), rs.getString(30), rs.getLong(31), null);
} else {
throw new SQLException("No results");
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new SQLException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
}
rs = null;
}
}
/**
* Returns a <code>TimeSpan</code> for the specified range and park by name.
*
* @param start Staring <code>YearMonth</code>.
* @param end Ending <code>YearMonth</code>.
* @param parkName The park name.
* @return <code>TimeSpan</code> for the specified range and park by name.
* @throws SQLException If an SQLException occurs.
*/
public final TimeSpan getTimeSpanForPark(
final YearMonth start, final YearMonth end, final String parkName) throws SQLException {
TimeSpan ts = new TimeSpan(start, end);
ParkMonth pm = new ParkMonth(parkName);
ts.putParkMonth(parkName, pm);
psSelectMonthDataByParkNameAndRange.setString(1, parkName);
psSelectMonthDataByParkNameAndRange.setDate(2, yearMonthToDate(start));
psSelectMonthDataByParkNameAndRange.setDate(3, yearMonthToDate(end));
try {
rs = psSelectMonthDataByParkNameAndRange.executeQuery();
if (rs != null) {
while (rs.next()) {
YearMonth ym = dateToYearMonth(rs.getDate(2));
MonthData md = new MonthData(ym, rs.getBigDecimal(3), rs.getLong(4),
rs.getLong(5), rs.getLong(6), rs.getLong(7), rs.getLong(8), rs.getLong(9), rs.getLong(10),
rs.getLong(11), rs.getLong(12), rs.getLong(13), rs.getLong(14), rs.getLong(15), rs.getLong(16),
rs.getBigDecimal(17), rs.getLong(18), rs.getLong(19), rs.getLong(20), rs.getBigDecimal(21),
rs.getLong(22), rs.getLong(23), rs.getLong(24), rs.getLong(25), rs.getLong(26), rs.getLong(27),
rs.getLong(28), rs.getLong(29), rs.getString(30), rs.getInt(31), null);
pm.putMonthData(ym, md);
}
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new SQLException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
}
rs = null;
}
return ts;
}
/**
* Stores a <code>ParkMonth</code> into the database.
* First writes a MonthData's 449 Form then writes the MonthData.
*
* @param pm The ParkMonth
* @throws SQLException If an SQL Exception occurs.
*/
public void storeParkMonth(final ParkMonth pm) throws SQLException {
int parkId = -1;
if (pm != null) {
try {
// get the parkId from the database
psSelectParkIdByName.setString(1, pm.getParkName());
rs = psSelectParkIdByName.executeQuery();
// should only have a single result
rs.next();
parkId = rs.getInt(1);
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
throw new SQLException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
}
rs = null;
}
if (parkId > 0) {
for (MonthData md : pm.getAllMonthData()) {
if (doesRecordExist(md.getMonth(), pm.getParkName())) {
updateMonthData(md, parkId);
} else {
insertMonthData(md, parkId);
}
}
} else {
throw new SQLException("Park Id not found for park: " + pm.getParkName());
}
}
}
private void insertMonthData(final MonthData md, final long parkId) throws SQLException {
// insert 449 Form into database
insert449Form(md);
// insert monthdata
psInsertMonthData.setLong(1, parkId);
psInsertMonthData.setDate(2, yearMonthToDate(md.getMonth()));
psInsertMonthData.setBigDecimal(3, md.getPduConversionFactor());
psInsertMonthData.setLong(4, md.getPduTotals());
psInsertMonthData.setLong(5, md.getPduSpecialEvents());
psInsertMonthData.setLong(6, md.getPduAnnualDayUse());
psInsertMonthData.setLong(7, md.getPduDayUse());
psInsertMonthData.setLong(8, md.getPduSenior());
psInsertMonthData.setLong(9, md.getPduDisabled());
psInsertMonthData.setLong(10, md.getPduGoldenBear());
psInsertMonthData.setLong(11, md.getPduDisabledVeteran());
psInsertMonthData.setLong(12, md.getPduNonResOHVPass());
psInsertMonthData.setLong(13, md.getPduAnnualPassSale());
psInsertMonthData.setLong(14, md.getPduCamping());
psInsertMonthData.setLong(15, md.getPduSeniorCamping());
psInsertMonthData.setLong(16, md.getPduDisabledCamping());
psInsertMonthData.setBigDecimal(17, md.getFduConversionFactor());
psInsertMonthData.setLong(18, md.getFduTotals());
psInsertMonthData.setLong(19, md.getFscTotalVehicles());
psInsertMonthData.setLong(20, md.getFscTotalPeople());
psInsertMonthData.setBigDecimal(21, md.getFscRatio());
psInsertMonthData.setLong(22, md.getoMC());
psInsertMonthData.setLong(23, md.getoATV());
psInsertMonthData.setLong(24, md.getO4X4());
psInsertMonthData.setLong(25, md.getoROV());
psInsertMonthData.setLong(26, md.getoAQMA());
psInsertMonthData.setLong(27, md.getoAllStarKarting());
psInsertMonthData.setLong(28, md.getoHangtown());
psInsertMonthData.setLong(29, md.getoOther());
psInsertMonthData.setString(30, md.getComment());
psInsertMonthData.execute();
}
private void updateMonthData(final MonthData md, final long parkId) throws SQLException {
// insert new 449 Form in database
insert449Form(md);
// update monthdata
psUpdateMonthData.setBigDecimal(1, md.getPduConversionFactor());
psUpdateMonthData.setLong(2, md.getPduTotals());
psUpdateMonthData.setLong(3, md.getPduSpecialEvents());
psUpdateMonthData.setLong(4, md.getPduAnnualDayUse());
psUpdateMonthData.setLong(5, md.getPduDayUse());
psUpdateMonthData.setLong(6, md.getPduSenior());
psUpdateMonthData.setLong(7, md.getPduDisabled());
psUpdateMonthData.setLong(8, md.getPduGoldenBear());
psUpdateMonthData.setLong(9, md.getPduDisabledVeteran());
psUpdateMonthData.setLong(10, md.getPduNonResOHVPass());
psUpdateMonthData.setLong(11, md.getPduAnnualPassSale());
psUpdateMonthData.setLong(12, md.getPduCamping());
psUpdateMonthData.setLong(13, md.getPduSeniorCamping());
psUpdateMonthData.setLong(14, md.getPduDisabledCamping());
psUpdateMonthData.setBigDecimal(15, md.getFduConversionFactor());
psUpdateMonthData.setLong(16, md.getFduTotals());
psUpdateMonthData.setLong(17, md.getFscTotalVehicles());
psUpdateMonthData.setLong(18, md.getFscTotalPeople());
psUpdateMonthData.setBigDecimal(19, md.getFscRatio());
psUpdateMonthData.setLong(20, md.getoMC());
psUpdateMonthData.setLong(21, md.getoATV());
psUpdateMonthData.setLong(22, md.getO4X4());
psUpdateMonthData.setLong(23, md.getoROV());
psUpdateMonthData.setLong(24, md.getoAQMA());
psUpdateMonthData.setLong(25, md.getoAllStarKarting());
psUpdateMonthData.setLong(26, md.getoHangtown());
psUpdateMonthData.setLong(27, md.getoOther());
psUpdateMonthData.setString(28, md.getComment());
psUpdateMonthData.setDate(29, yearMonthToDate(md.getMonth()));
psUpdateMonthData.setLong(30, parkId);
psUpdateMonthData.execute();
}
private void insert449Form(final MonthData md) throws SQLException {
Blob blob = null;
try {
Path path = md.getForm449File().toPath();
byte[] pathBytes = Files.readAllBytes(path);
blob = con.createBlob();
blob.setBytes(1, pathBytes);
psInsertForm.setString(1, md.getForm449File().getName());
psInsertForm.setBlob(2, blob);
psInsertForm.execute();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally {
if (blob != null) {
blob.free();
}
blob = null;
}
}
/**
* Stores an array of <code>ParkMonth</code> in the database.
*
* @param pms An array of <code>ParkMonth</code>.
* @throws SQLException
*/
public void storeAllParkMonth(final ParkMonth ... pms) throws SQLException {
// cheating for now, can probably make this less hacky
for (ParkMonth pm : pms) {
storeParkMonth(pm);
}
}
/**
* Stores a <code>Collection</code> of <code>ParkMonth</code> in the database.
*
* @param pms A <code>Collection</code> of <code>ParkMonth</code>.
* @throws SQLException If an SQLException occurs.
*/
public void storeAllParkMonth(final Collection<ParkMonth> pms) throws SQLException {
// cheating for now, can probably make this less hacky
for (ParkMonth pm : pms) {
storeParkMonth(pm);
}
}
/**
* @return A <code>List</code> of park name strings.
*/
public List<String> getAllParkNames() {
List<String> parkNames = new ArrayList<String>();
try {
rs = psSelectAllParkNames.executeQuery();
if (rs != null) {
while (rs.next()) {
parkNames.add(rs.getString(1));
}
}
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
}
rs = null;
}
return parkNames;
}
/**
* Inserts a new park name into the database.
*
* If any exception is thrown, the park was not added.
*
* @param parkName The parkname.
* @throws SQLException If any SQLException occurs.
*/
public void insertParkName(final String parkName) throws SQLException {
if ("".equals(parkName) || parkName == null) {
throw new SQLException("Park Name cannot be empty or null");
}
psInsertPark.setString(1, parkName);
psInsertPark.execute();
}
/**
* Determines if a record already exists in the database.
*
* @param ym The <code>YearMonth</code>.
* @param parkName The park name.
* @return True if the record exists.
* @throws SQLException If an SQLException occurs.
*/
public boolean doesRecordExist(final YearMonth ym, final String parkName) throws SQLException {
if (ym == null) throw new SQLException("YearMonth cannot be null");
if ("".equals(parkName) || parkName == null) throw new SQLException("parkName cannot be empty or null");
psSelectDoesMonthDataExist.setDate(1, yearMonthToDate(ym));
psSelectDoesMonthDataExist.setString(2, parkName);
try {
rs = psSelectDoesMonthDataExist.executeQuery();
if (rs != null) {
// should only have a single result
rs.next();
if (rs.isBeforeFirst()) {
int row = rs.getInt(1);
if (row > 0) {
return true;
}
}
return false;
}
} catch (SQLException e) {
// log and throw
LOG.error(e.getMessage(), e);
throw e;
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
}
rs = null;
}
return false;
}
/**
* Returns a query string for the specified input.
*
* Used to build a custom query for graphing data.
*
* @param field The column to graph.
* @param start The starting <code>YearMonth</code>.
* @param end The ending <code>YearMonth</code>.
* @param parkName The park name.
* @return The custom query.
*/
private String getCustomGraphQuery(final String field,
final YearMonth start, final YearMonth end, final String parkName) {
StringBuilder sb = new StringBuilder("SELECT ");
sb.append(field);
sb.append(", month");
sb.append(" FROM data JOIN parks ON data.park = parks.id WHERE ");
sb.append("month >= ");
sb.append(yearMonthToDate(start));
sb.append(" AND month <= ");
sb.append(yearMonthToDate(end));
sb.append(" AND parks.name = ");
sb.append(parkName);
return sb.toString();
}
/**
* Returns a Map of Maps, which represent graph data.
*
* Map has key of ParkName,
* and value of a Map, which has key of YearMonth and value of field data.
*
* @param field The field to query data from.
* @param start The starting <code>YearMonth</code>.
* @param end The ending <code>YearMonth</code>.
* @param parkNames The list of park names.
* @return A map of data.
*/
public final Map<String, HashMap<YearMonth, Long>> getGraphData(
final String field, final YearMonth start, final YearMonth end, final List<String> parkNames) {
Map<String, HashMap<YearMonth, Long>> map =
new HashMap<String, HashMap<YearMonth, Long>>();
for (String parkName : parkNames) {
String query = getCustomGraphQuery(field, start, end, parkName);
PreparedStatement statement = null;
ResultSet results = null;
try {
statement = con.prepareStatement(query);
results = statement.executeQuery();
if (results != null) {
while (results.next()) {
HashMap<YearMonth, Long> m = new HashMap<YearMonth, Long>();
m.put(dateToYearMonth(results.getDate(2)), results.getLong(1));
map.put(parkName, m);
}
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
} finally {
DatabaseManager.Narvaro.closeStatement(results, statement);
}
}
return map;
}
/**
* @return a List of all column names in the data table.
*/
public List<String> getSchemaColumnNamesFromData() {
List<String> s = new ArrayList<String>();
try {
rs = psSelectSchemaColumnNamesFromData.executeQuery();
if (rs != null) {
while(rs.next()) {
s.add(rs.getString(1));
}
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
}
rs = null;
}
return s;
}
/**
* Utility method to convert a <code>YearMonth</code> into a <code>java.sql.Date</code>.
*
* @param ym The <code>YearMonth</code> to convert.
* @return The converted date.
*/
public static Date yearMonthToDate(final YearMonth ym) {
Calendar cal = Calendar.getInstance();
cal.clear();
// Gregorian calendar has months 0 - 11, 0 being January.
// java.time is more sane and has months 1 - 12, 1 being January.
// So we must convert them here...
cal.set(Calendar.MONTH, (ym.getMonthValue() - 1));
// Since we cannot have a date object without a day, we must pick one
// or the system will use today, whatever day of the month that happens to be.
// So to avoid situations where it's the 30th day of the month, but the user is
// trying to work with February (29 days), we should pick a sane default... the 1st.
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.YEAR, ym.getYear());
return new Date(cal.getTime().getTime());
}
/**
* Converts a <code>java.sql.Date</code> into a <code>YearMonth</code>.
*
* @param date the <code>java.sql.Date</code> to convert.
* @return The converted <code>YearMonth</code>.
*/
public static YearMonth dateToYearMonth(final Date date) {
return YearMonth.from(date.toLocalDate());
}
}
|
package org.antlr.jetbrains.sample;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.jetbrains.adaptor.lexer.PSIElementTypeFactory;
import org.antlr.jetbrains.adaptor.lexer.RuleIElementType;
import org.antlr.jetbrains.adaptor.lexer.TokenIElementType;
import org.antlr.jetbrains.adaptor.parser.ANTLRParserAdaptor;
import org.antlr.jetbrains.adaptor.psi.ANTLRPsiNodeAdaptor;
import org.antlr.jetbrains.sample.parser.SampleLanguageLexer;
import org.antlr.jetbrains.sample.parser.SampleLanguageParser;
import org.antlr.jetbrains.sample.psi.FunctionSubtree;
import org.antlr.jetbrains.sample.psi.SamplePSIFileRoot;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.tree.ParseTree;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class SampleParserDefinition implements ParserDefinition {
public static final IFileElementType FILE =
new IFileElementType(SampleLanguage.INSTANCE);
public static TokenIElementType ID;
static {
PSIElementTypeFactory.defineLanguageIElementTypes(SampleLanguage.INSTANCE,
SampleLanguageParser.tokenNames,
SampleLanguageParser.ruleNames);
List<TokenIElementType> tokenIElementTypes =
PSIElementTypeFactory.getTokenIElementTypes(SampleLanguage.INSTANCE);
ID = tokenIElementTypes.get(SampleLanguageLexer.ID);
}
public static final TokenSet COMMENTS =
PSIElementTypeFactory.createTokenSet(
SampleLanguage.INSTANCE,
SampleLanguageLexer.COMMENT,
SampleLanguageLexer.LINE_COMMENT);
public static final TokenSet WHITESPACE =
PSIElementTypeFactory.createTokenSet(
SampleLanguage.INSTANCE,
SampleLanguageLexer.WS);
public static final TokenSet STRING =
PSIElementTypeFactory.createTokenSet(
SampleLanguage.INSTANCE,
SampleLanguageLexer.STRING);
@NotNull
@Override
public Lexer createLexer(Project project) {
SampleLanguageLexer lexer = new SampleLanguageLexer(null);
return new ANTLRLexerAdaptor(SampleLanguage.INSTANCE, lexer);
}
@NotNull
public PsiParser createParser(final Project project) {
final SampleLanguageParser parser = new SampleLanguageParser(null);
return new ANTLRParserAdaptor(SampleLanguage.INSTANCE, parser) {
@Override
protected ParseTree parse(Parser parser, IElementType root) {
// start rule is always script and so it must also handle
// plain ID tokens for renaming.
return ((SampleLanguageParser) parser).script();
}
};
}
/** "Tokens of those types are automatically skipped by PsiBuilder." */
@NotNull
public TokenSet getWhitespaceTokens() {
return WHITESPACE;
}
@NotNull
public TokenSet getCommentTokens() {
return COMMENTS;
}
@NotNull
public TokenSet getStringLiteralElements() {
return STRING;
}
public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) {
return SpaceRequirements.MAY;
}
/** What is the IFileElementType of the root parse tree node? It
* is called from {@link #createFile(FileViewProvider)} at least.
*/
@Override
public IFileElementType getFileNodeType() {
return FILE;
}
/** Create the root of your PSI tree (a PsiFile).
*
* From IntelliJ IDEA Architectural Overview:
* "A PSI (Program Structure Interface) file is the root of a structure
* representing the contents of a file as a hierarchy of elements
* in a particular programming language."
*
* PsiFile is to be distinguished from a FileASTNode, which is a parse
* tree node that eventually becomes a PsiFile. From PsiFile, we can get
* it back via: {@link PsiFile#getNode}.
*/
@Override
public PsiFile createFile(FileViewProvider viewProvider) {
return new SamplePSIFileRoot(viewProvider);
}
/** Convert from *NON-LEAF* parse node (AST they call it)
* to PSI node. Leaves are created in the AST factory.
* Rename re-factoring can cause this to be
* called on a TokenIElementType since we want to rename ID nodes.
* In that case, this method is called to create the root node
* but with ID type. Kind of strange, but we can simply create a
* ASTWrapperPsiElement to make everything work correctly.
*
* RuleIElementType. Ah! It's that ID is the root
* IElementType requested to parse, which means that the root
* node returned from parsetree->PSI conversion. But, it
* must be a CompositeElement! The adaptor calls
* rootMarker.done(root) to finish off the PSI conversion.
* See {@link ANTLRParserAdaptor#parse(IElementType root,
* PsiBuilder)}
*
* If you don't care to distinguish PSI nodes by type, it is
* sufficient to create a {@link ANTLRPsiNodeAdaptor} around
* the parse tree node
*/
@NotNull
public PsiElement createElement(ASTNode node) {
IElementType elType = node.getElementType();
if ( elType instanceof TokenIElementType ) {
return new ANTLRPsiNodeAdaptor(node);
}
if ( !(elType instanceof RuleIElementType) ) {
return new ANTLRPsiNodeAdaptor(node);
}
RuleIElementType ruleElType = (RuleIElementType) elType;
switch ( ruleElType.getRuleIndex() ) {
case SampleLanguageParser.RULE_function :
return new FunctionSubtree(node);
// case SampleLanguageParser.RULE_vardef :
// case SampleLanguageParser.RULE_formal_arg :
// return new IdentifierDefSubtree(node);
default :
return new ANTLRPsiNodeAdaptor(node);
}
}
}
|
package org.apache.log4j.chainsaw;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.log4j.chainsaw.icons.ChainsawIcons;
import org.apache.log4j.chainsaw.prefs.LoadSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SaveSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SettingsListener;
import org.apache.log4j.helpers.LogLog;
/**
* Encapsulates the full Toolbar, and menus and all the actions that can be performed from it.
* @author Paul Smith <psmith@apache.org>
* @author Scott Deboy <sdeboy@apache.org>
*/
class ChainsawToolBarAndMenus implements ChangeListener, SettingsListener {
private static final String SETTING_RESPONSIVENESS = "Responsiveness";
private static final String SETTING_TAB_PLACEMENT = "tab.placement";
private final SmallToggleButton showReceiversButton;
final JTextField findTextField;
private final Action changeModelAction;
private final Action clearAction;
private final Action closeAction;
private final Action findNextAction;
private final Action lockToolbarAction;
private final Action pauseAction;
private final Action showPreferencesAction;
private final Action showReceiversAction;
private final Action toggleLogTreeAction;
private final Action toggleDetailPaneAction;
private final Action toggleToolbarAction;
private final Action undockAction;
private final Collection lookAndFeelMenus = new ArrayList();
private final JCheckBoxMenuItem toggleShowReceiversCheck =
new JCheckBoxMenuItem();
private final JCheckBoxMenuItem toggleDetailMenuItem =
new JCheckBoxMenuItem();
private final JCheckBoxMenuItem toggleCyclicMenuItem =
new JCheckBoxMenuItem();
private final FileMenu fileMenu;
private final JCheckBoxMenuItem toggleStatusBarCheck =
new JCheckBoxMenuItem();
private final JMenu viewMenu = new JMenu("View");
private final JMenuBar menuBar;
private final JCheckBoxMenuItem menuItemClose = new JCheckBoxMenuItem();
private final JRadioButtonMenuItem levelDisplayIcon =
new JRadioButtonMenuItem("Icon");
private final JRadioButtonMenuItem levelDisplayText =
new JRadioButtonMenuItem("Text");
private final JRadioButtonMenuItem tabsBottom =
new JRadioButtonMenuItem("Bottom");
private final JRadioButtonMenuItem tabsTop = new JRadioButtonMenuItem("Top");
private final JSlider responsiveSlider;
private final JToolBar toolbar;
private LogUI logui;
private final SmallButton clearButton = new SmallButton();
private final SmallToggleButton detailPaneButton = new SmallToggleButton();
private final SmallToggleButton logTreePaneButton = new SmallToggleButton();
private final SmallToggleButton pauseButton = new SmallToggleButton();
private final SmallToggleButton toggleCyclicButton = new SmallToggleButton();
private String lastFind = "";
private String levelDisplay = ChainsawConstants.LEVEL_DISPLAY_ICONS;
private final Action[] logPanelSpecificActions;
private final ChangeListener panelListener;
private Map panelMenuMap = new HashMap();
private Map panelEnabledMap = new HashMap();
private JMenuItem showTabs;
ChainsawToolBarAndMenus(final LogUI logui) {
this.logui = logui;
toolbar = new JToolBar(JToolBar.HORIZONTAL);
menuBar = new JMenuBar();
fileMenu = new FileMenu(logui);
closeAction = createCloseHelpAction();
changeModelAction = createChangeModelAction();
findTextField = createFindField();
findNextAction = setupFindFieldsAndActions();
showPreferencesAction = createShowPreferencesAction();
lockToolbarAction = createLockableToolbarAction();
toggleToolbarAction = createToggleToolbarAction();
toggleLogTreeAction = createToggleLogTreeAction();
pauseAction = createPauseAction();
clearAction = createClearAction();
undockAction = createUndockAction();
showReceiversAction = createShowReceiversAction();
showReceiversButton = new SmallToggleButton(showReceiversAction);
toggleDetailPaneAction = createToggleDetailPaneAction();
responsiveSlider =
new JSlider(JSlider.VERTICAL, 0, 5000, logui.handler.getQueueInterval());
createMenuBar();
createToolbar();
panelListener =
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Map m = logui.getPanels();
if (m != null) {
Set s = m.entrySet();
Iterator iter = s.iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
if (!panelMenuMap.keySet().contains(entry.getKey())) {
panelMenuMap.put(
entry.getKey(),
getDisplayPanelMenuItem(entry.getKey().toString()));
//default to enabled
panelEnabledMap.put(entry.getKey(), Boolean.TRUE);
showTabs.add(
(JCheckBoxMenuItem) panelMenuMap.get(entry.getKey()));
}
boolean entryEnabled =
((Boolean) panelEnabledMap.get(entry.getKey())).booleanValue();
boolean newEnabled =
((Boolean) entry.getValue()).booleanValue();
if (entryEnabled != newEnabled) {
((JCheckBoxMenuItem) panelMenuMap.get(entry.getKey())).getModel()
.setEnabled(newEnabled);
panelEnabledMap.put(entry.getKey(), new Boolean(newEnabled));
}
}
}
}
};
logPanelSpecificActions =
new Action[] {
pauseAction, findNextAction, clearAction, fileMenu.getFileSaveAction(),
toggleDetailPaneAction, showPreferencesAction, undockAction,
toggleLogTreeAction, changeModelAction,
};
}
/**
* @return
*/
private Action createChangeModelAction() {
Action action =
new AbstractAction("Use Cyclic", new ImageIcon(ChainsawIcons.REFRESH)) {
public void actionPerformed(ActionEvent arg0) {
LogPanel logPanel = logui.getCurrentLogPanel();
logPanel.toggleCyclic();
scanState();
}
};
action.putValue(
Action.SHORT_DESCRIPTION, "Changes between Cyclic and Unlimited mode.");
return action;
}
/**
* @return
*/
private Action createToggleLogTreeAction() {
Action action =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (logui.getCurrentLogPanel() != null) {
logui.getCurrentLogPanel().toggleLogTreePanel();
}
}
};
action.putValue(Action.NAME, "Logger Tree");
action.putValue(Action.SHORT_DESCRIPTION, "Toggles the Log Tree panel");
action.putValue("enabled", Boolean.TRUE);
action.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_T));
action.putValue(
Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
// TODO find an icon
return action;
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
public void loadSettings(LoadSettingsEvent event) {
try {
levelDisplay = event.getSetting(ChainsawConstants.LEVEL_DISPLAY);
if (levelDisplay.equals(ChainsawConstants.LEVEL_DISPLAY_ICONS)) {
levelDisplayIcon.setSelected(true);
} else {
levelDisplayText.setSelected(true);
}
final int responsiveness =
event.asInt(ChainsawToolBarAndMenus.SETTING_RESPONSIVENESS);
final int tabPlacement =
event.asInt(ChainsawToolBarAndMenus.SETTING_TAB_PLACEMENT);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
responsiveSlider.setValue(responsiveness);
logui.getTabbedPane().setTabPlacement(tabPlacement);
scanState();
}
});
} catch (NullPointerException e) {
LogLog.error("error decoding setting", e);
}
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
public void saveSettings(SaveSettingsEvent event) {
event.saveSetting(
ChainsawToolBarAndMenus.SETTING_RESPONSIVENESS,
responsiveSlider.getValue());
event.saveSetting(
ChainsawToolBarAndMenus.SETTING_TAB_PLACEMENT,
logui.getTabbedPane().getTabPlacement());
event.saveSetting(ChainsawConstants.LEVEL_DISPLAY, levelDisplay);
}
/**
* DOCUMENT ME!
*/
public void stateChange() {
scanState();
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
public void stateChanged(ChangeEvent e) {
scanState();
}
JMenuBar getMenubar() {
return menuBar;
}
JToolBar getToolbar() {
return toolbar;
}
private Action createClearAction() {
final Action action =
new AbstractAction("Clear") {
public void actionPerformed(ActionEvent e) {
LogPanel logPanel = logui.getCurrentLogPanel();
if (logPanel == null) {
return;
}
logPanel.clearModel();
}
};
action.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_C));
action.putValue(
Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, InputEvent.CTRL_MASK));
action.putValue(
Action.SHORT_DESCRIPTION, "Removes all the events from the current view");
action.putValue(Action.SMALL_ICON, new ImageIcon(ChainsawIcons.DELETE));
return action;
}
private Action createCloseHelpAction() {
final Action action =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
closeAction.putValue(Action.NAME, "Welcome tab");
logui.removeWelcomePanel();
if (menuItemClose.isSelected()) {
logui.addWelcomePanel();
} else {
}
}
};
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F1"));
// action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK));
action.putValue(Action.SHORT_DESCRIPTION, "Toggles the Welcome tab");
action.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_C));
action.putValue(Action.NAME, "Welcome tab");
return action;
}
private void createFindDocListener(final JTextField field) {
field.getDocument().addDocumentListener(
new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
find(false);
}
public void removeUpdate(DocumentEvent e) {
find(false);
}
public void changedUpdate(DocumentEvent e) {
find(false);
}
});
}
static JTextField createFindField() {
JTextField tf = new JTextField();
Dimension fixedSize = new Dimension(132, 24);
tf.setPreferredSize(fixedSize);
tf.setMaximumSize(fixedSize);
tf.setMinimumSize(fixedSize);
tf.setToolTipText("type in a simple string to find events");
return tf;
}
private Action createLockableToolbarAction() {
final Action lockToolbarAction =
new AbstractAction("Lock Toolbar") {
private boolean lock = true;
public void actionPerformed(ActionEvent e) {
lock = !lock;
final boolean isLocked = lock;
Runnable runnable = null;
runnable =
new Runnable() {
public void run() {
toolbar.setFloatable(!isLocked);
toolbar.repaint();
}
};
SwingUtilities.invokeLater(runnable);
}
};
return lockToolbarAction;
}
private void createMenuBar() {
JMenu activeTabMenu = new JMenu("Current tab");
JMenuItem menuItemUseRightMouse =
new JMenuItem(
"Other options available via panel's right mouse button popup menu");
menuItemUseRightMouse.setEnabled(false);
viewMenu.setMnemonic('V');
JCheckBoxMenuItem lockToolbarCheck =
new JCheckBoxMenuItem(lockToolbarAction);
lockToolbarCheck.setSelected(true);
JCheckBoxMenuItem showToolbarCheck =
new JCheckBoxMenuItem(toggleToolbarAction);
showToolbarCheck.setSelected(true);
menuItemClose.setAction(closeAction);
JCheckBoxMenuItem pause = new JCheckBoxMenuItem(pauseAction);
JMenuItem menuPrefs = new JMenuItem(showPreferencesAction);
menuPrefs.setText(
showPreferencesAction.getValue(Action.SHORT_DESCRIPTION).toString());
JMenuItem menuUndock = new JMenuItem(undockAction);
showTabs = new JMenu("Display tabs");
toggleDetailMenuItem.setAction(toggleDetailPaneAction);
toggleDetailMenuItem.setSelected(true);
toggleCyclicMenuItem.setAction(changeModelAction);
toggleCyclicMenuItem.setSelected(true);
JCheckBoxMenuItem toggleLogTreeMenuItem =
new JCheckBoxMenuItem(toggleLogTreeAction);
toggleLogTreeMenuItem.setSelected(true);
final Action toggleStatusBarAction =
new AbstractAction("Show Status bar") {
public void actionPerformed(ActionEvent arg0) {
if (toggleStatusBarCheck.isSelected()) {
logui.addStatusBar();
} else {
logui.removeStatusBar();
}
}
};
toggleStatusBarAction.putValue(
Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_B));
toggleStatusBarCheck.setAction(toggleStatusBarAction);
toggleStatusBarCheck.setSelected(true);
activeTabMenu.add(pause);
activeTabMenu.add(toggleCyclicMenuItem);
activeTabMenu.addSeparator();
activeTabMenu.add(toggleDetailMenuItem);
activeTabMenu.add(toggleLogTreeMenuItem);
activeTabMenu.addSeparator();
activeTabMenu.add(menuUndock);
activeTabMenu.add(menuPrefs);
activeTabMenu.addSeparator();
activeTabMenu.add(new JMenuItem(clearAction));
activeTabMenu.addSeparator();
activeTabMenu.add(menuItemUseRightMouse);
viewMenu.add(showToolbarCheck);
viewMenu.add(toggleStatusBarCheck);
viewMenu.add(toggleShowReceiversCheck);
viewMenu.add(menuItemClose);
viewMenu.addSeparator();
ButtonGroup tabPlacementGroup = new ButtonGroup();
JMenu tabMenu = new JMenu("Tabs");
tabMenu.setMnemonic('a');
tabPlacementGroup.add(tabsTop);
tabPlacementGroup.add(tabsBottom);
tabsTop.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
logui.getTabbedPane().setTabPlacement(JTabbedPane.TOP);
}
});
tabsBottom.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
logui.getTabbedPane().setTabPlacement(JTabbedPane.BOTTOM);
}
});
JMenu responsiveNess =
new JMenu(ChainsawToolBarAndMenus.SETTING_RESPONSIVENESS);
responsiveNess.setMnemonic('R');
responsiveNess.add(createResponsivenessSlider());
final JMenu lookAndFeelMenu = new JMenu("Look & Feel");
lookAndFeelMenu.setMnemonic('L');
UIManager.LookAndFeelInfo[] lookAndFeels =
UIManager.getInstalledLookAndFeels();
final ButtonGroup lookAndFeelGroup = new ButtonGroup();
for (int i = 0; i < lookAndFeels.length; i++) {
final UIManager.LookAndFeelInfo lfInfo = lookAndFeels[i];
final JRadioButtonMenuItem lfItemMenu =
new JRadioButtonMenuItem(lfInfo.getName());
lfItemMenu.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
logui.setLookAndFeel(lfInfo.getClassName());
}
});
}
});
lookAndFeelGroup.add(lfItemMenu);
lookAndFeelMenu.add(lfItemMenu);
lookAndFeelMenus.add(lfItemMenu);
}
try {
final Class gtkLF =
Class.forName("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
final JRadioButtonMenuItem lfIGTK = new JRadioButtonMenuItem("GTK+ 2.0");
lfIGTK.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
logui.setLookAndFeel(gtkLF.getName());
}
});
}
});
lookAndFeelGroup.add(lfIGTK);
lookAndFeelMenu.add(lfIGTK);
lookAndFeelMenus.add(lfIGTK);
} catch (Exception e) {
LogLog.debug("Can't find new GTK L&F, might be Windows, or <JDK1.4.2");
}
if (levelDisplay.equals(ChainsawConstants.LEVEL_DISPLAY_ICONS)) {
levelDisplayIcon.setSelected(true);
} else {
levelDisplayText.setSelected(true);
}
tabMenu.add(tabsTop);
tabMenu.add(tabsBottom);
viewMenu.add(showTabs);
viewMenu.add(tabMenu);
viewMenu.add(responsiveNess);
viewMenu.add(lookAndFeelMenu);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
JMenuItem about = new JMenuItem("About Chainsaw v2...");
about.setMnemonic('A');
about.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
logui.showAboutBox();
}
});
Action startTutorial =
new AbstractAction("Tutorial...", new ImageIcon(ChainsawIcons.HELP)) {
public void actionPerformed(ActionEvent e) {
logui.setupTutorial();
}
};
startTutorial.putValue(
Action.SHORT_DESCRIPTION, "Starts the tutorial process");
helpMenu.add(startTutorial);
helpMenu.addSeparator();
helpMenu.add(about);
menuBar.add(fileMenu);
menuBar.add(viewMenu);
menuBar.add(activeTabMenu);
menuBar.add(helpMenu);
}
private Action createPauseAction() {
final Action pauseAction =
new AbstractAction("Pause") {
public void actionPerformed(ActionEvent evt) {
LogPanel logPanel = logui.getCurrentLogPanel();
if (logPanel == null) {
return;
}
String ident = logPanel.getIdentifier();
logPanel.setPaused(!logPanel.isPaused());
scanState();
}
};
pauseAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_P));
pauseAction.putValue(
Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F12"));
pauseAction.putValue(
Action.SHORT_DESCRIPTION,
"Causes incoming events for this tab to be discarded");
pauseAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.PAUSE));
return pauseAction;
}
private JComponent createResponsivenessSlider() {
JPanel responsiveNessPanel = new JPanel();
BoxLayout layout = new BoxLayout(responsiveNessPanel, BoxLayout.Y_AXIS);
responsiveNessPanel.setLayout(layout);
responsiveSlider.setAlignmentY(JComponent.CENTER_ALIGNMENT);
responsiveSlider.setAlignmentX(JComponent.CENTER_ALIGNMENT);
responsiveSlider.setMinorTickSpacing(250);
responsiveSlider.setMajorTickSpacing(1000);
responsiveSlider.setToolTipText(
"Adjust to set the responsiveness of the app. How often the view is updated.");
responsiveSlider.setSnapToTicks(true);
responsiveSlider.setPaintTicks(true);
responsiveSlider.setPaintLabels(true);
responsiveSlider.setPaintTrack(true);
responsiveSlider.setInverted(true);
responsiveSlider.getModel().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (responsiveSlider.getValueIsAdjusting()) {
/**
* We'll wait until it stops.
*/
} else {
int value = responsiveSlider.getValue();
if (value == 0) {
value = 100;
}
System.out.println("Adjust responsiveness to " + value + "ms");
logui.handler.setQueueInterval(value);
}
}
});
JLabel l1 = new JLabel("Update frequently (100ms)");
JLabel l2 = new JLabel("Update infrequently (5 seconds)");
responsiveNessPanel.add(l1);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
panel.add(responsiveSlider);
responsiveNessPanel.add(panel);
responsiveNessPanel.add(l2);
return responsiveNessPanel;
}
private Action createShowPreferencesAction() {
Action showPreferences =
new AbstractAction("", ChainsawIcons.ICON_PREFERENCES) {
public void actionPerformed(ActionEvent arg0) {
LogPanel logPanel = logui.getCurrentLogPanel();
if (logPanel != null) {
logPanel.showPreferences();
}
}
};
showPreferences.putValue(
Action.SHORT_DESCRIPTION, "Define display and color filters...");
// TODO think of good mnemonics and HotKey for this action
return showPreferences;
}
/**
* @return
*/
private Action createShowReceiversAction() {
final Action action =
new AbstractAction("Show Receivers") {
public void actionPerformed(ActionEvent arg0) {
logui.toggleReceiversPanel();
}
};
action.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_E));
action.putValue(
Action.SHORT_DESCRIPTION,
"Shows the currently configured Log4j Receivers");
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F6"));
action.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.ANIM_NET_CONNECT));
toggleShowReceiversCheck.setAction(action);
return action;
}
private Action createToggleDetailPaneAction() {
Action action =
new AbstractAction("Show Detail Pane") {
boolean enabled = true;
public void actionPerformed(ActionEvent evt) {
LogPanel logPanel = logui.getCurrentLogPanel();
if (logPanel == null) {
return;
}
logPanel.toggleDetailPanel();
scanState();
}
};
action.putValue("enabled", Boolean.TRUE);
action.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_D));
action.putValue(
Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.ALT_MASK));
action.putValue(Action.SHORT_DESCRIPTION, "Hides/Shows the Detail Pane");
action.putValue(Action.SMALL_ICON, new ImageIcon(ChainsawIcons.INFO));
return action;
}
private Action createToggleToolbarAction() {
/**
* -== Begin of Show/Hide toolbar action
*/
final Action toggleToolbarAction =
new AbstractAction("Show Toolbar") {
private boolean hide = false;
public void actionPerformed(ActionEvent e) {
hide = !hide;
Runnable runnable = null;
if (hide) {
runnable =
new Runnable() {
public void run() {
logui.getContentPane().remove(toolbar);
logui.getRootPane().repaint();
logui.getRootPane().revalidate();
}
};
} else {
runnable =
new Runnable() {
public void run() {
logui.getContentPane().add(toolbar, BorderLayout.NORTH);
logui.getRootPane().repaint();
logui.getRootPane().revalidate();
}
};
}
SwingUtilities.invokeLater(runnable);
}
};
toggleToolbarAction.putValue(
Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_T));
return toggleToolbarAction;
}
private void createToolbar() {
Insets buttonMargins = new Insets(1, 1, 1, 1);
FileMenu fileMenu = (FileMenu) menuBar.getMenu(0);
JButton fileOpenButton =
new SmallButton(fileMenu.getLog4JFileOpenAction());
fileOpenButton.setMargin(buttonMargins);
JButton fileSaveButton = new SmallButton(fileMenu.getFileSaveAction());
fileSaveButton.setMargin(buttonMargins);
fileOpenButton.setText("");
fileSaveButton.setText("");
toolbar.add(fileOpenButton);
toolbar.add(fileSaveButton);
toolbar.addSeparator();
pauseButton.setAction(pauseAction);
pauseButton.setText("");
// pauseButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F12"),pauseAction.getValue(Action.NAME) );
pauseButton.getActionMap().put(
pauseAction.getValue(Action.NAME), pauseAction);
toggleCyclicButton.setAction(changeModelAction);
toggleCyclicButton.setText(null);
detailPaneButton.setAction(toggleDetailPaneAction);
detailPaneButton.setText(null);
detailPaneButton.getActionMap().put(
toggleDetailPaneAction.getValue(Action.NAME), toggleDetailPaneAction);
detailPaneButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.ALT_MASK),
toggleDetailPaneAction.getValue(Action.NAME));
logTreePaneButton.setAction(toggleLogTreeAction);
// logTreePaneButton.setText(null);
logTreePaneButton.getActionMap().put(
toggleLogTreeAction.getValue(Action.NAME), toggleLogTreeAction);
logTreePaneButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK),
toggleDetailPaneAction.getValue(Action.NAME));
SmallButton prefsButton = new SmallButton(showPreferencesAction);
SmallButton undockButton = new SmallButton(undockAction);
undockButton.setText("");
toolbar.add(undockButton);
toolbar.add(pauseButton);
toolbar.add(toggleCyclicButton);
toolbar.addSeparator();
toolbar.add(detailPaneButton);
toolbar.add(logTreePaneButton);
toolbar.add(prefsButton);
toolbar.addSeparator();
toolbar.add(clearButton);
clearButton.setAction(clearAction);
clearButton.setText("");
toolbar.addSeparator();
JButton findNextButton = new SmallButton(findNextAction);
findNextButton.setText("");
findNextButton.getActionMap().put(
findNextAction.getValue(Action.NAME), findNextAction);
findNextButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
(KeyStroke) findNextAction.getValue(Action.ACCELERATOR_KEY),
findNextAction.getValue(Action.NAME));
toolbar.add(findNextButton);
Box findBox = Box.createHorizontalBox();
findBox.add(findTextField);
toolbar.add(findBox);
toolbar.addSeparator();
showReceiversButton.setText(null);
toolbar.add(showReceiversButton);
toolbar.add(Box.createHorizontalGlue());
toolbar.setMargin(buttonMargins);
toolbar.setFloatable(false);
}
private Action createUndockAction() {
Action action =
new AbstractAction("Undock", ChainsawIcons.ICON_UNDOCK) {
public void actionPerformed(ActionEvent arg0) {
LogPanel logPanel = logui.getCurrentLogPanel();
if (logPanel != null) {
logPanel.undock();
}
}
};
action.putValue(
Action.SHORT_DESCRIPTION,
"Undocks the current Log panel into it's own window");
// TODO think of some mnemonics and HotKeys for this action
return action;
}
private void find(boolean next) {
LogPanel logPanel = logui.getCurrentLogPanel();
if (logPanel != null) {
if (next) {
logPanel.find(findTextField.getText());
} else {
logPanel.find(findTextField.getText());
}
}
}
private void scanState() {
switch (logui.getTabbedPane().getTabPlacement()) {
case SwingConstants.TOP:
tabsTop.setSelected(true);
break;
case SwingConstants.BOTTOM:
tabsBottom.setSelected(true);
break;
}
toggleStatusBarCheck.setSelected(logui.isStatusBarVisible());
toggleShowReceiversCheck.setSelected(logui.isReceiverPanelVisible());
logTreePaneButton.setSelected(logui.isLogTreePanelVisible());
showReceiversButton.setSelected(logui.isReceiverPanelVisible());
menuItemClose.setSelected(logui.getTabbedPane().containsWelcomePanel());
/**
* We get the currently selected LogPanel, and if null, deactivate some
* actions
*/
LogPanel logPanel = logui.getCurrentLogPanel();
boolean activateLogPanelActions = true;
if (logPanel == null) {
activateLogPanelActions = false;
logui.getStatusBar().clear();
findTextField.setEnabled(false);
closeAction.setEnabled(true);
} else {
fileMenu.getFileSaveAction().setEnabled(true);
findTextField.setEnabled(true);
pauseButton.getModel().setSelected(logPanel.isPaused());
toggleCyclicButton.setSelected(logPanel.getModel().isCyclic());
logui.getStatusBar().setPaused(logPanel.isPaused());
toggleDetailMenuItem.setSelected(logPanel.isDetailPaneVisible());
toggleCyclicMenuItem.setSelected(logPanel.getModel().isCyclic());
detailPaneButton.getModel().setSelected(logPanel.isDetailPaneVisible());
}
for (int i = 0; i < logPanelSpecificActions.length; i++) {
logPanelSpecificActions[i].setEnabled(activateLogPanelActions);
}
String currentLookAndFeel =
UIManager.getLookAndFeel().getClass().getName();
String currentLookAndFeelName = UIManager.getLookAndFeel().getName();
for (Iterator iter = lookAndFeelMenus.iterator(); iter.hasNext();) {
JRadioButtonMenuItem element = (JRadioButtonMenuItem) iter.next();
if (element.getText().equals(currentLookAndFeelName)) {
element.setSelected(true);
} else {
element.setSelected(false);
}
}
}
ChangeListener getPanelListener() {
return panelListener;
}
private JCheckBoxMenuItem getDisplayPanelMenuItem(final String panelName) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem(panelName, true);
final Action action =
new AbstractAction(panelName) {
public void actionPerformed(ActionEvent e) {
logui.displayPanel(panelName, item.isSelected());
}
};
item.setAction(action);
return item;
}
private Action setupFindFieldsAndActions() {
createFindDocListener(findTextField);
final Action action =
new AbstractAction("Find Next") {
public void actionPerformed(ActionEvent e) {
find(true);
}
};
// action.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_F));
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F3"));
action.putValue(
Action.SHORT_DESCRIPTION, "Finds the next occurrence of the Find string");
action.putValue(Action.SMALL_ICON, new ImageIcon(ChainsawIcons.FIND));
return action;
}
}
|
package org.jdesktop.swingx.painter;
import java.awt.Insets;
import java.awt.Rectangle;
/**
* An abstract base class for any painter which can be positioned. This means
* the painter has some intrinsic size to what it is drawing and
* can be stretched or aligned both horizontally and vertically.
*
*
* The AbstractLayoutPainter class provides the following configuraable properties:
*
* <ul>
* <li>horizonalAlignment - the horizonal alignment (left, center, and right)</li>
* <li>verticalAlignment - the verticalAlignment alignment (top, center, and bottom)</li>
* <li>fillHorizontal - indicates if the painter should stretch to fill the available space horizontally</li>
* <li>fillVertical - indicates if the painter should stretch to fill the available space vertically</li>
* <li>insets - whitespace on the top, bottom, left, and right.
* </ul>
* @author joshy
*/
public abstract class AbstractLayoutPainter<T> extends AbstractPainter<T> {
/**
* Specifies how to draw the image, i.e. what kind of Style to use
* when drawing
*/
private VerticalAlignment verticalAlignment = VerticalAlignment.CENTER;
private HorizontalAlignment horizontalAlignment = HorizontalAlignment.CENTER;
private Insets insets = new Insets(0,0,0,0);
private boolean fillVertical = false;
private boolean fillHorizontal = false;
/**
* Creates a new instance of AbstractLayoutPainter
*/
public AbstractLayoutPainter() {
}
/**
* An enum which controls horizontalAlignment alignment
*/
public static enum HorizontalAlignment { LEFT, CENTER, RIGHT }
/**
* An enum which controls verticalAlignment alignment
*/
public static enum VerticalAlignment { TOP, CENTER, BOTTOM }
/**
* Gets the current horizontalAlignment alignment.
*
* @return the current horizontalAlignment alignment
*/
public HorizontalAlignment getHorizontalAlignment() {
return horizontalAlignment;
}
/**
* Gets the current whitespace insets.
* @return the current insets
*/
public Insets getInsets() {
return insets;
}
/**
* gets the current verticalAlignment alignment
*
* @return current verticalAlignment alignment
*/
public VerticalAlignment getVerticalAlignment() {
return verticalAlignment;
}
/**
* indicates if the painter content is stretched horizontally
*
* @return the current horizontalAlignment stretch value
*/
public boolean isFillHorizontal() {
return fillHorizontal;
}
/**
* indicates if the painter content is stretched vertically
*
* @return the current verticalAlignment stretch value
*/
public boolean isFillVertical() {
return fillVertical;
}
/**
* Sets a new horizontalAlignment alignment. Used to position the content at the left, right, or center.
*
* @param horizontal new horizontalAlignment alignment
*/
public void setHorizontalAlignment(HorizontalAlignment horizontal) {
HorizontalAlignment old = this.getHorizontalAlignment();
this.horizontalAlignment = horizontal;
firePropertyChange("horizontal",old,this.horizontalAlignment);
}
/**
* Sets if the content should be stretched horizontally to fill all available horizontalAlignment
* space (minus the left and right insets).
*
*
* @param fillHorizontal new horizonal stretch value
*/
public void setFillHorizontal(boolean fillHorizontal) {
boolean old = this.isFillHorizontal();
this.fillHorizontal = fillHorizontal;
firePropertyChange("horizontalStretch",old,this.fillHorizontal);
}
/**
* Sets the current whitespace insets.
* @param insets new insets
*/
public void setInsets(Insets insets) {
Insets old = this.getInsets();
this.insets = insets;
firePropertyChange("insets",old,this.insets);
}
/**
* Sets a new verticalAlignment alignment. Used to position the content at the top, bottom, or center.
*
* @param vertical new verticalAlignment alignment
*/
public void setVerticalAlignment(VerticalAlignment vertical) {
VerticalAlignment old = this.getVerticalAlignment();
this.verticalAlignment = vertical;
firePropertyChange("vertical",old,this.verticalAlignment);
}
/**
* Sets if the content should be stretched vertically to fill all available verticalAlignment
* space (minus the top and bottom insets).
*
*
* @param verticalStretch new verticalAlignment stretch value
*/
public void setFillVertical(boolean verticalStretch) {
boolean old = this.isFillVertical();
this.fillVertical = verticalStretch;
firePropertyChange("verticalStretch",old,this.fillVertical);
}
/**
* a protected method used by subclasses to calculate the final position of the
* content. Subclasses usually don't need to override this.
* @param contentWidth The width of the content to be painted
* @param contentHeight The height of the content to be painted
* @param width the width of the area that the content will be positioned in
* @param height the height of the area that the content will be positioned in
* @return the rectangle for the content to be painted in
*/
protected final Rectangle calculateLayout(final int contentWidth, final int contentHeight,
final int width, final int height) {
Rectangle rect = new Rectangle();
rect.width = contentWidth;
rect.height = contentHeight;
if(isFillHorizontal()) {
rect.width = width - insets.left - insets.right;
}
if(isFillVertical()) {
rect.height = height - insets.top - insets.bottom;
}
rect.x = calculateX(rect.width, width);
rect.y = calculateY(rect.height, height);
return rect;
}
private int calculateY(final int imgHeight, final int height) {
int y = 0;
if(getVerticalAlignment() == VerticalAlignment.TOP) {
y = 0;
y+= insets.top;
}
if(getVerticalAlignment() == VerticalAlignment.CENTER) {
y = (height-imgHeight)/2;
y += insets.top;
}
if(getVerticalAlignment() == VerticalAlignment.BOTTOM) {
y = height-imgHeight;
y-= insets.bottom;
}
return y;
}
private int calculateX(final int imgWidth, final int width) {
int x = 0;
if(getHorizontalAlignment() == HorizontalAlignment.LEFT) {
x = 0;
x+= insets.left;
}
if(getHorizontalAlignment() == HorizontalAlignment.CENTER) {
x = (width-imgWidth)/2;
x += insets.left;
}
if(getHorizontalAlignment() == HorizontalAlignment.RIGHT) {
x = width-imgWidth;
x-= insets.right;
}
return x;
}
}
|
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.DataOutputStream;
import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.Variable;
// this must sent random transactions to the server
public class TransactionClient
{
private String input_filename;
private String server_http_address;
private String source_graph;
private String dest_graph;
private int reset_flag;
private int snapshot_flag;
private String read_cons;
private String write_cons;
private String trans_lock_gran;
private int repl_factor;
private String check_my_writes;
private int no_threads;
private int time_run_per_th;
// after this timeout the results are gathered
private int warmup_period;
private int operation_type;
private int no_operations_per_transaction;
private int no_retrials;
private String distr_flag;
private String operation_name;
private String working_dir;
private String client_id;
private Integer client_dec_id;
private String conflictFlag;
private int numDiffEnt;
private int numDiffPropPerEnt;
private int numDiffValuePerProp;
private String transactionalSupport;
private ArrayList<Node[]> input_triples;
private Thread[] client_threads;
public int total_successful;
final public static String SERVER_TRANSACTION_SERVLET="/ers/transaction";
final public static String SERVER_HANDLE_GRAPHS_SERVLET="/ers/graph";
final public static String SERVER_SETUP_SERVLET="/ers/setup";
final public static String SERVER_VERSIONS_STATS="/ers/query_versions_stats";
final public static String SERVER_CREATE_SERVLET="/ers/create";
final public static String SERVER_READ_SERVLET="/ers/query";
public static final String FILENAME_SUFFIX_READY_WARMUP = "-client-ready-for-warmup";
public static final String FILENAME_SUFFIX_START_SENDING_REQUESTS = "-start-sending-requests";
public static final String FILENAME_SUFFIX_FINISHED = "-finished";
class ClientThread extends Thread
{
private int operation_type;
private int no_op_per_t;
private int retrials;
private int thread_id;
// this flag will be set to true after the warmup period
private boolean collect_results;
private long start_collection_res_time;
private boolean finished;
private long stop_time;
private Random random_gen;
private int size;
private int total_run_trans;
private int successful_trans;
private int conflicted_trans;
private int aborted_trans;
private int total_trans;
private HttpURLConnection connection;
private final int PperE = 20;
private final int VperP = 5;
// used to create non conflicting data when conflict flag is set to 'no'
private int counter_e;
private int counter_p;
private int counter_v;
public ClientThread(int operation_type, int no_op_per_t, int retrials,
int thread_id) {
this.operation_type = operation_type;
this.no_op_per_t = no_op_per_t;
this.retrials = retrials;
this.thread_id = thread_id;
this.collect_results = false;
this.finished = false;
this.random_gen = new Random(client_dec_id*thread_id);
this.size = input_triples.size();
this.total_run_trans = 0;
this.successful_trans = 0;
this.conflicted_trans = 0;
this.aborted_trans = 0;
this.total_trans = 0;
this.counter_e = 0;
this.counter_p = 0;
this.counter_v = 0;
}
public int getSuccessfulTrans() {
return this.successful_trans;
}
public int getConflictedTrans() {
return this.conflicted_trans;
}
public int getAbortedTrans() {
return this.aborted_trans;
}
public int getTotalTrans() {
return this.total_trans;
}
public void stopSendingTrans() {
this.finished = true;
this.stop_time = System.currentTimeMillis();
}
public void startCollectingResults() {
this.collect_results = true;
this.start_collection_res_time = System.currentTimeMillis();
}
private Node[] getRandomNode(boolean fullEntity, boolean insert) {
String randomE, randomP, randomV;
Node[] n = new Node[3];
int carry = 0;
if( conflictFlag.equals("yes") ) {
if( insert ) {
// change entity id for each operation
//++counter_e;
counter_e = random_gen.nextInt(numDiffEnt);
/*if( counter_e >= numDiffEnt ) {
counter_e = 0;
}*/
if( ++counter_v >= numDiffPropPerEnt ) {
counter_v = 0;
if( ++counter_p >= numDiffValuePerProp ) {
counter_p = 0;
counter_e++;
}
}
if( counter_e >= numDiffEnt ) {
counter_e = 0;
}
randomE = String.valueOf(counter_e);
randomP = String.valueOf(counter_p);
randomV = String.valueOf(counter_v);
}
else {
randomE = String.valueOf(random_gen.nextInt(numDiffEnt));
randomP = String.valueOf(random_gen.nextInt(numDiffPropPerEnt));
randomV = String.valueOf(random_gen.nextInt(numDiffValuePerProp));
}
}
else {
//if( fullEntity )
if( fullEntity || insert )
++counter_e;
else {
if( ++counter_v >= numDiffPropPerEnt ) {
counter_v = 0;
if( ++counter_p >= numDiffValuePerProp ) {
counter_p = 0;
counter_e++;
}
}
}
if( counter_e >= numDiffEnt ) {
counter_e = 0;
/*// do not increment carry when sending 'fullEntity' transactions
// by doing so it may send transactions to non-existing records
if( !fullEntity )
++carry;*/
}
randomE = client_dec_id + "-" + thread_id + "-" + counter_e;// + "--" + carry;
randomP = client_dec_id + "-" + thread_id + "-" + counter_e
+ "-" + counter_p;// + "--" + carry;
randomV = client_dec_id + "-" + thread_id + "-" + counter_e
+ "-" + counter_p + "-" + counter_v;// + "--" + carry;
}
n[0] = new Variable("eeeeeeeeeeeeeeeeeeeeee"+randomE);
n[1] = new Variable("pppppppppppppppppppppp"+randomP);
n[2] = new Variable("vvvvvvvvvvvvvvvvvvvvvv"+randomV);
//return input_triples.get(randomInt);
return n;
}
private String createAnInsert(Integer linkFlag) {
//Node[] random_node = input_triples.get(randomInt);
Node[] random_node;
if( linkFlag == 0 )
random_node = getRandomNode(false, true);
else
random_node = getRandomNode(false, false);
// create one insert ere
StringBuilder sb = new StringBuilder();
if( linkFlag != 0 )
sb.append("insert_link(");
else
sb.append("insert(");
sb.append("<"+random_node[0]+">").append(",");
sb.append("<"+random_node[1]+">").append(",");
// new value
sb.append("<"+random_node[2]+">").append(",");
sb.append(source_graph).append(");");
return sb.toString();
}
private String createAnUpdate(Integer linkFlag) {
Node[] random_node = getRandomNode(false, false);
// create one update here
StringBuilder sb = new StringBuilder();
if( linkFlag != 0 )
sb.append("update_link(");
else
sb.append("update(");
sb.append("<"+random_node[0]+">").append(",");
sb.append("<"+random_node[1]+">").append(",");
// new value
//sb.append("<"+random_node[2]+">").append(",");
sb.append("<"+random_node[2]+">").append(",");
sb.append(source_graph);
sb.append(",");
// old value of the update
sb.append("<"+random_node[2]+">").append(");");
return sb.toString();
}
private String createADelete(Integer linkFlag) {
Node[] random_node = getRandomNode(false, false);
// create one insert ere
StringBuilder sb = new StringBuilder();
if( linkFlag != 0 )
sb.append("delete_link(");
else
sb.append("delete(");
sb.append("<"+random_node[0]+">").append(",");
sb.append("<"+random_node[1]+">").append(",");
sb.append("<"+random_node[2]+">").append(",");
sb.append(source_graph).append(");");
return sb.toString();
}
private String createAnCopyShallow() {
Node[] random_node = getRandomNode(true, false);
// create one shallow copy here
StringBuilder sb = new StringBuilder();
sb.append("shallow_clone(");
sb.append("<"+random_node[0]+">").append(",");
sb.append(source_graph).append(",");
// new entity
sb.append("<NEW_"+random_node[2]+">").append(",");
sb.append(dest_graph);
sb.append(");");
return sb.toString();
}
private String createAnCopyDeep() {
Node[] random_node = getRandomNode(true, false);
// create one deep copy
StringBuilder sb = new StringBuilder();
sb.append("deep_clone(");
sb.append("<"+random_node[0]+">").append(",");
sb.append(source_graph).append(",");
// new entity
sb.append("<NEW_"+random_node[2]+">").append(",");
sb.append(dest_graph);
sb.append(");");
return sb.toString();
}
private String createDeleteEntity() {
Node[] random_node = getRandomNode(true, false);
// create one deep copy
StringBuilder sb = new StringBuilder();
sb.append("delete_all(");
sb.append("<"+random_node[0]+">").append(",");
sb.append(source_graph);
sb.append(");");
return sb.toString();
}
private StringBuilder createTransaction() {
StringBuilder sb = new StringBuilder();
sb.append("BEGIN");
for( int i=0; i<no_op_per_t; ++i ) {
switch( operation_type ) {
case 0: //insert
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/IP-tx_client");
sb.append(";");
sb.append(createAnInsert(0));
break;
case 1: // insert link
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/IL-tx_client");
sb.append(";");
sb.append(createAnInsert(1));
break;
case 2: // update
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/UP-tx_client");
sb.append(";");
sb.append(createAnUpdate(0));
break;
case 3: // update link
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/UL-tx_client");
sb.append(";");
sb.append(createAnUpdate(1));
break;
case 4: // delete
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DP-tx_client");
sb.append(";");
sb.append(createADelete(0));
break;
case 5:
// delete link
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DL-tx_client");
sb.append(";");
sb.append(createADelete(1));
break;
case 6: // entity shallow copy
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/SC-tx_client");
sb.append(";");
sb.append(createAnCopyShallow());
break;
case 7: // entity deep copy
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if( i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DC-tx_client");
sb.append(";");
sb.append(createAnCopyDeep());
break;
case 8: // entity full delete
// append to BEGIN the type of TX and URN [note: only one type of op are currently supported]
if(i==0 && transactionalSupport.equalsIgnoreCase("mvcc") )
sb.append("/DE-tx_client");
sb.append(";");
sb.append(createDeleteEntity());
break;
default:
break;
}
}
sb.append("COMMIT;");
//System.out.println("TRANSACTION: ");
//System.out.println(sb.toString());
return sb;
}
private void sendTransaction() {
StringBuilder transaction = createTransaction();
String urlParameters = "g="+source_graph+"&retries="+this.retrials+"&t="+transaction.toString();
try {
URL url = new URL(server_http_address+SERVER_TRANSACTION_SERVLET);
this.connection = (HttpURLConnection) url.openConnection();
this.connection.setDoOutput(true);
this.connection.setDoInput(true);
this.connection.setInstanceFollowRedirects(false);
this.connection.setRequestMethod("POST");
this.connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
this.connection.setRequestProperty("Connection", "Keep-Alive");
this.connection.setRequestProperty("charset", "utf-8");
this.connection.setUseCaches(false);
this.connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
//System.out.println(line);
if( collect_results ) {
if( line.equals("0") )
successful_trans++;
else if( line.equals("-1") )
aborted_trans++;
else {
conflicted_trans += Integer.valueOf(line);
// even if there were conflicts, this T was run successfully at the end
successful_trans++;
}
this.total_trans++;
}
wr.close();
reader.close();
this.connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
private void sendSimpleInsert() {
Node[] randomNode = getRandomNode(false, false);
String urlParameters = "g="+source_graph+"&e="+randomNode[0].toN3()+
"&p="+randomNode[1].toN3()+"&v="+randomNode[2].toN3();
try {
URL url = new URL(server_http_address+SERVER_CREATE_SERVLET);
this.connection = (HttpURLConnection) url.openConnection();
this.connection.setDoOutput(true);
this.connection.setDoInput(true);
this.connection.setInstanceFollowRedirects(false);
this.connection.setRequestMethod("POST");
this.connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
this.connection.setRequestProperty("Connection", "Keep-Alive");
this.connection.setRequestProperty("charset", "utf-8");
this.connection.setUseCaches(false);
this.connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
//System.out.println(line);
wr.close();
reader.close();
this.connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
private void sendSimpleRead() {
Node[] randomNode = getRandomNode(false, false);
String urlParameters = "g="+source_graph+"&e="+randomNode[0].toN3()+
"&p="+randomNode[1].toN3()+"&v="+randomNode[2].toN3();
try {
URL url = new URL(server_http_address+SERVER_READ_SERVLET+"?"+urlParameters);
this.connection = (HttpURLConnection) url.openConnection();
this.connection.setDoOutput(true);
this.connection.setDoInput(true);
this.connection.setInstanceFollowRedirects(false);
this.connection.setRequestMethod("GET");
this.connection.setRequestProperty("Connection", "Keep-Alive");
this.connection.setRequestProperty("charset", "utf-8");
this.connection.setUseCaches(false);
int responseCode = connection.getResponseCode();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
//System.out.println(line);
reader.close();
this.connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void run() {
while( ! this.finished ) {
// simple insert, without TX context !!
if( operation_type == 10 ) {
sendSimpleInsert();
}
// simple read, without TX context !!
else if( operation_type == 20 ) {
sendSimpleRead();
}
else {
//send here a transaction to server
sendTransaction();
}
}
}
}
public TransactionClient() {
this.input_triples = new ArrayList<Node[]>();
}
// read the input file and populate the input_triples structure
public void init() {
this.client_threads = new ClientThread[this.no_threads];
/*File input_f = new File(this.input_filename);
if( ! input_f.exists() ) {
System.err.println("Input file " + input_filename + " does not exist!");
System.exit(2);
}
// load the triples file in memory
try {
FileInputStream fis = new FileInputStream(input_f);
Iterator<Node[]> nxp = new NxParser(fis);
while (nxp.hasNext()) {
boolean skip = false;
Node[] nx = nxp.next();
// filter here the triples that contain 'white_spaces' in one of the param
// reason: our primitive transaction engine do not accept this
for( int j=0; j<nx.length; ++j ) {
String n = nx[j].toString();
if( n.contains(" ") ) {
skip = true;
break;
}
}
if( skip )
continue;
this.input_triples.add(nx);
}
} catch( FileNotFoundException ex) {
ex.printStackTrace();
System.exit(3);
}*/
}
public void dbinit() throws InterruptedException {
// change consistency
changeReadWriteConsistency(read_cons, write_cons);
// change transaction locking granularity
changeTransactionLockingGranularity(trans_lock_gran);
// also change replication facotr
changeReplicationFactor(repl_factor);
// change transaction support mode
changeTransactionalSupport(transactionalSupport);
// change check-my-writes cons mode (valid only for MVCC)
changeCheckMyWritesMode(check_my_writes);
// reset the graph if needed (only for insert)
if( (reset_flag == 1 || reset_flag == 2) &&
(operation_type == 0 || operation_type == 10) ) {
System.out.println("Truncate the graph " + source_graph);
deleteGraph(source_graph, false);
if( transactionalSupport.equalsIgnoreCase("mvcc") ) {
// truncate the ERS_versions keyspace also
deleteGraph("<ERS_versions>", false);
}
}
System.out.println("Create the source graph " + source_graph);
createNewGraph(source_graph);
// truncate and create the destination
deleteGraph(dest_graph, false);
System.out.println("Create the dest graph " + dest_graph);
createNewGraph(dest_graph);
}
public void dbclear() {
// if truncate and deletion was is meant
if( reset_flag == 2 && operation_type == 0) {
System.out.println("Delete the graph " + source_graph);
deleteGraph(source_graph, true);
System.out.println("Now sleep 5s to leave some time for deletion ... ");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(TransactionClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void startThreads() {
for(int i=0; i<this.no_threads; ++i)
client_threads[i] = new ClientThread(
operation_type, no_operations_per_transaction,
no_retrials, i);
for(int i=0; i<this.no_threads; ++i)
client_threads[i].start();
}
public int getTotalTransactionsSent() {
int counter = 0;
for(int i=0; i<this.no_threads; ++i) {
counter += ((ClientThread)client_threads[i]).getTotalTrans();
}
return counter;
}
public double getSuccessfulRate(int total_tx) {
for(int i=0; i<this.no_threads; ++i)
total_successful+=((ClientThread)client_threads[i]).getSuccessfulTrans();
return ((double)total_successful/total_tx)*100;
}
public int getTotalConflicts() {
int r = 0;
for(int i=0; i<this.no_threads; ++i)
r+=((ClientThread)client_threads[i]).getConflictedTrans();
return r;
}
public int getTotalAborted() {
int r = 0;
for(int i=0; i<this.no_threads; ++i)
r+=((ClientThread)client_threads[i]).getAbortedTrans();
return r;
}
public void joinThreads() {
for(int i=0; i<this.no_threads; ++i) {
((ClientThread)client_threads[i]).stopSendingTrans();
}
try {
for(int i=0; i<this.no_threads; ++i)
client_threads[i].join();
} catch( InterruptedException ex ) {
ex.printStackTrace();
}
}
public void startCollectingResults() {
for(int i=0; i<this.no_threads; ++i) {
((ClientThread)client_threads[i]).startCollectingResults();
}
}
// delete an existing graph
public void deleteGraph(String graph, boolean cleanup) {
HttpURLConnection connection;
try {
URL url;
if( cleanup )
url = new URL(server_http_address+SERVER_HANDLE_GRAPHS_SERVLET+"?g="+graph+"&f=y");
else
url = new URL(server_http_address+SERVER_HANDLE_GRAPHS_SERVLET+"?g="+graph+"&f=y&truncate=y");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("DELETE");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println(line);
reader.close();
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void createNewGraph(String graph) {
HttpURLConnection connection;
String urlParameters = "g_id="+graph+"&g_p=<createdBy>&g_v=\"transaction_client\"";
if( transactionalSupport.equalsIgnoreCase("mvcc"))
urlParameters +="&ver";
try {
URL url = new URL(server_http_address+SERVER_HANDLE_GRAPHS_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Create new graph: " + line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeTransactionLockingGranularity(String transLockGran) {
HttpURLConnection connection;
String urlParameters = "trans_lock_gran="+transLockGran;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change read and write consistency levels: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeReadWriteConsistency(String readCons, String writeCons) {
HttpURLConnection connection;
String urlParameters = "read_cons="+readCons+"&write_cons="+writeCons;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change read and write consistency levels: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeReplicationFactor(int replFactor) {
HttpURLConnection connection;
String urlParameters = "repl_factor="+replFactor;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change replication factor to: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public void changeCheckMyWritesMode(String mode) {
HttpURLConnection connection;
String urlParameters = "check_my_writes="+mode;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change check my writes consistency mode: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
public String getVersionsStats(String keyspace) {
HttpURLConnection connection;
String output="";
String urlParameters = "graph="+keyspace;
try {
URL url = new URL(server_http_address+SERVER_VERSIONS_STATS+"?"+urlParameters);
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setUseCaches (false);
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while(true) {
line = reader.readLine();
if( line == null )
break;
output += line +"\n";
}
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
return output;
}
public void changeTransactionalSupport(String txSupportMode) {
HttpURLConnection connection;
String urlParameters = "trans_support="+txSupportMode;
try {
URL url = new URL(server_http_address+SERVER_SETUP_SERVLET);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = reader.readLine();
System.out.println("Change read and write consistency levels: "+line);
connection.disconnect();
} catch( MalformedURLException ex ) {
ex.printStackTrace();
} catch( IOException ex ) {
ex.printStackTrace();
}
}
private static String getOperationName(Integer operation_type) {
String operation_name;
switch( operation_type ) {
case 0:
operation_name = "insert";
break;
case 1:
operation_name = "insert link";
break;
case 2:
operation_name = "update";
break;
case 3:
operation_name = "update link";
break;
case 4:
operation_name = "delete";
break;
case 5:
operation_name = "delete link";
break;
case 6:
operation_name = "entity shallow copy";
break;
case 7:
operation_name = "entity deep copy";
break;
case 8:
operation_name = "entity full delete";
break;
case 10:
operation_name = "insert without transactional context";
break;
case 20:
operation_name = "read without transactional context";
break;
default:
operation_name = null;
break;
}
return operation_name;
}
public static void main(String[] args) throws IOException, InterruptedException {
if( args.length < 22 ) {
System.err.println("Usage: \n" +
"1. server http address \n"+
"2. source graph/dest graph (both separated by /) \n" +
"3. reset graph (0:do nothing, 1:delete&create)\n" +
"4. snashot graph (0:do nothing, 1:delete&create)\n" +
"5. read consistency (one, two, three, quorum, all)\n" +
"6. write consistency (one, two, three, quorum, all, any)\n" +
"7. transactional locking granularity (e, ep, epv)\n" +
"8. replication factor \n"+
"9. no of threads \n" +
"10. time to run per thread (sec) \n" +
"11. warm-up period (sec) \n" +
"12. operation type (0:insert, 1:insert_link, 2:update, 3:update_link" +
", 4:delete, 5:delete_link, 6:entity_shallow_copy, 7:entity_deep_copy," +
" 8:entity_full_delete; 10:insert-NO-TX; 20:read-NO-TX) \n" +
"13. number of operations to run per transaction \n" +
"14. number of retrials (if transaction conficts)\n" +
"15. distributed mode flag (yes/no); NOTE: if yes, the following parameters are used\n" +
"16. working directory (needed to run remote ssh commands)\n" +
"17. client hexa ID (used by reomte ssh commands)\n" +
"18. client deci ID (used by data generator)\n" +
"19. conflicts flag (if no, the following params are not used)\n" +
"20. number different entities \n" +
"21. number different properties per entity \n" +
"22. number different values per property \n" +
"23. transactional support (zookeeper, default, MVCC);\n" +
"24. check my writes mode (on, off) -> valid only for MVCC\n" +
"25. INIT FLAG (at most 1client must use this flag; it resets consistency, graph and others)");
System.exit(1);
}
//IMPORTANT FOR TESTING TOOL; DO NOT DELETE!( Integer.valueOf(args[22]) < 1 ) ? 1 : Integer.valueOf
String PID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
System.out.println("PID: "+PID);
System.out.flush();
System.out.print("Arguments passed: ");
for( int i=0; i<args.length; ++i )
System.out.print(args[i] + " ");
System.out.println("");
TransactionClient tc = new TransactionClient();
tc.server_http_address = args[0];
// just a work around here :)
if( tc.server_http_address.startsWith("http://134.21.")) {
tc.server_http_address = new String(tc.server_http_address+"/ers");
}
tc.source_graph = args[1].substring(0, args[1].indexOf("/"));
tc.dest_graph = args[1].substring(args[1].indexOf("/")+1);
tc.reset_flag = Integer.valueOf(args[2]);
tc.snapshot_flag = Integer.valueOf(args[3]);
tc.read_cons = args[4];
tc.write_cons = args[5];
tc.trans_lock_gran = args[6];
tc.repl_factor = Integer.valueOf(args[7]);
tc.no_threads = ( Integer.valueOf(args[8]) < 1 ) ? 1 : Integer.valueOf(args[8]);
tc.time_run_per_th = ( Integer.valueOf(args[9]) < 1 ) ? 1 : Integer.valueOf(args[9]);
// after this timeout the results are gathered
tc.warmup_period = Integer.valueOf(args[10]);
tc.operation_type = Integer.valueOf(args[11]);
tc.no_operations_per_transaction = ( Integer.valueOf(args[12]) < 1 ) ? 1 : Integer.valueOf(args[12]);
tc.no_retrials = Integer.valueOf(args[13]);
tc.distr_flag = args[14];
tc.operation_name = getOperationName(tc.operation_type);
if( tc.operation_name == null ) {
System.out.println("[ERROR] Please pass a correct operation type. See the 'usage'!");
return;
}
System.out.println("Create transactions with " + tc.no_operations_per_transaction
+ " " + tc.operation_name + " per T");
tc.working_dir="";
tc.client_id="-1";
if( tc.distr_flag !=null && ! tc.distr_flag.isEmpty() && tc.distr_flag.equals("yes") ) {
System.out.println("Distributed mode is on, thus use synch mechanism ... ");
tc.working_dir = args[15];
tc.client_id = args[16];
tc.client_dec_id = Integer.valueOf(args[17]);
}
tc.conflictFlag = args[18];
tc.numDiffEnt = ( Integer.valueOf(args[19]) < 1 ) ? 1 : Integer.valueOf(args[19]);
tc.numDiffPropPerEnt = ( Integer.valueOf(args[20]) < 1 ) ? 1 : Integer.valueOf(args[20]);
tc.numDiffValuePerProp = ( Integer.valueOf(args[21]) < 1 ) ? 1 : Integer.valueOf(args[21]);
tc.transactionalSupport = args[22];
tc.check_my_writes = args[23];
tc.init();
// does this client initialize/setup the DB?
if( args[24] != null && args[24].equals("yes") ) {
tc.dbinit();
}
if( tc.distr_flag !=null && ! tc.distr_flag.isEmpty() && tc.distr_flag.equals("yes") ) {
// initializations are done, so create the local msg
String ready_warmup_filename = tc.working_dir+"/"+tc.client_id+FILENAME_SUFFIX_READY_WARMUP;
new File(ready_warmup_filename).createNewFile();
System.out.println("Client ready for warmup and sending requests ...");
// now, we wait until the coordinator creates another local file
String read_to_start_filename = tc.working_dir+"/"+tc.client_id+
FILENAME_SUFFIX_START_SENDING_REQUESTS;
while( ! new File(read_to_start_filename).exists() ) {
Thread.sleep(50);
}
System.out.println("Warmup begins now and in " + tc.warmup_period
+ "sec statistics will start to be gathered ...");
}
// start threads to send 'operation_type' transaction for no_op.. times
tc.startThreads();
long start_time = 0;
// wait to warmup before signaling the other threads to go ahead
try {
System.out.println("Threads have been started, but wait " + tc.warmup_period
+ " seconds to warmup ... ");
for( int i=0; i<tc.warmup_period; ++i ) {
Thread.sleep(1000);
System.out.print("warmup ");
}
// now its time to start collecting data
System.out.println("Signal threads that now they can record statistical data");
tc.startCollectingResults();
start_time = System.currentTimeMillis();
// now wait the given period for the threads to run transactions before joining them
System.out.println("Leave threads to send transactions for "
+ tc.time_run_per_th + " seconds ... ");
for( int i=0; i<tc.time_run_per_th; i=i+5) {
System.out.print((tc.time_run_per_th-i)+"s ");
if( i+5 > tc.time_run_per_th )
Thread.sleep(tc.time_run_per_th-i * 1000);
else
Thread.sleep(5000);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
// stop all the trans threads here
System.out.println("\nStop threads and gather statistics ");
tc.joinThreads();
if( args[22] != null && args[22].equals("yes") ) {
tc.dbclear();
}
long total_time = System.currentTimeMillis()-start_time;
int total_trans = tc.getTotalTransactionsSent();
double s_rate = tc.getSuccessfulRate(total_trans);
int conflicts = tc.getTotalConflicts();
int aborted = tc.getTotalAborted();
System.out.println("Time time needed for sending " + total_trans + " transactions " + total_time +"ms");
System.out.println(" ... " + tc.no_operations_per_transaction + " no of " + tc.operation_name + " ran per transaction ");
System.out.println(" ... with a successful rate of " + s_rate + "% => transaction rate of " + ((double)tc.total_successful/total_time*1000) + "tx/sec" );
System.out.println(" ... " + conflicts + " total number of conflicts; 1 unit means one certain transaction was restarted");
System.out.println(" ... " + aborted + " total number of aborted transactions");
System.out.println(" ... after " + tc.no_retrials + " of retrials a transaction was aborted!");
System.out.println();
System.out.println("No threads,Total time, total trans, conflicts, aborted, successful rate/sec, no retrials");
System.out.println(tc.no_threads + " " + total_time + " " + total_trans + " " + conflicts + " " + aborted + " " +
((double)tc.total_successful/total_time*1000) + " " + tc.no_retrials);
if( args[24] != null && args[24].equals("yes") ) {
System.out.println("Versions stats: ");
System.out.println(tc.getVersionsStats(tc.dest_graph));
}
if( tc.distr_flag !=null && ! tc.distr_flag.isEmpty() && tc.distr_flag.equals("yes") ) {
// as the threads are finished, signal it again with a new empty file
String ready_filename = tc.working_dir+"/"+tc.client_id+FILENAME_SUFFIX_FINISHED;
new File(ready_filename).createNewFile();
}
}
}
|
package lbms.plugins.mldht.kad.messages;
import java.util.Map;
import java.util.TreeMap;
import lbms.plugins.mldht.kad.DHT;
import lbms.plugins.mldht.kad.DHT.DHTtype;
import lbms.plugins.mldht.kad.NodeList;
public class AbstractLookupResponse extends MessageBase {
protected NodeList nodes;
protected NodeList nodes6;
private byte[] token;
public void setNodes(NodeList nodes) {
switch (nodes.type()) {
case V4:
this.nodes = nodes;
break;
case V6:
this.nodes6 = nodes;
break;
default:
throw new UnsupportedOperationException("should not happen");
}
}
public byte[] getToken () {
return token;
}
public void setToken(byte[] t) {
token = t;
}
@Override
public void apply(DHT dh_table) {
dh_table.response(this);
}
public AbstractLookupResponse(byte[] mtid, Method m, Type t) {
super(mtid, m, t);
}
@Override
public Map<String, Object> getInnerMap() {
Map<String, Object> inner = new TreeMap<String, Object>();
inner.put("id", id.getHash());
if(token != null)
inner.put("token", token);
if(nodes != null)
inner.put("nodes", nodes.writer());
if(nodes6 != null)
inner.put("nodes6", nodes6.writer());
return inner;
}
public NodeList getNodes(DHTtype type)
{
if(type == DHTtype.IPV4_DHT)
return nodes;
if(type == DHTtype.IPV6_DHT)
return nodes6;
return null;
}
@Override
public String toString() {
return super.toString() +
(nodes != null ? "contains: "+ (nodes.packedSize()/DHTtype.IPV4_DHT.NODES_ENTRY_LENGTH) + " nodes " : "") +
(nodes6 != null ? "contains: "+ (nodes6.packedSize()/DHTtype.IPV6_DHT.NODES_ENTRY_LENGTH) + " nodes6 " : "") +
(token != null ? "token "+token.length+" | " : "");
}
}
|
package cz.metacentrum.perun.webgui.json.servicesManager;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.client.UiElements;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.JsonPostClient;
import cz.metacentrum.perun.webgui.model.PerunError;
/**
* Ajax query which creates a new service.
*
* @author Pavel Zlamal <256627@mail.muni.cz>
* @author Vaclav Mach <374430@mail.muni.cz>
*/
public class CreateService {
// web session
private PerunWebSession session = PerunWebSession.getInstance();
// service name
private String serviceName = "";
// URL to call
final String JSON_URL = "servicesManager/createService";
// custom events
private JsonCallbackEvents events = new JsonCallbackEvents();
/**
* Creates a new request
*/
public CreateService() {
}
/**
* Creates a new request with custom events passed from tab or page
*
* @param events external events
*/
public CreateService(final JsonCallbackEvents events) {
this.events = events;
}
/**
* Tests the values, if the process can continue
*
* @return true/false for continue/stop
*/
private boolean testCreating()
{
boolean result = true;
String errorMsg = "";
if(serviceName.length() == 0){
errorMsg += "You must fill in the parameter 'Name'.</br>";
result = false;
}
if(errorMsg.length()>0){
UiElements.generateAlert("Parameter error", errorMsg);
}
return result;
}
/**
* Attempts to create a new Service, it first tests the values and then submits them.
*
* @param name service Name
*/
public void createService(final String name)
{
this.serviceName = name;
// test arguments
if(!this.testCreating()){
return;
}
// new events
JsonCallbackEvents newEvents = new JsonCallbackEvents(){
public void onError(PerunError error) {
session.getUiElements().setLogErrorText("Creating service " + serviceName + " failed.");
events.onError(error); // custom events
};
public void onFinished(JavaScriptObject jso) {
session.getUiElements().setLogSuccessText("Service " + serviceName + " created.");
events.onFinished(jso);
};
public void onLoadingStart() {
events.onLoadingStart();
};
};
// sending data
JsonPostClient jspc = new JsonPostClient(newEvents);
jspc.sendData(JSON_URL, prepareJSONObject());
}
/**
* Prepares a JSON object
* @return JSONObject the whole query
*/
private JSONObject prepareJSONObject()
{
// service
JSONObject service = new JSONObject();
service.put("name", new JSONString(serviceName)); // service name as object
// whole JSON query
JSONObject jsonQuery = new JSONObject();
jsonQuery.put("service", service); // service object
return jsonQuery;
}
}
|
package br.gov.servicos.editor.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import static br.gov.servicos.editor.usuarios.Papeis.*;
class SecurityConfig extends WebSecurityConfigurerAdapter {
private PasswordEncoder passwordEncoder;
public SecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/editar/info").permitAll()
.antMatchers("/editar/health").permitAll()
|
package com.codecheck123.dumb_bdd.example;
import java.util.ArrayList;
import java.util.List;
public class Calculator {
List<Integer> numbers = new ArrayList<>();
public void enter(int number) {
numbers.add(number);
}
public int command(String cmd) {
int result = 0;
switch(cmd){
case "add":
for(Integer number : numbers){
result += number;
}
break;
case "minus":
result = numbers.get(0);
for (int i = 1; i < numbers.size(); i++) {
result -= numbers.get(i);
}
break;
}
return Math.abs(result);
}
}
|
package com.conveyal.gtfs.loader;
import com.conveyal.gtfs.model.Calendar;
import com.conveyal.gtfs.model.CalendarDate;
import org.apache.commons.dbutils.DbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.conveyal.gtfs.util.Util.randomIdString;
/**
* This class takes a feedId that represents a feed already in the database and creates a copy of the entire feed.
* All tables except for the derived error and service tables are copied over (the derived pattern and pattern stop
* tables ARE copied over).
*
* This copy functionality is intended to make the feed editable and so the resulting feed
* tables are somewhat modified from their original read-only source. For instance, the ID column has been modified
* so that it is an auto-incrementing serial integer, changing the meaning of the column from csv_line (for feeds
* loaded from GTFS) to a unique identifier used to reference entities in an API.
*/
public class JdbcGtfsSnapshotter {
private static final Logger LOG = LoggerFactory.getLogger(JdbcGtfsSnapshotter.class);
private final DataSource dataSource;
// These fields will be filled in once feed snapshot begins.
private Connection connection;
private String tablePrefix;
// The reference feed ID (namespace) to copy.
private final String feedIdToSnapshot;
/**
* @param feedId namespace (schema) to snapshot. If null, a blank snapshot will be created.
* @param dataSource the JDBC data source with database connection details
*/
public JdbcGtfsSnapshotter(String feedId, DataSource dataSource) {
this.feedIdToSnapshot = feedId;
this.dataSource = dataSource;
}
/**
* Copy primary entity tables as well as Pattern and PatternStops tables.
*/
public FeedLoadResult copyTables() {
// This result object will be returned to the caller to summarize the feed and report any critical errors.
FeedLoadResult result = new FeedLoadResult();
try {
long startTime = System.currentTimeMillis();
// We get a single connection object and share it across several different methods.
// This ensures that actions taken in one method are visible to all subsequent SQL statements.
// If we create a schema or table on one connection, then access it in a separate connection, we have no
// guarantee that it exists when the accessing statement is executed.
connection = dataSource.getConnection();
// Generate a unique prefix that will identify this feed.
this.tablePrefix = randomIdString();
result.uniqueIdentifier = tablePrefix;
// Create entry in snapshots table.
registerSnapshot();
// Include the dot separator in the table prefix.
// This allows everything to work even when there's no prefix.
this.tablePrefix += ".";
// Copy each table in turn
// FIXME: NO non-fatal exception errors are being captured during copy operations.
result.agency = copy(Table.AGENCY, true);
result.calendar = copy(Table.CALENDAR, true);
result.calendarDates = copy(Table.CALENDAR_DATES, true);
result.fareAttributes = copy(Table.FARE_ATTRIBUTES, true);
result.fareRules = copy(Table.FARE_RULES, true);
result.feedInfo = copy(Table.FEED_INFO, true);
result.frequencies = copy(Table.FREQUENCIES, true);
result.routes = copy(Table.ROUTES, true);
// FIXME: Find some place to store errors encountered on copy for patterns and pattern stops.
copy(Table.PATTERNS, true);
copy(Table.PATTERN_STOP, true);
// see method comments fo why different logic is needed for this table
createScheduleExceptionsTable();
result.shapes = copy(Table.SHAPES, true);
result.stops = copy(Table.STOPS, true);
// TODO: Should we defer index creation on stop times?
// Copying all tables for STIF w/ stop times idx = 156 sec; w/o = 28 sec
// Other feeds w/ stop times AC Transit = 3 sec; Brooklyn bus =
result.stopTimes = copy(Table.STOP_TIMES, true);
result.transfers = copy(Table.TRANSFERS, true);
result.trips = copy(Table.TRIPS, true);
result.completionTime = System.currentTimeMillis();
result.loadTimeMillis = result.completionTime - startTime;
LOG.info("Copying tables took {} sec", (result.loadTimeMillis) / 1000);
} catch (Exception ex) {
// Note: Exceptions that occur during individual table loads are separately caught and stored in
// TableLoadResult.
LOG.error("Exception while creating snapshot: {}", ex.toString());
ex.printStackTrace();
result.fatalException = ex.getMessage();
}
return result;
}
/**
* This is the main table copy method that wraps a call to Table#createSqlTableFrom and creates indexes for
* the table.
*/
private TableLoadResult copy (Table table, boolean createIndexes) {
// This object will be returned to the caller to summarize the contents of the table and any errors.
// FIXME: Should there be a separate TableSnapshotResult? Load result is empty except for fatal exception.
TableLoadResult tableLoadResult = new TableLoadResult();
try {
// FIXME this is confusing, we only create a new table object so we can call a couple of methods on it,
// all of which just need a list of fields.
Table targetTable = new Table(tablePrefix + table.name, table.entityClass, table.required, table.fields);
boolean success;
if (feedIdToSnapshot == null) {
// If there is no feedId to snapshot (i.e., we're making an empty snapshot), simply create the table.
success = targetTable.createSqlTable(connection, true);
} else {
// Otherwise, use the createTableFrom method to copy the data from the original.
String fromTableName = String.format("%s.%s", feedIdToSnapshot, table.name);
LOG.info("Copying table {} to {}", fromTableName, targetTable.name);
success = targetTable.createSqlTableFrom(connection, fromTableName);
}
// Only create indexes if table creation was successful.
if (success && createIndexes) {
addEditorSpecificFields(connection, tablePrefix, table);
// Use spec table to create indexes. See createIndexes method for more info on why.
table.createIndexes(connection, tablePrefix);
// Populate default values for editor fields, including normalization of stop time stop sequences.
populateDefaultEditorValues(connection, tablePrefix, table);
}
LOG.info("Committing transaction...");
connection.commit();
LOG.info("Done.");
} catch (Exception ex) {
tableLoadResult.fatalException = ex.getMessage();
LOG.error("Error: ", ex);
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
return tableLoadResult;
}
/**
* Special logic is needed for creating the schedule_exceptions table.
*
* gtfs-lib has some more advanced data types in addition to those available in the calendar_dates.txt file of the
* GTFS specification. The schedule_exceptions table is the source of truth for exceptions to regular schedules.
* When exporting to a GTFS, the calendar_dates table is completely ignored if the schedule_exceptions table exists.
*
* When creating a snapshot, if the schedule_exceptions table doesn't currently exist, it is assumed that the feed
* being copied has just been imported and additional data to explain schedule_exceptions has not been generated yet.
* If the schedule_exceptions does already exist, that table is simply copied over.
*
* If the calendar table does not exist in the feed being copied from, it might have been the case that the
* imported feed did not have a calendar.txt file. If that was the case, then the schedule exceptions need to be
* generated from the calendar_dates table and also the calendar table needs to be populated with dummy entries so
* that it is possible to export the data to a GTFS because of current logic in JdbcGtfsExporter. The way
* JdbcGtfsExporter will only export calendar_dates that have a corresponding entry in the calendar table and have a
* service span that applies to a schedule_exception. Furthermore, the dummy calendar entries are currently needed
* for the downstream library datatools-server/datatools-ui to work properly.
*/
private TableLoadResult createScheduleExceptionsTable() {
// check to see if the schedule_exceptions table exists
boolean scheduleExceptionsTableExists = feedIdToSnapshot != null &&
tableExists(feedIdToSnapshot, "schedule_exceptions");
String scheduleExceptionsTableName = tablePrefix + "schedule_exceptions";
if (scheduleExceptionsTableExists) {
// schedule_exceptions table already exists in namespace being copied from. Therefore, we simply copy it.
return copy(Table.SCHEDULE_EXCEPTIONS, true);
} else {
// schedule_exceptions does not exist. Therefore, we generate schedule_exceptions from the calendar_dates.
TableLoadResult tableLoadResult = new TableLoadResult();
try {
Table.SCHEDULE_EXCEPTIONS.createSqlTable(
connection,
tablePrefix.replace(".", ""),
true
);
String sql = String.format(
"insert into %s (name, dates, exemplar, added_service, removed_service) values (?, ?, ?, ?, ?)",
scheduleExceptionsTableName
);
PreparedStatement scheduleExceptionsStatement = connection.prepareStatement(sql);
final BatchTracker scheduleExceptionsTracker = new BatchTracker(
"schedule_exceptions",
scheduleExceptionsStatement
);
JDBCTableReader<CalendarDate> calendarDatesReader = new JDBCTableReader(
Table.CALENDAR_DATES,
dataSource,
feedIdToSnapshot + ".",
EntityPopulator.CALENDAR_DATE
);
Iterable<CalendarDate> calendarDates = calendarDatesReader.getAll();
// keep track of calendars by service id in case we need to add dummy calendar entries
Map<String, Calendar> calendarsByServiceId = new HashMap<>();
// iterate through calendar dates to build up to get list of dates with exceptions
HashMap<String, List<String>> removedServiceDays = new HashMap<>();
HashMap<String, List<String>> addedServiceDays = new HashMap<>();
List<String> datesWithExceptions = new ArrayList<>();
for (CalendarDate calendarDate : calendarDates) {
String date = calendarDate.date.format(DateTimeFormatter.BASIC_ISO_DATE);
datesWithExceptions.add(date);
if (calendarDate.exception_type == 1) {
List<String> dateAddedServices = addedServiceDays.getOrDefault(date, new ArrayList<>());
dateAddedServices.add(calendarDate.service_id);
addedServiceDays.put(date, dateAddedServices);
// create (if needed) and extend range of dummy calendar that would need to be created if we are
// copying from a feed that doesn't have the calendar.txt file
Calendar calendar = calendarsByServiceId.getOrDefault(calendarDate.service_id, new Calendar());
calendar.service_id = calendarDate.service_id;
if (calendar.start_date == null || calendar.start_date.isAfter(calendarDate.date)) {
calendar.start_date = calendarDate.date;
}
if (calendar.end_date == null || calendar.end_date.isBefore(calendarDate.date)) {
calendar.end_date = calendarDate.date;
}
calendarsByServiceId.put(calendarDate.service_id, calendar);
} else {
List<String> dateRemovedServices = removedServiceDays.getOrDefault(date, new ArrayList<>());
dateRemovedServices.add(calendarDate.service_id);
removedServiceDays.put(date, dateRemovedServices);
}
}
// iterate through days and add to database
// for usability and simplicity of code, don't attempt to find all dates with similar
// added and removed services, but simply create an entry for each found date
for (String dateWithException : datesWithExceptions) {
scheduleExceptionsStatement.setString(1, dateWithException);
String[] dates = {dateWithException};
scheduleExceptionsStatement.setArray(2, connection.createArrayOf("text", dates));
scheduleExceptionsStatement.setInt(3, 9); // FIXME use better static type
scheduleExceptionsStatement.setArray(
4,
connection.createArrayOf(
"text",
addedServiceDays.getOrDefault(dateWithException, new ArrayList<>()).toArray()
)
);
scheduleExceptionsStatement.setArray(
5,
connection.createArrayOf(
"text",
removedServiceDays.getOrDefault(dateWithException, new ArrayList<>()).toArray()
)
);
scheduleExceptionsTracker.addBatch();
}
scheduleExceptionsTracker.executeRemaining();
// determine if we appear to be working with a calendar_dates-only feed.
// If so, we must also add dummy entries to the calendar table
if (!tableExists(feedIdToSnapshot, "calendar") && calendarDatesReader.getRowCount() > 0) {
sql = String.format(
"insert into %s (service_id, description, start_date, end_date, " +
"monday, tuesday, wednesday, thursday, friday, saturday, sunday)" +
"values (?, ?, ?, ?, 0, 0, 0, 0, 0, 0, 0)",
tablePrefix + "calendar"
);
PreparedStatement calendarStatement = connection.prepareStatement(sql);
final BatchTracker calendarsTracker = new BatchTracker(
"calendar",
calendarStatement
);
for (Calendar calendar : calendarsByServiceId.values()) {
calendarStatement.setString(1, calendar.service_id);
calendarStatement.setString(
2,
String.format("%s (auto-generated)", calendar.service_id)
);
calendarStatement.setString(
3,
calendar.start_date.format(DateTimeFormatter.BASIC_ISO_DATE)
);
calendarStatement.setString(
4,
calendar.end_date.format(DateTimeFormatter.BASIC_ISO_DATE)
);
calendarsTracker.addBatch();
}
calendarsTracker.executeRemaining();
}
connection.commit();
} catch (SQLException e) {
tableLoadResult.fatalException = e.getMessage();
LOG.error("Error creating schedule Exceptions: ", e);
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
LOG.info("done creating schedule exceptions");
return tableLoadResult;
}
}
/**
* Helper method to determine if a table exists within a namespace.
*/
private boolean tableExists(String namespace, String tableName) {
try {
// This statement is postgres-specific.
PreparedStatement tableExistsStatement = connection.prepareStatement(
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?)"
);
tableExistsStatement.setString(1, namespace);
tableExistsStatement.setString(2, tableName);
ResultSet resultSet = tableExistsStatement.executeQuery();
resultSet.next();
return resultSet.getBoolean(1);
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Add columns for any required, optional, or editor fields that don't already exist as columns on the table.
* This method contains a SQL statement that requires PostgreSQL 9.6+.
*/
private void addEditorSpecificFields(Connection connection, String tablePrefix, Table table) throws SQLException {
LOG.info("Adding any missing columns for {}", tablePrefix + table.name);
Statement statement = connection.createStatement();
for (Field field : table.editorFields()) {
// The following statement requires PostgreSQL 9.6+.
String addColumnSql = String.format("ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s",
tablePrefix + table.name,
field.name,
field.getSqlTypeName());
LOG.info(addColumnSql);
statement.execute(addColumnSql);
}
}
/**
* Populates editor-specific fields added during GTFS-to-snapshot operation with default values. This method also
* "normalizes" the stop sequences for stop times to zero-based, incremented integers. NOTE: stop time normalization
* can take a significant amount of time (for large feeds up to 5 minutes) if the update is large.
*/
private void populateDefaultEditorValues(Connection connection, String tablePrefix, Table table) throws SQLException {
Statement statement = connection.createStatement();
if (Table.ROUTES.name.equals(table.name)) {
// Set default values for route status and publicly visible to "Approved" and "Public", respectively.
// This prevents unexpected results when users attempt to export a GTFS feed from the editor and no
// routes are exported due to undefined values for status and publicly visible.
String updateStatusSql = String.format(
"update %sroutes set status = 2, publicly_visible = 1 where status is NULL AND publicly_visible is NULL",
tablePrefix);
int updatedRoutes = statement.executeUpdate(updateStatusSql);
LOG.info("Updated status for {} routes", updatedRoutes);
}
if (Table.CALENDAR.name.equals(table.name)) {
// Set default values for description field. Basically constructs a description from the days of the week
// for which the calendar is active.
LOG.info("Updating calendar descriptions");
String[] daysOfWeek = new String[]{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};
String concatenatedDaysOfWeek = String.join(", ",
Arrays.stream(daysOfWeek)
.map(d -> String.format(
"case %s when 1 then '%s' else '' end",
d,
// Capitalize first letter. Converts days of week from "monday" -> "Mo".
d.substring(0, 1).toUpperCase() + d.substring(1, 2))).toArray(String[]::new));
String updateOtherSql = String.format(
"update %scalendar set description = concat(%s) where description is NULL",
tablePrefix,
concatenatedDaysOfWeek);
LOG.info(updateOtherSql);
int calendarsUpdated = statement.executeUpdate(updateOtherSql);
LOG.info("Updated description for {} calendars", calendarsUpdated);
}
if (Table.TRIPS.name.equals(table.name)) {
// Update use_frequency field for patterns. This sets all patterns that have a frequency trip to use
// frequencies. NOTE: This is performed after copying the TRIPS table rather than after PATTERNS because
// both tables (plus, frequencies) need to exist for the successful operation.
// TODO: How should this handle patterns that have both timetable- and frequency-based trips?
// NOTE: The below substitution uses argument indexing. All values "%1$s" reference the first argument
// supplied (i.e., tablePrefix).
String updatePatternsSql = String.format(
"update %1$spatterns set use_frequency = 1 " +
"from (select distinct %1$strips.pattern_id from %1$strips, %1$sfrequencies where %1$sfrequencies.trip_id = %1$strips.trip_id) freq " +
"where freq.pattern_id = %1$spatterns.pattern_id",
tablePrefix);
LOG.info(updatePatternsSql);
int patternsUpdated = statement.executeUpdate(updatePatternsSql);
LOG.info("Updated use_frequency for {} patterns", patternsUpdated);
}
// TODO: Add simple conversion from calendar_dates to schedule_exceptions if no exceptions exist? See
}
/**
* Add a line to the list of loaded feeds to record the snapshot and which feed the snapshot replicates.
*/
private void registerSnapshot () {
try {
Statement statement = connection.createStatement();
// TODO copy over feed_id and feed_version from source namespace?
// FIXME do the following only on databases that support schemas.
// SQLite does not support them. Is there any advantage of schemas over flat tables?
statement.execute("create schema " + tablePrefix);
// TODO: Record total snapshot processing time?
// Simply insert into feeds table (no need for table creation) because making a snapshot presumes that the
// feeds table already exists.
PreparedStatement insertStatement = connection.prepareStatement(
"insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)");
insertStatement.setString(1, tablePrefix);
insertStatement.setString(2, feedIdToSnapshot);
insertStatement.execute();
connection.commit();
LOG.info("Created new snapshot namespace: {}", insertStatement);
} catch (Exception ex) {
LOG.error("Exception while registering snapshot namespace in feeds table: {}", ex.getMessage());
DbUtils.closeQuietly(connection);
}
}
}
|
package com.intellij.openapi.editor.colors.impl;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.configurationStore.BundledSchemeEP;
import com.intellij.configurationStore.LazySchemeProcessor;
import com.intellij.configurationStore.SchemeDataHolder;
import com.intellij.configurationStore.SchemeExtensionProvider;
import com.intellij.ide.WelcomeWizardUtil;
import com.intellij.ide.ui.LafManager;
import com.intellij.ide.ui.UITheme;
import com.intellij.ide.ui.laf.UIThemeBasedLookAndFeelInfo;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.ApplicationImpl;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsListener;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.options.SchemeManager;
import com.intellij.openapi.options.SchemeManagerFactory;
import com.intellij.openapi.options.SchemeState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ComponentTreeEventDispatcher;
import com.intellij.util.JdomKt;
import com.intellij.util.io.URLUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.xmlb.annotations.OptionTag;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
@State(
name = "EditorColorsManagerImpl",
storages = @Storage("colors.scheme.xml"),
additionalExportFile = EditorColorsManagerImpl.FILE_SPEC
)
public class EditorColorsManagerImpl extends EditorColorsManager implements PersistentStateComponent<EditorColorsManagerImpl.State> {
private static final Logger LOG = Logger.getInstance(EditorColorsManagerImpl.class);
private static final ExtensionPointName<BundledSchemeEP> BUNDLED_EP_NAME = ExtensionPointName.create("com.intellij.bundledColorScheme");
private final ComponentTreeEventDispatcher<EditorColorsListener> myTreeDispatcher = ComponentTreeEventDispatcher.create(EditorColorsListener.class);
private final DefaultColorSchemesManager myDefaultColorSchemeManager;
private final SchemeManager<EditorColorsScheme> mySchemeManager;
static final String FILE_SPEC = "colors";
private State myState = new State();
public EditorColorsManagerImpl(@NotNull DefaultColorSchemesManager defaultColorSchemeManager, @NotNull SchemeManagerFactory schemeManagerFactory) {
myDefaultColorSchemeManager = defaultColorSchemeManager;
class EditorColorSchemeProcessor extends LazySchemeProcessor<EditorColorsScheme, EditorColorsSchemeImpl> implements SchemeExtensionProvider {
@NotNull
@Override
public EditorColorsSchemeImpl createScheme(@NotNull SchemeDataHolder<? super EditorColorsSchemeImpl> dataHolder,
@NotNull String name,
@NotNull Function<String, String> attributeProvider,
boolean isBundled) {
EditorColorsSchemeImpl scheme = isBundled ? new BundledScheme() : new EditorColorsSchemeImpl(null);
// todo be lazy
scheme.readExternal(dataHolder.read());
// we don't need to update digest for bundled scheme because
// 1) it can be computed on demand later (because bundled scheme is not mutable)
// 2) in the future user copy of bundled scheme will use bundled scheme as parent (not as full copy)
if (isBundled) {
scheme.optimizeAttributeMap();
}
return scheme;
}
@NotNull
@Override
public SchemeState getState(@NotNull EditorColorsScheme scheme) {
return scheme instanceof ReadOnlyColorsScheme ? SchemeState.NON_PERSISTENT : SchemeState.POSSIBLY_CHANGED;
}
@Override
public void onCurrentSchemeSwitched(@Nullable EditorColorsScheme oldScheme, @Nullable EditorColorsScheme newScheme) {
ApplicationManager.getApplication().invokeLater(() -> { // don't do heavy operations right away
LafManager.getInstance().updateUI();
schemeChangedOrSwitched(newScheme);
});
}
@NotNull
@NonNls
@Override
public String getSchemeExtension() {
return COLOR_SCHEME_FILE_EXTENSION;
}
@Override
public boolean isSchemeEqualToBundled(@NotNull EditorColorsSchemeImpl scheme) {
if (!scheme.getName().startsWith(SchemeManager.EDITABLE_COPY_PREFIX)) {
return false;
}
AbstractColorsScheme bundledScheme =
(AbstractColorsScheme)mySchemeManager.findSchemeByName(scheme.getName().substring(SchemeManager.EDITABLE_COPY_PREFIX.length()));
if (bundledScheme == null) {
return false;
}
return scheme.settingsEqual(bundledScheme);
}
@Override
public void reloaded(@NotNull SchemeManager<EditorColorsScheme> schemeManager,
@NotNull Collection<? extends EditorColorsScheme> schemes) {
loadBundledSchemes();
loadSchemesFromThemes();
initEditableDefaultSchemesCopies();
initEditableBundledSchemesCopies();
}
}
mySchemeManager = schemeManagerFactory.create(FILE_SPEC, new EditorColorSchemeProcessor());
initDefaultSchemes();
loadBundledSchemes();
loadSchemesFromThemes();
mySchemeManager.loadSchemes();
String wizardEditorScheme = WelcomeWizardUtil.getWizardEditorScheme();
EditorColorsScheme scheme = null;
if (wizardEditorScheme != null) {
scheme = getScheme(wizardEditorScheme);
LOG.assertTrue(scheme != null, "Wizard scheme " + wizardEditorScheme + " not found");
}
initEditableDefaultSchemesCopies();
initEditableBundledSchemesCopies();
resolveLinksToBundledSchemes();
setGlobalSchemeInner(scheme == null ? getDefaultScheme() : scheme);
}
private void initDefaultSchemes() {
for (DefaultColorsScheme defaultScheme : myDefaultColorSchemeManager.getAllSchemes()) {
mySchemeManager.addScheme(defaultScheme);
}
loadAdditionalTextAttributes();
}
private void initEditableDefaultSchemesCopies() {
for (DefaultColorsScheme defaultScheme : myDefaultColorSchemeManager.getAllSchemes()) {
if (defaultScheme.hasEditableCopy()) {
createEditableCopy(defaultScheme, defaultScheme.getEditableCopyName());
}
}
}
private void loadBundledSchemes() {
if (!isUnitTestOrHeadlessMode()) {
for (BundledSchemeEP ep : BUNDLED_EP_NAME.getExtensions()) {
mySchemeManager.loadBundledScheme(ep.getPath() + ".xml", ep);
}
}
}
private void loadSchemesFromThemes() {
if (!isUnitTestOrHeadlessMode()) {
for (UIManager.LookAndFeelInfo laf : LafManager.getInstance().getInstalledLookAndFeels()) {
if (laf instanceof UIThemeBasedLookAndFeelInfo) {
UITheme theme = ((UIThemeBasedLookAndFeelInfo)laf).getTheme();
String path = theme.getEditorScheme();
if (path != null) {
mySchemeManager.loadBundledScheme(path, theme.getProviderClass());
}
}
}
}
}
private void initEditableBundledSchemesCopies() {
for (EditorColorsScheme scheme : mySchemeManager.getAllSchemes()) {
if (scheme instanceof BundledScheme) {
createEditableCopy((BundledScheme)scheme, SchemeManager.EDITABLE_COPY_PREFIX + scheme.getName());
}
}
}
private void resolveLinksToBundledSchemes() {
for (EditorColorsScheme scheme : mySchemeManager.getAllSchemes()) {
if (scheme instanceof AbstractColorsScheme && !(scheme instanceof ReadOnlyColorsScheme)) {
try {
((AbstractColorsScheme)scheme).resolveParent(name -> mySchemeManager.findSchemeByName(name));
}
catch (InvalidDataException e) {
String message = "Color scheme '" + scheme.getName() + "'" +
" points to incorrect or non-existent default (base) scheme " +
e.getMessage();
Notifications.Bus.notify(
new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Incompatible color scheme", message, NotificationType.ERROR));
}
}
}
}
private void createEditableCopy(@NotNull AbstractColorsScheme initialScheme, @NotNull String editableCopyName) {
AbstractColorsScheme editableCopy = (AbstractColorsScheme)getScheme(editableCopyName);
if (editableCopy == null) {
editableCopy = (AbstractColorsScheme)initialScheme.clone();
editableCopy.setName(editableCopyName);
mySchemeManager.addScheme(editableCopy);
}
editableCopy.setCanBeDeleted(false);
}
@Deprecated
public static void schemeChangedOrSwitched() {
EditorColorsManagerImpl manager = (EditorColorsManagerImpl)getInstance();
manager.schemeChangedOrSwitched(manager.getGlobalScheme());
}
public void schemeChangedOrSwitched(@Nullable EditorColorsScheme newScheme) {
// refreshAllEditors is not enough - for example, change "Errors and warnings -> Typo" from green (default) to red
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
DaemonCodeAnalyzer.getInstance(project).restart();
}
// we need to push events to components that use editor font, e.g. HTML editor panes
ApplicationManager.getApplication().getMessageBus().syncPublisher(TOPIC).globalSchemeChange(newScheme);
myTreeDispatcher.getMulticaster().globalSchemeChange(newScheme);
}
static class BundledScheme extends EditorColorsSchemeImpl implements ReadOnlyColorsScheme {
public BundledScheme() {
super(null);
}
@Override
public boolean isVisible() {
return false;
}
}
static class State {
public boolean USE_ONLY_MONOSPACED_FONTS = true;
@OptionTag(tag = "global_color_scheme", nameAttribute = "", valueAttribute = "name")
public String colorScheme;
}
private static boolean isUnitTestOrHeadlessMode() {
return ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment();
}
public TextAttributes getDefaultAttributes(TextAttributesKey key) {
final boolean dark = UIUtil.isUnderDarcula() && getScheme("Darcula") != null;
// It is reasonable to fetch attributes from Default color scheme. Otherwise if we launch IDE and then
// try switch from custom colors scheme (e.g. with dark background) to default one. Editor will show
// incorrect highlighting with "traces" of color scheme which was active during IDE startup.
return getScheme(dark ? "Darcula" : EditorColorsScheme.DEFAULT_SCHEME_NAME).getAttributes(key);
}
private void loadAdditionalTextAttributes() {
for (AdditionalTextAttributesEP attributesEP : AdditionalTextAttributesEP.EP_NAME.getExtensions()) {
EditorColorsScheme editorColorsScheme = mySchemeManager.findSchemeByName(attributesEP.scheme);
if (editorColorsScheme == null) {
if (!isUnitTestOrHeadlessMode()) {
LOG.warn("Cannot find scheme: " + attributesEP.scheme + " from plugin: " + attributesEP.getPluginDescriptor().getPluginId());
}
continue;
}
URL resource = attributesEP.getLoaderForClass().getResource(attributesEP.file);
if (resource == null) {
LOG.warn("resource not found: " + attributesEP.file);
continue;
}
try {
((AbstractColorsScheme)editorColorsScheme).readAttributes(JdomKt.loadElement(URLUtil.openStream(resource)));
}
catch (Exception e) {
LOG.error(e);
}
}
}
@Override
public void addColorsScheme(@NotNull EditorColorsScheme scheme) {
if (!isDefaultScheme(scheme) && !StringUtil.isEmpty(scheme.getName())) {
mySchemeManager.addScheme(scheme);
}
}
@Override
public void removeAllSchemes() {
}
@NotNull
@Override
public EditorColorsScheme[] getAllSchemes() {
EditorColorsScheme[] result = getAllVisibleSchemes(mySchemeManager.getAllSchemes());
Arrays.sort(result, EditorColorSchemesComparator.INSTANCE);
return result;
}
private static EditorColorsScheme[] getAllVisibleSchemes(@NotNull Collection<EditorColorsScheme> schemes) {
List<EditorColorsScheme> visibleSchemes = new ArrayList<>(schemes.size() - 1);
for (EditorColorsScheme scheme : schemes) {
if (AbstractColorsScheme.isVisible(scheme)) {
visibleSchemes.add(scheme);
}
}
return visibleSchemes.toArray(new EditorColorsScheme[0]);
}
@Override
public void setGlobalScheme(@Nullable EditorColorsScheme scheme) {
Application application = ApplicationManager.getApplication();
boolean notify = (application instanceof ApplicationImpl && ((ApplicationImpl)application).isLoaded());
mySchemeManager.setCurrent(scheme == null ? getDefaultScheme() : scheme, notify);
}
private void setGlobalSchemeInner(@Nullable EditorColorsScheme scheme) {
mySchemeManager.setCurrent(scheme == null ? getDefaultScheme() : scheme, false);
}
@NotNull
private EditorColorsScheme getDefaultScheme() {
DefaultColorsScheme defaultScheme = myDefaultColorSchemeManager.getFirstScheme();
String editableCopyName = defaultScheme.getEditableCopyName();
EditorColorsScheme editableCopy = getScheme(editableCopyName);
assert editableCopy != null : "An editable copy of " + defaultScheme.getName() + " has not been initialized.";
return editableCopy;
}
@NotNull
@Override
public EditorColorsScheme getGlobalScheme() {
EditorColorsScheme scheme = mySchemeManager.getActiveScheme();
String editableCopyName = null;
if (scheme instanceof DefaultColorsScheme && ((DefaultColorsScheme)scheme).hasEditableCopy()) {
editableCopyName = ((DefaultColorsScheme)scheme).getEditableCopyName();
}
else if (scheme instanceof BundledScheme) {
editableCopyName = SchemeManager.EDITABLE_COPY_PREFIX + scheme.getName();
}
if (editableCopyName != null) {
EditorColorsScheme editableCopy = getScheme(editableCopyName);
if (editableCopy != null) return editableCopy;
}
return scheme == null ? getDefaultScheme() : scheme;
}
@Override
public EditorColorsScheme getScheme(@NotNull String schemeName) {
return mySchemeManager.findSchemeByName(schemeName);
}
@Override
public void setUseOnlyMonospacedFonts(boolean value) {
myState.USE_ONLY_MONOSPACED_FONTS = value;
}
@Override
public boolean isUseOnlyMonospacedFonts() {
return myState.USE_ONLY_MONOSPACED_FONTS;
}
@Nullable
@Override
public State getState() {
String currentSchemeName = mySchemeManager.getCurrentSchemeName();
if (currentSchemeName != null) {
myState.colorScheme = ("Default".equals(currentSchemeName) || (SchemeManager.EDITABLE_COPY_PREFIX + "Default").equals(
currentSchemeName)) ? null : currentSchemeName;
}
return myState;
}
@Override
public void loadState(@NotNull State state) {
myState = state;
setGlobalSchemeInner(myState.colorScheme == null ? getDefaultScheme() : mySchemeManager.findSchemeByName(myState.colorScheme));
}
@Override
public boolean isDefaultScheme(EditorColorsScheme scheme) {
return scheme instanceof DefaultColorsScheme;
}
@NotNull
@Override
public EditorColorsScheme getSchemeForCurrentUITheme() {
String schemeName = UIUtil.isUnderDarcula() ? "Darcula" : DEFAULT_SCHEME_NAME;
EditorColorsScheme scheme = myDefaultColorSchemeManager.getScheme(schemeName);
assert scheme != null :
"The default scheme '" + schemeName + "' not found, " +
"available schemes: " + Arrays.toString(myDefaultColorSchemeManager.listNames());
if (((DefaultColorsScheme)scheme).hasEditableCopy()) {
EditorColorsScheme editableCopy = getScheme(((DefaultColorsScheme)scheme).getEditableCopyName());
if (editableCopy != null) return editableCopy;
}
return scheme;
}
@NotNull
public SchemeManager<EditorColorsScheme> getSchemeManager() {
return mySchemeManager;
}
}
|
package com.excelsiorsoft.saml;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.joda.time.DateTime;
import org.opensaml.DefaultBootstrap;
import org.opensaml.common.SAMLVersion;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.AttributeValue;
import org.opensaml.saml2.core.AuthnContext;
import org.opensaml.saml2.core.AuthnContextClassRef;
import org.opensaml.saml2.core.AuthnStatement;
import org.opensaml.saml2.core.Issuer;
import org.opensaml.saml2.core.NameID;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.core.Status;
import org.opensaml.saml2.core.StatusCode;
import org.opensaml.saml2.core.Subject;
import org.opensaml.saml2.core.SubjectConfirmation;
import org.opensaml.saml2.core.SubjectConfirmationData;
import org.opensaml.saml2.core.impl.AssertionBuilder;
import org.opensaml.saml2.core.impl.AttributeBuilder;
import org.opensaml.saml2.core.impl.AttributeStatementBuilder;
import org.opensaml.saml2.core.impl.AuthnContextBuilder;
import org.opensaml.saml2.core.impl.AuthnContextClassRefBuilder;
import org.opensaml.saml2.core.impl.AuthnStatementBuilder;
import org.opensaml.saml2.core.impl.IssuerBuilder;
import org.opensaml.saml2.core.impl.NameIDBuilder;
import org.opensaml.saml2.core.impl.ResponseBuilder;
import org.opensaml.saml2.core.impl.ResponseMarshaller;
import org.opensaml.saml2.core.impl.StatusBuilder;
import org.opensaml.saml2.core.impl.StatusCodeBuilder;
import org.opensaml.saml2.core.impl.SubjectBuilder;
import org.opensaml.saml2.core.impl.SubjectConfirmationBuilder;
import org.opensaml.saml2.core.impl.SubjectConfirmationDataBuilder;
import org.opensaml.xml.schema.XSString;
import org.opensaml.xml.schema.impl.XSStringBuilder;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureConstants;
import org.opensaml.xml.signature.Signer;
import org.opensaml.xml.signature.impl.SignatureBuilder;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Element;
public class SamlAssertionProducer {
private String privateKeyLocation;
private String publicKeyLocation;
private CertManager certManager = new CertManager();
public Response createSAMLResponse(final String subjectId,
final DateTime authenticationTime, final String credentialType,
final HashMap<String, List<String>> attributes, String issuer,
Integer samlAssertionDays) {
try {
DefaultBootstrap.bootstrap();
Signature signature = createSignature();
Status status = createStatus();
Issuer responseIssuer = null;
Issuer assertionIssuer = null;
Subject subject = null;
AttributeStatement attributeStatement = null;
if (issuer != null) {
responseIssuer = createIssuer(issuer, false);
assertionIssuer = createIssuer(issuer, true);
}
if (subjectId != null) {
subject = createSubject(subjectId, samlAssertionDays);
}
if (attributes != null && attributes.size() != 0) {
attributeStatement = createAttributeStatement(attributes);
}
AuthnStatement authnStatement = createAuthnStatement(authenticationTime);
Assertion assertion = createAssertion(new DateTime(), subject,
assertionIssuer, authnStatement, attributeStatement);
Response response = createResponse(new DateTime(), responseIssuer,
status, assertion);
response.setSignature(signature);
ResponseMarshaller marshaller = new ResponseMarshaller();
Element element = marshaller.marshall(response);
if (response.getSignature() != null) {
Signer.signObject(signature);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLHelper.writeNode(element, baos);
return response;
} catch (Throwable t) {
t.printStackTrace();
return null;
}
}
public String getPrivateKeyLocation() {
return privateKeyLocation;
}
public void setPrivateKeyLocation(String privateKeyLocation) {
this.privateKeyLocation = privateKeyLocation;
}
public String getPublicKeyLocation() {
return publicKeyLocation;
}
public void setPublicKeyLocation(String publicKeyLocation) {
this.publicKeyLocation = publicKeyLocation;
}
private Response createResponse(final DateTime issueDate, Issuer issuer,
Status status, Assertion assertion) {
ResponseBuilder responseBuilder = new ResponseBuilder();
Response response = responseBuilder.buildObject();
response.setID(UUID.randomUUID().toString());
response.setIssueInstant(issueDate);
response.setVersion(SAMLVersion.VERSION_20);
response.setIssuer(issuer);
response.setStatus(status);
response.getAssertions().add(assertion);
return response;
}
private Assertion createAssertion(final DateTime issueDate,
Subject subject, Issuer issuer, AuthnStatement authnStatement,
AttributeStatement attributeStatement) {
AssertionBuilder assertionBuilder = new AssertionBuilder();
Assertion assertion = assertionBuilder.buildObject();
assertion.setID(UUID.randomUUID().toString());
assertion.setIssueInstant(issueDate);
assertion.setSubject(subject);
assertion.setIssuer(issuer);
if (authnStatement != null)
assertion.getAuthnStatements().add(authnStatement);
if (attributeStatement != null)
assertion.getAttributeStatements().add(attributeStatement);
return assertion;
}
private Issuer createIssuer(final String issuerName, final boolean needFormat) {
// create Issuer object
IssuerBuilder issuerBuilder = new IssuerBuilder();
Issuer issuer = issuerBuilder.buildObject();
issuer.setValue(issuerName);
if (needFormat) issuer.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
return issuer;
}
private Subject createSubject(final String subjectId,
final Integer samlAssertionDays) {
DateTime currentDate = new DateTime();
if (samlAssertionDays != null)
currentDate = currentDate.plusDays(samlAssertionDays);
// create name element
NameIDBuilder nameIdBuilder = new NameIDBuilder();
NameID nameId = nameIdBuilder.buildObject();
nameId.setValue(subjectId);
nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
SubjectConfirmationDataBuilder dataBuilder = new SubjectConfirmationDataBuilder();
SubjectConfirmationData subjectConfirmationData = dataBuilder
.buildObject();
subjectConfirmationData.setNotOnOrAfter(currentDate);
SubjectConfirmationBuilder subjectConfirmationBuilder = new SubjectConfirmationBuilder();
SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder
.buildObject();
subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");
subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);
// create subject element
SubjectBuilder subjectBuilder = new SubjectBuilder();
Subject subject = subjectBuilder.buildObject();
subject.setNameID(nameId);
subject.getSubjectConfirmations().add(subjectConfirmation);
return subject;
}
private AuthnStatement createAuthnStatement(final DateTime issueDate) {
// create authcontextclassref object
//AuthnContextClassRefBuilder classRefBuilder = new AuthnContextClassRefBuilder();
AuthnContextClassRef classRef = new AuthnContextClassRefBuilder().buildObject();
classRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
// create authcontext object
//AuthnContextBuilder authContextBuilder = new AuthnContextBuilder();
AuthnContext authnContext = new AuthnContextBuilder().buildObject();
authnContext.setAuthnContextClassRef(classRef);
// create authenticationstatement object
//AuthnStatementBuilder authStatementBuilder = new AuthnStatementBuilder();
AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
authnStatement.setAuthnInstant(issueDate);
authnStatement.setAuthnContext(authnContext);
return authnStatement;
}
private AttributeStatement createAttributeStatement(
HashMap<String, List<String>> attributes) {
// create authenticationstatement object
//AttributeStatementBuilder attributeStatementBuilder = new AttributeStatementBuilder();
AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
AttributeBuilder attributeBuilder = new AttributeBuilder();
if (attributes != null) {
for (Map.Entry<String, List<String>> entry : attributes.entrySet()) {
Attribute attribute = attributeBuilder.buildObject();
attribute.setName(entry.getKey());
for (String value : entry.getValue()) {
XSStringBuilder stringBuilder = new XSStringBuilder();
XSString attributeValue = stringBuilder.buildObject(
AttributeValue.DEFAULT_ELEMENT_NAME,
XSString.TYPE_NAME);
attributeValue.setValue(value);
attribute.getAttributeValues().add(attributeValue);
}
attributeStatement.getAttributes().add(attribute);
}
}
return attributeStatement;
}
private Status createStatus() {
//StatusCodeBuilder statusCodeBuilder = new StatusCodeBuilder();
StatusCode statusCode = new StatusCodeBuilder().buildObject();
statusCode.setValue(StatusCode.SUCCESS_URI);
StatusBuilder statusBuilder = new StatusBuilder();
Status status = statusBuilder.buildObject();
status.setStatusCode(statusCode);
return status;
}
private Signature createSignature() throws Throwable {
if (publicKeyLocation != null && privateKeyLocation != null) {
//SignatureBuilder builder = new SignatureBuilder();
Signature signature = new SignatureBuilder().buildObject();
signature.setSigningCredential(certManager.getSigningCredential(
publicKeyLocation, privateKeyLocation));
signature
.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
signature
.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
return signature;
}
return null;
}
}
|
package com.j256.ormlite.jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.stmt.GenericRowMapper;
import com.j256.ormlite.support.DatabaseConnection;
import com.j256.ormlite.support.GeneratedKeyHolder;
import com.j256.ormlite.support.PreparedStmt;
import com.j256.ormlite.support.Results;
public class JdbcDatabaseConnection implements DatabaseConnection {
private static Object[] noArgs = new Object[0];
private static int[] noArgTypes = new int[0];
private static GenericRowMapper<Long> longWrapper = new OneLongWrapper();
private Connection connection;
private DatabaseMetaData metaData = null;
public JdbcDatabaseConnection(Connection connection) {
this.connection = connection;
}
public boolean isSupportsSavepoints() throws SQLException {
if (metaData == null) {
metaData = connection.getMetaData();
}
return metaData.supportsSavepoints();
}
public boolean getAutoCommit() throws SQLException {
return connection.getAutoCommit();
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
connection.setAutoCommit(autoCommit);
}
public Savepoint setSavepoint(String name) throws SQLException {
return connection.setSavepoint(name);
}
public void commit() throws SQLException {
connection.commit();
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
connection.releaseSavepoint(savepoint);
}
public void rollback() throws SQLException {
connection.rollback();
}
public void rollback(Savepoint savepoint) throws SQLException {
connection.rollback(savepoint);
}
public PreparedStmt prepareStatement(String sql) throws SQLException {
return new JdbcPreparedStmt(connection.prepareStatement(sql));
}
public void close() throws SQLException {
connection.close();
}
/**
* Returns whether the connection has already been closed. Used by {@link JdbcConnectionSource}.
*/
public boolean isClosed() throws SQLException {
return connection.isClosed();
}
public int insert(String statement, Object[] args, int[] argFieldTypeVals) throws SQLException {
// it's a call to executeUpdate
return update(statement, args, argFieldTypeVals);
}
public int insert(String statement, Object[] args, int[] argFieldTypeVals, GeneratedKeyHolder keyHolder)
throws SQLException {
PreparedStatement stmt = connection.prepareStatement(statement, Statement.RETURN_GENERATED_KEYS);
statementSetArgs(stmt, args, argFieldTypeVals);
int rowN = stmt.executeUpdate();
Results results = new JdbcResults(stmt, stmt.getGeneratedKeys());
if (results == null) {
// may never happen but let's be careful
throw new SQLException("No generated key results returned from update: " + statement);
}
int colN = results.getColumnCount();
while (results.next()) {
for (int colC = 1; colC <= colN; colC++) {
String colName = results.getColumnName(colC);
DataType dataType = results.getColumnDataType(colC);
Number id = dataType.resultToId(results, colC);
if (id == null) {
// may never happen but let's be careful
throw new SQLException("Generated column " + colName + " is invalid type " + dataType);
} else {
keyHolder.addKey(id);
}
}
}
return rowN;
}
public int update(String statement, Object[] args, int[] argFieldTypeVals) throws SQLException {
PreparedStatement stmt = connection.prepareStatement(statement);
statementSetArgs(stmt, args, argFieldTypeVals);
return stmt.executeUpdate();
}
public int delete(String statement, Object[] args, int[] argFieldTypeVals) throws SQLException {
// it's a call to executeUpdate
return update(statement, args, argFieldTypeVals);
}
public <T> Object queryForOne(String statement, Object[] args, int[] argFieldTypeVals, GenericRowMapper<T> rowMapper)
throws SQLException {
PreparedStatement stmt =
connection.prepareStatement(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
statementSetArgs(stmt, args, argFieldTypeVals);
Results results = new JdbcResults(stmt, stmt.executeQuery());
if (!results.next()) {
// no results at all
return null;
}
T first = rowMapper.mapRow(results);
if (results.next()) {
return MORE_THAN_ONE;
} else {
return first;
}
}
public long queryForLong(String statement) throws SQLException {
Object result = queryForOne(statement, noArgs, noArgTypes, longWrapper);
if (result == null) {
throw new SQLException("No results returned in query-for-long: " + statement);
} else if (result == MORE_THAN_ONE) {
throw new SQLException("More than 1 result returned in query-for-long: " + statement);
} else {
return (Long) result;
}
}
private void statementSetArgs(PreparedStatement stmt, Object[] args, int[] argFieldTypeVals) throws SQLException {
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
if (arg == null) {
stmt.setNull(i + 1, argFieldTypeVals[i]);
} else {
stmt.setObject(i + 1, arg, argFieldTypeVals[i]);
}
}
}
/**
* Row mapper that handles a single long result.
*/
private static class OneLongWrapper implements GenericRowMapper<Long> {
public Long mapRow(Results rs) throws SQLException {
// maps the first column (sql
return rs.getLong(1);
}
}
}
|
package com.mitchellbosecke.pebble.loader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mitchellbosecke.pebble.error.LoaderException;
/**
* This loader searches for a file located anywhere on the filesystem. It uses
* java.io.File to perform the lookup.
*
* @author mbosecke
*
*/
public class FileLoader implements Loader {
private static final Logger logger = LoggerFactory.getLogger(FileLoader.class);
private String prefix;
private String suffix;
private String charset = "UTF-8";
@Override
public Reader getReader(String templateName) throws LoaderException {
InputStreamReader isr = null;
Reader reader = null;
InputStream is = null;
// add the prefix and ensure the prefix ends with a separator character
StringBuilder path = new StringBuilder("");
if (getPrefix() != null) {
path.append(getPrefix());
if (!getPrefix().endsWith(String.valueOf(File.separatorChar))) {
path.append(File.separatorChar);
}
}
String location = path.toString() + templateName + (getSuffix() == null ? "" : getSuffix());
logger.debug("Looking for template in {}.", location);
/*
* if template name contains path segments, move those segments into the
* path variable. The below technique needs to know the difference
* between the path and file name.
*/
String[] pathSegments = templateName.split("\\\\|/");
if (pathSegments.length > 1) {
// file name is the last segment
templateName = pathSegments[pathSegments.length - 1];
}
for (int i = 0; i < (pathSegments.length - 1); i++) {
path.append(pathSegments[i]).append(File.separatorChar);
}
// try to load File
if (is == null) {
File file = new File(path.toString(), templateName + (getSuffix() == null ? "" : getSuffix()));
if (file.exists() && file.isFile()) {
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
}
}
}
if (is == null) {
throw new LoaderException(null, "Could not find template \"" + location + "\"");
}
try {
isr = new InputStreamReader(is, charset);
reader = new BufferedReader(isr);
} catch (UnsupportedEncodingException e) {
}
return reader;
}
public String getSuffix() {
return suffix;
}
@Override
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getPrefix() {
return prefix;
}
@Override
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getCharset() {
return charset;
}
@Override
public void setCharset(String charset) {
this.charset = charset;
}
}
|
package org.geomajas.layer.tms;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.geomajas.configuration.RasterLayerInfo;
import org.geomajas.configuration.client.ScaleInfo;
import org.geomajas.geometry.Bbox;
import org.geomajas.layer.LayerType;
import org.geomajas.layer.tms.configuration.BoundingBoxInfo;
import org.geomajas.layer.tms.configuration.TileMapInfo;
import org.geomajas.layer.tms.configuration.TileSetInfo;
import org.springframework.stereotype.Component;
/**
* Configuration service for TMS layers. Based upon the base TMS URL, it can retrieve the TMS configuration and present
* it as a Java object. This service can also transform this TMS configuration object into a {@link RasterLayerInfo}
* object.
*
* @author Pieter De Graef
*/
@Component
public class TmsConfigurationService {
/**
* Get the configuration for a TMS layer by retrieving and parsing it's XML description file. The parsing is done
* using JaxB.
*
* @param layerCapabilitiesUrl
* The TMS base URL where to find the description.
* @return Returns the description as a Java configuration object.
* @throws TmsConfigurationException
* In case something went wrong trying to find or parse the XML description file.
*/
public TileMapInfo getCapabilities(String layerCapabilitiesUrl) throws TmsConfigurationException {
try {
// Create a JaxB unmarshaller:
JAXBContext context = JAXBContext.newInstance(TileMapInfo.class);
Unmarshaller um = context.createUnmarshaller();
// Find out where to retrieve the capabilities and unmarshall:
if (layerCapabilitiesUrl.startsWith("classpath:")) {
String location = layerCapabilitiesUrl.substring(10);
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (null == cl) {
cl = getClass().getClassLoader();
}
InputStream is = cl.getResourceAsStream(location);
return (TileMapInfo) um.unmarshal(is);
}
// Normal case, find the URL and unmarshal:
URL url = new URL(layerCapabilitiesUrl);
return (TileMapInfo) um.unmarshal(url);
} catch (JAXBException e) {
throw new TmsConfigurationException("Could not read the capabilities file.", e);
} catch (MalformedURLException e) {
throw new TmsConfigurationException("Could not find the capabilities file.", e);
}
}
/**
* Transform a TMS layer description object into a raster layer info object.
*
* @param tileMapInfo
* The TMS layer description object.
* @return The raster layer info object as used by Geomajas.
*/
public RasterLayerInfo asLayerInfo(TileMapInfo tileMapInfo) {
RasterLayerInfo layerInfo = new RasterLayerInfo();
layerInfo.setCrs(tileMapInfo.getSrs());
layerInfo.setDataSourceName(tileMapInfo.getTitle());
layerInfo.setLayerType(LayerType.RASTER);
layerInfo.setMaxExtent(asBbox(tileMapInfo.getBoundingBox()));
layerInfo.setTileHeight(tileMapInfo.getTileFormat().getHeight());
layerInfo.setTileWidth(tileMapInfo.getTileFormat().getWidth());
List<ScaleInfo> zoomLevels = new ArrayList<ScaleInfo>(tileMapInfo.getTileSets().getTileSets().size());
for (TileSetInfo tileSet : tileMapInfo.getTileSets().getTileSets()) {
zoomLevels.add(asScaleInfo(tileSet));
}
layerInfo.setZoomLevels(zoomLevels);
return layerInfo;
}
/**
* Transforms a TMS bounding box information object into a Geomajas {@link Bbox} object.
*
* @param boundingBoxInfo
* The TMS bounding box object.
* @return The default Geomajas bounding box.
*/
public Bbox asBbox(BoundingBoxInfo boundingBoxInfo) {
double width = boundingBoxInfo.getMaxX() - boundingBoxInfo.getMinX();
double height = boundingBoxInfo.getMaxY() - boundingBoxInfo.getMinY();
return new Bbox(boundingBoxInfo.getMinX(), boundingBoxInfo.getMinY(), width, height);
}
/**
* Transforms a TMS tile-set description object into a Geomajas {@link ScaleInfo} object.
*
* @param tileSetInfo
* The tile set description.
* @return The default Geomajas scale object.
*/
public ScaleInfo asScaleInfo(TileSetInfo tileSetInfo) {
ScaleInfo scaleInfo = new ScaleInfo();
scaleInfo.setPixelPerUnit(1 / tileSetInfo.getUnitsPerPixel());
return scaleInfo;
}
}
|
package com.mitrapps.mocaFileTransfer;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicArrowButton;
import com.redprairie.moca.MocaException;
import com.redprairie.moca.MocaResults;
import com.redprairie.moca.client.ConnectionUtils;
import com.redprairie.moca.client.DirectConnection;
import com.redprairie.moca.client.HttpConnection;
import com.redprairie.moca.client.LoginFailedException;
import com.redprairie.moca.client.MocaConnection;
public class FileTransferUI extends JFrame {
public static final String REMOTE_HOME_DIR = "$LESDIR";
private static final long serialVersionUID = 1L;
private static MocaConnection conn;
private File currentLocalDirectory;
private JPanel contentPane;
private JTextField localPath;
private JTextField remotePath;
private JTextField mocaUrl;
private JTextField mocaUid;
private JPasswordField mocaPwd;
private JTable localListing;
private JTable remoteListing;
private JButton uploadButton;
private JButton downloadButton;
private JButton loginButton;
private JTextArea logArea;
private String tempPathString; // used in FocusListener to see if the path has changed
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FileTransferUI frame = new FileTransferUI();
setLookAndFeel();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public FileTransferUI() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(100, 100, 900, 600);
setMinimumSize(new Dimension(600, 400));
contentPane = new JPanel();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
JLabel localPathLabel = new JLabel("Local: ");
JLabel remotePathLabel = new JLabel("Remote: ");
this.localPath = new JTextField();
this.remotePath = new JTextField();
this.localPath.setEditable(true);
this.remotePath.setEditable(true);
this.localPath.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
tempPathString = localPath.getText();
};
public void focusLost(FocusEvent e) {
if (!e.isTemporary() && !tempPathString.equalsIgnoreCase(localPath.getText())) {
setLocalPathManually();
}
}
});
Action localEnterAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
setLocalPathManually();
}
};
this.localPath.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
this.localPath.getActionMap().put("enter", localEnterAction);
this.remotePath.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
tempPathString = remotePath.getText();
};
public void focusLost(FocusEvent e) {
if (!e.isTemporary() && !tempPathString.equalsIgnoreCase(remotePath.getText())) {
setRemotePathManually();
}
}
});
Action remoteEnterAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
setRemotePathManually();
}
};
this.remotePath.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
this.remotePath.getActionMap().put("enter", remoteEnterAction);
this.mocaUrl = new JTextField();
this.mocaUid = new JTextField();
this.mocaPwd = new JPasswordField();
Action passwordEnterKeyAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
if (mocaUrl.getText().length() > 0 && mocaUid.getText().length() > 0 &&
new String(mocaPwd.getPassword()).length() > 0) {
login();
}
}
};
this.mocaPwd.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
this.mocaPwd.getActionMap().put("enter", passwordEnterKeyAction);
this.currentLocalDirectory = new File(".");
JLabel mocaUrlLabel = new JLabel("URL: ", SwingConstants.RIGHT);
JLabel mocaUidLabel = new JLabel("UID: ", SwingConstants.RIGHT);
JLabel mocaPwdLabel = new JLabel("PWD: ", SwingConstants.RIGHT);
this.loginButton = new JButton("Login");
this.loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
login();
}
});
this.localListing = new JTable(new LocalListingTableModel(this.currentLocalDirectory));
this.remoteListing = new JTable(new RemoteListingTableModel(null, REMOTE_HOME_DIR));
this.localListing.setAutoCreateRowSorter(true);
this.remoteListing.setAutoCreateRowSorter(true);
this.localListing.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable table = (JTable) me.getSource();
Point p = me.getPoint();
int row = table.rowAtPoint(p);
boolean canDelete = (localListing.getSelectedRowCount() > 0);
// TODO: boolean canRename = (localListing.getSelectedRowCount() == 0);
if (me.getClickCount() == 2) {
String fileType = (String)table.getValueAt(row, AbstractListingTableModel.FILE_TYPE_COLUMN_INDEX);
if (fileType.equalsIgnoreCase(AbstractListingTableModel.DIRECTORY_TYPE)) {
performLocalDirectoryChange(row);
}
} else if (me.isPopupTrigger() && me.getComponent() instanceof JTable ) {
JMenuItem itemDelete = new JMenuItem("Delete");
JMenuItem itemRename = new JMenuItem("Rename");
if (!canDelete) { itemDelete.setEnabled(false); }
// TODO: if (!canRename) { itemRename.setEnabled(false); }
itemRename.setEnabled(false);
itemDelete.addActionListener(new ActionListener() {
// TODO: Implement rename functionality
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Action from " + e.getSource().toString());
int[] rows = localListing.getSelectedRows();
StringBuilder prompt = new StringBuilder();
prompt.append("Delete the following files:\n");
for (int rowIndex : rows) {
String fileName = localListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX).toString();
prompt.append(" - " + fileName + "\n");
}
int selectedOption = promptConfirmDelete(prompt.toString());
if (selectedOption == JOptionPane.YES_OPTION) {
for (int rowIndex : rows) {
String fileType = localListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_TYPE_COLUMN_INDEX).toString();
String fileName = localListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX).toString();
if (AbstractListingTableModel.FILE_TYPE.equalsIgnoreCase(fileType)) {
final String sourceFile = String.format("%s/%s", localPath.getText(), fileName);
File file = new File(sourceFile);
if (file.delete()) {
String logMessage = String.format("Deleted %s\n", sourceFile);
logArea.append(logMessage);
} else {
String logMessage = String.format("Could not delete %s\n", sourceFile);
logArea.append(logMessage);
}
} else {
String logMessage = String.format("Could not delete %s - deleting a directory is not supported at this time.\n", fileName);
logArea.append(logMessage);
}
}
getLocalDirectoryListing(localPath.getText());
}
}
});
JPopupMenu popup = new JPopupMenu("Test"); //createYourPopUp();
popup.add(itemDelete);
popup.add(itemRename);
popup.show(me.getComponent(), me.getX(), me.getY());
//System.out.println("Pop up menu");
// also mouse released for non-ios
}
}
});
this.remoteListing.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable table = (JTable) me.getSource();
Point p = me.getPoint();
int row = table.rowAtPoint(p);
boolean canDelete = (remoteListing.getSelectedRowCount() > 0);
// TODO: boolean canRename = (remoteListing.getSelectedRowCount() == 0);
if (me.getClickCount() == 2) {
String fileType = (String)table.getValueAt(row, AbstractListingTableModel.FILE_TYPE_COLUMN_INDEX);
if (fileType.equalsIgnoreCase(AbstractListingTableModel.DIRECTORY_TYPE)) {
performRemoteDirectoryChange(row);
}
} else if (me.isPopupTrigger() && me.getComponent() instanceof JTable ) {
JMenuItem itemDelete = new JMenuItem("Delete");
JMenuItem itemRename = new JMenuItem("Rename");
if (!canDelete) { itemDelete.setEnabled(false); }
// TODO: if (!canRename) { itemRename.setEnabled(false); }
itemRename.setEnabled(false);
itemDelete.addActionListener(new ActionListener() {
// TODO: Implement rename functionality
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Action from " + e.getSource().toString());
int[] rows = remoteListing.getSelectedRows();
StringBuilder prompt = new StringBuilder();
prompt.append("Delete the following files:\n");
for (int rowIndex : rows) {
String fileName = remoteListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX).toString();
prompt.append(" - " + fileName + "\n");
}
int selectedOption = promptConfirmDelete(prompt.toString());
if (selectedOption == JOptionPane.YES_OPTION) {
for (int rowIndex : rows) {
String fileName = remoteListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX).toString();
String fileType = remoteListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_TYPE_COLUMN_INDEX).toString();
if (AbstractListingTableModel.FILE_TYPE.equalsIgnoreCase(fileType)) {
final String sourceFile = String.format("%s/%s", remotePath.getText(), fileName);
String cmd = String.format("[["
+ " File file = new File(\"%s\");"
+ " file.delete();"
+ "]]", sourceFile.replace("\\", "\\\\"));
try {
conn.executeCommand(cmd);
String logMessage = String.format("Deleted %s\n", sourceFile);
logArea.append(logMessage);
} catch (MocaException e1) {
String logMessage = String.format("Could not delete %s\n", sourceFile);
logArea.append(logMessage);
logArea.append("Ran:\n" + cmd + "\n");
logArea.append(e1.getLocalizedMessage());
logArea.append("\n");
}
} else {
String logMessage = String.format("Could not delete %s - deleting a directory is not supported at this time.\n", fileName);
logArea.append(logMessage);
}
}
getRemoteDirectoryListing(remotePath.getText());
}
}
});
JPopupMenu popup = new JPopupMenu("Test"); //createYourPopUp();
popup.add(itemDelete);
popup.add(itemRename);
popup.show(me.getComponent(), me.getX(), me.getY());
//System.out.println("Pop up menu");
// also mouse released for non-ios
}
}
});
JScrollPane localScrollPane = new JScrollPane(this.localListing);
JScrollPane remoteScrollPane = new JScrollPane(this.remoteListing);
this.uploadButton = new BasicArrowButton(BasicArrowButton.EAST);
this.uploadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
performUpload();
}
});
this.downloadButton = new BasicArrowButton(BasicArrowButton.WEST);
this.downloadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
performDownload();
}
});
this.logArea = new JTextArea(80, 80);
JScrollPane logScrollPane = new JScrollPane(this.logArea);
contentPane.add(mocaUrlLabel);
contentPane.add(this.mocaUrl);
contentPane.add(mocaUidLabel);
contentPane.add(this.mocaUid);
contentPane.add(mocaPwdLabel);
contentPane.add(this.mocaPwd);
contentPane.add(this.loginButton);
contentPane.add(localPathLabel);
contentPane.add(this.localPath);
contentPane.add(remotePathLabel);
contentPane.add(this.remotePath);
contentPane.add(localScrollPane);
contentPane.add(remoteScrollPane);
contentPane.add(this.uploadButton);
contentPane.add(this.downloadButton);
contentPane.add(logScrollPane);
// pin all the connection info 5 from the top
layout.putConstraint(SpringLayout.NORTH, mocaUrlLabel, 5, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, this.mocaUrl, 5, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, mocaUidLabel, 5, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, this.mocaUid, 5, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, mocaPwdLabel, 5, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, this.mocaPwd, 5, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.NORTH, this.loginButton, 5, SpringLayout.NORTH, contentPane);
// pin the right/left of the connection info and set the label widths
SpringLayout.Constraints contraints = layout.getConstraints(mocaUrlLabel);
contraints.setWidth(Spring.constant(40));
layout.putConstraint(SpringLayout.WEST, mocaUrlLabel, 5, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.WEST, this.mocaUrl, 5, SpringLayout.EAST, mocaUrlLabel);
// last element
layout.putConstraint(SpringLayout.EAST, this.loginButton, -5, SpringLayout.EAST, contentPane);
layout.putConstraint(SpringLayout.WIDTH, mocaUidLabel, 0, SpringLayout.WIDTH, mocaUrlLabel);
layout.putConstraint(SpringLayout.EAST, this.mocaUrl, -5, SpringLayout.WEST, mocaUidLabel);
contraints = layout.getConstraints(this.mocaUid);
contraints.setWidth(Spring.constant(100));
layout.putConstraint(SpringLayout.EAST, mocaUidLabel, -5, SpringLayout.WEST, this.mocaUid);
layout.putConstraint(SpringLayout.WIDTH, mocaPwdLabel, 0, SpringLayout.WIDTH, mocaUrlLabel);
layout.putConstraint(SpringLayout.EAST, this.mocaUid, -5, SpringLayout.WEST, mocaPwdLabel);
layout.putConstraint(SpringLayout.WIDTH, this.mocaPwd, 0, SpringLayout.WIDTH, this.mocaUid);
layout.putConstraint(SpringLayout.EAST, mocaPwdLabel, -5, SpringLayout.WEST, this.mocaPwd);
contraints = layout.getConstraints(this.loginButton);
contraints.setWidth(Spring.constant(80));
layout.putConstraint(SpringLayout.EAST, this.mocaPwd, -5, SpringLayout.WEST, this.loginButton);
// File/Directory related field layouts
layout.putConstraint(SpringLayout.WEST, localPathLabel, 5, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, localPathLabel, 50, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, this.localPath, 5, SpringLayout.EAST, localPathLabel);
layout.putConstraint(SpringLayout.NORTH, this.localPath, 50, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, remotePathLabel, 5, SpringLayout.EAST, this.localPath);
layout.putConstraint(SpringLayout.NORTH, remotePathLabel, 50, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, this.remotePath, 5, SpringLayout.EAST, remotePathLabel);
layout.putConstraint(SpringLayout.NORTH, this.remotePath, 50, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.EAST, contentPane, 5, SpringLayout.EAST, remotePath);
layout.putConstraint(SpringLayout.WIDTH, this.localPath, 0, SpringLayout.WIDTH, this.remotePath);
layout.putConstraint(SpringLayout.WEST, localScrollPane, 0, SpringLayout.WEST, this.localPath);
layout.putConstraint(SpringLayout.EAST, localScrollPane, 0, SpringLayout.EAST, this.localPath);
layout.putConstraint(SpringLayout.NORTH, localScrollPane, 50, SpringLayout.NORTH, this.localPath);
layout.putConstraint(SpringLayout.WEST, remoteScrollPane, 0, SpringLayout.WEST, this.remotePath);
layout.putConstraint(SpringLayout.EAST, remoteScrollPane, 0, SpringLayout.EAST, this.remotePath);
layout.putConstraint(SpringLayout.NORTH, remoteScrollPane, 50, SpringLayout.NORTH, this.localPath);
layout.putConstraint(SpringLayout.HORIZONTAL_CENTER, this.uploadButton, 25, SpringLayout.EAST, localScrollPane);
layout.putConstraint(SpringLayout.HORIZONTAL_CENTER, this.downloadButton, 25, SpringLayout.EAST, localScrollPane);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, this.uploadButton, -50, SpringLayout.VERTICAL_CENTER, localScrollPane);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, this.downloadButton, -20, SpringLayout.VERTICAL_CENTER, localScrollPane);
// add log scroll pane
layout.putConstraint(SpringLayout.SOUTH, logScrollPane, -20, SpringLayout.SOUTH, contentPane);
layout.putConstraint(SpringLayout.WEST, logScrollPane, 5, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.EAST, logScrollPane, -5, SpringLayout.EAST, contentPane);
contraints = layout.getConstraints(logScrollPane);
contraints.setHeight(Spring.constant(120));
layout.putConstraint(SpringLayout.SOUTH, remoteScrollPane, -20, SpringLayout.NORTH, logScrollPane);
layout.putConstraint(SpringLayout.SOUTH, localScrollPane, -20, SpringLayout.NORTH, logScrollPane);
setContentPane(contentPane);
Action refreshAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
refresh();
}
};
this.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F5"), "refresh");
this.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_R, Event.META_MASK), "refresh");
this.contentPane.getActionMap().put("refresh", refreshAction);
this.setTitle("moca File Transfer");
this.fetchUserDefaults();
this.setLocalPath(this.currentLocalDirectory.getAbsolutePath());
resetColumnSizes();
}
private void resetColumnSizes() {
this.resetLocalColumnSizes();
this.resetRemoteColumnSizes();
}
private void resetLocalColumnSizes() {
this.localListing.getColumnModel().getColumn(0).setMaxWidth(60);
this.localListing.getColumnModel().getColumn(2).setPreferredWidth(40);
}
private void resetRemoteColumnSizes() {
this.remoteListing.getColumnModel().getColumn(0).setMaxWidth(60);
this.remoteListing.getColumnModel().getColumn(2).setPreferredWidth(40);
}
public static void setLookAndFeel() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
private void refresh() {
getLocalDirectoryListing(localPath.getText());
if (this.remotePath.getText().length() > 0) {
this.getRemoteDirectoryListing(this.remotePath.getText());
}
}
private void login() {
try {
conn = makeConnections();
String remotePathString = REMOTE_HOME_DIR;
MocaResults rs = conn.executeCommand(String.format("find file where filnam = '%s'", REMOTE_HOME_DIR));
while (rs.next()) {
remotePathString = rs.getString("pathname");
this.remotePath.setText(remotePathString);
}
RemoteListingTableModel model = new RemoteListingTableModel(conn, REMOTE_HOME_DIR);
this.remoteListing.setModel(model);
this.resetRemoteColumnSizes();
} catch (MocaException e) {
displayException(e);
}
}
private void displayException(Exception e) {
StackTraceElement[] st = e.getStackTrace();
for (StackTraceElement element : st) {
this.logArea.append(element.toString());
this.logArea.append("\n");
}
}
private MocaConnection makeConnections() throws MocaException, LoginFailedException {
MocaConnection newConn = null;
if (this.mocaUrl.getText().startsWith("http")) {
this.logArea.append("Connecting to " + this.mocaUrl.getText() + "\n");
newConn = new HttpConnection(this.mocaUrl.getText());
} else {
String[] tokens = this.mocaUrl.getText().split(":");
String host = tokens[0];
int port = Integer.parseInt(tokens[1]);
this.logArea.append("Connecting to " + host + ":" + port + "\n");
newConn = new DirectConnection(host, port);
}
ConnectionUtils.login(newConn, this.mocaUid.getText(), new String(this.mocaPwd.getPassword()));
this.storeUserDefaults();
return newConn;
}
private void fetchUserDefaults() {
Preferences prefs = Preferences.userRoot().node(this.getClass().getName()); //Preferences.userNodeForPackage(this);
String host = prefs.get("host", "http://localhost:4500/service");
String user = prefs.get("user", "super");
this.mocaUrl.setText(host);
this.mocaUid.setText(user);
}
private void storeUserDefaults() {
Preferences prefs = Preferences.userRoot().node(this.getClass().getName()); //Preferences.userNodeForPackage(this);
prefs.put("host", this.mocaUrl.getText());
prefs.put("user", this.mocaUid.getText());
}
private int promptConfirmDelete(String message) {
return JOptionPane.showConfirmDialog(this, message, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
}
private void setLocalPath(String path) {
File f = new File(path);
String s;
try {
s = f.getCanonicalPath();
this.localPath.setText(s);
this.currentLocalDirectory = new File(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setLocalPathManually() {
File path = new File(this.localPath.getText());
if (!path.exists()) {
JOptionPane.showMessageDialog(this,
"Path is invalid.",
"Error",
JOptionPane.ERROR_MESSAGE);
SwingUtilities.invokeLater(new FocusGrabber(this.localPath));
} else {
getLocalDirectoryListing(this.localPath.getText());
}
}
private void setRemotePathManually() {
try {
MocaResults rs = conn.executeCommand(String.format("find file where filnam = '%s'", this.remotePath.getText()));
if (!rs.hasNext()) {
throw new MocaException(510);
}
this.getRemoteDirectoryListing(this.remotePath.getText());
} catch (MocaException e) {
JOptionPane.showMessageDialog(this,
"Path is invalid.",
"Error",
JOptionPane.ERROR_MESSAGE);
SwingUtilities.invokeLater(new FocusGrabber(this.remotePath));
}
}
private void performLocalDirectoryChange(int row) {
String subdirectory = (String)this.localListing.getValueAt(row, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX);
String newdirectory = String.format("%s/%s", this.localPath.getText(), subdirectory);
this.getLocalDirectoryListing(newdirectory);
}
private void getLocalDirectoryListing(String path) {
this.currentLocalDirectory = new File(path);
this.setLocalPath(path);
LocalListingTableModel model = new LocalListingTableModel(currentLocalDirectory);
this.localListing.setModel(model);
this.resetLocalColumnSizes();
}
private void performRemoteDirectoryChange(int row) {
String subdirectory = (String)this.remoteListing.getValueAt(row, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX);
String newdirectory = String.format("%s/%s", this.remotePath.getText(), subdirectory);
this.getRemoteDirectoryListing(newdirectory);
}
private void getRemoteDirectoryListing(String path) {
RemoteListingTableModel model = new RemoteListingTableModel(conn, path);
this.remoteListing.setModel(model);
this.remotePath.setText(model.getCurrentPath());
this.resetRemoteColumnSizes();
}
private void performUpload() {
if (this.localListing.getSelectedRowCount() > 0) {
final String destinationPath = this.remotePath.getText();
String sourcePath = this.localPath.getText();
int[] rows = this.localListing.getSelectedRows();
for (int rowIndex : rows) {
String fileName = this.localListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX).toString();
final String sourceFile = String.format("%s/%s", sourcePath, fileName);
final String destinationFile = String.format("%s/%s", destinationPath, fileName);
//this.logArea.append(String.format("Uploading %s to %s ..... \n", sourceFile, destinationFile));
String logMessage = String.format("Uploading %s to %s ..... \n", sourceFile, destinationFile);
this.logArea.append(logMessage);
//this.logArea.repaint();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
FileUploader.transferFile(conn, sourceFile, destinationFile);
return null;
}
@Override
public void done() {
logArea.append("Done!\n");
// TODO: Refactor this and the download equivalent to their own methods
RemoteListingTableModel model = new RemoteListingTableModel(conn, destinationPath);
remoteListing.setModel(model);
remotePath.setText(model.getCurrentPath());
resetRemoteColumnSizes();
}
};
worker.execute();
}
} else {
this.logArea.append("Nothing to upload\n");
}
}
private void performDownload() {
if (this.remoteListing.getSelectedRowCount() > 0) {
final String destinationPath = this.localPath.getText();
final String sourcePath = this.remotePath.getText();
int[] rows = this.remoteListing.getSelectedRows();
for (int rowIndex : rows) {
final String fileName = this.remoteListing.getValueAt(rowIndex, AbstractListingTableModel.FILE_NAME_COLUMN_INDEX).toString();
final String sourceFile = String.format("%s/%s", sourcePath, fileName);
final String destinationFile = String.format("%s/%s", destinationPath, fileName);
this.logArea.append(String.format("Downloading %s to %s ..... \n", sourceFile, destinationFile));
//this.logArea.repaint();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
// multi-threading, we'll need multiple connections
try {
MocaConnection connForDownload = makeConnections();
FileDownloader.transferFile(sourceFile, destinationFile, connForDownload);
} catch (LoginFailedException e) {
displayException(e);
} catch (MocaException e) {
displayException(e);
}
return null;
}
@Override
public void done() {
logArea.append("Done downloading " + fileName + "!\n");
// TODO: Refactor this and the download equivalent to their own methods
currentLocalDirectory = new File(destinationPath);
LocalListingTableModel model = new LocalListingTableModel(currentLocalDirectory);
localListing.setModel(model);
resetLocalColumnSizes();
}
};
worker.execute();
}
} else {
this.logArea.append("Nothing to download\n");
}
}
class FocusGrabber implements Runnable {
private JComponent component;
public FocusGrabber(JComponent component) {
this.component = component;
}
public void run() {
component.grabFocus();
}
}
}
|
package com.mixpanel.android.viewcrawler;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.ArrayMap;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mixpanel.android.mpmetrics.MPConfig;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
@TargetApi(MPConfig.UI_FEATURES_MIN_API)
/* package */ abstract class ViewVisitor implements Pathfinder.Accumulator {
/**
* OnEvent will be fired when whatever the ViewVisitor installed fires
* (For example, if the ViewVisitor installs watches for clicks, then OnEvent will be called
* on click)
*/
public interface OnEventListener {
public void OnEvent(View host, String eventName, boolean debounce);
}
public interface OnLayoutErrorListener {
public void onLayoutError(ViewVisitor.CantVisitException e);
}
public static class CantVisitException extends Exception {
public CantVisitException(String message, String exceptionType, String name) {
super(message);
mExceptionType = exceptionType;
mName = name;
}
public String getExceptionType() {
return mExceptionType;
}
public String getName() {
return mName;
}
private final String mExceptionType;
private final String mName;
}
/**
* Attempts to apply mutator to every matching view. Use this to update properties
* in the view hierarchy. If accessor is non-null, it will be used to attempt to
* prevent calls to the mutator if the property already has the intended value.
*/
public static class PropertySetVisitor extends ViewVisitor {
public PropertySetVisitor(List<Pathfinder.PathElement> path, Caller mutator, Caller accessor) {
super(path);
mMutator = mutator;
mAccessor = accessor;
mOriginalValueHolder = new Object[1];
mOriginalValues = new WeakHashMap<View, Object>();
}
@Override
public void cleanup() {
for (Map.Entry<View, Object> original:mOriginalValues.entrySet()) {
final View changedView = original.getKey();
final Object originalValue = original.getValue();
if (null != originalValue) {
mOriginalValueHolder[0] = originalValue;
mMutator.applyMethodWithArguments(changedView, mOriginalValueHolder);
}
}
}
@Override
public void accumulate(View found) {
if (null != mAccessor) {
final Object[] setArgs = mMutator.getArgs();
if (1 == setArgs.length) {
final Object desiredValue = setArgs[0];
final Object currentValue = mAccessor.applyMethod(found);
if (desiredValue == currentValue) {
return;
}
if (null != desiredValue) {
if (desiredValue instanceof Bitmap && currentValue instanceof Bitmap) {
final Bitmap desiredBitmap = (Bitmap) desiredValue;
final Bitmap currentBitmap = (Bitmap) currentValue;
if (desiredBitmap.sameAs(currentBitmap)) {
return;
}
} else if (desiredValue instanceof BitmapDrawable && currentValue instanceof BitmapDrawable) {
final Bitmap desiredBitmap = ((BitmapDrawable) desiredValue).getBitmap();
final Bitmap currentBitmap = ((BitmapDrawable) currentValue).getBitmap();
if (desiredBitmap != null && desiredBitmap.sameAs(currentBitmap)) {
return;
}
} else if (desiredValue.equals(currentValue)) {
return;
}
}
if (currentValue instanceof Bitmap ||
currentValue instanceof BitmapDrawable ||
mOriginalValues.containsKey(found)) {
; // Cache exactly one non-image original value
} else {
mOriginalValueHolder[0] = currentValue;
if (mMutator.argsAreApplicable(mOriginalValueHolder)) {
mOriginalValues.put(found, currentValue);
} else {
mOriginalValues.put(found, null);
}
}
}
}
mMutator.applyMethod(found);
}
protected String name() {
return "Property Mutator";
}
private final Caller mMutator;
private final Caller mAccessor;
private final WeakHashMap<View, Object> mOriginalValues;
private final Object[] mOriginalValueHolder;
}
public static class LayoutUpdateVisitor extends ViewVisitor {
private class CycleDetector {
/**
* This function detects circular dependencies for all the views under the parent
* of the updated view. The basic idea is to consider the views as a directed
* graph and perform a DFS on all the nodes in the graph. If the current node is
* in the DFS stack already, there must be a circle in the graph. To speed up the
* search, all the parsed nodes will be removed from the graph.
*/
public boolean hasCycle(ArrayMap<View, ArrayList<View>> dependencyGraph) {
ArrayList<View> dfsStack = new ArrayList<View>();
while (!dependencyGraph.isEmpty()) {
View currentNode = dependencyGraph.keyAt(0);
if (!detectSubgraphCycle(dependencyGraph, currentNode, dfsStack)) {
return false;
}
}
return true;
}
private boolean detectSubgraphCycle(ArrayMap<View, ArrayList<View>> dependencyGraph,
View currentNode, ArrayList<View> dfsStack) {
if (dfsStack.contains(currentNode)) {
return false;
}
if (dependencyGraph.containsKey(currentNode)) {
ArrayList<View> dependencies = dependencyGraph.remove(currentNode);
dfsStack.add(currentNode);
int size = dependencies.size();
for (int i = 0; i < size; i++) {
if (!detectSubgraphCycle(dependencyGraph, dependencies.get(i), dfsStack)) {
return false;
}
}
dfsStack.remove(currentNode);
}
return true;
}
}
public LayoutUpdateVisitor(List<Pathfinder.PathElement> path, ArrayList<LayoutRule> args,
String name, OnLayoutErrorListener onEditErrorListener) {
super(path);
mOriginalValues = new WeakHashMap<View, int[]>();
mArgs = args;
mName = name;
mAlive = true;
mOnEditErrorListener = onEditErrorListener;
mCycleDetector = new CycleDetector();
}
@Override
public void cleanup() {
// TODO find a way to optimize this.. remove this visitor and trigger a re-layout??
for (Map.Entry<View, int[]> original:mOriginalValues.entrySet()) {
final View changedView = original.getKey();
final int[] originalValue = original.getValue();
final RelativeLayout.LayoutParams originalParams = (RelativeLayout.LayoutParams) changedView.getLayoutParams();
for (int i = 0; i < originalValue.length; i++) {
originalParams.addRule(i, originalValue[i]);
}
changedView.setLayoutParams(originalParams);
}
mAlive = false;
}
@Override
public void visit(View rootView) {
// this check is necessary - if the layout change is invalid, accumulate will send an error message
// to the Web UI; before Web UI removes such change, this visit may get called by Android again and
// thus send another error message to Web UI which leads to lots of weird problems
if (mAlive) {
getPathfinder().findTargetsInRoot(rootView, getPath(), this);
}
}
// layout changes are performed on the children of found according to the LayoutRule
@Override
public void accumulate(View found) {
try {
setLayout(found);
} catch (CantVisitException e) {
cleanup();
mOnEditErrorListener.onLayoutError(e);
}
}
private void setLayout(View target) throws CantVisitException {
ViewGroup parent = (ViewGroup) target;
SparseArray<View> idToChild = new SparseArray<View>();
int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
View child = parent.getChildAt(i);
int childId = child.getId();
if (childId > 0) {
idToChild.put(childId, child);
}
}
int size = mArgs.size();
for (int i = 0; i < size; i++) {
LayoutRule layoutRule = mArgs.get(i);
final int viewId = layoutRule.viewId;
final int newVerb = layoutRule.verb;
final int newAnchorId = layoutRule.anchor;
final View currentNode = idToChild.get(viewId);
// typecast ViewGroup.LayoutParams is needed for API 18 and lower
final RelativeLayout.LayoutParams currentParams = (RelativeLayout.LayoutParams) currentNode.getLayoutParams();
final int[] currentRules = currentParams.getRules().clone();
if (currentRules[newVerb] == newAnchorId) {
continue;
}
if (mOriginalValues.containsKey(currentNode)) {
; // Cache exactly one
} else {
mOriginalValues.put(currentNode, currentRules);
}
RelativeLayout.LayoutParams newParams = (RelativeLayout.LayoutParams)currentNode.getLayoutParams();
newParams.addRule(newVerb, newAnchorId);
// only need to verify the last layout change as others have been verified in the previous visit
if (i == size - 1) {
final Set<Integer> rules;
if (mHorizontalRules.contains(newVerb)) {
rules = mHorizontalRules;
} else if (mVerticalRules.contains(newVerb)) {
rules = mVerticalRules;
} else {
rules = null;
}
if (rules != null && !verifyLayout(rules, idToChild)) {
throw new CantVisitException("Circular dependency detected!", "circular_dependency", mName);
}
}
currentNode.setLayoutParams(newParams);
}
}
private boolean verifyLayout(Set<Integer> rules, SparseArray<View> idToChild) {
ArrayMap<View, ArrayList<View>> dependencyGraph = new ArrayMap<View, ArrayList<View>>();
int size = idToChild.size();
for (int i = 0; i < size; i++) {
final View child = idToChild.valueAt(i);
final RelativeLayout.LayoutParams childLayoutParams = (RelativeLayout.LayoutParams) child.getLayoutParams();
int[] layoutRules = childLayoutParams.getRules();
ArrayList<View> dependencies = new ArrayList<View>();
for (int rule : rules) {
int dependencyId = layoutRules[rule];
if (dependencyId > 0 && dependencyId != child.getId()) {
dependencies.add(idToChild.get(dependencyId));
}
}
dependencyGraph.put(child, dependencies);
}
return mCycleDetector.hasCycle(dependencyGraph);
}
protected String name() { return "Layout Update"; }
private final WeakHashMap<View, int[]> mOriginalValues;
private final ArrayList<LayoutRule> mArgs;
private final String mName;
private static final Set<Integer> mHorizontalRules = new HashSet<Integer>(Arrays.asList(
RelativeLayout.LEFT_OF, RelativeLayout.RIGHT_OF,
RelativeLayout.ALIGN_LEFT, RelativeLayout.ALIGN_RIGHT
));
private static final Set<Integer> mVerticalRules = new HashSet<Integer>(Arrays.asList(
RelativeLayout.ABOVE, RelativeLayout.BELOW,
RelativeLayout.ALIGN_BASELINE, RelativeLayout.ALIGN_TOP,
RelativeLayout.ALIGN_BOTTOM
));
private boolean mAlive;
private final OnLayoutErrorListener mOnEditErrorListener;
private final CycleDetector mCycleDetector;
}
public static class LayoutRule {
public LayoutRule(int vi, int v, int a) {
viewId = vi;
verb = v;
anchor = a;
}
public final int viewId;
public final int verb;
public final int anchor;
}
/**
* Adds an accessibility event, which will fire OnEvent, to every matching view.
*/
public static class AddAccessibilityEventVisitor extends EventTriggeringVisitor {
public AddAccessibilityEventVisitor(List<Pathfinder.PathElement> path, int accessibilityEventType, String eventName, OnEventListener listener) {
super(path, eventName, listener, false);
mEventType = accessibilityEventType;
mWatching = new WeakHashMap<View, TrackingAccessibilityDelegate>();
}
@Override
public void cleanup() {
for (final Map.Entry<View, TrackingAccessibilityDelegate> entry:mWatching.entrySet()) {
final View v = entry.getKey();
final TrackingAccessibilityDelegate toCleanup = entry.getValue();
final View.AccessibilityDelegate currentViewDelegate = getOldDelegate(v);
if (currentViewDelegate == toCleanup) {
v.setAccessibilityDelegate(toCleanup.getRealDelegate());
} else if (currentViewDelegate instanceof TrackingAccessibilityDelegate) {
final TrackingAccessibilityDelegate newChain = (TrackingAccessibilityDelegate) currentViewDelegate;
newChain.removeFromDelegateChain(toCleanup);
} else {
// Assume we've been replaced, zeroed out, or for some other reason we're already gone.
// (This isn't too weird, for example, it's expected when views get recycled)
}
}
mWatching.clear();
}
@Override
public void accumulate(View found) {
final View.AccessibilityDelegate realDelegate = getOldDelegate(found);
if (realDelegate instanceof TrackingAccessibilityDelegate) {
final TrackingAccessibilityDelegate currentTracker = (TrackingAccessibilityDelegate) realDelegate;
if (currentTracker.willFireEvent(getEventName())) {
return; // Don't double track
}
}
// We aren't already in the tracking call chain of the view
final TrackingAccessibilityDelegate newDelegate = new TrackingAccessibilityDelegate(realDelegate);
found.setAccessibilityDelegate(newDelegate);
mWatching.put(found, newDelegate);
}
@Override
protected String name() {
return getEventName() + " event when (" + mEventType + ")";
}
private View.AccessibilityDelegate getOldDelegate(View v) {
View.AccessibilityDelegate ret = null;
try {
Class<?> klass = v.getClass();
Method m = klass.getMethod("getAccessibilityDelegate");
ret = (View.AccessibilityDelegate) m.invoke(v);
} catch (NoSuchMethodException e) {
// In this case, we just overwrite the original.
} catch (IllegalAccessException e) {
// In this case, we just overwrite the original.
} catch (InvocationTargetException e) {
Log.w(LOGTAG, "getAccessibilityDelegate threw an exception when called.", e);
}
return ret;
}
private class TrackingAccessibilityDelegate extends View.AccessibilityDelegate {
public TrackingAccessibilityDelegate(View.AccessibilityDelegate realDelegate) {
mRealDelegate = realDelegate;
}
public View.AccessibilityDelegate getRealDelegate() {
return mRealDelegate;
}
public boolean willFireEvent(final String eventName) {
if (getEventName() == eventName) {
return true;
} else if (mRealDelegate instanceof TrackingAccessibilityDelegate) {
return ((TrackingAccessibilityDelegate) mRealDelegate).willFireEvent(eventName);
} else {
return false;
}
}
public void removeFromDelegateChain(final TrackingAccessibilityDelegate other) {
if (mRealDelegate == other) {
mRealDelegate = other.getRealDelegate();
} else if (mRealDelegate instanceof TrackingAccessibilityDelegate) {
final TrackingAccessibilityDelegate child = (TrackingAccessibilityDelegate) mRealDelegate;
child.removeFromDelegateChain(other);
} else {
// We can't see any further down the chain, just return.
}
}
@Override
public void sendAccessibilityEvent(View host, int eventType) {
if (eventType == mEventType) {
fireEvent(host);
}
if (null != mRealDelegate) {
mRealDelegate.sendAccessibilityEvent(host, eventType);
}
}
private View.AccessibilityDelegate mRealDelegate;
}
private final int mEventType;
private final WeakHashMap<View, TrackingAccessibilityDelegate> mWatching;
}
/**
* Installs a TextWatcher in each matching view. Does nothing if matching views are not TextViews.
*/
public static class AddTextChangeListener extends EventTriggeringVisitor {
public AddTextChangeListener(List<Pathfinder.PathElement> path, String eventName, OnEventListener listener) {
super(path, eventName, listener, true);
mWatching = new HashMap<TextView, TextWatcher>();
}
@Override
public void cleanup() {
for (final Map.Entry<TextView, TextWatcher> entry:mWatching.entrySet()) {
final TextView v = entry.getKey();
final TextWatcher watcher = entry.getValue();
v.removeTextChangedListener(watcher);
}
mWatching.clear();
}
@Override
public void accumulate(View found) {
if (found instanceof TextView) {
final TextView foundTextView = (TextView) found;
final TextWatcher watcher = new TrackingTextWatcher(foundTextView);
final TextWatcher oldWatcher = mWatching.get(foundTextView);
if (null != oldWatcher) {
foundTextView.removeTextChangedListener(oldWatcher);
}
foundTextView.addTextChangedListener(watcher);
mWatching.put(foundTextView, watcher);
}
}
@Override
protected String name() {
return getEventName() + " on Text Change";
}
private class TrackingTextWatcher implements TextWatcher {
public TrackingTextWatcher(View boundTo) {
mBoundTo = boundTo;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
; // Nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
; // Nothing
}
@Override
public void afterTextChanged(Editable s) {
fireEvent(mBoundTo);
}
private final View mBoundTo;
}
private final Map<TextView, TextWatcher> mWatching;
}
/**
* Monitors the view tree for the appearance of matching views where there were not
* matching views before. Fires only once per traversal.
*/
public static class ViewDetectorVisitor extends EventTriggeringVisitor {
public ViewDetectorVisitor(List<Pathfinder.PathElement> path, String eventName, OnEventListener listener) {
super(path, eventName, listener, false);
mSeen = false;
}
@Override
public void cleanup() {
; // Do nothing, we don't have anything to leak :)
}
@Override
public void accumulate(View found) {
if (found != null && !mSeen) {
fireEvent(found);
}
mSeen = (found != null);
}
@Override
protected String name() {
return getEventName() + " when Detected";
}
private boolean mSeen;
}
private static abstract class EventTriggeringVisitor extends ViewVisitor {
public EventTriggeringVisitor(List<Pathfinder.PathElement> path, String eventName, OnEventListener listener, boolean debounce) {
super(path);
mListener = listener;
mEventName = eventName;
mDebounce = debounce;
}
protected void fireEvent(View found) {
mListener.OnEvent(found, mEventName, mDebounce);
}
protected String getEventName() {
return mEventName;
}
private final OnEventListener mListener;
private final String mEventName;
private final boolean mDebounce;
}
/**
* Scans the View hierarchy below rootView, applying it's operation to each matching child view.
*/
public void visit(View rootView) {
mPathfinder.findTargetsInRoot(rootView, mPath, this);
}
/**
* Removes listeners and frees resources associated with the visitor. Once cleanup is called,
* the ViewVisitor should not be used again.
*/
public abstract void cleanup();
protected ViewVisitor(List<Pathfinder.PathElement> path) {
mPath = path;
mPathfinder = new Pathfinder();
}
protected List<Pathfinder.PathElement> getPath() {
return mPath;
}
protected Pathfinder getPathfinder() {
return mPathfinder;
}
protected abstract String name();
private final List<Pathfinder.PathElement> mPath;
private final Pathfinder mPathfinder;
private static final String LOGTAG = "MixpanelAPI.ViewVisitor";
}
|
package org.jetbrains.plugins.gradle.sync.conflict;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.LibraryOrderEntry;
import com.intellij.openapi.roots.ModuleOrderEntry;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.Ref;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.diff.GradleProjectStructureChange;
import org.jetbrains.plugins.gradle.model.intellij.IntellijEntityVisitor;
import org.jetbrains.plugins.gradle.model.intellij.ModuleAwareContentRoot;
import org.jetbrains.plugins.gradle.util.GradleUtil;
import javax.swing.*;
import java.util.Collection;
/**
* We want to be able to show changes for the conflicting gradle and intellij project structure entities.
* <p/>
* For example, there is a possible case that particular library has a different classpath configuration at the gradle and the intellij.
* We want to be able to show them to the user.
* <p/>
* This class allows to retrieve UI controls for such a conflicting changes.
* <p/>
* Thread-safe.
*
* @author Denis Zhdanov
* @since 3/2/12 3:03 PM
*/
public class GradleConflictControlFactory {
@NotNull private final GradleLibraryDependencyConflictControlFactory myLibraryDependencyFactory;
@NotNull private final GradleCommonDependencyConflictControlFactory myCommonDependencyFactory;
public GradleConflictControlFactory(@NotNull GradleLibraryDependencyConflictControlFactory libraryFactory,
@NotNull GradleCommonDependencyConflictControlFactory commonDependencyFactory) {
myLibraryDependencyFactory = libraryFactory;
myCommonDependencyFactory = commonDependencyFactory;
}
/**
* Tries to build UI control for showing the differences between the gradle and intellij setup of the given project structure entity.
*
* @param entity target entity
* @param changes known changes for the given entity
* @return UI control for showing the differences between the gradle and intellij setup of the given project structure entity;
* <code>null</code> if there are no differences or if we don't know how to show them
*/
@Nullable
public JComponent getDiffControl(@NotNull Object entity, final @NotNull Collection<GradleProjectStructureChange> changes) {
final Ref<JComponent> result = new Ref<JComponent>();
GradleUtil.dispatch(entity, new IntellijEntityVisitor() {
@Override
public void visit(@NotNull Project project) {
}
@Override
public void visit(@NotNull Module module) {
}
@Override
public void visit(@NotNull ModuleAwareContentRoot contentRoot) {
}
@Override
public void visit(@NotNull LibraryOrderEntry libraryDependency) {
result.set(myLibraryDependencyFactory.getControl(libraryDependency, changes));
}
@Override
public void visit(@NotNull ModuleOrderEntry moduleDependency) {
result.set(myCommonDependencyFactory.getControl(moduleDependency, changes));
}
@Override
public void visit(@NotNull Library library) {
}
});
return result.get();
}
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.tools;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.File;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.samskivert.util.StringUtil;
import com.threerings.util.ActionScript;
import com.threerings.presents.client.Client;
import com.threerings.presents.client.InvocationService;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.data.InvocationMarshaller;
import com.threerings.presents.dobj.InvocationResponseEvent;
import com.threerings.presents.server.InvocationDispatcher;
import com.threerings.presents.server.InvocationException;
import com.threerings.presents.server.InvocationProvider;
/**
* An Ant task for generating invocation service marshalling and
* unmarshalling classes.
* TODO: when generating the imports for exported action script files, there are just enough
* conversions of primitive types (e.g. float -> Number), array types (e.g. int[] -> TypedArray)
* and three rings utility types (e.g. float -> Float) to make the existing serivces work. It
* should be possible to create a complete list of these conversions so that future services
* can be generated without problems.
*/
public class GenServiceTask extends InvocationTask
{
/** Used to keep track of custom InvocationListener derivations. */
public class ServiceListener implements Comparable<ServiceListener>
{
public Class<?> listener;
public List<ServiceMethod> methods = Lists.newArrayList();
/** Contains all imports required for the parameters of the methods in this listener. */
public ImportSet imports = new ImportSet();
public ServiceListener (Class<?> service, Class<?> listener)
{
this.listener = listener;
// compute the union of all InvocationListener extensions implemented by this interface
Set<Class<?>> ifaces = Sets.newHashSet();
addInterfaces(listener, ifaces);
// add method marshallers for all methods in all interfaces (the marshaller will not
// extend the marshallers for its parent interfaces and will use its own codes)
for (Class<?> iface : ifaces) {
Method[] methdecls = iface.getDeclaredMethods();
for (Method m : methdecls) {
// service interface methods must be public and abstract
if (!Modifier.isPublic(m.getModifiers()) &&
!Modifier.isAbstract(m.getModifiers())) {
continue;
}
if (_verbose) {
System.out.println("Adding " + m + ", imports are " +
StringUtil.toString(imports));
}
methods.add(new ServiceMethod(m, imports));
if (_verbose) {
System.out.println("Added " + m + ", imports are " +
StringUtil.toString(imports));
}
}
}
Collections.sort(methods);
}
protected void addInterfaces (Class<?> listener, Set<Class<?>> ifaces)
{
if (!_ilistener.isAssignableFrom(listener) || _ilistener.equals(listener)) {
return;
}
ifaces.add(listener);
for (Class<?> iface : listener.getInterfaces()) {
addInterfaces(iface, ifaces);
}
}
/**
* Checks whether any of our methods have parameterized types.
*/
public boolean hasParameterizedMethodArgs ()
{
return Iterables.any(methods, new Predicate<ServiceMethod>() {
public boolean apply (ServiceMethod sm) {
return sm.hasParameterizedArgs();
}
});
}
public String getListenerName ()
{
String name = GenUtil.simpleName(listener);
name = name.replace("Listener", "");
int didx = name.indexOf(".");
return name.substring(didx+1);
}
public String adapterCtorArgs () {
StringBuilder sb = new StringBuilder();
for (ServiceMethod m : methods) {
sb.append(m.method.getName() + " :Function, ");
}
return sb.toString();
}
// from interface Comparable<ServiceListener>
public int compareTo (ServiceListener other)
{
return getListenerName().compareTo(other.getListenerName());
}
@Override
public boolean equals (Object other)
{
return (other != null) && getClass().equals(other.getClass()) &&
listener.equals(((ServiceListener)other).listener);
}
@Override
public int hashCode ()
{
return listener.getName().hashCode();
}
}
/** Used to track services for which we should not generate a provider interface. */
public class Providerless
{
public void setService (String className)
{
_providerless.add(className);
}
}
/** Used to track services for which we should create listener adapters in actionscript. */
public class Adapter
{
public void setService (String className)
{
_aslistenerAdapters.add(className);
}
}
/**
* Configures to output extra information when generating code.
*/
public void setVerbose (boolean verbose)
{
_verbose = verbose;
}
/**
* Configures the path to our ActionScript source files.
*/
public void setAsroot (File asroot)
{
_asroot = asroot;
}
public Providerless createProviderless ()
{
return new Providerless();
}
public Adapter createAdapter ()
{
return new Adapter();
}
// documentation inherited
@Override
public void processClass (File source, Class<?> service)
throws Exception
{
System.out.println("Processing " + service.getName() + "...");
// verify that the service class name is as we expect it to be
if (!service.getName().endsWith("Service")) {
System.err.println("Cannot process '" + service.getName() + "':");
System.err.println("Service classes must be named SomethingService.");
return;
}
ServiceDescription desc = new ServiceDescription(service);
generateMarshaller(source, desc);
// generateDispatcher(source, desc); // dispatchers are no longer needed
if (!_providerless.contains(service.getSimpleName())) {
generateProvider(source, desc);
}
}
protected void generateMarshaller (File source, ServiceDescription sdesc)
throws Exception
{
if (_verbose) {
System.out.println("Generating marshaller");
}
String sname = sdesc.sname;
String name = sname.replace("Service", "");
String mname = sname.replace("Service", "Marshaller");
String mpackage = sdesc.spackage.replace(".client", ".data");
// start with all imports (service methods and listener methods)
ImportSet imports = sdesc.constructAllImports();
// import things marshaller will always need
imports.add(sdesc.service);
imports.add(InvocationMarshaller.class);
// if any listeners are to be present, they need the response event
if (sdesc.listeners.size() > 0) {
imports.add(InvocationResponseEvent.class);
}
// import classes contained in arrays
imports.translateClassArrays();
// get rid of java.lang stuff and primitives
imports.removeGlobals();
// get rid of all arrays (they are automatic in java)
imports.removeArrays();
// for each listener type, also import the corresponding marshaller
imports.duplicateAndMunge("*Listener",
"Service", "Marshaller",
"Listener", "Marshaller",
".client.", ".data.");
// import the parent class of Foo$Bar
imports.swapInnerClassesForParents();
// remove imports in our own package
imports.removeSamePackage(mpackage);
Map<String, Object> ctx = new HashMap<String, Object>();
ctx.put("name", name);
ctx.put("generated", getGeneratedAnnotation(name));
ctx.put("package", mpackage);
ctx.put("methods", sdesc.methods);
ctx.put("listeners", sdesc.listeners);
ctx.put("imports", imports.toList());
// determine the path to our marshaller file
String mpath = source.getPath();
mpath = mpath.replace("Service", "Marshaller");
mpath = replacePath(mpath, "/client/", "/data/");
writeTemplate(MARSHALLER_TMPL, mpath, ctx);
// if we're not configured with an ActionScript source root, don't generate the
// ActionScript versions
if (_asroot == null || sdesc.skipAS) {
return;
}
// start with the service method imports
imports = sdesc.imports.clone();
// add some things that marshallers just need
imports.add(sdesc.service);
imports.add(Client.class);
imports.add(InvocationMarshaller.class);
// replace inner classes with action script equivalents
imports.translateInnerClasses();
// replace primitive types with OOO types (required for unboxing)
imports.replace("byte", "com.threerings.util.Byte");
imports.replace("int", "com.threerings.util.Integer");
imports.replace("boolean", "com.threerings.util.langBoolean");
imports.replace("[B", "flash.utils.ByteArray");
imports.replace("float", "com.threerings.util.Float");
imports.replace("[I", "com.threerings.io.TypedArray");
// ye olde special case - any method that uses a default listener
// causes the need for the default listener marshaller
imports.duplicateAndMunge("*.InvocationService_InvocationListener",
"InvocationService_InvocationListener",
"InvocationMarshaller_ListenerMarshaller",
".client.", ".data.");
// any use of a listener requires the listener marshaller
imports.pushOut("*.InvocationService_InvocationListener");
imports.duplicateAndMunge("*Listener",
"Service", "Marshaller",
"Listener", "Marshaller",
".client.", ".data.");
imports.popIn();
// convert java primitive types to ooo util types
imports.replace(Integer.class, "com.threerings.util.Integer");
// get rid of java.lang stuff and any remaining primitives
imports.removeGlobals();
if (imports.removeAll("[L*") > 0) {
imports.add("com.threerings.io.TypedArray");
}
// get rid of remaining arrays
imports.removeArrays();
// remove imports in our own package
imports.removeSamePackage(mpackage);
ctx.put("imports", imports.toList());
// now generate ActionScript versions of our marshaller
// make sure our marshaller directory exists
String mppath = mpackage.replace('.', File.separatorChar);
new File(_asroot + File.separator + mppath).mkdirs();
// generate an ActionScript version of our marshaller
String ampath = _asroot + File.separator + mppath + File.separator + mname + ".as";
writeTemplate(AS_MARSHALLER_TMPL, ampath, ctx);
Class<?> imlm = InvocationMarshaller.ListenerMarshaller.class;
// now generate ActionScript versions of our listener marshallers
// because those have to be in separate files
for (ServiceListener listener : sdesc.listeners) {
// start imports with just those used by listener methods
imports = listener.imports.clone();
// always need the super class and the listener class
imports.add(imlm);
imports.add(listener.listener);
// replace '$' with '_' for action script naming convention
imports.translateInnerClasses();
// convert primitive java types to ooo util types
imports.replace("long", "com.threerings.util.Long");
// convert object arrays to typed arrays
if (imports.removeAll("[L*") > 0) {
imports.add("com.threerings.io.TypedArray");
}
// get rid of remaining primitives and java.lang types
imports.removeGlobals();
// remove imports in our own package
imports.removeSamePackage(mpackage);
ctx.put("imports", imports.toList());
ctx.put("listener", listener);
String aslpath = _asroot + File.separator + mppath +
File.separator + mname + "_" + listener.getListenerName() + "Marshaller.as";
writeTemplate(AS_LISTENER_MARSHALLER_TMPL, aslpath, ctx);
}
// then make some changes to the context and generate ActionScript
// versions of the service interface itself
// start with the service methods' imports
imports = sdesc.imports.clone();
// add some things required by action script
imports.add(Client.class);
imports.add(InvocationService.class);
// allow primitive types in service methods
imports.replace("[B", "flash.utils.ByteArray");
imports.replace("[I", "com.threerings.io.TypedArray");
// convert java primitive types to ooo util types
imports.replace("java.lang.Integer", "com.threerings.util.Integer");
if (imports.removeAll("[L*") > 0) {
imports.add("com.threerings.io.TypedArray");
}
// get rid of primitives and java.lang classes
imports.removeGlobals();
// get rid of remaining arrays
imports.removeArrays();
// change imports of Foo$Bar to Foo_Bar
imports.translateInnerClasses();
// remove imports in our own package
imports.removeSamePackage(sdesc.spackage);
ctx.put("imports", imports.toList());
ctx.put("package", sdesc.spackage);
// make sure our service directory exists
String sppath = sdesc.spackage.replace('.', File.separatorChar);
new File(_asroot + File.separator + sppath).mkdirs();
// generate an ActionScript version of our service
String aspath = _asroot + File.separator + sppath + File.separator + sname + ".as";
writeTemplate(AS_SERVICE_TMPL, aspath, ctx);
Class<?> isil = InvocationService.InvocationListener.class;
// also generate ActionScript versions of any inner listener
// interfaces because those have to be in separate files
for (ServiceListener listener : sdesc.listeners) {
// start with just the imports needed by listener methods
imports = listener.imports.clone();
// add things needed by all listeners
imports.add(isil);
imports.add(listener.listener);
// change Foo$Bar to Foo_Bar
imports.translateInnerClasses();
// use a typed array for any arrays of objects
if (imports.removeAll("[L*") > 0) {
imports.add("com.threerings.io.TypedArray");
}
// convert java primitive types to ooo util types
imports.replace("long", "com.threerings.util.Long");
// get rid of remaining primitives and java.lang types
imports.removeGlobals();
// remove imports in our own package
imports.removeSamePackage(sdesc.spackage);
ctx.put("imports", imports.toList());
ctx.put("listener", listener);
String aslpath = _asroot + File.separator + sppath + File.separator +
sname + "_" + listener.getListenerName() + "Listener.as";
writeTemplate(AS_LISTENER_SERVICE_TMPL, aslpath, ctx);
if (_aslistenerAdapters.contains(sname)) {
String aslapath = _asroot + File.separator + sppath + File.separator +
sname + "_" + listener.getListenerName() + "ListenerAdapter.as";
writeTemplate(AS_LISTENER_ADAPTER_SERVICE_TMPL, aslapath, ctx);
}
}
}
protected void generateDispatcher (File source, ServiceDescription sdesc)
throws Exception
{
if (_verbose) {
System.out.println("Generating dispatcher");
}
String name = sdesc.sname.replace("Service", "");
String dpackage = sdesc.spackage.replace(".client", ".server");
// start with the imports required by service methods
ImportSet imports = sdesc.imports.clone();
// If any listeners are to be used in dispatches, we need to import the service
if (sdesc.listeners.size() > 0) {
imports.add(sdesc.service);
}
// swap Client for ClientObject
imports.add(ClientObject.class);
imports.remove(Client.class);
// add some classes required for all dispatchers
imports.add(InvocationDispatcher.class);
imports.add(InvocationException.class);
// import classes contained in arrays
imports.translateClassArrays();
// get rid of primitives and java.lang types
imports.removeGlobals();
// get rid of arrays
imports.removeArrays();
// import the Marshaller corresponding to the service
imports.addMunged(sdesc.service,
"Service", "Marshaller",
".client.", ".data.");
// import Foo instead of Foo$Bar
imports.swapInnerClassesForParents();
// remove imports in our own package
imports.removeSamePackage(dpackage);
// determine the path to our marshaller file
String mpath = source.getPath();
mpath = mpath.replace("Service", "Dispatcher");
mpath = replacePath(mpath, "/client/", "/server/");
writeTemplate(DISPATCHER_TMPL, mpath,
"name", name,
"generated", getGeneratedAnnotation(name),
"package", dpackage,
"methods", sdesc.methods,
"imports", imports.toList());
}
protected void generateProvider (File source, ServiceDescription sdesc)
throws Exception
{
if (_verbose) {
System.out.println("Generating provider");
}
String name = sdesc.sname.replace("Service", "");
String mpackage = sdesc.spackage.replace(".client", ".server");
// start with imports required by service methods
ImportSet imports = sdesc.imports.clone();
// swap Client for ClientObject
imports.add(ClientObject.class);
imports.remove(Client.class);
// import superclass and service
imports.add(InvocationProvider.class);
imports.add(sdesc.service);
// any method that takes a listener may throw this
if (sdesc.hasAnyListenerArgs()) {
imports.add(InvocationException.class);
}
// import classes contained in arrays
imports.translateClassArrays();
// get rid of primitives and java.lang types
imports.removeGlobals();
// get rid of arrays
imports.removeArrays();
// import Foo instead of Foo$Bar
imports.swapInnerClassesForParents();
// remove imports in our own package
imports.removeSamePackage(mpackage);
// determine the path to our provider file
String mpath = source.getPath();
mpath = mpath.replace("Service", "Provider");
mpath = replacePath(mpath, "/client/", "/server/");
writeTemplate(PROVIDER_TMPL, mpath,
"name", name,
"generated", getGeneratedAnnotation(name),
"package", mpackage,
"methods", sdesc.methods,
"listeners", sdesc.listeners,
"imports", imports.toList());
}
/**
* Helper to get the appropriate "@Generated" annotation for service classes.
*/
protected String getGeneratedAnnotation (String name)
{
return GenUtil.getGeneratedAnnotation(getClass(), 0, false,
"Derived from " + name + "Service.java.");
}
/** Rolls up everything needed for the generate* methods. */
protected class ServiceDescription
{
public Class<?> service;
public String sname;
public String spackage;
public ImportSet imports = new ImportSet();
public List<ServiceMethod> methods = Lists.newArrayList();
public List<ServiceListener> listeners = Lists.newArrayList();
public final boolean skipAS;
public ServiceDescription (Class<?> serviceClass)
{
service = serviceClass;
sname = service.getSimpleName();
spackage = service.getPackage().getName();
ActionScript asa = service.getAnnotation(ActionScript.class);
skipAS = (asa != null) && asa.omit();
// look through and locate our service methods, also locating any
// custom InvocationListener derivations along the way
Method[] methdecls = service.getDeclaredMethods();
for (Method m : methdecls) {
// service interface methods must be public and abstract
if (!Modifier.isPublic(m.getModifiers()) &&
!Modifier.isAbstract(m.getModifiers())) {
continue;
}
// check this method for custom listener declarations
Class<?>[] args = m.getParameterTypes();
for (Class<?> arg : args) {
if (_ilistener.isAssignableFrom(arg) &&
GenUtil.simpleName(arg).startsWith(sname + ".")) {
checkedAdd(listeners, new ServiceListener(service, arg));
}
}
if (_verbose) {
System.out.println("Adding " + m + ", imports are " +
StringUtil.toString(imports));
}
methods.add(new ServiceMethod(m, imports));
if (_verbose) {
System.out.println("Added " + m + ", imports are " +
StringUtil.toString(imports));
}
}
Collections.sort(listeners);
Collections.sort(methods);
}
/**
* Checks if any of the service method arguments are listener types.
*/
public boolean hasAnyListenerArgs ()
{
return Iterables.any(methods, new Predicate<ServiceMethod>() {
public boolean apply (ServiceMethod sm) {
return !sm.listenerArgs.isEmpty();
}
});
}
/**
* Constructs a union of the imports of the service methods and all listener methods.
*/
public ImportSet constructAllImports ()
{
ImportSet allimports = imports.clone();
for (ServiceListener listener : listeners) {
allimports.addAll(listener.imports);
}
return allimports;
}
}
/** Show extra output if set. */
protected boolean _verbose;
/** The path to our ActionScript source files. */
protected File _asroot;
/** Services for which we should not generate provider interfaces. */
protected Set<String> _providerless = Sets.newHashSet();
/** Services for which we should generate actionscript listener adapters. */
protected Set<String> _aslistenerAdapters = Sets.newHashSet();
/** Specifies the path to the marshaller template. */
protected static final String MARSHALLER_TMPL =
"com/threerings/presents/tools/marshaller.tmpl";
/** Specifies the path to the dispatcher template. */
protected static final String DISPATCHER_TMPL =
"com/threerings/presents/tools/dispatcher.tmpl";
/** Specifies the path to the provider template. */
protected static final String PROVIDER_TMPL =
"com/threerings/presents/tools/provider.tmpl";
/** Specifies the path to the ActionScript service template. */
protected static final String AS_SERVICE_TMPL =
"com/threerings/presents/tools/service_as.tmpl";
/** Specifies the path to the ActionScript listener service template. */
protected static final String AS_LISTENER_SERVICE_TMPL =
"com/threerings/presents/tools/service_listener_as.tmpl";
/** Specifies the path to the ActionScript listener adapter service template. */
protected static final String AS_LISTENER_ADAPTER_SERVICE_TMPL =
"com/threerings/presents/tools/service_listener_adapter_as.tmpl";
/** Specifies the path to the ActionScript marshaller template. */
protected static final String AS_MARSHALLER_TMPL =
"com/threerings/presents/tools/marshaller_as.tmpl";
/** Specifies the path to the ActionScript listener marshaller template. */
protected static final String AS_LISTENER_MARSHALLER_TMPL =
"com/threerings/presents/tools/marshaller_listener_as.tmpl";
}
|
package com.topsy.jmxproxy.jmx;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
public class ConnectionCredentials {
@NotEmpty
@JsonProperty
private final String username;
@NotEmpty
@JsonProperty
private final String password;
public ConnectionCredentials(@JsonProperty("username") String username, @JsonProperty("password") String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
@Override
public boolean equals(Object peer) {
if (peer == null || !(peer instanceof ConnectionCredentials)) {
return false;
}
ConnectionCredentials auth = (ConnectionCredentials) peer;
return username.equals(auth.getUsername()) && password.equals(auth.getPassword());
}
}
|
package com.wizzardo.http.websocket;
import com.wizzardo.epoll.ByteBufferProvider;
import com.wizzardo.epoll.Connection;
import com.wizzardo.epoll.readable.ReadableBuilder;
import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.http.Handler;
import com.wizzardo.http.HttpConnection;
import com.wizzardo.http.InputListener;
import com.wizzardo.http.request.Header;
import com.wizzardo.http.request.Request;
import com.wizzardo.http.response.Response;
import com.wizzardo.http.response.Status;
import com.wizzardo.tools.security.Base64;
import com.wizzardo.tools.security.SHA1;
import java.io.IOException;
public class WebSocketHandler<T extends WebSocketHandler.WebSocketListener> implements Handler {
@Override
public Response handle(Request request, Response response) {
if (request.method() != Request.Method.GET)
return response.status(Status._405).header(Header.KEY_ALLOW, Request.Method.GET.name());
if (!Header.VALUE_WEBSOCKET.value.equals(request.header(Header.KEY_UPGRADE)))
return response.status(Status._400);
String connection = request.header(Header.KEY_CONNECTION);
if (!Header.VALUE_UPGRADE.value.equals(connection) && !"keep-alive, Upgrade".equalsIgnoreCase(connection))
return response.status(Status._400);
if (request.headerLong(Header.KEY_SEC_WEBSOCKET_VERSION, -1) != 13)
return response.status(Status._400);
String key = request.header(Header.KEY_SEC_WEBSOCKET_KEY);
if (key == null || key.isEmpty())
return response.status(Status._400);
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // websocket magic
key = Base64.encodeToString(SHA1.create().update(key.getBytes()).asBytes());
request.connection().upgrade(createListener(request.connection(), this));
return response.status(Status._101)
.header(Header.KEY_UPGRADE, Header.VALUE_WEBSOCKET)
.header(Header.KEY_CONNECTION, Header.VALUE_UPGRADE)
.header(Header.KEY_SEC_WEBSOCKET_ACCEPT, key);
}
protected T createListener(HttpConnection connection, WebSocketHandler handler) {
return (T) new WebSocketListener(connection, handler);
}
public static class WebSocketListener implements InputListener<HttpConnection> {
protected final HttpConnection connection;
protected final WebSocketHandler webSocketHandler;
private Message tempMessage;
private Frame tempFrame;
private int read = 0;
public WebSocketListener(HttpConnection connection, WebSocketHandler webSocketHandler) {
this.connection = connection;
this.webSocketHandler = webSocketHandler;
}
@Override
public void onReadyToRead(HttpConnection connection) {
try {
byte[] buffer = connection.getBuffer();
int r;
outer:
while ((r = connection.read(buffer, read, buffer.length - read, (ByteBufferProvider) Thread.currentThread())) > 0) {
read += r;
while (read > 0) {
if (tempFrame == null) {
if (!Frame.hasHeaders(buffer, 0, read))
continue outer;
tempFrame = new Frame(connection.getServer().getWebsocketFrameLengthLimit());
}
int k = tempFrame.read(buffer, 0, read);
read -= k;
if (read != 0)
System.arraycopy(buffer, k, buffer, 0, read);
if (tempFrame.isComplete()) {
if (tempFrame.isMasked())
tempFrame.unmask();
if (handlePing())
continue;
if (handleClose())
continue;
if (tempMessage == null)
tempMessage = new Message();
tempMessage.add(tempFrame);
tempFrame = null;
}
if (tempMessage != null && tempMessage.isComplete()) {
webSocketHandler.onMessage(this, tempMessage);
tempMessage = null;
}
}
}
} catch (Exception e) {
e.printStackTrace();
try {
connection.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private boolean handlePing() {
if (tempFrame.isPing()) {
tempFrame.setOpcode(Frame.OPCODE_PONG);
sendFrame(tempFrame);
tempFrame = null;
return true;
}
return false;
}
private boolean handleClose() {
if (tempFrame.isClose()) {
sendFrame(tempFrame);
connection.setCloseOnFinishWriting(true);
tempFrame = null;
return true;
}
return false;
}
@Override
public void onReady(HttpConnection connection) {
webSocketHandler.onConnect(this);
}
public synchronized void sendMessage(Message message) {
for (Frame frame : message.getFrames()) {
connection.write(convertFrameToReadableData(frame), (ByteBufferProvider) Thread.currentThread());
}
}
private synchronized void sendFrame(Frame frame) {
connection.write(convertFrameToReadableData(frame), (ByteBufferProvider) Thread.currentThread());
}
public void close() {
if (connection.isAlive())
sendFrame(new Frame(Frame.OPCODE_CONNECTION_CLOSE));
webSocketHandler.onDisconnect(this);
}
private ReadableData convertFrameToReadableData(Frame frame) {
return new ReadableByteArray(frame.getFrameBytes(), frame.getFrameOffset(), frame.getFrameLength());
}
}
public void onConnect(T listener) {
}
public void onDisconnect(T listener) {
}
public void onMessage(T listener, Message message) {
}
}
|
package org.jkiss.dbeaver.ui.controls.resultset;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.StringConverter;
import org.eclipse.jface.text.IFindReplaceTarget;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.actions.CompoundContributionItem;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.DBeaverPreferences;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.CoreCommands;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.core.DBeaverUI;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.data.*;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.impl.local.StatResultSet;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress;
import org.jkiss.dbeaver.model.runtime.RunnableWithResult;
import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.dbeaver.model.virtual.*;
import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer;
import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer;
import org.jkiss.dbeaver.tools.transfer.wizard.DataTransferWizard;
import org.jkiss.dbeaver.ui.*;
import org.jkiss.dbeaver.ui.actions.navigator.NavigatorHandlerObjectOpen;
import org.jkiss.dbeaver.ui.controls.CImageCombo;
import org.jkiss.dbeaver.ui.controls.resultset.view.EmptyPresentation;
import org.jkiss.dbeaver.ui.controls.resultset.view.StatisticsPresentation;
import org.jkiss.dbeaver.ui.data.IValueController;
import org.jkiss.dbeaver.ui.data.managers.BaseValueManager;
import org.jkiss.dbeaver.ui.dialogs.ActiveWizardDialog;
import org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog;
import org.jkiss.dbeaver.ui.dialogs.EditTextDialog;
import org.jkiss.dbeaver.ui.dialogs.struct.EditConstraintDialog;
import org.jkiss.dbeaver.ui.dialogs.struct.EditDictionaryDialog;
import org.jkiss.dbeaver.ui.editors.data.DatabaseDataEditor;
import org.jkiss.dbeaver.ui.preferences.PrefPageDataFormat;
import org.jkiss.dbeaver.ui.preferences.PrefPageDatabaseGeneral;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.List;
/**
* ResultSetViewer
*
* TODO: fix copy multiple cells - tabulation broken
* TODO: links in both directions, multiple links support (context menu)
* TODO: not-editable cells (struct owners in record mode)
* TODO: PROBLEM. Multiple occurrences of the same struct type in a single table.
* Need to make wrapper over DBSAttributeBase or something. Or maybe it is not a problem
* because we search for binding by attribute only in constraints and for unique key columns which are unique?
* But what PK has struct type?
*
*/
public class ResultSetViewer extends Viewer
implements DBPContextProvider, IResultSetController, ISaveablePart2, IAdaptable
{
private static final Log log = Log.getLog(ResultSetViewer.class);
public static final String SETTINGS_SECTION_PRESENTATIONS = "presentations";
@NotNull
private static IResultSetFilterManager filterManager = new SimpleFilterManager();
@NotNull
private final IWorkbenchPartSite site;
private final Composite viewerPanel;
private ResultSetFilterPanel filtersPanel;
private SashForm viewerSash;
private CTabFolder panelFolder;
private ToolBarManager panelToolBar;
private final Composite presentationPanel;
private Text statusLabel;
private final DynamicFindReplaceTarget findReplaceTarget;
// Presentation
@NotNull
private IResultSetPresentation activePresentation;
private ResultSetPresentationDescriptor activePresentationDescriptor;
private List<ResultSetPresentationDescriptor> availablePresentations;
private PresentationSwitchCombo presentationSwitchCombo;
private final List<ResultSetPanelDescriptor> availablePanels = new ArrayList<>();
private final Map<ResultSetPresentationDescriptor, PresentationSettings> presentationSettings = new HashMap<>();
private final Map<String, IResultSetPanel> activePanels = new HashMap<>();
@NotNull
private final IResultSetContainer container;
@NotNull
private final ResultSetDataReceiver dataReceiver;
private ToolBarManager mainToolbar;
// Current row/col number
@Nullable
private ResultSetRow curRow;
// Mode
private boolean recordMode;
private final List<IResultSetListener> listeners = new ArrayList<>();
private volatile ResultSetDataPumpJob dataPumpJob;
private final ResultSetModel model = new ResultSetModel();
private HistoryStateItem curState = null;
private final List<HistoryStateItem> stateHistory = new ArrayList<>();
private int historyPosition = -1;
private final IDialogSettings viewerSettings;
private final Color colorRed;
private boolean actionsDisabled;
public ResultSetViewer(@NotNull Composite parent, @NotNull IWorkbenchPartSite site, @NotNull IResultSetContainer container)
{
super();
this.site = site;
this.recordMode = false;
this.container = container;
this.dataReceiver = new ResultSetDataReceiver(this);
this.colorRed = Display.getDefault().getSystemColor(SWT.COLOR_RED);
this.viewerSettings = UIUtils.getDialogSettings(ResultSetViewer.class.getSimpleName());
loadPresentationSettings();
this.viewerPanel = UIUtils.createPlaceholder(parent, 1);
UIUtils.setHelp(this.viewerPanel, IHelpContextIds.CTX_RESULT_SET_VIEWER);
this.filtersPanel = new ResultSetFilterPanel(this);
this.findReplaceTarget = new DynamicFindReplaceTarget();
this.viewerSash = UIUtils.createPartDivider(site.getPart(), viewerPanel, SWT.HORIZONTAL | SWT.SMOOTH);
this.viewerSash.setLayoutData(new GridData(GridData.FILL_BOTH));
this.presentationPanel = UIUtils.createPlaceholder(this.viewerSash, 1);
this.presentationPanel.setLayoutData(new GridData(GridData.FILL_BOTH));
this.panelFolder = new CTabFolder(this.viewerSash, SWT.FLAT | SWT.TOP);
this.panelFolder.marginWidth = 0;
this.panelFolder.marginHeight = 0;
this.panelFolder.setMinimizeVisible(true);
this.panelFolder.setMRUVisible(true);
this.panelFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
this.panelToolBar = new ToolBarManager(SWT.HORIZONTAL | SWT.RIGHT | SWT.FLAT);
ToolBar panelToolbarControl = this.panelToolBar.createControl(panelFolder);
this.panelFolder.setTopRight(panelToolbarControl, SWT.RIGHT | SWT.WRAP);
this.panelFolder.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CTabItem activeTab = panelFolder.getSelection();
if (activeTab != null) {
setActivePanel((String) activeTab.getData());
}
}
});
this.panelFolder.addListener(SWT.Resize, new Listener() {
@Override
public void handleEvent(Event event)
{
if (!viewerSash.isDisposed()) {
int[] weights = viewerSash.getWeights();
getPresentationSettings().panelRatio = weights[1];
}
}
});
this.panelFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
@Override
public void close(CTabFolderEvent event) {
CTabItem item = (CTabItem) event.item;
String panelId = (String) item.getData();
removePanel(panelId);
}
@Override
public void minimize(CTabFolderEvent event) {
showPanels(false);
}
@Override
public void maximize(CTabFolderEvent event) {
}
});
setActivePresentation(new EmptyPresentation());
createStatusBar();
this.viewerPanel.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
dispose();
}
});
changeMode(false);
}
@Override
@NotNull
public IResultSetContainer getContainer() {
return container;
}
// Filters
boolean supportsDataFilter()
{
DBSDataContainer dataContainer = getDataContainer();
return dataContainer != null &&
(dataContainer.getSupportedFeatures() & DBSDataContainer.DATA_FILTER) == DBSDataContainer.DATA_FILTER;
}
public void resetDataFilter(boolean refresh)
{
setDataFilter(model.createDataFilter(), refresh);
}
public void updateFiltersText()
{
updateFiltersText(true);
}
private void updateFiltersText(boolean resetFilterValue)
{
boolean enableFilters = false;
DBCExecutionContext context = getExecutionContext();
if (context != null) {
if (activePresentation instanceof StatisticsPresentation) {
enableFilters = false;
} else {
StringBuilder where = new StringBuilder();
SQLUtils.appendConditionString(model.getDataFilter(), context.getDataSource(), null, where, true);
String whereCondition = where.toString().trim();
if (resetFilterValue) {
filtersPanel.setFilterValue(whereCondition);
if (!whereCondition.isEmpty()) {
filtersPanel.addFiltersHistory(whereCondition);
}
}
if (container.isReadyToRun() && !model.isUpdateInProgress() && model.getVisibleAttributeCount() > 0) {
enableFilters = true;
}
}
}
filtersPanel.enableFilters(enableFilters);
presentationSwitchCombo.combo.setEnabled(enableFilters);
}
public void setDataFilter(final DBDDataFilter dataFilter, boolean refreshData)
{
if (!model.getDataFilter().equals(dataFilter)) {
//model.setDataFilter(dataFilter);
if (refreshData) {
refreshWithFilter(dataFilter);
} else {
model.setDataFilter(dataFilter);
activePresentation.refreshData(true, false);
updateFiltersText();
}
}
}
// Misc
@NotNull
public DBPPreferenceStore getPreferenceStore()
{
DBCExecutionContext context = getExecutionContext();
if (context != null) {
return context.getDataSource().getContainer().getPreferenceStore();
}
return DBeaverCore.getGlobalPreferenceStore();
}
@Override
public IDialogSettings getViewerSettings() {
return viewerSettings;
}
@NotNull
@Override
public Color getDefaultBackground() {
return filtersPanel.getEditControl().getBackground();
}
@NotNull
@Override
public Color getDefaultForeground() {
return filtersPanel.getEditControl().getForeground();
}
private void persistConfig() {
DBCExecutionContext context = getExecutionContext();
if (context != null) {
context.getDataSource().getContainer().persistConfiguration();
}
}
// Presentation & panels
public List<ResultSetPresentationDescriptor> getAvailablePresentations() {
return availablePresentations;
}
@Override
@NotNull
public IResultSetPresentation getActivePresentation() {
return activePresentation;
}
void updatePresentation(final DBCResultSet resultSet) {
try {
if (resultSet instanceof StatResultSet) {
// Statistics - let's use special presentation for it
availablePresentations = Collections.emptyList();
setActivePresentation(new StatisticsPresentation());
activePresentationDescriptor = null;
} else {
// Regular results
IResultSetContext context = new IResultSetContext() {
@Override
public boolean supportsAttributes() {
DBDAttributeBinding[] attrs = model.getAttributes();
return attrs.length > 0 &&
(attrs[0].getDataKind() != DBPDataKind.DOCUMENT || !CommonUtils.isEmpty(attrs[0].getNestedBindings()));
}
@Override
public boolean supportsDocument() {
return model.getDocumentAttribute() != null;
}
@Override
public String getDocumentContentType() {
DBDAttributeBinding docAttr = model.getDocumentAttribute();
return docAttr == null ? null : docAttr.getValueHandler().getValueContentType(docAttr);
}
};
availablePresentations = ResultSetPresentationRegistry.getInstance().getAvailablePresentations(resultSet, context);
if (!availablePresentations.isEmpty()) {
for (ResultSetPresentationDescriptor pd : availablePresentations) {
if (pd == activePresentationDescriptor) {
// Keep the same presentation
return;
}
}
String defaultPresentationId = getPreferenceStore().getString(DBeaverPreferences.RESULT_SET_PRESENTATION);
ResultSetPresentationDescriptor newPresentation = null;
if (!CommonUtils.isEmpty(defaultPresentationId)) {
for (ResultSetPresentationDescriptor pd : availablePresentations) {
if (pd.getId().equals(defaultPresentationId)) {
newPresentation = pd;
break;
}
}
}
if (newPresentation == null) {
newPresentation = availablePresentations.get(0);
}
try {
IResultSetPresentation instance = newPresentation.createInstance();
activePresentationDescriptor = newPresentation;
setActivePresentation(instance);
} catch (DBException e) {
log.error(e);
}
}
}
} finally {
// Update combo
CImageCombo combo = presentationSwitchCombo.combo;
combo.setRedraw(false);
try {
if (activePresentationDescriptor == null) {
combo.setEnabled(false);
} else {
combo.setEnabled(true);
combo.removeAll();
for (ResultSetPresentationDescriptor pd : availablePresentations) {
combo.add(DBeaverIcons.getImage(pd.getIcon()), pd.getLabel(), null, pd);
}
combo.select(activePresentationDescriptor);
}
} finally {
// Enable redraw
combo.setRedraw(true);
}
}
}
private void setActivePresentation(@NotNull IResultSetPresentation presentation) {
// Dispose previous presentation and panels
for (Control child : presentationPanel.getChildren()) {
child.dispose();
}
for (CTabItem panelItem : panelFolder.getItems()) {
panelItem.dispose();
}
// Set new presentation
activePresentation = presentation;
availablePanels.clear();
activePanels.clear();
if (activePresentationDescriptor != null) {
availablePanels.addAll(ResultSetPresentationRegistry.getInstance().getSupportedPanels(activePresentationDescriptor));
}
activePresentation.createPresentation(this, presentationPanel);
// Activate panels
{
boolean panelsVisible = false;
int[] panelWeights = new int[]{700, 300};
if (activePresentationDescriptor != null) {
PresentationSettings settings = getPresentationSettings();
panelsVisible = settings.panelsVisible;
if (settings.panelRatio > 0) {
panelWeights = new int[] {1000 - settings.panelRatio, settings.panelRatio};
}
activateDefaultPanels(settings);
}
showPanels(panelsVisible);
viewerSash.setWeights(panelWeights);
}
presentationPanel.layout();
// Update dynamic find/replace target
{
IFindReplaceTarget nested = null;
if (presentation instanceof IAdaptable) {
nested = ((IAdaptable) presentation).getAdapter(IFindReplaceTarget.class);
}
findReplaceTarget.setTarget(nested);
}
if (mainToolbar != null) {
mainToolbar.update(true);
}
// Set focus in presentation control
// Use async exec to avoid focus switch after user UI interaction (e.g. combo)
Display display = getControl().getDisplay();
if (UIUtils.isParent(viewerPanel, display.getFocusControl())) {
display.asyncExec(new Runnable() {
@Override
public void run() {
activePresentation.getControl().setFocus();
}
});
}
}
/**
* Switch to the next presentation
*/
void switchPresentation() {
if (availablePresentations.size() < 2) {
return;
}
int index = availablePresentations.indexOf(activePresentationDescriptor);
if (index < availablePresentations.size() - 1) {
index++;
} else {
index = 0;
}
switchPresentation(availablePresentations.get(index));
}
private void switchPresentation(ResultSetPresentationDescriptor selectedPresentation) {
try {
IResultSetPresentation instance = selectedPresentation.createInstance();
activePresentationDescriptor = selectedPresentation;
setActivePresentation(instance);
instance.refreshData(true, false);
presentationSwitchCombo.combo.select(activePresentationDescriptor);
// Save in global preferences
DBeaverCore.getGlobalPreferenceStore().setValue(DBeaverPreferences.RESULT_SET_PRESENTATION, activePresentationDescriptor.getId());
savePresentationSettings();
} catch (Throwable e1) {
UIUtils.showErrorDialog(
viewerPanel.getShell(),
"Presentation switch",
"Can't switch presentation",
e1);
}
}
private void loadPresentationSettings() {
IDialogSettings pSections = viewerSettings.getSection(SETTINGS_SECTION_PRESENTATIONS);
if (pSections != null) {
for (IDialogSettings pSection : ArrayUtils.safeArray(pSections.getSections())) {
String pId = pSection.getName();
ResultSetPresentationDescriptor presentation = ResultSetPresentationRegistry.getInstance().getPresentation(pId);
if (presentation == null) {
log.warn("Presentation '" + pId + "' not found. ");
continue;
}
PresentationSettings settings = new PresentationSettings();
String panelIdList = pSection.get("enabledPanelIds");
if (panelIdList != null) {
Collections.addAll(settings.enabledPanelIds, panelIdList.split(","));
}
settings.activePanelId = pSection.get("activePanelId");
settings.panelRatio = pSection.getInt("panelRatio");
settings.panelsVisible = pSection.getBoolean("panelsVisible");
presentationSettings.put(presentation, settings);
}
}
}
private PresentationSettings getPresentationSettings() {
PresentationSettings settings = this.presentationSettings.get(activePresentationDescriptor);
if (settings == null) {
settings = new PresentationSettings();
this.presentationSettings.put(activePresentationDescriptor, settings);
}
return settings;
}
private void savePresentationSettings() {
IDialogSettings pSections = UIUtils.getSettingsSection(viewerSettings, SETTINGS_SECTION_PRESENTATIONS);
for (Map.Entry<ResultSetPresentationDescriptor, PresentationSettings> pEntry : presentationSettings.entrySet()) {
if (pEntry.getKey() == null) {
continue;
}
String pId = pEntry.getKey().getId();
PresentationSettings settings = pEntry.getValue();
IDialogSettings pSection = UIUtils.getSettingsSection(pSections, pId);
pSection.put("enabledPanelIds", CommonUtils.joinStrings(",", settings.enabledPanelIds));
pSection.put("activePanelId", settings.activePanelId);
pSection.put("panelRatio", settings.panelRatio);
pSection.put("panelsVisible", settings.panelsVisible);
}
}
IResultSetPanel getVisiblePanel() {
return activePanels.get(getPresentationSettings().activePanelId);
}
@Override
public IResultSetPanel[] getActivePanels() {
return activePanels.values().toArray(new IResultSetPanel[activePanels.size()]);
}
@Override
public void activatePanel(String id, boolean setActive, boolean showPanels) {
if (showPanels && !isPanelsVisible()) {
showPanels(true);
}
PresentationSettings presentationSettings = getPresentationSettings();
IResultSetPanel panel = activePanels.get(id);
if (panel != null) {
CTabItem panelTab = getPanelTab(id);
if (panelTab != null) {
if (setActive) {
panelFolder.setSelection(panelTab);
presentationSettings.activePanelId = id;
}
return;
} else {
log.warn("Panel '" + id + "' tab not found");
}
}
// Create panel
ResultSetPanelDescriptor panelDescriptor = getPanelDescriptor(id);
if (panelDescriptor == null) {
log.error("Panel '" + id + "' not found");
return;
}
try {
panel = panelDescriptor.createInstance();
} catch (DBException e) {
UIUtils.showErrorDialog(getSite().getShell(), "Can't show panel", "Can't create panel '" + id + "'", e);
return;
}
activePanels.put(id, panel);
// Create control and tab item
Control panelControl = panel.createContents(activePresentation, panelFolder);
boolean firstPanel = panelFolder.getItemCount() == 0;
CTabItem panelTab = new CTabItem(panelFolder, SWT.CLOSE);
panelTab.setData(id);
panelTab.setText(panel.getPanelTitle());
panelTab.setImage(DBeaverIcons.getImage(panelDescriptor.getIcon()));
panelTab.setToolTipText(panel.getPanelDescription());
panelTab.setControl(panelControl);
if (setActive || firstPanel) {
panelFolder.setSelection(panelTab);
}
presentationSettings.enabledPanelIds.add(id);
if (setActive) {
setActivePanel(id);
}
}
private void activateDefaultPanels(PresentationSettings settings) {
if (settings.enabledPanelIds.isEmpty()) {
for (ResultSetPanelDescriptor pd : availablePanels) {
if (pd.isShowByDefault()) {
settings.enabledPanelIds.add(pd.getId());
}
}
}
if (!settings.enabledPanelIds.isEmpty()) {
for (String panelId : settings.enabledPanelIds) {
activatePanel(panelId, panelId.equals(settings.activePanelId), false);
}
}
}
private void setActivePanel(String panelId) {
PresentationSettings settings = getPresentationSettings();
if (CommonUtils.equalObjects(settings.activePanelId, panelId)) {
return;
}
settings.activePanelId = panelId;
IResultSetPanel panel = activePanels.get(panelId);
if (panel != null) {
panelToolBar.removeAll();
panel.activatePanel(panelToolBar);
addDefaultPanelActions();
panelToolBar.update(true);
}
}
private void removePanel(String panelId) {
IResultSetPanel panel = activePanels.remove(panelId);
if (panel != null) {
panel.deactivatePanel();
}
getPresentationSettings().enabledPanelIds.remove(panelId);
if (activePanels.isEmpty()) {
showPanels(false);
}
}
private ResultSetPanelDescriptor getPanelDescriptor(String id) {
for (ResultSetPanelDescriptor panel : availablePanels) {
if (panel.getId().equals(id)) {
return panel;
}
}
return null;
}
private CTabItem getPanelTab(String panelId) {
for (CTabItem tab : panelFolder.getItems()) {
if (CommonUtils.equalObjects(tab.getData(), panelId)) {
return tab;
}
}
return null;
}
public boolean isPanelsVisible() {
return viewerSash.getMaximizedControl() == null;
}
public void showPanels(boolean show) {
if (!show) {
viewerSash.setMaximizedControl(presentationPanel);
} else {
activateDefaultPanels(getPresentationSettings());
viewerSash.setMaximizedControl(null);
panelToolBar.removeAll();
IResultSetPanel panel = getVisiblePanel();
if (panel != null) {
panel.activatePanel(panelToolBar);
}
addDefaultPanelActions();
panelToolBar.update(true);
activePresentation.updateValueView();
}
getPresentationSettings().panelsVisible = show;
// Refresh elements
ICommandService commandService = getSite().getService(ICommandService.class);
if (commandService != null) {
commandService.refreshElements(ResultSetCommandHandler.CMD_TOGGLE_PANELS, null);
}
}
private List<IContributionItem> fillPanelsMenu() {
List<IContributionItem> items = new ArrayList<>();
for (final ResultSetPanelDescriptor panel : availablePanels) {
Action panelAction = new Action(panel.getLabel(), Action.AS_CHECK_BOX) {
@Override
public boolean isChecked() {
return activePanels.containsKey(panel.getId());
}
@Override
public void run() {
if (isPanelsVisible() && isChecked()) {
CTabItem panelTab = getPanelTab(panel.getId());
if (panelTab != null) {
panelTab.dispose();
removePanel(panel.getId());
}
} else {
activatePanel(panel.getId(), true, true);
}
}
};
//panelAction.setImageDescriptor(DBeaverIcons.getImageDescriptor(panel.getIcon()));
items.add(new ActionContributionItem(panelAction));
}
return items;
}
private void addDefaultPanelActions() {
panelToolBar.add(new Action("View Menu", ImageDescriptor.createFromImageData(DBeaverIcons.getViewMenuImage().getImageData())) {
@Override
public void run() {
ToolBar tb = panelToolBar.getControl();
for (ToolItem item : tb.getItems()) {
if (item.getData() instanceof ActionContributionItem && ((ActionContributionItem) item.getData()).getAction() == this) {
MenuManager panelMenu = new MenuManager();
for (IContributionItem menuItem : fillPanelsMenu()) {
panelMenu.add(menuItem);
}
final Menu swtMenu = panelMenu.createContextMenu(panelToolBar.getControl());
Rectangle ib = item.getBounds();
Point displayAt = item.getParent().toDisplay(ib.x, ib.y + ib.height);
swtMenu.setLocation(displayAt);
swtMenu.setVisible(true);
return;
}
}
}
});
}
// Actions
public boolean isActionsDisabled() {
return actionsDisabled;
}
@Override
public void lockActionsByControl(Control lockedBy) {
if (checkDoubleLock(lockedBy)) {
return;
}
actionsDisabled = true;
lockedBy.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
actionsDisabled = false;
}
});
}
@Override
public void lockActionsByFocus(final Control lockedBy) {
lockedBy.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
checkDoubleLock(lockedBy);
actionsDisabled = true;
}
@Override
public void focusLost(FocusEvent e) {
actionsDisabled = false;
}
});
lockedBy.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
actionsDisabled = false;
}
});
}
private boolean checkDoubleLock(Control lockedBy) {
if (actionsDisabled) {
log.debug("Internal error: actions double-lock by [" + lockedBy + "]");
return true;
}
return false;
}
@Nullable
@Override
public <T> T getAdapter(Class<T> adapter)
{
if (adapter == IFindReplaceTarget.class) {
return adapter.cast(findReplaceTarget);
}
if (adapter.isAssignableFrom(activePresentation.getClass())) {
return adapter.cast(activePresentation);
}
// Try to get it from adapter
if (activePresentation instanceof IAdaptable) {
return ((IAdaptable) activePresentation).getAdapter(adapter);
}
return null;
}
public void addListener(IResultSetListener listener)
{
synchronized (listeners) {
listeners.add(listener);
}
}
public void removeListener(IResultSetListener listener)
{
synchronized (listeners) {
listeners.remove(listener);
}
}
private void updateRecordMode()
{
//Object state = savePresentationState();
//this.redrawData(false);
activePresentation.refreshData(true, false);
this.updateStatusMessage();
//restorePresentationState(state);
}
public void updateEditControls()
{
ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_EDITABLE);
ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CHANGED);
updateToolbar();
}
/**
* It is a hack function. Generally all command associated widgets should be updated automatically by framework.
* Freaking E4 do not do it. I've spent a couple of days fighting it. Guys, you owe me.
*/
private void updateToolbar()
{
if (!mainToolbar.isEmpty()) {
for (IContributionItem item : mainToolbar.getItems()) {
item.update();
}
}
if (!panelToolBar.isEmpty()) {
for (IContributionItem item : panelToolBar.getItems()) {
item.update();
}
}
}
public void redrawData(boolean rowsChanged)
{
if (viewerPanel.isDisposed()) {
return;
}
if (rowsChanged) {
int rowCount = model.getRowCount();
if (curRow == null || curRow.getVisualNumber() >= rowCount) {
curRow = rowCount == 0 ? null : model.getRow(rowCount - 1);
}
// Set cursor on new row
if (!recordMode) {
activePresentation.refreshData(false, false);
this.updateFiltersText();
this.updateStatusMessage();
} else {
this.updateRecordMode();
}
} else {
activePresentation.refreshData(false, false);
}
}
private void createStatusBar()
{
UIUtils.createHorizontalLine(viewerPanel);
Composite statusBar = new Composite(viewerPanel, SWT.NONE);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
statusBar.setLayoutData(gd);
GridLayout gl = new GridLayout(4, false);
gl.marginWidth = 0;
gl.marginHeight = 0;
//gl.marginBottom = 5;
statusBar.setLayout(gl);
statusLabel = new Text(statusBar, SWT.READ_ONLY);
gd = new GridData(GridData.FILL_HORIZONTAL);
statusLabel.setLayoutData(gd);
statusLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e)
{
EditTextDialog.showText(site.getShell(), CoreMessages.controls_resultset_viewer_dialog_status_title, statusLabel.getText());
}
});
mainToolbar = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL);
// Add presentation switcher
presentationSwitchCombo = new PresentationSwitchCombo();
presentationSwitchCombo.createControl(statusBar);
//mainToolbar.add(presentationSwitchCombo);
//mainToolbar.add(new Separator());
// handle own commands
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_APPLY_CHANGES));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_REJECT_CHANGES));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_GENERATE_SCRIPT));
mainToolbar.add(new Separator());
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_ADD));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_COPY));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_DELETE));
mainToolbar.add(new Separator());
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_FIRST));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_PREVIOUS));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_NEXT));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_LAST));
mainToolbar.add(new Separator());
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_FETCH_PAGE));
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_FETCH_ALL));
// Use simple action for refresh to avoid ambiguous behaviour of F5 shortcut
mainToolbar.add(new Separator());
// // FIXME: Link to standard Find/Replace action - it has to be handled by owner site
// mainToolbar.add(ActionUtils.makeCommandContribution(
// site,
// IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE,
// CommandContributionItem.STYLE_PUSH,
// UIIcon.FIND_TEXT));
mainToolbar.add(new Separator());
mainToolbar.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_MODE, CommandContributionItem.STYLE_CHECK));
CommandContributionItem panelsAction = new CommandContributionItem(new CommandContributionItemParameter(
site,
"org.jkiss.dbeaver.core.resultset.panels",
ResultSetCommandHandler.CMD_TOGGLE_PANELS,
CommandContributionItem.STYLE_PULLDOWN));
//panelsAction.
mainToolbar.add(panelsAction);
mainToolbar.add(new Separator());
mainToolbar.add(new ConfigAction());
mainToolbar.createControl(statusBar);
//updateEditControls();
}
@Nullable
public DBSDataContainer getDataContainer()
{
return curState != null ? curState.dataContainer : container.getDataContainer();
}
// Grid/Record mode
@Override
public boolean isRecordMode() {
return recordMode;
}
public void toggleMode()
{
changeMode(!recordMode);
// Refresh elements
ICommandService commandService = site.getService(ICommandService.class);
if (commandService != null) {
commandService.refreshElements(ResultSetCommandHandler.CMD_TOGGLE_MODE, null);
}
}
private void changeMode(boolean recordMode)
{
//Object state = savePresentationState();
this.recordMode = recordMode;
//redrawData(false);
activePresentation.refreshData(true, false);
activePresentation.changeMode(recordMode);
updateStatusMessage();
//restorePresentationState(state);
}
// Misc
private void dispose()
{
savePresentationSettings();
clearData();
if (mainToolbar != null) {
try {
mainToolbar.dispose();
} catch (Throwable e) {
// ignore
log.debug("Error disposing toolbar", e);
}
}
}
public boolean isAttributeReadOnly(DBDAttributeBinding attribute)
{
if (isReadOnly()) {
return true;
}
if (!model.isAttributeReadOnly(attribute)) {
return false;
}
boolean newRow = (curRow != null && curRow.getState() == ResultSetRow.STATE_ADDED);
return !newRow;
}
private Object savePresentationState() {
if (activePresentation instanceof IStatefulControl) {
return ((IStatefulControl) activePresentation).saveState();
} else {
return null;
}
}
private void restorePresentationState(Object state) {
if (activePresentation instanceof IStatefulControl) {
((IStatefulControl) activePresentation).restoreState(state);
}
}
// History
List<HistoryStateItem> getStateHistory() {
return stateHistory;
}
private void setNewState(DBSDataContainer dataContainer, @Nullable DBDDataFilter dataFilter) {
// Create filter copy to avoid modifications
dataFilter = new DBDDataFilter(dataFilter);
// Search in history
for (int i = 0; i < stateHistory.size(); i++) {
HistoryStateItem item = stateHistory.get(i);
if (item.dataContainer == dataContainer && CommonUtils.equalObjects(item.filter, dataFilter)) {
curState = item;
historyPosition = i;
return;
}
}
// Save current state in history
while (historyPosition < stateHistory.size() - 1) {
stateHistory.remove(stateHistory.size() - 1);
}
curState = new HistoryStateItem(
dataContainer,
dataFilter,
curRow == null ? -1 : curRow.getVisualNumber());
stateHistory.add(curState);
historyPosition = stateHistory.size() - 1;
}
public void resetHistory() {
curState = null;
stateHistory.clear();
historyPosition = -1;
}
// Misc
@Nullable
public ResultSetRow getCurrentRow()
{
return curRow;
}
@Override
public void setCurrentRow(@Nullable ResultSetRow curRow) {
this.curRow = curRow;
if (curState != null && curRow != null) {
curState.rowNumber = curRow.getVisualNumber();
}
// if (recordMode) {
// updateRecordMode();
}
// Status
public void setStatus(String status)
{
setStatus(status, false);
}
public void setStatus(String status, boolean error)
{
if (statusLabel.isDisposed()) {
return;
}
if (error) {
statusLabel.setForeground(colorRed);
} else if (colorRed.equals(statusLabel.getForeground())) {
statusLabel.setForeground(getDefaultForeground());
}
if (status == null) {
status = "???"; //$NON-NLS-1$
}
statusLabel.setText(status);
}
public void updateStatusMessage()
{
if (model.getRowCount() == 0) {
if (model.getVisibleAttributeCount() == 0) {
setStatus(CoreMessages.controls_resultset_viewer_status_empty + getExecutionTimeMessage());
} else {
setStatus(CoreMessages.controls_resultset_viewer_status_no_data + getExecutionTimeMessage());
}
} else {
if (recordMode) {
setStatus(CoreMessages.controls_resultset_viewer_status_row + (curRow == null ? 0 : curRow.getVisualNumber() + 1) + "/" + model.getRowCount() + getExecutionTimeMessage());
} else {
setStatus(String.valueOf(model.getRowCount()) + CoreMessages.controls_resultset_viewer_status_rows_fetched + getExecutionTimeMessage());
}
}
}
private String getExecutionTimeMessage()
{
DBCStatistics statistics = model.getStatistics();
if (statistics == null || statistics.isEmpty()) {
return "";
}
return " - " + RuntimeUtils.formatExecutionTime(statistics.getTotalTime());
}
/**
* Sets new metadata of result set
* @param attributes attributes metadata
*/
void setMetaData(DBDAttributeBinding[] attributes)
{
model.setMetaData(attributes);
activePresentation.clearMetaData();
}
void setData(List<Object[]> rows)
{
if (viewerPanel.isDisposed()) {
return;
}
this.curRow = null;
this.model.setData(rows);
this.curRow = (this.model.getRowCount() > 0 ? this.model.getRow(0) : null);
{
if (getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_AUTO_SWITCH_MODE)) {
boolean newRecordMode = (rows.size() == 1);
if (newRecordMode != recordMode) {
toggleMode();
// ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CAN_TOGGLE);
}
}
}
this.activePresentation.refreshData(true, false);
if (recordMode) {
this.updateRecordMode();
}
this.updateFiltersText();
this.updateStatusMessage();
this.updateEditControls();
}
void appendData(List<Object[]> rows)
{
model.appendData(rows);
//redrawData(true);
activePresentation.refreshData(false, true);
setStatus(NLS.bind(CoreMessages.controls_resultset_viewer_status_rows_size, model.getRowCount(), rows.size()) + getExecutionTimeMessage());
updateEditControls();
}
@Override
public int promptToSaveOnClose()
{
if (!isDirty()) {
return ISaveablePart2.YES;
}
int result = ConfirmationDialog.showConfirmDialog(
viewerPanel.getShell(),
DBeaverPreferences.CONFIRM_RS_EDIT_CLOSE,
ConfirmationDialog.QUESTION_WITH_CANCEL);
if (result == IDialogConstants.YES_ID) {
return ISaveablePart2.YES;
} else if (result == IDialogConstants.NO_ID) {
rejectChanges();
return ISaveablePart2.NO;
} else {
return ISaveablePart2.CANCEL;
}
}
@Override
public void doSave(IProgressMonitor monitor)
{
applyChanges(RuntimeUtils.makeMonitor(monitor));
}
public void doSave(DBRProgressMonitor monitor)
{
applyChanges(monitor);
}
@Override
public void doSaveAs()
{
}
@Override
public boolean isDirty()
{
return model.isDirty();
}
@Override
public boolean isSaveAsAllowed()
{
return false;
}
@Override
public boolean isSaveOnCloseNeeded()
{
return true;
}
@Override
public boolean hasData()
{
return model.hasData();
}
@Override
public boolean isHasMoreData() {
return getExecutionContext() != null && dataReceiver.isHasMoreData();
}
@Override
public boolean isReadOnly()
{
if (model.isUpdateInProgress() || !(activePresentation instanceof IResultSetEditor)) {
return true;
}
DBCExecutionContext executionContext = getExecutionContext();
return
executionContext == null ||
!executionContext.isConnected() ||
executionContext.getDataSource().getContainer().isConnectionReadOnly() ||
executionContext.getDataSource().getInfo().isReadOnlyData();
}
/**
* Checks that current state of result set allows to insert new rows
* @return true if new rows insert is allowed
*/
public boolean isInsertable()
{
return
!isReadOnly() &&
model.isSingleSource() &&
model.getVisibleAttributeCount() > 0;
}
public boolean isRefreshInProgress() {
return dataPumpJob != null;
}
// Context menu & filters
@NotNull
public static IResultSetFilterManager getFilterManager() {
return filterManager;
}
public static void registerFilterManager(@Nullable IResultSetFilterManager filterManager) {
if (filterManager == null) {
filterManager = new SimpleFilterManager();
}
ResultSetViewer.filterManager = filterManager;
}
public void showFiltersMenu() {
DBDAttributeBinding curAttribute = getActivePresentation().getCurrentAttribute();
if (curAttribute == null) {
return;
}
Control control = getActivePresentation().getControl();
Point cursorLocation = getActivePresentation().getCursorLocation();
Point location = control.getDisplay().map(control, null, cursorLocation);
MenuManager menuManager = new MenuManager();
fillFiltersMenu(curAttribute, menuManager);
final Menu contextMenu = menuManager.createContextMenu(control);
contextMenu.setLocation(location);
contextMenu.setVisible(true);
}
@Override
public void fillContextMenu(@NotNull IMenuManager manager, @Nullable final DBDAttributeBinding attr, @Nullable final ResultSetRow row)
{
final DBPDataSource dataSource = getDataContainer() == null ? null : getDataContainer().getDataSource();
// Custom oldValue items
final ResultSetValueController valueController;
if (attr != null && row != null) {
valueController = new ResultSetValueController(
this,
attr,
row,
IValueController.EditType.NONE,
null);
final Object value = valueController.getValue();
{
// Standard items
manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_CUT));
manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_COPY));
MenuManager extCopyMenu = new MenuManager(ActionUtils.findCommandName(CoreCommands.CMD_COPY_SPECIAL));
extCopyMenu.add(ActionUtils.makeCommandContribution(site, CoreCommands.CMD_COPY_SPECIAL));
extCopyMenu.add(new Action("Copy column name(s)") {
@Override
public void run() {
StringBuilder buffer = new StringBuilder();
for (DBDAttributeBinding attr : getSelection().getSelectedAttributes()) {
if (buffer.length() > 0) {
buffer.append("\t");
}
buffer.append(attr.getName());
}
ResultSetUtils.copyToClipboard(buffer.toString());
}
});
extCopyMenu.add(new Action("Copy row number(s)") {
@Override
public void run() {
StringBuilder buffer = new StringBuilder();
for (ResultSetRow row : getSelection().getSelectedRows()) {
if (buffer.length() > 0) {
buffer.append("\n");
}
buffer.append(row.getVisualNumber());
}
ResultSetUtils.copyToClipboard(buffer.toString());
}
});
manager.add(extCopyMenu);
manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_PASTE));
manager.add(ActionUtils.makeCommandContribution(site, CoreCommands.CMD_PASTE_SPECIAL));
manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_DELETE));
// Edit items
manager.add(new Separator());
manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT));
manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT_INLINE));
if (!valueController.isReadOnly() && !DBUtils.isNullValue(value)/* && !attr.isRequired()*/) {
manager.add(new Action(CoreMessages.controls_resultset_viewer_action_set_to_null) {
@Override
public void run()
{
valueController.updateValue(
BaseValueManager.makeNullValue(valueController));
}
});
}
manager.add(new GroupMarker(MENU_GROUP_EDIT));
}
// Menus from value handler
try {
manager.add(new Separator());
valueController.getValueManager().contributeActions(manager, valueController, null);
}
catch (Exception e) {
log.error(e);
}
if (row.isChanged()) {
Action resetValueAction = new Action(CoreMessages.controls_resultset_viewer_action_reset_value) {
@Override
public void run() {
model.resetCellValue(attr, row);
updatePanelsContent();
}
};
resetValueAction.setAccelerator(SWT.ESC);
manager.insertAfter(IResultSetController.MENU_GROUP_EDIT, resetValueAction);
}
} else {
valueController = null;
}
if (dataSource != null && attr != null && model.getVisibleAttributeCount() > 0 && !model.isUpdateInProgress()) {
// Filters and View
manager.add(new Separator());
{
String filtersShortcut = ActionUtils.findCommandDescription(ResultSetCommandHandler.CMD_FILTER_MENU, getSite(), true);
String menuName = CoreMessages.controls_resultset_viewer_action_order_filter;
if (!CommonUtils.isEmpty(filtersShortcut)) {
menuName += " (" + filtersShortcut + ")";
}
MenuManager filtersMenu = new MenuManager(
menuName,
DBeaverIcons.getImageDescriptor(UIIcon.FILTER),
"filters"); //$NON-NLS-1$
filtersMenu.setRemoveAllWhenShown(true);
filtersMenu.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
fillFiltersMenu(attr, manager);
}
});
manager.add(filtersMenu);
}
{
MenuManager viewMenu = new MenuManager(
"View/Format",
null,
"view"); //$NON-NLS-1$
List<? extends DBDAttributeTransformerDescriptor> transformers =
dataSource.getContainer().getApplication().getValueHandlerRegistry().findTransformers(
dataSource, attr, null);
if (!CommonUtils.isEmpty(transformers)) {
MenuManager transformersMenu = new MenuManager("View as");
transformersMenu.setRemoveAllWhenShown(true);
transformersMenu.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
fillAttributeTransformersMenu(manager, attr);
}
});
viewMenu.add(transformersMenu);
} else {
final Action customizeAction = new Action("View as") {};
customizeAction.setEnabled(false);
viewMenu.add(customizeAction);
}
if (getModel().isSingleSource()) {
if (valueController != null) {
viewMenu.add(new SetRowColorAction(attr, valueController.getValue()));
if (getModel().hasColorMapping(attr)) {
viewMenu.add(new ResetRowColorAction(attr, valueController.getValue()));
}
}
viewMenu.add(new CustomizeColorsAction(attr, row));
viewMenu.add(new Separator());
}
viewMenu.add(new Action("Data formats ...") {
@Override
public void run() {
UIUtils.showPreferencesFor(
getControl().getShell(),
null,
PrefPageDataFormat.PAGE_ID);
}
});
manager.add(viewMenu);
}
{
// Navigate
MenuManager navigateMenu = new MenuManager(
"Navigate",
null,
"navigate"); //$NON-NLS-1$
if (ActionUtils.isCommandEnabled(ResultSetCommandHandler.CMD_NAVIGATE_LINK, site)) {
navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_NAVIGATE_LINK));
navigateMenu.add(new Separator());
}
navigateMenu.add(new Separator());
navigateMenu.add(ActionUtils.makeCommandContribution(site, ITextEditorActionDefinitionIds.LINE_GOTO));
navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_FIRST));
navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_NEXT));
navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_PREVIOUS));
navigateMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_LAST));
manager.add(navigateMenu);
}
{
// Layout
MenuManager layoutMenu = new MenuManager(
"Layout",
null,
"layout"); //$NON-NLS-1$
layoutMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_MODE));
layoutMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_PANELS));
layoutMenu.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_SWITCH_PRESENTATION));
{
layoutMenu.add(new Separator());
for (IContributionItem item : fillPanelsMenu()) {
layoutMenu.add(item);
}
}
manager.add(layoutMenu);
}
manager.add(new Separator());
}
// Fill general menu
final DBSDataContainer dataContainer = getDataContainer();
if (dataContainer != null && model.hasData()) {
manager.add(new Action(CoreMessages.controls_resultset_viewer_action_export, DBeaverIcons.getImageDescriptor(UIIcon.EXPORT)) {
@Override
public void run() {
ActiveWizardDialog dialog = new ActiveWizardDialog(
site.getWorkbenchWindow(),
new DataTransferWizard(
new IDataTransferProducer[]{
new DatabaseTransferProducer(dataContainer, model.getDataFilter())},
null
),
getSelection()
);
dialog.open();
}
});
}
manager.add(new GroupMarker(CoreCommands.GROUP_TOOLS));
if (dataContainer != null && model.hasData()) {
manager.add(new Separator());
manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.FILE_REFRESH));
}
manager.add(new Separator());
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
}
private class TransformerAction extends Action {
private final DBDAttributeBinding attrribute;
public TransformerAction(DBDAttributeBinding attr, String text, int style, boolean checked) {
super(text, style);
this.attrribute = attr;
setChecked(checked);
}
@NotNull
DBVTransformSettings getTransformSettings() {
final DBVTransformSettings settings = DBVUtils.getTransformSettings(attrribute, true);
if (settings == null) {
throw new IllegalStateException("Can't get/create transformer settings for '" + attrribute.getFullQualifiedName() + "'");
}
return settings;
}
protected void saveTransformerSettings() {
attrribute.getDataSource().getContainer().persistConfiguration();
refreshData(null);
}
}
private void fillAttributeTransformersMenu(IMenuManager manager, final DBDAttributeBinding attr) {
final DBSDataContainer dataContainer = getDataContainer();
if (dataContainer == null) {
return;
}
final DBPDataSource dataSource = dataContainer.getDataSource();
final DBDRegistry registry = dataSource.getContainer().getApplication().getValueHandlerRegistry();
final DBVTransformSettings transformSettings = DBVUtils.getTransformSettings(attr, false);
DBDAttributeTransformerDescriptor customTransformer = null;
if (transformSettings != null && transformSettings.getCustomTransformer() != null) {
customTransformer = registry.getTransformer(transformSettings.getCustomTransformer());
}
List<? extends DBDAttributeTransformerDescriptor> customTransformers =
registry.findTransformers(dataSource, attr, true);
if (customTransformers != null && !customTransformers.isEmpty()) {
manager.add(new TransformerAction(
attr,
"Default",
IAction.AS_RADIO_BUTTON,
transformSettings == null || CommonUtils.isEmpty(transformSettings.getCustomTransformer()))
{
@Override
public void run() {
if (isChecked()) {
getTransformSettings().setCustomTransformer(null);
saveTransformerSettings();
}
}
});
for (final DBDAttributeTransformerDescriptor descriptor : customTransformers) {
final TransformerAction action = new TransformerAction(
attr,
descriptor.getName(),
IAction.AS_RADIO_BUTTON,
transformSettings != null && descriptor.getId().equals(transformSettings.getCustomTransformer()))
{
@Override
public void run() {
if (isChecked()) {
final DBVTransformSettings settings = getTransformSettings();
final String oldCustomTransformer = settings.getCustomTransformer();
settings.setCustomTransformer(descriptor.getId());
TransformerSettingsDialog settingsDialog = new TransformerSettingsDialog(
ResultSetViewer.this, attr, settings);
if (settingsDialog.open() == IDialogConstants.OK_ID) {
saveTransformerSettings();
} else {
settings.setCustomTransformer(oldCustomTransformer);
}
}
}
};
manager.add(action);
}
}
if (customTransformer != null && !CommonUtils.isEmpty(customTransformer.getProperties())) {
manager.add(new TransformerAction(attr, "Settings ...", IAction.AS_UNSPECIFIED, false) {
@Override
public void run() {
TransformerSettingsDialog settingsDialog = new TransformerSettingsDialog(
ResultSetViewer.this, attr, transformSettings);
if (settingsDialog.open() == IDialogConstants.OK_ID) {
saveTransformerSettings();
}
}
});
}
List<? extends DBDAttributeTransformerDescriptor> applicableTransformers =
registry.findTransformers(dataSource, attr, false);
if (applicableTransformers != null) {
manager.add(new Separator());
for (final DBDAttributeTransformerDescriptor descriptor : applicableTransformers) {
boolean checked;
if (transformSettings != null) {
if (descriptor.isApplicableByDefault()) {
checked = !transformSettings.isExcluded(descriptor.getId());
} else {
checked = transformSettings.isIncluded(descriptor.getId());
}
} else {
checked = descriptor.isApplicableByDefault();
}
manager.add(new TransformerAction(attr, descriptor.getName(), IAction.AS_CHECK_BOX, checked) {
@Override
public void run() {
getTransformSettings().enableTransformer(descriptor, !isChecked());
saveTransformerSettings();
}
});
}
}
}
private void fillFiltersMenu(@NotNull DBDAttributeBinding attribute, @NotNull IMenuManager filtersMenu)
{
if (supportsDataFilter()) {
//filtersMenu.add(new FilterByListAction(operator, type, attribute));
DBCLogicalOperator[] operators = attribute.getValueHandler().getSupportedOperators(attribute);
// Operators with multiple inputs
for (DBCLogicalOperator operator : operators) {
if (operator.getArgumentCount() < 0) {
filtersMenu.add(new FilterByAttributeAction(operator, FilterByAttributeType.INPUT, attribute));
}
}
filtersMenu.add(new Separator());
// Operators with no inputs
for (DBCLogicalOperator operator : operators) {
if (operator.getArgumentCount() == 0) {
filtersMenu.add(new FilterByAttributeAction(operator, FilterByAttributeType.NONE, attribute));
}
}
for (FilterByAttributeType type : FilterByAttributeType.values()) {
if (type == FilterByAttributeType.NONE) {
// Value filters are available only if certain cell is selected
continue;
}
filtersMenu.add(new Separator());
if (type.getValue(this, attribute, DBCLogicalOperator.EQUALS, true) == null) {
// Null cell value - no operators can be applied
continue;
}
for (DBCLogicalOperator operator : operators) {
if (operator.getArgumentCount() > 0) {
filtersMenu.add(new FilterByAttributeAction(operator, type, attribute));
}
}
}
filtersMenu.add(new Separator());
DBDAttributeConstraint constraint = model.getDataFilter().getConstraint(attribute);
if (constraint != null && constraint.hasCondition()) {
filtersMenu.add(new FilterResetAttributeAction(attribute));
}
}
filtersMenu.add(new Separator());
filtersMenu.add(new ToggleServerSideOrderingAction());
filtersMenu.add(new ShowFiltersAction(true));
}
@Override
public void navigateAssociation(@NotNull DBRProgressMonitor monitor, @NotNull DBDAttributeBinding attr, @NotNull ResultSetRow row, boolean newWindow)
throws DBException
{
if (getExecutionContext() == null) {
throw new DBException("Not connected");
}
DBSEntityAssociation association = null;
List<DBSEntityReferrer> referrers = attr.getReferrers();
if (referrers != null) {
for (final DBSEntityReferrer referrer : referrers) {
if (referrer instanceof DBSEntityAssociation) {
association = (DBSEntityAssociation) referrer;
break;
}
}
}
if (association == null) {
throw new DBException("Association not found in attribute [" + attr.getName() + "]");
}
DBSEntityConstraint refConstraint = association.getReferencedConstraint();
if (refConstraint == null) {
throw new DBException("Broken association (referenced constraint missing)");
}
if (!(refConstraint instanceof DBSEntityReferrer)) {
throw new DBException("Referenced constraint [" + refConstraint + "] is not a referrer");
}
DBSEntity targetEntity = refConstraint.getParentObject();
if (targetEntity == null) {
throw new DBException("Null constraint parent");
}
if (!(targetEntity instanceof DBSDataContainer)) {
throw new DBException("Entity [" + DBUtils.getObjectFullName(targetEntity) + "] is not a data container");
}
// make constraints
List<DBDAttributeConstraint> constraints = new ArrayList<>();
int visualPosition = 0;
// Set conditions
List<? extends DBSEntityAttributeRef> ownAttrs = CommonUtils.safeList(((DBSEntityReferrer) association).getAttributeReferences(monitor));
List<? extends DBSEntityAttributeRef> refAttrs = CommonUtils.safeList(((DBSEntityReferrer) refConstraint).getAttributeReferences(monitor));
if (ownAttrs.size() != refAttrs.size()) {
throw new DBException(
"Entity [" + DBUtils.getObjectFullName(targetEntity) + "] association [" + association.getName() +
"] columns differs from referenced constraint [" + refConstraint.getName() + "] (" + ownAttrs.size() + "<>" + refAttrs.size() + ")");
}
// Add association constraints
for (int i = 0; i < ownAttrs.size(); i++) {
DBSEntityAttributeRef ownAttr = ownAttrs.get(i);
DBSEntityAttributeRef refAttr = refAttrs.get(i);
DBDAttributeBinding ownBinding = model.getAttributeBinding(ownAttr.getAttribute());
assert ownBinding != null;
DBDAttributeConstraint constraint = new DBDAttributeConstraint(refAttr.getAttribute(), visualPosition++);
constraint.setVisible(true);
constraints.add(constraint);
Object keyValue = model.getCellValue(ownBinding, row);
constraint.setOperator(DBCLogicalOperator.EQUALS);
constraint.setValue(keyValue);
}
DBDDataFilter newFilter = new DBDDataFilter(constraints);
if (newWindow) {
openResultsInNewWindow(monitor, targetEntity, newFilter);
} else {
runDataPump((DBSDataContainer) targetEntity, newFilter, 0, getSegmentMaxRows(), -1, null);
}
}
private void openResultsInNewWindow(DBRProgressMonitor monitor, DBSEntity targetEntity, final DBDDataFilter newFilter) {
final DBNDatabaseNode targetNode = getExecutionContext().getDataSource().getContainer().getApplication().getNavigatorModel().getNodeByObject(monitor, targetEntity, false);
if (targetNode == null) {
UIUtils.showMessageBox(null, "Open link", "Can't navigate to '" + DBUtils.getObjectFullName(targetEntity) + "' - navigator node not found", SWT.ICON_ERROR);
return;
}
UIUtils.runInDetachedUI(null, new Runnable() {
@Override
public void run() {
openNewDataEditor(targetNode, newFilter);
}
});
}
@Override
public int getHistoryPosition() {
return historyPosition;
}
@Override
public int getHistorySize() {
return stateHistory.size();
}
@Override
public void navigateHistory(int position) {
if (position < 0 || position >= stateHistory.size()) {
// out of range
log.debug("Wrong history position: " + position);
return;
}
HistoryStateItem state = stateHistory.get(position);
int segmentSize = getSegmentMaxRows();
if (state.rowNumber >= 0 && state.rowNumber >= segmentSize && segmentSize > 0) {
segmentSize = (state.rowNumber / segmentSize + 1) * segmentSize;
}
runDataPump(state.dataContainer, state.filter, 0, segmentSize, state.rowNumber, null);
}
@Override
public void updatePanelsContent() {
updateEditControls();
for (IResultSetPanel panel : getActivePanels()) {
panel.refresh();
}
}
@Override
public Composite getControl()
{
return this.viewerPanel;
}
@NotNull
@Override
public IWorkbenchPartSite getSite()
{
return site;
}
@Override
@NotNull
public ResultSetModel getModel()
{
return model;
}
@Override
public ResultSetModel getInput()
{
return model;
}
@Override
public void setInput(Object input)
{
throw new IllegalArgumentException("ResultSet model can't be changed");
}
@Override
@NotNull
public IResultSetSelection getSelection()
{
if (activePresentation instanceof ISelectionProvider) {
ISelection selection = ((ISelectionProvider) activePresentation).getSelection();
if (selection instanceof IResultSetSelection) {
return (IResultSetSelection) selection;
} else {
log.debug("Bad selection type (" + selection + ") in presentation " + activePresentation);
}
}
return new EmptySelection();
}
@Override
public void setSelection(ISelection selection, boolean reveal)
{
if (activePresentation instanceof ISelectionProvider) {
((ISelectionProvider) activePresentation).setSelection(selection);
}
}
@NotNull
@Override
public DBDDataReceiver getDataReceiver() {
return dataReceiver;
}
@Nullable
@Override
public DBCExecutionContext getExecutionContext() {
return container.getExecutionContext();
}
@Override
public void refresh()
{
// Check if we are dirty
if (isDirty()) {
switch (promptToSaveOnClose()) {
case ISaveablePart2.CANCEL:
return;
case ISaveablePart2.YES:
// Apply changes
applyChanges(null, new ResultSetPersister.DataUpdateListener() {
@Override
public void onUpdate(boolean success) {
if (success) {
getControl().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
refresh();
}
});
}
}
});
return;
default:
// Just ignore previous RS values
break;
}
}
// Pump data
ResultSetRow oldRow = curRow;
DBSDataContainer dataContainer = getDataContainer();
if (container.isReadyToRun() && dataContainer != null && dataPumpJob == null) {
int segmentSize = getSegmentMaxRows();
if (oldRow != null && oldRow.getVisualNumber() >= segmentSize && segmentSize > 0) {
segmentSize = (oldRow.getVisualNumber() / segmentSize + 1) * segmentSize;
}
runDataPump(dataContainer, null, 0, segmentSize, oldRow == null ? -1 : oldRow.getVisualNumber(), new Runnable() {
@Override
public void run()
{
activePresentation.formatData(true);
}
});
} else {
UIUtils.showErrorDialog(
null,
"Error executing query",
dataContainer == null ?
"Viewer detached from data source" :
dataPumpJob == null ?
"Can't refresh after reconnect. Re-execute query." :
"Previous query is still running");
}
}
public void refreshWithFilter(DBDDataFilter filter) {
DBSDataContainer dataContainer = getDataContainer();
if (dataContainer != null) {
runDataPump(
dataContainer,
filter,
0,
getSegmentMaxRows(),
-1,
null);
}
}
@Override
public boolean refreshData(@Nullable Runnable onSuccess) {
DBSDataContainer dataContainer = getDataContainer();
if (container.isReadyToRun() && dataContainer != null && dataPumpJob == null) {
int segmentSize = getSegmentMaxRows();
if (curRow != null && curRow.getVisualNumber() >= segmentSize && segmentSize > 0) {
segmentSize = (curRow.getVisualNumber() / segmentSize + 1) * segmentSize;
}
return runDataPump(dataContainer, null, 0, segmentSize, -1, onSuccess);
} else {
return false;
}
}
public synchronized void readNextSegment()
{
if (!dataReceiver.isHasMoreData()) {
return;
}
DBSDataContainer dataContainer = getDataContainer();
if (dataContainer != null && !model.isUpdateInProgress() && dataPumpJob == null) {
dataReceiver.setHasMoreData(false);
dataReceiver.setNextSegmentRead(true);
runDataPump(
dataContainer,
null,
model.getRowCount(),
getSegmentMaxRows(),
-1,//curRow == null ? -1 : curRow.getRowNumber(), // Do not reposition cursor after next segment read!
null);
}
}
@Override
public void readAllData() {
if (!dataReceiver.isHasMoreData()) {
return;
}
if (ConfirmationDialog.showConfirmDialogEx(
viewerPanel.getShell(),
DBeaverPreferences.CONFIRM_RS_FETCH_ALL,
ConfirmationDialog.QUESTION,
ConfirmationDialog.WARNING) != IDialogConstants.YES_ID)
{
return;
}
DBSDataContainer dataContainer = getDataContainer();
if (dataContainer != null && !model.isUpdateInProgress() && dataPumpJob == null) {
dataReceiver.setHasMoreData(false);
dataReceiver.setNextSegmentRead(true);
runDataPump(
dataContainer,
null,
model.getRowCount(),
-1,
curRow == null ? -1 : curRow.getRowNumber(),
null);
}
}
int getSegmentMaxRows()
{
if (getDataContainer() == null) {
return 0;
}
return getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS);
}
synchronized boolean runDataPump(
@NotNull final DBSDataContainer dataContainer,
@Nullable final DBDDataFilter dataFilter,
final int offset,
final int maxRows,
final int focusRow,
@Nullable final Runnable finalizer)
{
if (dataPumpJob != null) {
UIUtils.showMessageBox(viewerPanel.getShell(), "Data read", "Data read is in progress - can't run another", SWT.ICON_WARNING);
return false;
}
// Read data
final DBDDataFilter useDataFilter = dataFilter != null ? dataFilter :
(dataContainer == getDataContainer() ? model.getDataFilter() : null);
Composite progressControl = viewerPanel;
if (activePresentation.getControl() instanceof Composite) {
progressControl = (Composite) activePresentation.getControl();
}
final Object presentationState = savePresentationState();
dataPumpJob = new ResultSetDataPumpJob(
dataContainer,
useDataFilter,
this,
getExecutionContext(),
progressControl);
dataPumpJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void aboutToRun(IJobChangeEvent event) {
model.setUpdateInProgress(true);
getControl().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
filtersPanel.enableFilters(false);
}
});
}
@Override
public void done(IJobChangeEvent event) {
ResultSetDataPumpJob job = (ResultSetDataPumpJob)event.getJob();
final Throwable error = job.getError();
if (job.getStatistics() != null) {
model.setStatistics(job.getStatistics());
}
final Control control = getControl();
if (control.isDisposed()) {
return;
}
control.getDisplay().asyncExec(new Runnable() {
@Override
public void run()
{
try {
if (control.isDisposed()) {
return;
}
final Shell shell = control.getShell();
if (error != null) {
//setStatus(error.getMessage(), true);
UIUtils.showErrorDialog(
shell,
"Error executing query",
"Query execution failed",
error);
} else if (focusRow >= 0 && focusRow < model.getRowCount() && model.getVisibleAttributeCount() > 0) {
// Seems to be refresh
// Restore original position
curRow = model.getRow(focusRow);
//curAttribute = model.getVisibleAttribute(0);
if (recordMode) {
updateRecordMode();
} else {
updateStatusMessage();
}
restorePresentationState(presentationState);
}
activePresentation.updateValueView();
if (error == null) {
setNewState(dataContainer, dataFilter != null ? dataFilter :
(dataContainer == getDataContainer() ? model.getDataFilter() : null));
}
model.setUpdateInProgress(false);
if (error == null && dataFilter != null) {
model.updateDataFilter(dataFilter);
activePresentation.refreshData(true, false);
}
updateFiltersText(error == null);
updateToolbar();
fireResultSetLoad();
} finally {
if (finalizer != null) {
try {
finalizer.run();
} catch (Throwable e) {
log.error(e);
}
}
dataPumpJob = null;
}
}
});
}
});
dataPumpJob.setOffset(offset);
dataPumpJob.setMaxRows(maxRows);
dataPumpJob.schedule();
return true;
}
private void clearData()
{
this.model.clearData();
this.curRow = null;
this.activePresentation.clearMetaData();
}
@Override
public boolean applyChanges(@Nullable DBRProgressMonitor monitor)
{
return applyChanges(monitor, null);
}
/**
* Saves changes to database
* @param monitor monitor. If null then save will be executed in async job
* @param listener finish listener (may be null)
*/
public boolean applyChanges(@Nullable DBRProgressMonitor monitor, @Nullable ResultSetPersister.DataUpdateListener listener)
{
try {
ResultSetPersister persister = createDataPersister(false);
return persister.applyChanges(monitor, false, listener);
} catch (DBException e) {
UIUtils.showErrorDialog(null, "Apply changes error", "Error saving changes in database", e);
return false;
}
}
@Override
public void rejectChanges()
{
if (!isDirty()) {
return;
}
try {
createDataPersister(true).rejectChanges();
} catch (DBException e) {
log.debug(e);
}
}
@Override
public List<DBEPersistAction> generateChangesScript(@NotNull DBRProgressMonitor monitor)
{
try {
ResultSetPersister persister = createDataPersister(false);
persister.applyChanges(monitor, true, null);
return persister.getScript();
} catch (DBException e) {
UIUtils.showErrorDialog(null, "SQL script generate error", "Error saving changes in database", e);
return Collections.emptyList();
}
}
@NotNull
private ResultSetPersister createDataPersister(boolean skipKeySearch)
throws DBException
{
if (!skipKeySearch && !model.isSingleSource()) {
throw new DBException("Can't save data for result set from multiple sources");
}
boolean needPK = false;
if (!skipKeySearch) {
for (ResultSetRow row : model.getAllRows()) {
if (row.getState() == ResultSetRow.STATE_REMOVED || (row.getState() == ResultSetRow.STATE_NORMAL && row.isChanged())) {
needPK = true;
break;
}
}
}
if (needPK) {
// If we have deleted or updated rows then check for unique identifier
if (!checkEntityIdentifier()) {
throw new DBException("No unique identifier defined");
}
}
return new ResultSetPersister(this);
}
void addNewRow(final boolean copyCurrent, boolean afterCurrent)
{
int rowNum = curRow == null ? 0 : curRow.getVisualNumber();
if (rowNum >= model.getRowCount()) {
rowNum = model.getRowCount() - 1;
}
if (rowNum < 0) {
rowNum = 0;
}
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext == null) {
return;
}
// Add new row
final DBDAttributeBinding docAttribute = model.getDocumentAttribute();
final DBDAttributeBinding[] attributes = model.getAttributes();
final Object[] cells;
final int currentRowNumber = rowNum;
// Copy cell values in new context
try (DBCSession session = executionContext.openSession(VoidProgressMonitor.INSTANCE, DBCExecutionPurpose.UTIL, CoreMessages.controls_resultset_viewer_add_new_row_context_name)) {
if (docAttribute != null) {
cells = new Object[1];
if (copyCurrent && currentRowNumber >= 0 && currentRowNumber < model.getRowCount()) {
Object[] origRow = model.getRowData(currentRowNumber);
try {
cells[0] = docAttribute.getValueHandler().getValueFromObject(session, docAttribute, origRow[0], true);
} catch (DBCException e) {
log.warn(e);
}
}
if (cells[0] == null) {
try {
cells[0] = DBUtils.makeNullValue(session, docAttribute.getValueHandler(), docAttribute.getAttribute());
} catch (DBCException e) {
log.warn(e);
}
}
} else {
cells = new Object[attributes.length];
if (copyCurrent && currentRowNumber >= 0 && currentRowNumber < model.getRowCount()) {
Object[] origRow = model.getRowData(currentRowNumber);
for (int i = 0; i < attributes.length; i++) {
DBDAttributeBinding metaAttr = attributes[i];
DBSAttributeBase attribute = metaAttr.getAttribute();
if (attribute.isAutoGenerated() || attribute.isPseudoAttribute()) {
// set pseudo and autoincrement attributes to null
cells[i] = null;
} else {
try {
cells[i] = metaAttr.getValueHandler().getValueFromObject(session, attribute, origRow[i], true);
} catch (DBCException e) {
log.warn(e);
try {
cells[i] = DBUtils.makeNullValue(session, metaAttr.getValueHandler(), attribute);
} catch (DBCException e1) {
log.warn(e1);
}
}
}
}
} else {
// Initialize new values
for (int i = 0; i < attributes.length; i++) {
DBDAttributeBinding metaAttr = attributes[i];
try {
cells[i] = DBUtils.makeNullValue(session, metaAttr.getValueHandler(), metaAttr.getAttribute());
} catch (DBCException e) {
log.warn(e);
}
}
}
}
}
curRow = model.addNewRow(afterCurrent ? rowNum + 1 : rowNum, cells);
redrawData(true);
updateEditControls();
fireResultSetChange();
}
void deleteSelectedRows()
{
Set<ResultSetRow> rowsToDelete = new LinkedHashSet<>();
if (recordMode) {
rowsToDelete.add(curRow);
} else {
IResultSetSelection selection = getSelection();
if (!selection.isEmpty()) {
rowsToDelete.addAll(selection.getSelectedRows());
}
}
if (rowsToDelete.isEmpty()) {
return;
}
int rowsRemoved = 0;
int lastRowNum = -1;
for (ResultSetRow row : rowsToDelete) {
if (model.deleteRow(row)) {
rowsRemoved++;
}
lastRowNum = row.getVisualNumber();
}
redrawData(rowsRemoved > 0);
// Move one row down (if we are in grid mode)
if (!recordMode && lastRowNum < model.getRowCount() - 1) {
activePresentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT);
}
updateEditControls();
fireResultSetChange();
}
// Virtual identifier management
@Nullable
DBDRowIdentifier getVirtualEntityIdentifier()
{
if (!model.isSingleSource() || model.getVisibleAttributeCount() == 0) {
return null;
}
DBDRowIdentifier rowIdentifier = model.getVisibleAttribute(0).getRowIdentifier();
DBSEntityReferrer identifier = rowIdentifier == null ? null : rowIdentifier.getUniqueKey();
if (identifier != null && identifier instanceof DBVEntityConstraint) {
return rowIdentifier;
} else {
return null;
}
}
boolean checkEntityIdentifier() throws DBException
{
DBSEntity entity = model.getSingleSource();
if (entity == null) {
UIUtils.showErrorDialog(
null,
"Unrecognized entity",
"Can't detect source entity");
return false;
}
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext == null) {
return false;
}
// Check for value locators
// Probably we have only virtual one with empty attribute set
final DBDRowIdentifier identifier = getVirtualEntityIdentifier();
if (identifier != null) {
if (CommonUtils.isEmpty(identifier.getAttributes())) {
// Empty identifier. We have to define it
RunnableWithResult<Boolean> confirmer = new RunnableWithResult<Boolean>() {
@Override
public void run()
{
result = ValidateUniqueKeyUsageDialog.validateUniqueKey(ResultSetViewer.this, executionContext);
}
};
UIUtils.runInUI(null, confirmer);
return confirmer.getResult();
}
}
{
// Check attributes of non-virtual identifier
DBDRowIdentifier rowIdentifier = model.getVisibleAttribute(0).getRowIdentifier();
if (rowIdentifier == null) {
// We shouldn't be here ever!
// Virtual id should be created if we missing natural one
UIUtils.showErrorDialog(
null,
"No entity identifier",
"Entity " + entity.getName() + " has no unique key");
return false;
} else if (CommonUtils.isEmpty(rowIdentifier.getAttributes())) {
UIUtils.showErrorDialog(
null,
"No entity identifier",
"Attributes of '" + DBUtils.getObjectFullName(rowIdentifier.getUniqueKey()) + "' are missing in result set");
return false;
}
}
return true;
}
boolean editEntityIdentifier(DBRProgressMonitor monitor) throws DBException
{
DBDRowIdentifier virtualEntityIdentifier = getVirtualEntityIdentifier();
if (virtualEntityIdentifier == null) {
log.warn("No virtual identifier");
return false;
}
DBVEntityConstraint constraint = (DBVEntityConstraint) virtualEntityIdentifier.getUniqueKey();
EditConstraintDialog dialog = new EditConstraintDialog(
getControl().getShell(),
"Define virtual unique identifier",
constraint);
if (dialog.open() != IDialogConstants.OK_ID) {
return false;
}
Collection<DBSEntityAttribute> uniqueAttrs = dialog.getSelectedAttributes();
constraint.setAttributes(uniqueAttrs);
virtualEntityIdentifier = getVirtualEntityIdentifier();
if (virtualEntityIdentifier == null) {
log.warn("No virtual identifier defined");
return false;
}
virtualEntityIdentifier.reloadAttributes(monitor, model.getAttributes());
persistConfig();
return true;
}
void clearEntityIdentifier(DBRProgressMonitor monitor) throws DBException
{
DBDAttributeBinding firstAttribute = model.getVisibleAttribute(0);
DBDRowIdentifier rowIdentifier = firstAttribute.getRowIdentifier();
if (rowIdentifier != null) {
DBVEntityConstraint virtualKey = (DBVEntityConstraint) rowIdentifier.getUniqueKey();
virtualKey.setAttributes(Collections.<DBSEntityAttribute>emptyList());
rowIdentifier.reloadAttributes(monitor, model.getAttributes());
virtualKey.getParentObject().setProperty(DBVConstants.PROPERTY_USE_VIRTUAL_KEY_QUIET, null);
}
persistConfig();
}
public void fireResultSetChange() {
synchronized (listeners) {
if (!listeners.isEmpty()) {
for (IResultSetListener listener : listeners) {
listener.handleResultSetChange();
}
}
}
}
public void fireResultSetLoad() {
synchronized (listeners) {
if (!listeners.isEmpty()) {
for (IResultSetListener listener : listeners) {
listener.handleResultSetLoad();
}
}
}
}
private static class SimpleFilterManager implements IResultSetFilterManager {
private final Map<String, List<String>> filterHistory = new HashMap<>();
@NotNull
@Override
public List<String> getQueryFilterHistory(@NotNull String query) throws DBException {
final List<String> filters = filterHistory.get(query);
if (filters != null) {
return filters;
}
return Collections.emptyList();
}
@Override
public void saveQueryFilterValue(@NotNull String query, @NotNull String filterValue) throws DBException {
List<String> filters = filterHistory.get(query);
if (filters == null) {
filters = new ArrayList<>();
filterHistory.put(query, filters);
}
filters.add(filterValue);
}
@Override
public void deleteQueryFilterValue(@NotNull String query, String filterValue) throws DBException {
List<String> filters = filterHistory.get(query);
if (filters != null) {
filters.add(filterValue);
}
}
}
private class EmptySelection extends StructuredSelection implements IResultSetSelection {
@NotNull
@Override
public IResultSetController getController() {
return ResultSetViewer.this;
}
@NotNull
@Override
public Collection<DBDAttributeBinding> getSelectedAttributes() {
return Collections.emptyList();
}
@NotNull
@Override
public Collection<ResultSetRow> getSelectedRows() {
return Collections.emptyList();
}
@Override
public DBDAttributeBinding getElementAttribute(Object element) {
return null;
}
@Override
public ResultSetRow getElementRow(Object element) {
return null;
}
}
public static class PanelsMenuContributor extends CompoundContributionItem
{
@Override
protected IContributionItem[] getContributionItems() {
final ResultSetViewer rsv = (ResultSetViewer) ResultSetCommandHandler.getActiveResultSet(
DBeaverUI.getActiveWorkbenchWindow().getActivePage().getActivePart());
if (rsv == null) {
return new IContributionItem[0];
}
List<IContributionItem> items = rsv.fillPanelsMenu();
return items.toArray(new IContributionItem[items.size()]);
}
}
private class ConfigAction extends Action implements IMenuCreator {
public ConfigAction()
{
super(CoreMessages.controls_resultset_viewer_action_options, IAction.AS_DROP_DOWN_MENU);
setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.CONFIGURATION));
}
@Override
public IMenuCreator getMenuCreator()
{
return this;
}
@Override
public void runWithEvent(Event event)
{
Menu menu = getMenu(activePresentation.getControl());
if (menu != null && event.widget instanceof ToolItem) {
Rectangle bounds = ((ToolItem) event.widget).getBounds();
Point point = ((ToolItem) event.widget).getParent().toDisplay(bounds.x, bounds.y + bounds.height);
menu.setLocation(point.x, point.y);
menu.setVisible(true);
}
}
@Override
public void dispose()
{
}
@Override
public Menu getMenu(Control parent)
{
MenuManager menuManager = new MenuManager();
menuManager.add(new ShowFiltersAction(false));
menuManager.add(new CustomizeColorsAction());
menuManager.add(new Separator());
menuManager.add(new VirtualKeyEditAction(true));
menuManager.add(new VirtualKeyEditAction(false));
menuManager.add(new DictionaryEditAction());
menuManager.add(new Separator());
menuManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_MODE, CommandContributionItem.STYLE_CHECK));
activePresentation.fillMenu(menuManager);
if (!CommonUtils.isEmpty(availablePresentations) && availablePresentations.size() > 1) {
menuManager.add(new Separator());
for (final ResultSetPresentationDescriptor pd : availablePresentations) {
Action action = new Action(pd.getLabel(), IAction.AS_RADIO_BUTTON) {
@Override
public boolean isEnabled() {
return !isRefreshInProgress();
}
@Override
public boolean isChecked() {
return pd == activePresentationDescriptor;
}
@Override
public void run() {
switchPresentation(pd);
}
};
if (pd.getIcon() != null) {
//action.setImageDescriptor(ImageDescriptor.createFromImage(pd.getIcon()));
}
menuManager.add(action);
}
}
menuManager.add(new Separator());
menuManager.add(new Action("Preferences") {
@Override
public void run()
{
UIUtils.showPreferencesFor(
getControl().getShell(),
ResultSetViewer.this,
PrefPageDatabaseGeneral.PAGE_ID);
}
});
return menuManager.createContextMenu(parent);
}
@Nullable
@Override
public Menu getMenu(Menu parent)
{
return null;
}
}
private class ShowFiltersAction extends Action {
public ShowFiltersAction(boolean context)
{
super(context ? "Customize ..." : "Order/Filter ...", DBeaverIcons.getImageDescriptor(UIIcon.FILTER));
}
@Override
public void run()
{
new FilterSettingsDialog(ResultSetViewer.this).open();
}
}
private class ToggleServerSideOrderingAction extends Action {
public ToggleServerSideOrderingAction()
{
super(CoreMessages.pref_page_database_resultsets_label_server_side_order);
}
@Override
public int getStyle()
{
return AS_CHECK_BOX;
}
@Override
public boolean isChecked()
{
return getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE);
}
@Override
public void run()
{
DBPPreferenceStore preferenceStore = getPreferenceStore();
preferenceStore.setValue(
DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE,
!preferenceStore.getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE));
}
}
private enum FilterByAttributeType {
VALUE(UIIcon.FILTER_VALUE) {
@Override
Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault)
{
final ResultSetRow row = viewer.getCurrentRow();
if (attribute == null || row == null) {
return null;
}
Object cellValue = viewer.model.getCellValue(attribute, row);
if (operator == DBCLogicalOperator.LIKE && cellValue != null) {
cellValue = "%" + cellValue + "%";
}
return cellValue;
}
},
INPUT(UIIcon.FILTER_INPUT) {
@Override
Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault)
{
if (useDefault) {
return "..";
} else {
ResultSetRow[] rows = null;
if (operator.getArgumentCount() < 0) {
Collection<ResultSetRow> selectedRows = viewer.getSelection().getSelectedRows();
rows = selectedRows.toArray(new ResultSetRow[selectedRows.size()]);
} else {
ResultSetRow focusRow = viewer.getCurrentRow();
if (focusRow != null) {
rows = new ResultSetRow[] { focusRow };
}
}
if (rows == null || rows.length == 0) {
return null;
}
FilterValueEditDialog dialog = new FilterValueEditDialog(viewer, attribute, rows, operator);
if (dialog.open() == IDialogConstants.OK_ID) {
return dialog.getValue();
} else {
return null;
}
}
}
},
CLIPBOARD(UIIcon.FILTER_CLIPBOARD) {
@Override
Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault)
{
try {
return ResultSetUtils.getAttributeValueFromClipboard(attribute);
} catch (DBCException e) {
log.debug("Error copying from clipboard", e);
return null;
}
}
},
NONE(UIIcon.FILTER_VALUE) {
@Override
Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault)
{
return null;
}
};
final ImageDescriptor icon;
FilterByAttributeType(DBPImage icon)
{
this.icon = DBeaverIcons.getImageDescriptor(icon);
}
@Nullable
abstract Object getValue(@NotNull ResultSetViewer viewer, @NotNull DBDAttributeBinding attribute, @NotNull DBCLogicalOperator operator, boolean useDefault);
}
private String translateFilterPattern(DBCLogicalOperator operator, FilterByAttributeType type, DBDAttributeBinding attribute)
{
Object value = type.getValue(this, attribute, operator, true);
DBCExecutionContext executionContext = getExecutionContext();
String strValue = executionContext == null ? String.valueOf(value) : attribute.getValueHandler().getValueDisplayString(attribute, value, DBDDisplayFormat.UI);
if (operator.getArgumentCount() == 0) {
return operator.getStringValue();
} else {
return operator.getStringValue() + " " + CommonUtils.truncateString(strValue, 64);
}
}
private class FilterByAttributeAction extends Action {
private final DBCLogicalOperator operator;
private final FilterByAttributeType type;
private final DBDAttributeBinding attribute;
public FilterByAttributeAction(DBCLogicalOperator operator, FilterByAttributeType type, DBDAttributeBinding attribute)
{
super(attribute.getName() + " " + translateFilterPattern(operator, type, attribute), type.icon);
this.operator = operator;
this.type = type;
this.attribute = attribute;
}
@Override
public void run()
{
Object value = type.getValue(ResultSetViewer.this, attribute, operator, false);
if (operator.getArgumentCount() != 0 && value == null) {
return;
}
DBDDataFilter filter = new DBDDataFilter(model.getDataFilter());
DBDAttributeConstraint constraint = filter.getConstraint(attribute);
if (constraint != null) {
constraint.setOperator(operator);
constraint.setValue(value);
setDataFilter(filter, true);
}
}
}
private class FilterResetAttributeAction extends Action {
private final DBDAttributeBinding attribute;
public FilterResetAttributeAction(DBDAttributeBinding attribute)
{
super("Remove filter for '" + attribute.getName() + "'", DBeaverIcons.getImageDescriptor(UIIcon.REVERT));
this.attribute = attribute;
}
@Override
public void run()
{
DBDDataFilter dataFilter = new DBDDataFilter(model.getDataFilter());
DBDAttributeConstraint constraint = dataFilter.getConstraint(attribute);
if (constraint != null) {
constraint.setCriteria(null);
setDataFilter(dataFilter, true);
}
}
}
private abstract class ColorAction extends Action {
protected ColorAction(String name) {
super(name);
}
@NotNull
protected DBVEntity getVirtualEntity(DBDAttributeBinding binding) {
final DBSEntity entity = getModel().getSingleSource();
if (entity == null) {
throw new IllegalStateException("No virtual entity for multi-source query");
}
final DBVEntity vEntity = DBVUtils.findVirtualEntity(entity, true);
assert vEntity != null;
return vEntity;
}
protected void updateColors(DBVEntity entity) {
model.updateColorMapping();
redrawData(false);
entity.getDataSource().getContainer().persistConfiguration();
}
}
private class SetRowColorAction extends ColorAction {
private final DBDAttributeBinding attribute;
private final Object value;
public SetRowColorAction(DBDAttributeBinding attr, Object value) {
super("Color by " + attr.getName());
this.attribute = attr;
this.value = value;
}
@Override
public void run() {
RGB color;
final Shell shell = UIUtils.createCenteredShell(getControl().getShell());
try {
ColorDialog cd = new ColorDialog(shell);
color = cd.open();
if (color == null) {
return;
}
} finally {
shell.dispose();
}
final DBVEntity vEntity = getVirtualEntity(attribute);
vEntity.setColorOverride(attribute, value, null, StringConverter.asString(color));
updateColors(vEntity);
}
}
private class ResetRowColorAction extends ColorAction {
private final DBDAttributeBinding attribute;
public ResetRowColorAction(DBDAttributeBinding attr, Object value) {
super("Reset color by " + attr.getName());
this.attribute = attr;
}
@Override
public void run() {
final DBVEntity vEntity = getVirtualEntity(attribute);
vEntity.removeColorOverride(attribute);
updateColors(vEntity);
}
}
private class CustomizeColorsAction extends ColorAction {
private final DBDAttributeBinding curAttribute;
private final ResultSetRow row;
public CustomizeColorsAction() {
this(null, null);
}
public CustomizeColorsAction(DBDAttributeBinding curAttribute, ResultSetRow row) {
super("Row colors ...");
this.curAttribute = curAttribute;
this.row = row;
}
@Override
public void run() {
ColorSettingsDialog dialog = new ColorSettingsDialog(ResultSetViewer.this, curAttribute, row);
if (dialog.open() != IDialogConstants.OK_ID) {
return;
}
final DBVEntity vEntity = getVirtualEntity(curAttribute);
//vEntity.removeColorOverride(attribute);
updateColors(vEntity);
}
@Override
public boolean isEnabled() {
return false;
}
}
private class VirtualKeyEditAction extends Action {
private boolean define;
public VirtualKeyEditAction(boolean define)
{
super(define ? "Define virtual unique key" : "Clear virtual unique key");
this.define = define;
}
@Override
public boolean isEnabled()
{
DBDRowIdentifier identifier = getVirtualEntityIdentifier();
return identifier != null && (define || !CommonUtils.isEmpty(identifier.getAttributes()));
}
@Override
public void run()
{
DBeaverUI.runUIJob("Edit virtual key", new DBRRunnableWithProgress() {
@Override
public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (define) {
editEntityIdentifier(monitor);
} else {
clearEntityIdentifier(monitor);
}
} catch (DBException e) {
throw new InvocationTargetException(e);
}
}
});
}
}
private class DictionaryEditAction extends Action {
public DictionaryEditAction()
{
super("Define dictionary");
}
@Override
public void run()
{
EditDictionaryDialog dialog = new EditDictionaryDialog(
getSite().getShell(),
"Edit dictionary",
model.getSingleSource());
dialog.open();
}
@Override
public boolean isEnabled()
{
final DBSEntity singleSource = model.getSingleSource();
return singleSource != null;
}
}
private class PresentationSwitchCombo extends ContributionItem implements SelectionListener {
private ToolItem toolitem;
private CImageCombo combo;
@Override
public void fill(ToolBar parent, int index) {
toolitem = new ToolItem(parent, SWT.SEPARATOR, index);
Control control = createControl(parent);
toolitem.setControl(control);
}
@Override
public void fill(Composite parent) {
createControl(parent);
}
protected Control createControl(Composite parent) {
combo = new CImageCombo(parent, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
combo.add(DBeaverIcons.getImage(DBIcon.TYPE_UNKNOWN), "", null, null);
final int textWidth = parent.getFont().getFontData()[0].getHeight() * 10;
combo.setWidthHint(textWidth);
if (toolitem != null) {
toolitem.setWidth(textWidth);
}
combo.addSelectionListener(this);
combo.setToolTipText(ActionUtils.findCommandDescription(ResultSetCommandHandler.CMD_SWITCH_PRESENTATION, getSite(), false));
return combo;
}
@Override
public void widgetSelected(SelectionEvent e) {
ResultSetPresentationDescriptor selectedPresentation = (ResultSetPresentationDescriptor) combo.getData(combo.getSelectionIndex());
if (activePresentationDescriptor == selectedPresentation) {
return;
}
switchPresentation(selectedPresentation);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
}
class HistoryStateItem {
DBSDataContainer dataContainer;
DBDDataFilter filter;
int rowNumber;
public HistoryStateItem(DBSDataContainer dataContainer, @Nullable DBDDataFilter filter, int rowNumber) {
this.dataContainer = dataContainer;
this.filter = filter;
this.rowNumber = rowNumber;
}
public String describeState() {
DBCExecutionContext context = getExecutionContext();
String desc = dataContainer.getName();
if (context != null && filter != null && filter.hasConditions()) {
StringBuilder condBuffer = new StringBuilder();
SQLUtils.appendConditionString(filter, context.getDataSource(), null, condBuffer, true);
desc += " [" + condBuffer + "]";
}
return desc;
}
}
static class PresentationSettings {
Set<String> enabledPanelIds = new HashSet<>();
String activePanelId;
int panelRatio;
boolean panelsVisible;
}
public static void openNewDataEditor(DBNDatabaseNode targetNode, DBDDataFilter newFilter) {
IEditorPart entityEditor = NavigatorHandlerObjectOpen.openEntityEditor(
targetNode,
DatabaseDataEditor.class.getName(),
Collections.<String, Object>singletonMap(DatabaseDataEditor.ATTR_DATA_FILTER, newFilter),
DBeaverUI.getActiveWorkbenchWindow()
);
if (entityEditor instanceof MultiPageEditorPart) {
Object selectedPage = ((MultiPageEditorPart) entityEditor).getSelectedPage();
if (selectedPage instanceof IResultSetContainer) {
ResultSetViewer rsv = (ResultSetViewer) ((IResultSetContainer) selectedPage).getResultSetController();
if (rsv != null && !rsv.isRefreshInProgress() && !newFilter.equals(rsv.getModel().getDataFilter())) {
// Set filter directly
rsv.refreshWithFilter(newFilter);
}
}
}
}
}
|
package edu.harvard.iq.dataverse;
import edu.harvard.iq.dataverse.engine.command.Command;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseThemeCommand;
import static edu.harvard.iq.dataverse.util.JsfHelper.JH;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang.StringUtils;
import org.primefaces.component.tabview.TabView;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
/**
*
* @author ellenk
*/
@ViewScoped
@Named
public class ThemeWidgetFragment implements java.io.Serializable {
static final String DEFAULT_LOGO_BACKGROUND_COLOR = "F5F5F5";
static final String DEFAULT_BACKGROUND_COLOR = "F5F5F5";
static final String DEFAULT_LINK_COLOR = "428BCA";
static final String DEFAULT_TEXT_COLOR = "888888";
@Inject DataversePage dataversePage;
private File tempDir;
private File uploadedFile;
private Dataverse editDv;
private TabView tabView;
@Inject
DataverseSession session;
@EJB
EjbDataverseEngine commandEngine;
@EJB
DataverseServiceBean dataverseServiceBean;
/**
* create tempDir, needs to be under docroot so that uploaded image is accessible in the page
*/
private boolean testVal;
public boolean isTestVal() {
System.out.println("getting testVal: "+testVal);
return testVal;
}
public void setTestVal(boolean testVal) {
System.out.println("setting testVal: "+testVal);
this.testVal = testVal;
}
public void testValListener(javax.faces.event.AjaxBehaviorEvent event) throws javax.faces.event.AbortProcessingException {
System.out.println("listener clicked, testVal: "+testVal);
}
private void createTempDir() {
try {
File tempRoot = Files.createDirectories(Paths.get("../docroot/logos/temp")).toFile();
tempDir = Files.createTempDirectory(tempRoot.toPath(),editDv.getId().toString()).toFile();
} catch (IOException e) {
throw new RuntimeException("Error creating temp directory", e); // improve error handling
}
}
@PreDestroy
/**
* Cleanup by deleting temp directory and uploaded files
*/
public void cleanupTempDirectory() {
try {
if (tempDir != null) {
for (File f : tempDir.listFiles()) {
Files.deleteIfExists(f.toPath());
}
Files.deleteIfExists(tempDir.toPath());
}
} catch (IOException e) {
throw new RuntimeException("Error deleting temp directory", e); // improve error handling
}
uploadedFile=null;
tempDir=null;
}
public void checkboxListener() {
System.out.println("checkbox clicked, themeRoot value: "+editDv.getThemeRoot());
}
public void initEditDv(Long dataverseId) {
editDv = dataverseServiceBean.find(dataverseId);
if (editDv.getOwner()==null) {
editDv.setThemeRoot(true);
}
if (editDv.getDataverseTheme()==null && editDv.isThemeRoot()) {
editDv.setDataverseTheme(initDataverseTheme());
}
// When you open the popup, the first tab (widgets) should be active
tabView.setActiveIndex(0);
}
private DataverseTheme initDataverseTheme() {
DataverseTheme dvt = new DataverseTheme();
dvt.setLinkColor(DEFAULT_LINK_COLOR);
dvt.setLogoBackgroundColor(DEFAULT_LOGO_BACKGROUND_COLOR);
dvt.setBackgroundColor(DEFAULT_BACKGROUND_COLOR);
dvt.setTextColor(DEFAULT_TEXT_COLOR);
return dvt;
}
public Dataverse getEditDv() {
return editDv;
}
public void setEditDv(Dataverse editDV) {
this.editDv = editDV;
}
public void validateUrl(FacesContext context, UIComponent component, Object value) throws ValidatorException {
try {
if (!StringUtils.isEmpty((String)value)){
URL test = new URL((String)value);
}
} catch(MalformedURLException e) {
System.out.println("url validation failed.");
FacesMessage msg =
new FacesMessage(" URL validation failed.",
"Please provide URL.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
public TabView getTabView() {
return tabView;
}
public void setTabView(TabView tabView) {
this.tabView = tabView;
}
public String getTempDirName() {
if (tempDir!=null) {
return tempDir.getName();
} else {
return null;
}
}
public boolean uploadExists() {
return uploadedFile!=null;
}
/**
* Copy uploaded file to temp area, until we are ready to save
* Copy filename into Dataverse logo
* @param event
*/
public void handleImageFileUpload(FileUploadEvent event) {
if (this.tempDir==null) {
createTempDir();
}
UploadedFile uFile = event.getFile();
try {
uploadedFile = new File(tempDir, uFile.getFileName());
if (!uploadedFile.exists()) {
uploadedFile.createNewFile();
}
Files.copy(uFile.getInputstream(), uploadedFile.toPath(),StandardCopyOption.REPLACE_EXISTING);
editDv.getDataverseTheme().setLogo(uFile.getFileName());
} catch (IOException e) {
throw new RuntimeException("Error uploading logo file", e); // improve error handling
}
// If needed, set the default values for the logo
if (editDv.getDataverseTheme().getLogoFormat()==null) {
editDv.getDataverseTheme().setLogoFormat(DataverseTheme.ImageFormat.SQUARE);
}
// Set the active index, so that Theme tab will still display after upload
tabView.setActiveIndex(0);
}
public void removeLogo() {
editDv.getDataverseTheme().setLogo(null);
this.cleanupTempDirectory();
}
public boolean getInheritCustomization() {
boolean inherit= editDv==null ? true : !editDv.getThemeRoot();
System.out.println("returning inherit: "+inherit);
return inherit;
}
public void setInheritCustomization(boolean inherit) {
System.out.println("setting inherit : "+inherit+", themeRoot = "+!inherit);
editDv.setThemeRoot(!inherit);
if (!inherit) {
if (editDv.getDataverseTheme(true)==null) {
editDv.setDataverseTheme(initDataverseTheme());
}
}
}
public void save() {
// If this Dv isn't the root, delete the uploaded file and remove theme
// before saving.
if (!editDv.isThemeRoot()) {
uploadedFile=null;
editDv.setDataverseTheme(null);
}
Command<Dataverse> cmd = new UpdateDataverseThemeCommand(editDv, this.uploadedFile, session.getUser());
try {
dataversePage.setDataverse(commandEngine.submit(cmd));
dataversePage.setEditMode(null);
} catch (CommandException ex) {
JH.addMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage());
}
this.cleanupTempDirectory();
}
}
|
package aQute.lib.json;
import java.io.*;
import java.lang.reflect.*;
import java.security.*;
import java.util.*;
import java.util.zip.*;
import aQute.lib.converter.*;
public class Decoder implements Closeable {
final JSONCodec codec;
Reader reader;
int current;
MessageDigest digest;
Map<String,Object> extra;
String encoding = "UTF-8";
boolean strict;
boolean inflate;
boolean keepOpen = false;
Decoder(JSONCodec codec) {
this.codec = codec;
}
public Decoder from(File file) throws Exception {
return from(new FileInputStream(file));
}
public Decoder from(InputStream in) throws Exception {
if (inflate)
in = new InflaterInputStream(in);
return from(new InputStreamReader(in, encoding));
}
public Decoder from(byte[] data) throws Exception {
return from(new ByteArrayInputStream(data));
}
public Decoder charset(String encoding) {
this.encoding = encoding;
return this;
}
public Decoder strict() {
this.strict = true;
return this;
}
public Decoder from(Reader in) throws Exception {
reader = in;
read();
return this;
}
public Decoder faq(String in) throws Exception {
return from(in.replace('\'', '"'));
}
public Decoder from(String in) throws Exception {
return from(new StringReader(in));
}
public Decoder mark() throws NoSuchAlgorithmException {
if (digest == null)
digest = MessageDigest.getInstance("SHA1");
digest.reset();
return this;
}
public byte[] digest() {
if (digest == null)
return null;
return digest.digest();
}
@SuppressWarnings("unchecked")
public <T> T get(Class<T> clazz) throws Exception {
try {
return (T) codec.decode(clazz, this);
}
finally {
if (!keepOpen)
close();
}
}
public Object get(Type type) throws Exception {
try {
return codec.decode(type, this);
}
finally {
if (!keepOpen)
close();
}
}
public Object get() throws Exception {
try {
return codec.decode(null, this);
}
finally {
if (!keepOpen)
close();
}
}
@SuppressWarnings("unchecked")
public <T> T get(TypeReference<T> ref) throws Exception {
try {
return (T) codec.decode(ref.getType(), this);
}
finally {
if (!keepOpen)
close();
}
}
public Decoder keepOpen() {
keepOpen = true;
return this;
}
int read() throws Exception {
current = reader.read();
if (digest != null) {
digest.update((byte) (current / 256));
digest.update((byte) (current % 256));
}
return current;
}
int current() {
return current;
}
/**
* Skip any whitespace.
*
* @return
* @throws Exception
*/
int skipWs() throws Exception {
while (Character.isWhitespace(current()))
read();
return current();
}
/**
* Skip any whitespace.
*
* @return
* @throws Exception
*/
int next() throws Exception {
read();
return skipWs();
}
void expect(String s) throws Exception {
for (int i = 0; i < s.length(); i++)
if (!(s.charAt(i) == read()))
throw new IllegalArgumentException("Expected " + s + " but got something different");
read();
}
public boolean isEof() throws Exception {
int c = skipWs();
return c < 0;
}
public void close() throws IOException {
reader.close();
}
public Map<String,Object> getExtra() {
if (extra == null)
extra = new HashMap<String,Object>();
return extra;
}
public Decoder inflate() {
if (reader != null)
throw new IllegalStateException("Reader already set, inflate must come before from()");
inflate = true;
return this;
}
}
|
package com.charlesmadere.hummingbird.misc;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MiscUtilsTest {
@Test
public void testBooleanEquals() throws Exception {
assertTrue(MiscUtils.booleanEquals(null, null));
assertTrue(MiscUtils.booleanEquals(Boolean.TRUE, Boolean.TRUE));
assertTrue(MiscUtils.booleanEquals(Boolean.TRUE, true));
assertTrue(MiscUtils.booleanEquals(true, Boolean.TRUE));
assertTrue(MiscUtils.booleanEquals(true, true));
assertTrue(MiscUtils.booleanEquals(Boolean.FALSE, Boolean.FALSE));
assertTrue(MiscUtils.booleanEquals(Boolean.FALSE, false));
assertTrue(MiscUtils.booleanEquals(false, Boolean.FALSE));
assertTrue(MiscUtils.booleanEquals(false, false));
assertFalse(MiscUtils.booleanEquals(Boolean.TRUE, Boolean.FALSE));
assertFalse(MiscUtils.booleanEquals(Boolean.TRUE, false));
assertFalse(MiscUtils.booleanEquals(Boolean.TRUE, null));
assertFalse(MiscUtils.booleanEquals(true, Boolean.FALSE));
assertFalse(MiscUtils.booleanEquals(true, false));
assertFalse(MiscUtils.booleanEquals(true, null));
assertFalse(MiscUtils.booleanEquals(Boolean.FALSE, Boolean.TRUE));
assertFalse(MiscUtils.booleanEquals(Boolean.FALSE, true));
assertFalse(MiscUtils.booleanEquals(Boolean.FALSE, null));
assertFalse(MiscUtils.booleanEquals(false, Boolean.TRUE));
assertFalse(MiscUtils.booleanEquals(false, true));
assertFalse(MiscUtils.booleanEquals(false, null));
}
@Test
public void testExclusiveAdd() throws Exception {
}
@Test
public void testIntegerEquals() throws Exception {
assertTrue(MiscUtils.integerEquals(null, null));
}
}
|
package org.jkiss.dbeaver.ui.dialogs.driver;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.wizard.ProgressMonitorPart;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.core.DBeaverActivator;
import org.jkiss.dbeaver.registry.DataSourceDescriptor;
import org.jkiss.dbeaver.registry.DataSourceProviderDescriptor;
import org.jkiss.dbeaver.registry.DataSourceProviderRegistry;
import org.jkiss.dbeaver.registry.DriverDescriptor;
import org.jkiss.dbeaver.ui.DBIcon;
import org.jkiss.dbeaver.ui.IHelpContextIds;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.DriverTreeControl;
import org.jkiss.dbeaver.ui.controls.DriverTreeViewer;
import org.jkiss.dbeaver.ui.dialogs.HelpEnabledDialog;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
/**
* EditDriverDialog
*/
public class DriverManagerDialog extends HelpEnabledDialog implements ISelectionChangedListener, IDoubleClickListener, IRunnableContext {
private DataSourceProviderDescriptor selectedProvider;
private DataSourceProviderDescriptor onlyManagableProvider;
private String selectedCategory;
private DriverDescriptor selectedDriver;
private Button newButton;
private Button editButton;
private Button deleteButton;
private DriverTreeControl treeControl;
private Image dialogImage;
//private Label driverDescription;
private ProgressMonitorPart monitorPart;
public DriverManagerDialog(Shell shell)
{
super(shell, IHelpContextIds.CTX_DRIVER_MANAGER);
}
@Override
protected Control createDialogArea(Composite parent)
{
List<DataSourceProviderDescriptor> providers = DataSourceProviderRegistry.getDefault().getDataSourceProviders();
{
DataSourceProviderDescriptor manProvider = null;
for (DataSourceProviderDescriptor provider : providers) {
if (provider.isDriversManagable()) {
if (manProvider != null) {
manProvider = null;
break;
}
manProvider = provider;
}
}
if (manProvider != null) {
onlyManagableProvider = manProvider;
}
}
getShell().setText(CoreMessages.dialog_driver_manager_title);
getShell().setMinimumSize(300, 300);
dialogImage = DBeaverActivator.getImageDescriptor("/icons/driver_manager.png").createImage(); //$NON-NLS-1$
getShell().setImage(dialogImage);
Composite group = UIUtils.createPlaceholder((Composite) super.createDialogArea(parent), 2);
group.setLayoutData(new GridData(GridData.FILL_BOTH));
{
treeControl = new DriverTreeControl(group, this, providers, false);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 300;
gd.widthHint = 300;
treeControl.setLayoutData(gd);
}
{
Composite buttonBar = new Composite(group, SWT.TOP);
buttonBar.setLayout(new GridLayout(1, false));
GridData gd = new GridData(GridData.FILL_VERTICAL);
gd.minimumWidth = 100;
buttonBar.setLayoutData(gd);
newButton = new Button(buttonBar, SWT.FLAT | SWT.PUSH);
newButton.setText(CoreMessages.dialog_driver_manager_button_new);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint = 100;
newButton.setLayoutData(gd);
newButton.addSelectionListener(new SelectionListener()
{
@Override
public void widgetSelected(SelectionEvent e)
{
createDriver();
}
@Override
public void widgetDefaultSelected(SelectionEvent e)
{
}
});
editButton = new Button(buttonBar, SWT.FLAT | SWT.PUSH);
editButton.setText(CoreMessages.dialog_driver_manager_button_edit);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint = 100;
editButton.setLayoutData(gd);
editButton.addSelectionListener(new SelectionListener()
{
@Override
public void widgetSelected(SelectionEvent e)
{
editDriver();
}
@Override
public void widgetDefaultSelected(SelectionEvent e)
{
}
});
deleteButton = new Button(buttonBar, SWT.FLAT | SWT.PUSH);
deleteButton.setText(CoreMessages.dialog_driver_manager_button_delete);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint = 100;
deleteButton.setLayoutData(gd);
deleteButton.addSelectionListener(new SelectionListener()
{
@Override
public void widgetSelected(SelectionEvent e)
{
deleteDriver();
}
@Override
public void widgetDefaultSelected(SelectionEvent e)
{
}
});
{
final Composite legend = UIUtils.createPlaceholder(buttonBar, 2, 5);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = 5;
gd.horizontalSpan = 2;
legend.setLayoutData(gd);
UIUtils.createImageLabel(legend, DBIcon.OVER_LAMP.getImage());
UIUtils.createTextLabel(legend, CoreMessages.dialog_driver_manager_label_user_defined);
UIUtils.createImageLabel(legend, DBIcon.OVER_ERROR.getImage());
UIUtils.createTextLabel(legend, CoreMessages.dialog_driver_manager_label_unavailable);
}
}
/*
{
Composite descBar = UIUtils.createPlaceholder(group, 1, 5);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
descBar.setLayoutData(gd);
Text text = new Text(descBar, SWT.READ_ONLY | SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
//gd.verticalIndent = 5;
text.setLayoutData(gd);
}
*/
//UIUtils.setHelp(group, IHelpContextIds.CTX_DRIVER_MANAGER);
//driverDescription = new Label(group, SWT.NONE);
monitorPart = new ProgressMonitorPart(group, null, true);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = 5;
gd.horizontalSpan = 2;
gd.grabExcessHorizontalSpace = true;
monitorPart.setLayoutData(gd);
monitorPart.setVisible(false);
//monitorPart.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return group;
}
@Override
protected void createButtonsForButtonBar(Composite parent)
{
createButton(
parent,
IDialogConstants.CLOSE_ID,
IDialogConstants.CLOSE_LABEL,
true);
}
@Override
protected void buttonPressed(int buttonId)
{
if (buttonId == IDialogConstants.CLOSE_ID) {
setReturnCode(OK);
close();
}
}
@Override
public void selectionChanged(SelectionChangedEvent event)
{
this.selectedDriver = null;
this.selectedProvider = null;
this.selectedCategory = null;
ISelection selection = event.getSelection();
if (selection instanceof IStructuredSelection) {
Object selectedObject = ((IStructuredSelection) selection).getFirstElement();
if (selectedObject instanceof DriverDescriptor) {
this.selectedDriver = (DriverDescriptor) selectedObject;
this.selectedCategory = selectedDriver.getCategory();
} else if (selectedObject instanceof DataSourceProviderDescriptor) {
this.selectedProvider = (DataSourceProviderDescriptor)selectedObject;
} else if (selectedObject instanceof DriverTreeViewer.DriverCategory) {
this.selectedProvider = null;
this.selectedCategory = ((DriverTreeViewer.DriverCategory) selectedObject).getName();
}
}
//super.updateStatus(new Status(Status.INFO, DBeaverConstants.PLUGIN_ID, selectedDriver == null ? "" : selectedDriver.getDescription()));
this.updateButtons();
}
@Override
public void doubleClick(DoubleClickEvent event)
{
if (selectedDriver != null) {
editDriver();
}
}
private void updateButtons()
{
newButton.setEnabled(onlyManagableProvider != null || (selectedProvider != null && selectedProvider.isDriversManagable()));
editButton.setEnabled(selectedDriver != null);
deleteButton.setEnabled(selectedDriver != null && selectedDriver.getProviderDescriptor().isDriversManagable());
if (selectedDriver != null) {
monitorPart.setTaskName(CommonUtils.toString(selectedDriver.getDescription()));
} else if (selectedCategory != null) {
monitorPart.setTaskName(selectedCategory + " drivers");
} else if (selectedProvider != null) {
monitorPart.setTaskName(selectedProvider.getName() + " provider");
} else {
monitorPart.setTaskName("");
}
}
private void createDriver()
{
if (onlyManagableProvider != null || selectedProvider != null) {
DataSourceProviderDescriptor provider = selectedProvider;
if (provider == null || !provider.isDriversManagable()) {
provider = onlyManagableProvider;
}
DriverEditDialog dialog = new DriverEditDialog(getShell(), provider, selectedCategory);
if (dialog.open() == IDialogConstants.OK_ID) {
treeControl.getViewer().refresh();
}
}
}
private void editDriver()
{
DriverDescriptor driver = selectedDriver;
if (driver != null) {
driver.validateFilesPresence(this);
DriverEditDialog dialog = new DriverEditDialog(getShell(), driver);
if (dialog.open() == IDialogConstants.OK_ID) {
// Do nothing
}
treeControl.getViewer().refresh(driver);
}
}
private void deleteDriver()
{
List<DataSourceDescriptor> usedDS = selectedDriver.getUsedBy();
if (!usedDS.isEmpty()) {
StringBuilder message = new StringBuilder(NLS.bind(CoreMessages.dialog_driver_manager_message_cant_delete_text, selectedDriver.getName()));
for (DataSourceDescriptor ds : usedDS) {
message.append("\n - ").append(ds.getName());
}
UIUtils.showMessageBox(getShell(), CoreMessages.dialog_driver_manager_message_cant_delete_title, message.toString(), SWT.ICON_ERROR);
return;
}
if (UIUtils.confirmAction(
getShell(),
CoreMessages.dialog_driver_manager_message_delete_driver_title,
CoreMessages.dialog_driver_manager_message_delete_driver_text + selectedDriver.getName() + "'?"))
{
selectedDriver.getProviderDescriptor().removeDriver(selectedDriver);
selectedDriver.getProviderDescriptor().getRegistry().saveDrivers();
treeControl.getViewer().refresh();
}
}
@Override
public boolean close()
{
UIUtils.dispose(dialogImage);
return super.close();
}
@Override
public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException
{
// Code copied from WizardDialog
if (monitorPart != null) {
monitorPart.setVisible(true);
monitorPart.layout();
monitorPart.attachToCancelComponent(null);
}
// The operation can only be canceled if it is executed in a separate
// thread.
// Otherwise the UI is blocked anyway.
try {
ModalContext.run(runnable, true, monitorPart, getShell().getDisplay());
} finally {
// explicitly invoke done() on our progress monitor so that its
// label does not spill over to the next invocation, see bug 271530
if (monitorPart != null) {
monitorPart.done();
monitorPart.setVisible(false);
}
}
}
}
|
package edu.hm.hafner.analysis.parser; // NOPMD
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.digester3.Digester;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.xml.sax.SAXException;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.IssueParser;
import edu.hm.hafner.analysis.LineRange;
import edu.hm.hafner.analysis.LineRangeList;
import edu.hm.hafner.analysis.ParsingException;
import edu.hm.hafner.analysis.ReaderFactory;
import edu.hm.hafner.analysis.Report;
import edu.hm.hafner.analysis.SecureDigester;
import edu.hm.hafner.analysis.Severity;
import edu.hm.hafner.util.VisibleForTesting;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.ba.SourceFile;
import edu.umd.cs.findbugs.ba.SourceFinder;
import static edu.hm.hafner.analysis.parser.FindBugsParser.PriorityProperty.*;
/**
* A parser for the native FindBugs XML files.
*
* @author Ullrich Hafner
*/
@SuppressWarnings("ClassFanOutComplexity")
public class FindBugsParser extends IssueParser {
private static final long serialVersionUID = 8306319007761954027L;
/**
* FindBugs 2 and 3 classifies issues using the bug rank and priority (now renamed confidence). Bugs are given a
* rank 1-20, and grouped into the categories scariest (rank 1-4), scary (rank 5-9), troubling (rank 10-14), and of
* concern (rank 15-20). Many people were confused by the priority reported by FindBugs, and considered all HIGH
* priority issues to be important. To reflect the actually meaning of this attribute of issues, it has been renamed
* confidence. Issues of different bug patterns should be compared by their rank, not their confidence.
*/
public enum PriorityProperty {
/** Use the priority/confidence to create corresponding {@link Severity priorities}. */
CONFIDENCE,
/** Use rank to create corresponding {@link Severity priorities}. */
RANK
}
private static final String DOT = ".";
private static final String SLASH = "/";
private static final int HIGH_PRIORITY_LOWEST_RANK = 4;
private static final int NORMAL_PRIORITY_LOWEST_RANK = 9;
/** Determines whether to use the rank when evaluation the priority. */
private final PriorityProperty priorityProperty;
private boolean isFirstError = true;
/**
* Creates a new instance of {@link FindBugsParser}.
*
* @param priorityProperty
* determines whether to use the rank or confidence when evaluation the {@link Severity}
*/
public FindBugsParser(final PriorityProperty priorityProperty) {
super();
this.priorityProperty = priorityProperty;
}
@Override
public Report parse(final ReaderFactory readerFactory) throws ParsingException {
Collection<String> sources = new ArrayList<>();
String moduleRoot = StringUtils.substringBefore(readerFactory.getFileName(), "/target/");
sources.add(moduleRoot + "/src/main/java");
sources.add(moduleRoot + "/src/test/java");
sources.add(moduleRoot + "/src");
return parse(readerFactory, sources, new IssueBuilder());
}
@VisibleForTesting
Report parse(final ReaderFactory readerFactory, final Collection<String> sources, final IssueBuilder builder)
throws ParsingException {
Map<String, String> hashToMessageMapping = new HashMap<>();
Map<String, String> categories = new HashMap<>();
try (Reader input = readerFactory.create()) {
List<XmlBugInstance> bugs = preParse(input);
for (XmlBugInstance bug : bugs) {
hashToMessageMapping.put(bug.getInstanceHash(), bug.getMessage());
categories.put(bug.getType(), bug.getCategory());
}
}
catch (SAXException | IOException exception) {
throw new ParsingException(exception);
}
return parse(readerFactory, sources, builder, hashToMessageMapping, categories);
}
/**
* Returns the parsed FindBugs analysis file. This scanner accepts files in the native FindBugs format.
*
* @param builder
* the issue builder
* @param readerFactory
* the FindBugs analysis file
* @param sources
* a collection of folders to scan for source files
* @param hashToMessageMapping
* mapping of hash codes to messages
* @param categories
* mapping from bug types to their categories
*
* @return the parsed result (stored in the module instance)
*/
private Report parse(final ReaderFactory readerFactory, final Collection<String> sources,
final IssueBuilder builder, final Map<String, String> hashToMessageMapping,
final Map<String, String> categories) {
try (Reader input = readerFactory.create()) {
SortedBugCollection bugs = readXml(input);
try (Project project = bugs.getProject()) {
return convertBugsToIssues(sources, builder, hashToMessageMapping, categories, bugs, project);
}
}
catch (DocumentException | IOException exception) {
throw new ParsingException(exception);
}
}
private Report convertBugsToIssues(final Collection<String> sources, final IssueBuilder builder,
final Map<String, String> hashToMessageMapping, final Map<String, String> categories,
final SortedBugCollection collection, final Project project) {
project.addSourceDirs(sources);
try (SourceFinder sourceFinder = new SourceFinder(project)) {
if (StringUtils.isNotBlank(project.getProjectName())) {
builder.setModuleName(project.getProjectName());
}
Collection<BugInstance> bugs = collection.getCollection();
Report report = new Report();
for (BugInstance warning : bugs) {
SourceLineAnnotation sourceLine = warning.getPrimarySourceLineAnnotation();
String message = warning.getMessage();
String type = warning.getType();
String category = categories.get(type);
if (category == null) { // alternately, only if warning.getBugPattern().getType().equals("UNKNOWN")
category = warning.getBugPattern().getCategory();
}
builder.setSeverity(getPriority(warning))
.setMessage(createMessage(hashToMessageMapping, warning, message))
.setCategory(category)
.setType(type)
.setLineStart(sourceLine.getStartLine())
.setLineEnd(sourceLine.getEndLine())
.setFileName(findSourceFile(project, sourceFinder, sourceLine))
.setPackageName(warning.getPrimaryClass().getPackageName())
.setFingerprint(warning.getInstanceHash());
setAffectedLines(warning, builder,
new LineRange(sourceLine.getStartLine(), sourceLine.getEndLine()));
report.add(builder.build());
}
return report;
}
}
/**
* Pre-parses a file for some information not available from the FindBugs parser. Creates a mapping of FindBugs
* warnings to messages. A bug is represented by its unique hash code. Also obtains original categories for bug
* types.
*
* @param file
* the FindBugs XML file
*
* @return the map of warning messages
* @throws SAXException
* if the file contains no valid XML
* @throws IOException
* signals that an I/O exception has occurred.
*/
@VisibleForTesting
List<XmlBugInstance> preParse(final Reader file) throws SAXException, IOException {
Digester digester = new SecureDigester(FindBugsParser.class);
String rootXPath = "BugCollection/BugInstance";
digester.addObjectCreate(rootXPath, XmlBugInstance.class);
digester.addSetProperties(rootXPath);
String fileXPath = rootXPath + "/LongMessage";
digester.addCallMethod(fileXPath, "setMessage", 0);
digester.addSetNext(rootXPath, "add", Object.class.getName());
ArrayList<XmlBugInstance> bugs = new ArrayList<>();
digester.push(bugs);
digester.parse(file);
return bugs;
}
private String createMessage(final Map<String, String> hashToMessageMapping, final BugInstance warning,
final String message) {
return StringUtils.defaultIfEmpty(hashToMessageMapping.get(warning.getInstanceHash()), message);
}
private Severity getPriority(final BugInstance warning) {
if (priorityProperty == RANK) {
return getPriorityByRank(warning);
}
else {
return getPriorityByPriority(warning);
}
}
private SortedBugCollection readXml(final Reader file) throws IOException, DocumentException {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(FindBugsParser.class.getClassLoader());
SortedBugCollection collection = new SortedBugCollection();
collection.readXML(file);
return collection;
}
finally {
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
private void setAffectedLines(final BugInstance warning, final IssueBuilder builder,
final LineRange primary) {
Iterator<BugAnnotation> annotationIterator = warning.annotationIterator();
LineRangeList lineRanges = new LineRangeList();
while (annotationIterator.hasNext()) {
BugAnnotation bugAnnotation = annotationIterator.next();
if (bugAnnotation instanceof SourceLineAnnotation) {
SourceLineAnnotation annotation = (SourceLineAnnotation) bugAnnotation;
LineRange lineRange = new LineRange(annotation.getStartLine(), annotation.getEndLine());
if (!lineRanges.contains(lineRange) && !primary.equals(lineRange)) {
lineRanges.add(lineRange);
}
}
}
builder.setLineRanges(lineRanges);
}
private String findSourceFile(final Project project, final SourceFinder sourceFinder,
final SourceLineAnnotation sourceLine) {
try {
SourceFile sourceFile = sourceFinder.findSourceFile(sourceLine);
return sourceFile.getFullFileName();
}
catch (IOException ignored) {
return sourceLine.getPackageName().replace(DOT, SLASH) + SLASH + sourceLine.getSourceFile();
}
}
/**
* Maps the FindBugs library rank to plug-in priority enumeration.
*
* @param warning
* the FindBugs warning
*
* @return mapped priority enumeration
*/
private Severity getPriorityByRank(final BugInstance warning) {
int rank = warning.getBugRank();
if (rank <= HIGH_PRIORITY_LOWEST_RANK) {
return Severity.WARNING_HIGH;
}
if (rank <= NORMAL_PRIORITY_LOWEST_RANK) {
return Severity.WARNING_NORMAL;
}
return Severity.WARNING_LOW;
}
/**
* Maps the FindBugs library priority to plug-in priority enumeration.
*
* @param warning
* the FindBugs warning
*
* @return mapped priority enumeration
*/
private Severity getPriorityByPriority(final BugInstance warning) {
switch (warning.getPriority()) {
case 1:
return Severity.WARNING_HIGH;
case 2:
return Severity.WARNING_NORMAL;
default:
return Severity.WARNING_LOW;
}
}
/**
* Java Bean to create the mapping of hash codes to messages using the Digester XML parser.
*
* @author Ullrich Hafner
*/
@SuppressWarnings("all")
public static class XmlBugInstance {
@Nullable
private String instanceHash;
@Nullable
private String message;
@Nullable
private String type;
@Nullable
private String category;
@Nullable
public String getInstanceHash() {
return instanceHash;
}
public void setInstanceHash(final String instanceHash) {
this.instanceHash = instanceHash;
}
@Nullable
public String getMessage() {
return message;
}
public void setMessage(final String message) {
this.message = message;
}
@Nullable
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
@Nullable
public String getCategory() {
return category;
}
public void setCategory(final String category) {
this.category = category;
}
}
}
|
package edu.uci.ics.biggraph.algo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import edu.uci.ics.biggraph.client.*;
import edu.uci.ics.biggraph.inputformat.SpanningTreeInputformat;
import edu.uci.ics.biggraph.io.FloatWritable;
import edu.uci.ics.biggraph.io.IntWritable;
import edu.uci.ics.biggraph.io.HelloCntParentIdWritable;
import edu.uci.ics.biggraph.io.VLongWritable;
import edu.uci.ics.biggraph.outputformat.SpanningTreeOutptFormat;
import edu.uci.ics.pregelix.api.graph.Edge;
import edu.uci.ics.pregelix.api.graph.Vertex;
import edu.uci.ics.pregelix.api.job.PregelixJob;
import edu.uci.ics.pregelix.api.util.DefaultMessageCombiner;
import edu.uci.ics.pregelix.example.data.VLongNormalizedKeyComputer;
public class SpanningTreeVertex extends Vertex<VLongWritable, IntWritable, FloatWritable, HelloCntParentIdWritable>{
/** The root vertex id, will be computed/set when read in graph */
// public static final String ROOT_ID = "SpanningTreeVertex.rootId";
/** Default root vertex id */
// public static final long ROOT_ID_DEFAULT = 0;
/** message to be sent */
HelloCntParentIdWritable msgToSent = new HelloCntParentIdWritable();
/** vertex value to be set */
IntWritable vertexValueToSet = new IntWritable();
/** deleted edge */
float edgeDeleted = -1.0f;
FloatWritable edgeDeletedWritable = new FloatWritable(-1.0f);
/** record the msg sender's id */
ArrayList<Long> msgSenderIds = new ArrayList<Long>();
List<Edge<VLongWritable, FloatWritable> > edgeList;
// check if the vertex is the root vertex
private boolean isRoot() {
return (getVertexValue().get() == 0);
// return (getVertexId().get() == getContext().getConfiguration().getLong(ROOT_ID, ROOT_ID_DEFAULT));
}
// get the root id
// private long getRootId() {
// return getContext().getConfiguration().getLong(ROOT_ID, ROOT_ID_DEFAULT);
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
int i = 0;
for (Edge<VLongWritable, FloatWritable> edge : getEdges()) {
if (!isEdgeDeleted(edge)) {
sb.append(" ").append(edge.getDestVertexId().get()).append(" ").append(edge.getEdgeValue().get());
++i;
}
}
// no tag information
sb.append(" ").append(0);
return Integer.toString(i) + sb.toString();
// if (i > 1)
// return "0";
// else
// return "";
}
@Override
public void compute(Iterator<HelloCntParentIdWritable> msgIterator) throws Exception {
/** in the first step,
* the root id sends the message claiming itself as root by
* sending value 0L
*/
if (getSuperstep() == 1) {
// System.out.println("ID: " + getVertexId().toString());
if (isRoot()) {
// set itself vertex value as 0
vertexValueToSet.set(0);
setVertexValue(vertexValueToSet);
// send message that it is the root by setting hello counter as 0
msgToSent.setHelloCounterParentId(0L, getVertexId().get());
for (Edge<VLongWritable, FloatWritable> edge : getEdges()) {
sendMsg(edge.getDestVertexId(), msgToSent);
// System.out.print(" send from root: " + getVertexId().toString());
// System.out.print(" to " + edge.getDestVertexId().toString());
}
} else {
// set itself vertex value as -1L
vertexValueToSet.set(Integer.MAX_VALUE);
setVertexValue(vertexValueToSet);
}
} else {
// get the list of edges
// if an edge value is set to be edgeDeleted
// then it is deleted
edgeList = getEdges();
/** see if it is the first time to receive the message
* by checking the vertex value
* First time: -1L
* Otherwise >= 0L
*/
int vertexValue = getVertexValue().get();
if (vertexValue == Integer.MAX_VALUE) {
// first time to receive the message
// init msgSenderIds
msgSenderIds.clear();
// Processing the message it got
// find the lowest hello counter it receives
int minCnt = Integer.MAX_VALUE;
long minCntVertexId = -1L;
while (msgIterator.hasNext()) {
HelloCntParentIdWritable msg = msgIterator.next();
// save the sender's id of message
msgSenderIds.add(msg.getParentId());
// update the minimum hello counter
if (minCnt > (int) msg.getHelloCounter()) {
minCnt = (int) msg.getHelloCounter();
minCntVertexId = msg.getParentId();
}
}
// set the hello counter by increment 1
++minCnt;
vertexValueToSet.set(minCnt);
setVertexValue(vertexValueToSet);
// send the message to all its neighbors except it's parent
// NOTE: we did not use the strategy that
// only send the message to the nodes it did not receive message
// this is because, we need the destination vertex to receive this obsolete
// message such that they can delete their out going edges to the vertex
msgToSent.setHelloCounterParentId(minCnt, getVertexId().get());
for (Edge<VLongWritable, FloatWritable> edge : getEdges()) {
long destVertexId = edge.getDestVertexId().get();
if (destVertexId != minCntVertexId
&& !isEdgeDeleted(edge)) { // must not be deleted edge
// don't sent message to its parent
// otherwise, its parent will delete the vertex
sendMsg(edge.getDestVertexId(), msgToSent);
// System.out.print("Parent id: " + minCntVertexId);
// System.out.print(" send from " + getVertexId().toString());
// System.out.print(" to " + edge.getDestVertexId().toString());
}
}
// now delete the edge that it receives message
// EXCEPT the PARENT it chooses
for (long id : msgSenderIds) {
if (id != minCntVertexId) { // EXCEPT the PARENT
// begin deleting
setEdgeDeleted(edgeList, id);
// System.out.print("vertex: " + getVertexId().toString());
// System.out.print(" remove edge to vertex: " + id);
}
}
} else {
// the vertex has already received the hello message
// just delete any edge if the message was sent through that edge
while (msgIterator.hasNext()) {
HelloCntParentIdWritable msg = msgIterator.next();
// begin deleting
setEdgeDeleted(edgeList, msg.getParentId());
// System.out.print("vertex: " + getVertexId().toString());
// System.out.print(" remove edge to vertex: " + msg.getParentId());
}
}
} // end of more than one time receives the message
voteToHalt();
}
private boolean isEdgeDeleted(Edge<VLongWritable, FloatWritable> edge) {
return (edge.getEdgeValue().get() == edgeDeleted);
}
private void setEdgeDeleted(List<Edge<VLongWritable, FloatWritable> > edgeList, long idToDelete) {
for (Edge<VLongWritable, FloatWritable> edge : edgeList) {
if (edge.getDestVertexId().get() == idToDelete) {
edge.setEdgeValue(edgeDeletedWritable);
return;
}
}
}
public static void main(String[] args) throws Exception {
PregelixJob job = new PregelixJob(SpanningTreeVertex.class.getSimpleName());
job.setVertexClass(SpanningTreeVertex.class);
job.setVertexInputFormatClass(SpanningTreeInputformat.class);
job.setVertexOutputFormatClass(SpanningTreeOutptFormat.class);
job.setMessageCombinerClass(DefaultMessageCombiner.class);
job.setNoramlizedKeyComputerClass(VLongNormalizedKeyComputer.class);
Client.run(args, job);
}
}
|
package hudson.plugins.report.jck;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import hudson.model.Job;
import hudson.model.Result;
import hudson.model.Run;
import hudson.plugins.report.jck.model.BuildReport;
import hudson.plugins.report.jck.model.Report;
import hudson.plugins.report.jck.model.Suite;
import hudson.plugins.report.jck.model.SuiteTestChanges;
import hudson.plugins.report.jck.model.SuiteTests;
import hudson.plugins.report.jck.model.TestStatus;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static hudson.plugins.report.jck.Constants.REPORT_JSON;
import static hudson.plugins.report.jck.Constants.REPORT_TESTS_LIST_JSON;
import hudson.plugins.report.jck.model.SuiteTestsWithResults;
import hudson.plugins.report.jck.model.SuitesWithResults;
import hudson.plugins.report.jck.wrappers.RunWrapper;
import hudson.plugins.report.jck.wrappers.RunWrapperFromDir;
import hudson.plugins.report.jck.wrappers.RunWrapperFromRun;
import hudson.util.RunList;
public class BuildSummaryParser {
private static interface ListProvider {
String getList();
int getSurrounding();
}
private final Set<String> prefixes = new HashSet<>();
private final AbstractReportPublisher settings;
public BuildSummaryParser(Collection<String> prefixes, AbstractReportPublisher settings) {
if (prefixes == null || prefixes.isEmpty()) {
throw new IllegalArgumentException("Prefixes cannot be null or empty");
}
this.prefixes.addAll(prefixes);
this.settings = settings;
}
List<String> getBlacklisted(Job<?, ?> job) {
return getBlacklisted(job.getBuilds());
}
List<String> getWhitelisted(Job<?, ?> job) {
return getWhitelisted(job.getBuilds());
}
int getWhiteListSizeWithoutSurroundings(Job<?, ?> job) {
return getWhiteListSizeWithoutSurroundings(job.getBuilds()).size();
}
List<String> getBlacklisted(RunList<?> runs) {
return getList(runs, new ListProvider() {
@Override
public String getList() {
return settings.getResultsBlackList();
}
@Override
public int getSurrounding() {
return 0;
}
});
}
List<String> getWhitelisted(RunList<?> runs) {
return getList(runs, new ListProvider() {
@Override
public String getList() {
return settings.getResultsWhiteList();
}
@Override
public int getSurrounding() {
return settings.getRangeAroundWlist();
}
});
}
List<String> getWhiteListSizeWithoutSurroundings(RunList<?> runs) {
return getList(runs, new ListProvider() {
@Override
public String getList() {
return settings.getResultsWhiteList();
}
@Override
public int getSurrounding() {
return 0;
}
});
}
List<String> getList(RunList<?> runs, ListProvider provider) {
final String list = provider.getList();
if (settings == null || list == null || list.trim().isEmpty()) {
return Collections.emptyList();
}
int limit = getMaxItems();
List<String> listed = new ArrayList<>(limit);
Run[] builds = runs.toArray(new Run[0]);
for (int i = 0; i < builds.length; i++) {
Run run = builds[i];
if (run.getResult() == null || run.getResult().isWorseThan(Result.UNSTABLE)) {
continue;
}
String[] items = list.split("\\s+");
for (String item : items) {
if (run.getDisplayName().matches(item)) {
int numberOfFailedBuilds = 0;
for (int j = 0; j <= provider.getSurrounding() + numberOfFailedBuilds; j++) {
if (addNotFailedBuild(i + j, listed, builds)) {
numberOfFailedBuilds++;
}
}
numberOfFailedBuilds = 0;
for (int j = -1; j >= -(provider.getSurrounding() + numberOfFailedBuilds); j
if (addNotFailedBuild(i + j, listed, builds)) {
numberOfFailedBuilds++;
}
}
}
}
}
return listed;
}
private boolean addNotFailedBuild(int position, List<String> result, Run[] builds) {
if (position >= 0 && position < builds.length) {
boolean crashed = builds[position].getResult() == null || builds[position].getResult().isWorseThan(Result.UNSTABLE);
if (crashed) {
return true;
}
/*Preventing duplicates in whitelist. Not because of the graph, there is
already chunk of code preventing from showing duplicity in the graph.
(The final list are recreated again with help of these lists)
Its because lenght of whitelist which is shown over the graph.
BUG
We have some point(a) which is in range around whitelist and point(b) which
have same name but its not in range. Bug is that both points are shown in result
its caused by generating second array(graph points) from names contained in this array*/
if (!result.contains(builds[position].getDisplayName())) {
result.add(builds[position].getDisplayName());
}
}
return false;
}
private int getMaxItems() {
int limit = 10;
if (settings != null) {
limit = settings.getIntMaxBuilds();
}
return limit;
}
public List<BuildReport> parseJobReports(Job<?, ?> job) {
return parseJobReports(job.getBuilds());
}
public List<BuildReport> parseJobReports(RunList<?> runs) {
int limit = getMaxItems();
List<BuildReport> list = new ArrayList<>();
List<String> blacklisted = getBlacklisted(runs);
List<String> whitelisted = getWhitelisted(runs);
for (Run run : runs) {
if (run.getResult() == null || run.getResult().isWorseThan(Result.UNSTABLE)) {
continue;
}
if (blacklisted.contains(run.getDisplayName())) {
continue;
}
if (!whitelisted.contains(run.getDisplayName()) && !whitelisted.isEmpty()) {
continue;
}
try {
BuildReport report = parseBuildReport(run);
list.add(report);
} catch (Exception ignore) {
}
if (list.size() == limit) {
break;
}
}
Collections.reverse(list);
return list;
}
public BuildReport parseJobReports(File dir1) {
try {
return parseBuildReport(new RunWrapperFromDir(dir1));
} catch (Exception ignore) {
ignore.printStackTrace();
return null;
}
}
public BuildReport parseBuildReport(Run<?, ?> build) throws Exception {
return parseBuildReport(new RunWrapperFromRun(build));
}
public BuildReport parseBuildReport(RunWrapper build) throws Exception {
List<Suite> suites = parseBuildSummary(build.getRoot());
int passed = 0;
int failed = 0;
int error = 0;
int total = 0;
int notRun = 0;
for (Suite suite : suites) {
passed += suite.getReport().getTestsPassed();
failed += suite.getReport().getTestsFailed();
error += suite.getReport().getTestsError();
total += suite.getReport().getTestsTotal();
notRun += suite.getReport().getTestsNotRun();
}
/*
This condition is very unhappy.
Tck is saving to json total summ of tests as all *runnable* tests. So total=total_runable+notRun (unexpected)
jtregs are saving total sum of tests of all *run* tests. so total_runable=total+notRun
To do this properly, means to fix it in {jck,jtreg}reportPublisher
but it also means to regenerate all the results:(
*/
//if (prefixes.contains("jck")){
// total -= notRun;
//you may seen the incoherency between:
//https://github.com/judovana/jenkins-report-jck/pull/8/files#diff-55fe100eb47db6ceae5e4a79319d5f1cR147
//and
//https://github.com/judovana/jenkins-report-jck/pull/7/files#diff-bac5b237e72448e452669002e9d2eac1R74
//in addition this chunk seems not fixing the issue of:
//jtregs currenlty do not have any excluded tests. Once thy have, the graph will probably become broken
return new BuildReport(build.getNumber(), build.getName(), passed, failed, error, suites, total, notRun);
}
public BuildReportExtended parseBuildReportExtended(Run<?, ?> build) throws Exception {
Run<?, ?> previousNotFailedBuild = build.getPreviousNotFailedBuild();
return parseBuildReportExtended(new RunWrapperFromRun(build), new RunWrapperFromRun(previousNotFailedBuild));
}
public BuildReportExtended parseBuildReportExtended(RunWrapper build, RunWrapper previousNotFailedBuild) throws Exception {
List<SuiteTests> currentBuildTestsList = parseSuiteTests(build.getRoot());
List<SuiteTests> prevBuildTestsList;
if (previousNotFailedBuild != null) {
prevBuildTestsList = parseSuiteTests(previousNotFailedBuild.getRoot());
} else {
prevBuildTestsList = new ArrayList<>();
}
Set<String> prevSuites = prevBuildTestsList.stream()
.sequential()
.map(s -> s.getName())
.collect(Collectors.toSet());
List<String> addedSuites = currentBuildTestsList.stream()
.sequential()
.map(s -> s.getName())
.filter(s -> !prevSuites.contains(s))
.collect(Collectors.toList());
Set<String> currentSuites = currentBuildTestsList.stream()
.sequential()
.map(s -> s.getName())
.collect(Collectors.toSet());
List<String> removedSuites = prevBuildTestsList.stream()
.sequential()
.map(s -> s.getName())
.filter(s -> !currentSuites.contains(s))
.collect(Collectors.toList());
List<SuiteTestChanges> result = new ArrayList<>();
BuildReport currentReport = parseBuildReport(build);
if (previousNotFailedBuild != null) {
BuildReport previousReport = parseBuildReport(previousNotFailedBuild);
Map<String, Report> prevReportsMap = previousReport.getSuites().stream()
.sequential()
.collect(Collectors.toMap(s -> s.getName(), s -> s.getReport()));
for (Suite suite : currentReport.getSuites()) {
if (!prevReportsMap.containsKey(suite.getName())) {
continue;
}
Set<String> currentFailedEroredTests = suite.getReport().getTestProblems().stream()
.sequential()
.map(t -> t.getName())
.collect(Collectors.toSet());
Set<TestDescriptor> currentTestsDescriptors = suite.getReport().getTestProblems().stream()
.sequential()
.map(t -> new TestDescriptor(t.getName(), t.getStatus()))
.collect(Collectors.toSet());
currentTestsDescriptors.addAll(currentBuildTestsList.stream()
.sequential()
.filter(s -> suite.getName().equals(s.getName()))
.flatMap(s -> s.getTests().stream())
.filter(s -> !currentFailedEroredTests.contains(s))
.map(s -> new TestDescriptor(s, TestStatus.PASSED))
.collect(Collectors.toList()));
Set<String> previousFailedErroredTests = prevReportsMap.get(suite.getName()).getTestProblems().stream()
.sequential()
.map(t -> t.getName())
.collect(Collectors.toSet());
Set<TestDescriptor> previousTestsDescriptors = prevReportsMap.get(suite.getName()).getTestProblems().stream()
.sequential()
.map(t -> new TestDescriptor(t.getName(), t.getStatus()))
.collect(Collectors.toSet());
previousTestsDescriptors.addAll(prevBuildTestsList.stream()
.sequential()
.filter(s -> suite.getName().equals(s.getName()))
.flatMap(s -> s.getTests().stream())
.filter(s -> !previousFailedErroredTests.contains(s))
.map(s -> new TestDescriptor(s, TestStatus.PASSED))
.collect(Collectors.toList()));
List<TestDescriptor> testChanges = currentTestsDescriptors.stream()
.sequential()
.filter(t -> !previousTestsDescriptors.contains(t))
.collect(Collectors.toList());
Set<String> previousTests = previousTestsDescriptors.stream()
.sequential()
.map(d -> d.name)
.collect(Collectors.toSet());
Set<String> currentTests = currentTestsDescriptors.stream()
.sequential()
.map(d -> d.name)
.collect(Collectors.toSet());
SuiteTestChanges changes = new SuiteTestChanges(
// suite name:
suite.getName(),
// new failures:
testChanges.stream()
.sequential()
.filter(t -> t.status == TestStatus.FAILED)
.map(t -> t.name)
.collect(Collectors.toList()),
// new errors:
testChanges.stream()
.sequential()
.filter(t -> t.status == TestStatus.ERROR)
.map(t -> t.name)
.collect(Collectors.toList()),
// new fixes:
testChanges.stream()
.sequential()
.filter(t -> t.status == TestStatus.PASSED)
.map(t -> t.name)
.collect(Collectors.toList()),
// added tests:
currentTests.stream()
.sequential()
.filter(s -> !previousTests.contains(s))
.sorted()
.collect(Collectors.toList()),
// removed tests:
previousTests.stream()
.sequential()
.filter(s -> !currentTests.contains(s))
.sorted()
.collect(Collectors.toList()));
result.add(changes);
}
}
SuitesWithResults allTests = null;
String job = build.getRoot().getParentFile().getParentFile().getName();
try {
allTests = SuitesWithResults.create(currentBuildTestsList, parseBuildReport(build), job, build.getNumber());
} catch (Exception ex) {
ex.printStackTrace();
}
return new BuildReportExtended(
currentReport.getBuildNumber(),
currentReport.getBuildName(),
currentReport.getPassed(),
currentReport.getFailed(),
currentReport.getError(),
currentReport.getSuites(),
addedSuites,
removedSuites,
result,
currentReport.getTotal(),
currentReport.getNotRun(),
allTests,
job);
}
private List<Suite> parseBuildSummary(Run<?, ?> build) throws Exception {
return parseBuildSummary(build.getRootDir());
}
private List<Suite> parseBuildSummary(File rootDir) throws Exception {
List<Suite> result = new ArrayList<>();
for (String prefix : prefixes) {
File reportFile = new File(rootDir, prefix + "-" + REPORT_JSON);
if (reportFile.exists() && reportFile.isFile() && reportFile.canRead()) {
try (Reader in = new InputStreamReader(new BufferedInputStream(new FileInputStream(reportFile)),
StandardCharsets.UTF_8)) {
List<Suite> list = new Gson().fromJson(in, new TypeToken<List<Suite>>() {
}.getType());
result.addAll(list);
}
}
}
return result;
}
private List<SuiteTests> parseSuiteTests(Run<?, ?> build) throws Exception {
return parseSuiteTests(build.getRootDir());
}
/**
* this is very costly mehtod, use rarely
*
* @param build
* @return list of all tests in suite
* @throws Exception
*/
public List<SuiteTests> parseSuiteTests(File build) throws Exception {
List<SuiteTests> result = new ArrayList<>();
for (String prefix : prefixes) {
File suiteTestsFile = new File(build, prefix + "-" + REPORT_TESTS_LIST_JSON);
if (suiteTestsFile.exists() && suiteTestsFile.isFile() && suiteTestsFile.canRead()) {
try (Reader in = new InputStreamReader(new BufferedInputStream(new FileInputStream(suiteTestsFile)),
StandardCharsets.UTF_8)) {
List<SuiteTests> list = new Gson().fromJson(in, new TypeToken<List<SuiteTests>>() {
}.getType());
result.addAll(list);
}
}
}
return result;
}
private class TestDescriptor {
private final String name;
private final TestStatus status;
public TestDescriptor(String name, TestStatus status) {
this.name = name;
this.status = status;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + Objects.hashCode(this.name);
hash = 79 * hash + Objects.hashCode(this.status);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TestDescriptor other = (TestDescriptor) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (this.status != other.status) {
return false;
}
return true;
}
}
}
|
package orwell.proxy.robot;
import lejos.mf.common.UnitMessage;
import lejos.mf.common.UnitMessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import orwell.proxy.EnumGameState;
public class RobotGameStateVisitor {
private final static Logger logback = LoggerFactory.getLogger(RobotGameStateVisitor.class);
private final static String VICTORY_PAYLOAD_HEADER = "game vict ";
private final static String DEFEAT_PAYLOAD_HEADER = "game fail ";
private final static String DRAW_PAYLOAD_HEADER = "game draw ";
private final String winningTeam;
private final EnumGameState gameState;
public RobotGameStateVisitor(final EnumGameState gameState,
final String winningTeam) {
this.gameState = gameState;
this.winningTeam = winningTeam;
}
public RobotGameStateVisitor(final EnumGameState gameState) {
this(gameState, null);
}
public void visit(final RobotsMap robotsMap) {
for (final IRobot robot : robotsMap.getRegisteredRobots()) {
setGameState(robot);
}
}
private void setGameState(final IRobot robot) {
switch (gameState) {
case WAITING_TO_START:
setWaitingToStart(robot);
break;
case PLAYING:
setPlaying(robot);
break;
case FINISHED:
setFinished(robot);
break;
case UNDEFINED:
setUndefined(robot);
break;
}
}
private void setFinished(final IRobot robot) {
if (null == winningTeam || winningTeam.equals("")) {
setDraw(robot);
} else if (winningTeam.equals(robot.getTeamName())) {
setVictory(robot);
} else {
setDefeat(robot);
}
}
private void setUndefined(final IRobot robot) {
logback.warn("Undefined victory state for robot " + robot.getRoutingId() + ". Ignored.");
}
private void setDraw(final IRobot robot) {
robot.setVictoryState(EnumRobotVictoryState.DRAW);
robot.sendUnitMessage(new UnitMessage(UnitMessageType.Command, DRAW_PAYLOAD_HEADER));
logback.info("Draw info sent to robot " + robot.getRoutingId());
}
private void setPlaying(final IRobot robot) {
robot.setVictoryState(EnumRobotVictoryState.PLAYING);
}
private void setWaitingToStart(final IRobot robot) {
robot.setVictoryState(EnumRobotVictoryState.WAITING_FOR_START);
logback.info("Robot " + robot.getRoutingId() + " is waiting for the game to start");
}
private void setVictory(final IRobot robot) {
robot.setVictoryState(EnumRobotVictoryState.WINNER);
robot.sendUnitMessage(new UnitMessage(UnitMessageType.Command, VICTORY_PAYLOAD_HEADER));
logback.info("Victory info sent to robot " + robot.getRoutingId());
}
private void setDefeat(final IRobot robot) {
robot.setVictoryState(EnumRobotVictoryState.DEFEATED);
robot.sendUnitMessage(new UnitMessage(UnitMessageType.Command, DEFEAT_PAYLOAD_HEADER));
logback.info("Defeat info sent to robot " + robot.getRoutingId());
}
}
|
package io.github.aquerr.eaglefactions;
import io.github.aquerr.eaglefactions.commands.CreateCommand;
import io.github.aquerr.eaglefactions.commands.EagleFactionsCommand;
import io.github.aquerr.eaglefactions.commands.HelpCommand;
import com.google.inject.Inject;
import io.github.aquerr.eaglefactions.config.FactionsConfig;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.text.Text;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Plugin(id = PluginInfo.Id, name = PluginInfo.Name, version = PluginInfo.Version, description = PluginInfo.Description)
public class EagleFactions
{
public static Map<List<String>, CommandSpec> _subcommands;
@Inject
private Logger _logger;
public Logger getLogger(){return _logger;}
private static EagleFactions eagleFactions;
public static EagleFactions getEagleFactions() {return eagleFactions;}
@Inject
@ConfigDir(sharedRoot = false)
private Path configDir;
public Path getConfigDir(){return configDir;}
@Listener
public void onServerInitialization(GameInitializationEvent event)
{
//TODO:Change color of loggs.
getLogger ().info("EagleFactions is loading...");
getLogger ().debug ("Preparing wings...");
getLogger().info("Configs...");
SetupConfigs();
getLogger().info("Commands...");
InitializeCommands();
}
private void SetupConfigs()
{
//Create config directory for EagleFactions.
try
{
Files.createDirectories(configDir);
}
catch (IOException e)
{
e.printStackTrace();
}
// Create settings & data directory for EagleFactions
if (!Files.exists(configDir.resolve("settings")))
{
try
{
Files.createDirectories(configDir.resolve("settings"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (!Files.exists(configDir.resolve("data")))
{
try
{
Files.createDirectories(configDir.resolve("data"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
getLogger().info("Setting up configs...");
// Create config.conf
//Config.getConfig().setup();
// Create messages.conf
//MessageConfig.getConfig().setup();
// Create teams.conf
//TODO:Error occour while loading FactionsConfig.
//FactionsConfig.getConfig().setup();
// Create claims.conf
//ClaimsConfig.getConfig().setup();
// Create claims.conf
//ClaimsConfig.getConfig().setup();
// Start Tax Service
//Utils.startTaxService();
}
private void InitializeCommands()
{
getLogger ().info ("Initializing commands...");
_subcommands = new HashMap<List<String>, CommandSpec>();
//Help command should display all possible commands in plugin.
_subcommands.put (Arrays.asList ("help"), CommandSpec.builder ()
.description (Text.of ("Help"))
.permission ("eaglefactions.command.help")
.executor (new HelpCommand ())
.build());
//Create command should create a faction.
_subcommands.put (Arrays.asList ("create"), CommandSpec.builder ()
.description (Text.of ("Create Faction Command"))
.permission ("eaglefactions.command.create")
.arguments (GenericArguments.onlyOne (GenericArguments.string (Text.of ("faction name"))))
.executor (new CreateCommand ())
.build ());
//Build all commands
CommandSpec commandEagleFactions = CommandSpec.builder ()
.description (Text.of ("Factions"))
.permission ("eaglefactions.command.*")
.executor (new EagleFactionsCommand ())
.children (_subcommands)
.build ();
//Register commands
Sponge.getCommandManager ().register (this, commandEagleFactions, "factions", "f");
//Display some info text in the console.
getLogger ().info ("EagleFactions is ready to use!");
getLogger ().info ("Thank you for choosing this plugin!");
getLogger ().info ("Current version " + PluginInfo.Version);
getLogger ().info ("Have a great time with EagleFactions! :D");
}
}
|
package org.xcolab.portlets.messaging.beans;
import com.ext.portlet.messaging.MessageUtil;
import com.ext.portlet.model.MessageRecipientStatus;
import com.ext.portlet.service.MessageRecipientStatusLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.User;
import org.xcolab.portlets.messaging.enums.MessageType;
import org.xcolab.portlets.messaging.paging.MessageDataPage;
import org.xcolab.portlets.messaging.paging.PageLinkWrapper;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MessagingBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final int PAGE_SIZE = 10;
private final static int PAGER_RANGE = 3;
private User user;
private MessageType messageType = MessageType.INBOX;
private int messagesCount;
private MessageDataPage dataPage;
private int pageNumber = 1;
@SuppressWarnings("unused")
public MessagingBean() { }
public MessagingBean(User user, int pageNumber, MessageType messageType) throws SystemException, PortalException {
this.user = user;
this.pageNumber = pageNumber;
this.messageType = messageType;
dataPage = new MessageDataPage(user, messageType, PAGE_SIZE, pageNumber);
messagesCount = MessageUtil.countMessages(user.getUserId(),
messageType.getTypeStr());
}
public MessageType getType() {
return messageType;
}
public int getMessagesCount() {
return messagesCount;
}
public void setMessageType(MessageType messageType) {
this.messageType = messageType;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void markMessageAsOpened(long messageId) throws PortalException, SystemException {
List<MessageRecipientStatus> statuses =
MessageRecipientStatusLocalServiceUtil.findByMessageId(messageId, 0, Integer.MAX_VALUE);
for (MessageRecipientStatus mr : statuses) {
if (mr.getUserId() == user.getUserId()) {
mr.setOpened(true);
MessageRecipientStatusLocalServiceUtil.updateMessageRecipientStatus(mr);
}
}
}
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public MessageDataPage getDataPage() {
return dataPage;
}
public void setDataPage(MessageDataPage dataPage) {
this.dataPage = dataPage;
}
public List<PageLinkWrapper> getPageLinks() {
List<PageLinkWrapper> pageLinks = new ArrayList<>();
pageLinks.add(new PageLinkWrapper("<< First", 1, messageType));
if (pageNumber > 1) {
pageLinks.add(new PageLinkWrapper("< Previous", pageNumber - 1, messageType));
}
for (int i = Math.max(1, pageNumber - PAGER_RANGE), stop =
Math.min(getNumberOfPages(), pageNumber + PAGER_RANGE); i <= stop; i++) {
pageLinks.add(new PageLinkWrapper("", i, messageType));
}
if (pageNumber < getNumberOfPages()) {
pageLinks.add(new PageLinkWrapper("Next >", pageNumber + 1, messageType));
}
pageLinks.add(new PageLinkWrapper("Last >>", getNumberOfPages(), messageType));
return pageLinks;
}
public int getNumberOfPages() {
int numPages = messagesCount / PAGE_SIZE;
if (messagesCount % PAGE_SIZE != 0) {
numPages++;
}
return numPages;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.