repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/LineChartPlotOptions.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType; | /*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class LineChartPlotOptions extends HighChartsPlotOptionsImpl {
public LineChartPlotOptions() { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/LineChartPlotOptions.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
/*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class LineChartPlotOptions extends HighChartsPlotOptionsImpl {
public LineChartPlotOptions() { | chartType = ChartType.LINE; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/ColumnChartPlotOptions.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType; | /*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class ColumnChartPlotOptions extends HighChartsPlotOptionsImpl {
public ColumnChartPlotOptions() { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/ColumnChartPlotOptions.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
/*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class ColumnChartPlotOptions extends HighChartsPlotOptionsImpl {
public ColumnChartPlotOptions() { | chartType = ChartType.COLUMN; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/HighChartsSeriesImpl.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.ArrayList;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: HighChartsSeriesImpl.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class HighChartsSeriesImpl implements HighChartsSeries {
ChartType chartType; | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/HighChartsSeriesImpl.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.ArrayList;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: HighChartsSeriesImpl.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class HighChartsSeriesImpl implements HighChartsSeries {
ChartType chartType; | List<HighChartsData> data = new ArrayList<>(); |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/FunnelChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: FunnelChartSeries.class<br>
* Erstellt am 25. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class FunnelChartSeries extends HighChartsSeriesImpl {
public FunnelChartSeries(String name) { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/FunnelChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: FunnelChartSeries.class<br>
* Erstellt am 25. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class FunnelChartSeries extends HighChartsSeriesImpl {
public FunnelChartSeries(String name) { | this.chartType = ChartType.FUNNEL; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/FunnelChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: FunnelChartSeries.class<br>
* Erstellt am 25. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class FunnelChartSeries extends HighChartsSeriesImpl {
public FunnelChartSeries(String name) {
this.chartType = ChartType.FUNNEL;
this.name = name;
}
| // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/FunnelChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: FunnelChartSeries.class<br>
* Erstellt am 25. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class FunnelChartSeries extends HighChartsSeriesImpl {
public FunnelChartSeries(String name) {
this.chartType = ChartType.FUNNEL;
this.name = name;
}
| public FunnelChartSeries(String name, List<HighChartsData> data) { |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/BoxPlotChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/BoxPlotChartData.java
// public class BoxPlotChartData implements HighChartsData {
//
// private String name = null;
// private double minimum;
// private double lowerQuartile;
// private double median;
// private double upperQuartile;
// private double maximum;
//
// public BoxPlotChartData(String name, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.name = name;
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public BoxPlotChartData(double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public double getMinimum() {
// return minimum;
// }
//
// public void setMinimum(double minimum) {
// this.minimum = minimum;
// }
//
// public double getLowerQuartile() {
// return lowerQuartile;
// }
//
// public void setLowerQuartile(double lowerQuartile) {
// this.lowerQuartile = lowerQuartile;
// }
//
// public double getMedian() {
// return median;
// }
//
// public void setMedian(double median) {
// this.median = median;
// }
//
// public double getUpperQuartile() {
// return upperQuartile;
// }
//
// public void setUpperQuartile(double upperQuartile) {
// this.upperQuartile = upperQuartile;
// }
//
// public double getMaximum() {
// return maximum;
// }
//
// public void setMaximum(double maximum) {
// this.maximum = maximum;
// }
//
// @Override
// public String getHighChartValue() {
// if (name != null) {
// return "['" + name + "', " + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// } else {
// return "[" + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// }
// }
//
// @Override
// public String toString() {
// return this.getHighChartValue();
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.BoxPlotChartData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaRangeChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class BoxPlotChartSeries extends HighChartsSeriesImpl {
public BoxPlotChartSeries(String name) { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/BoxPlotChartData.java
// public class BoxPlotChartData implements HighChartsData {
//
// private String name = null;
// private double minimum;
// private double lowerQuartile;
// private double median;
// private double upperQuartile;
// private double maximum;
//
// public BoxPlotChartData(String name, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.name = name;
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public BoxPlotChartData(double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public double getMinimum() {
// return minimum;
// }
//
// public void setMinimum(double minimum) {
// this.minimum = minimum;
// }
//
// public double getLowerQuartile() {
// return lowerQuartile;
// }
//
// public void setLowerQuartile(double lowerQuartile) {
// this.lowerQuartile = lowerQuartile;
// }
//
// public double getMedian() {
// return median;
// }
//
// public void setMedian(double median) {
// this.median = median;
// }
//
// public double getUpperQuartile() {
// return upperQuartile;
// }
//
// public void setUpperQuartile(double upperQuartile) {
// this.upperQuartile = upperQuartile;
// }
//
// public double getMaximum() {
// return maximum;
// }
//
// public void setMaximum(double maximum) {
// this.maximum = maximum;
// }
//
// @Override
// public String getHighChartValue() {
// if (name != null) {
// return "['" + name + "', " + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// } else {
// return "[" + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// }
// }
//
// @Override
// public String toString() {
// return this.getHighChartValue();
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/BoxPlotChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.BoxPlotChartData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaRangeChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class BoxPlotChartSeries extends HighChartsSeriesImpl {
public BoxPlotChartSeries(String name) { | chartType = ChartType.BOXPLOT; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/BoxPlotChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/BoxPlotChartData.java
// public class BoxPlotChartData implements HighChartsData {
//
// private String name = null;
// private double minimum;
// private double lowerQuartile;
// private double median;
// private double upperQuartile;
// private double maximum;
//
// public BoxPlotChartData(String name, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.name = name;
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public BoxPlotChartData(double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public double getMinimum() {
// return minimum;
// }
//
// public void setMinimum(double minimum) {
// this.minimum = minimum;
// }
//
// public double getLowerQuartile() {
// return lowerQuartile;
// }
//
// public void setLowerQuartile(double lowerQuartile) {
// this.lowerQuartile = lowerQuartile;
// }
//
// public double getMedian() {
// return median;
// }
//
// public void setMedian(double median) {
// this.median = median;
// }
//
// public double getUpperQuartile() {
// return upperQuartile;
// }
//
// public void setUpperQuartile(double upperQuartile) {
// this.upperQuartile = upperQuartile;
// }
//
// public double getMaximum() {
// return maximum;
// }
//
// public void setMaximum(double maximum) {
// this.maximum = maximum;
// }
//
// @Override
// public String getHighChartValue() {
// if (name != null) {
// return "['" + name + "', " + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// } else {
// return "[" + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// }
// }
//
// @Override
// public String toString() {
// return this.getHighChartValue();
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.BoxPlotChartData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaRangeChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class BoxPlotChartSeries extends HighChartsSeriesImpl {
public BoxPlotChartSeries(String name) {
chartType = ChartType.BOXPLOT;
this.name = name;
}
| // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/BoxPlotChartData.java
// public class BoxPlotChartData implements HighChartsData {
//
// private String name = null;
// private double minimum;
// private double lowerQuartile;
// private double median;
// private double upperQuartile;
// private double maximum;
//
// public BoxPlotChartData(String name, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.name = name;
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public BoxPlotChartData(double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public double getMinimum() {
// return minimum;
// }
//
// public void setMinimum(double minimum) {
// this.minimum = minimum;
// }
//
// public double getLowerQuartile() {
// return lowerQuartile;
// }
//
// public void setLowerQuartile(double lowerQuartile) {
// this.lowerQuartile = lowerQuartile;
// }
//
// public double getMedian() {
// return median;
// }
//
// public void setMedian(double median) {
// this.median = median;
// }
//
// public double getUpperQuartile() {
// return upperQuartile;
// }
//
// public void setUpperQuartile(double upperQuartile) {
// this.upperQuartile = upperQuartile;
// }
//
// public double getMaximum() {
// return maximum;
// }
//
// public void setMaximum(double maximum) {
// this.maximum = maximum;
// }
//
// @Override
// public String getHighChartValue() {
// if (name != null) {
// return "['" + name + "', " + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// } else {
// return "[" + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// }
// }
//
// @Override
// public String toString() {
// return this.getHighChartValue();
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/BoxPlotChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.BoxPlotChartData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaRangeChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class BoxPlotChartSeries extends HighChartsSeriesImpl {
public BoxPlotChartSeries(String name) {
chartType = ChartType.BOXPLOT;
this.name = name;
}
| public BoxPlotChartSeries(String name, List<BoxPlotChartData> data) { |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/BoxPlotChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/BoxPlotChartData.java
// public class BoxPlotChartData implements HighChartsData {
//
// private String name = null;
// private double minimum;
// private double lowerQuartile;
// private double median;
// private double upperQuartile;
// private double maximum;
//
// public BoxPlotChartData(String name, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.name = name;
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public BoxPlotChartData(double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public double getMinimum() {
// return minimum;
// }
//
// public void setMinimum(double minimum) {
// this.minimum = minimum;
// }
//
// public double getLowerQuartile() {
// return lowerQuartile;
// }
//
// public void setLowerQuartile(double lowerQuartile) {
// this.lowerQuartile = lowerQuartile;
// }
//
// public double getMedian() {
// return median;
// }
//
// public void setMedian(double median) {
// this.median = median;
// }
//
// public double getUpperQuartile() {
// return upperQuartile;
// }
//
// public void setUpperQuartile(double upperQuartile) {
// this.upperQuartile = upperQuartile;
// }
//
// public double getMaximum() {
// return maximum;
// }
//
// public void setMaximum(double maximum) {
// this.maximum = maximum;
// }
//
// @Override
// public String getHighChartValue() {
// if (name != null) {
// return "['" + name + "', " + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// } else {
// return "[" + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// }
// }
//
// @Override
// public String toString() {
// return this.getHighChartValue();
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.BoxPlotChartData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaRangeChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class BoxPlotChartSeries extends HighChartsSeriesImpl {
public BoxPlotChartSeries(String name) {
chartType = ChartType.BOXPLOT;
this.name = name;
}
public BoxPlotChartSeries(String name, List<BoxPlotChartData> data) {
chartType = ChartType.BOXPLOT;
this.name = name;
if (!data.isEmpty()) {
for (BoxPlotChartData boxPlotChartData : data) {
this.data.add(boxPlotChartData);
}
}
}
public void addData(BoxPlotChartData boxPlotChartData) {
this.data.add(boxPlotChartData);
}
/**
* @deprecated This method isn't implemented for this type.
* Use {@link #addData(BoxPlotChartData)} instead.
*/
@Deprecated
@Override | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/BoxPlotChartData.java
// public class BoxPlotChartData implements HighChartsData {
//
// private String name = null;
// private double minimum;
// private double lowerQuartile;
// private double median;
// private double upperQuartile;
// private double maximum;
//
// public BoxPlotChartData(String name, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.name = name;
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public BoxPlotChartData(double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) {
// this.minimum = minimum;
// this.lowerQuartile = lowerQuartile;
// this.median = median;
// this.upperQuartile = upperQuartile;
// this.maximum = maximum;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public double getMinimum() {
// return minimum;
// }
//
// public void setMinimum(double minimum) {
// this.minimum = minimum;
// }
//
// public double getLowerQuartile() {
// return lowerQuartile;
// }
//
// public void setLowerQuartile(double lowerQuartile) {
// this.lowerQuartile = lowerQuartile;
// }
//
// public double getMedian() {
// return median;
// }
//
// public void setMedian(double median) {
// this.median = median;
// }
//
// public double getUpperQuartile() {
// return upperQuartile;
// }
//
// public void setUpperQuartile(double upperQuartile) {
// this.upperQuartile = upperQuartile;
// }
//
// public double getMaximum() {
// return maximum;
// }
//
// public void setMaximum(double maximum) {
// this.maximum = maximum;
// }
//
// @Override
// public String getHighChartValue() {
// if (name != null) {
// return "['" + name + "', " + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// } else {
// return "[" + minimum + ", " + lowerQuartile + ", " + median + ", " + upperQuartile + ", " + maximum + "]";
// }
// }
//
// @Override
// public String toString() {
// return this.getHighChartValue();
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/BoxPlotChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.BoxPlotChartData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaRangeChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class BoxPlotChartSeries extends HighChartsSeriesImpl {
public BoxPlotChartSeries(String name) {
chartType = ChartType.BOXPLOT;
this.name = name;
}
public BoxPlotChartSeries(String name, List<BoxPlotChartData> data) {
chartType = ChartType.BOXPLOT;
this.name = name;
if (!data.isEmpty()) {
for (BoxPlotChartData boxPlotChartData : data) {
this.data.add(boxPlotChartData);
}
}
}
public void addData(BoxPlotChartData boxPlotChartData) {
this.data.add(boxPlotChartData);
}
/**
* @deprecated This method isn't implemented for this type.
* Use {@link #addData(BoxPlotChartData)} instead.
*/
@Deprecated
@Override | public void addData(HighChartsData highChartsData) { |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/AreaSplineChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaSplineChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class AreaSplineChartSeries extends HighChartsSeriesImpl {
public AreaSplineChartSeries(String name) { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/AreaSplineChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaSplineChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class AreaSplineChartSeries extends HighChartsSeriesImpl {
public AreaSplineChartSeries(String name) { | chartType = ChartType.AREASPLINE; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/AreaSplineChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaSplineChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class AreaSplineChartSeries extends HighChartsSeriesImpl {
public AreaSplineChartSeries(String name) {
chartType = ChartType.AREASPLINE;
this.name = name;
}
| // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/AreaSplineChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.series<br>
* Klasse: AreaSplineChartSeries.class<br>
* Erstellt am 21. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class AreaSplineChartSeries extends HighChartsSeriesImpl {
public AreaSplineChartSeries(String name) {
chartType = ChartType.AREASPLINE;
this.name = name;
}
| public AreaSplineChartSeries(String name, List<HighChartsData> data) { |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/ColumnChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
public class ColumnChartSeries extends HighChartsSeriesImpl {
public ColumnChartSeries(String name) { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/ColumnChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
public class ColumnChartSeries extends HighChartsSeriesImpl {
public ColumnChartSeries(String name) { | chartType = ChartType.COLUMN; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/ColumnChartSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List; | package at.downdrown.vaadinaddons.highchartsapi.model.series;
public class ColumnChartSeries extends HighChartsSeriesImpl {
public ColumnChartSeries(String name) {
chartType = ChartType.COLUMN;
this.name = name;
}
| // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/ColumnChartSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import java.util.List;
package at.downdrown.vaadinaddons.highchartsapi.model.series;
public class ColumnChartSeries extends HighChartsSeriesImpl {
public ColumnChartSeries(String name) {
chartType = ChartType.COLUMN;
this.name = name;
}
| public ColumnChartSeries(String name, List<HighChartsData> data) { |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/ErrorBarChartPlotOptions.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType; | package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.plotoptions<br>
* Klasse: ErrorBarChartPlotOptions.class<br>
* Erstellt am 25. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class ErrorBarChartPlotOptions extends HighChartsPlotOptionsImpl {
public ErrorBarChartPlotOptions() { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/ErrorBarChartPlotOptions.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
/**
* Projekt: VaadinHighChartsAPI<br>
* Package: at.downdrown.vaadinaddons.highchartsapi.model.plotoptions<br>
* Klasse: ErrorBarChartPlotOptions.class<br>
* Erstellt am 25. August 2015.<br>
* Copyright © HSWE Allg. Applikationen.<br>
* <br>
*
* @author Manfred Huber (02ub0j08)<br>
*/
public class ErrorBarChartPlotOptions extends HighChartsPlotOptionsImpl {
public ErrorBarChartPlotOptions() { | this.chartType = ChartType.ERRORBAR; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/HighChartsSeries.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/HighchartsObject.java
// public interface HighchartsObject {
//
// String getHighChartValue();
//
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.HighchartsObject; | /*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.series;
public interface HighChartsSeries extends HighchartsObject {
//Needed for script generation!
ChartType getChartType();
//Data manipulation | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/HighchartsObject.java
// public interface HighchartsObject {
//
// String getHighChartValue();
//
// }
//
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/data/HighChartsData.java
// public interface HighChartsData extends HighchartsObject {
//
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/series/HighChartsSeries.java
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.HighchartsObject;
/*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.series;
public interface HighChartsSeries extends HighchartsObject {
//Needed for script generation!
ChartType getChartType();
//Data manipulation | void addData(HighChartsData highChartsData); |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/AreaSplineRangeChartPlotOptions.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType; | /*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class AreaSplineRangeChartPlotOptions extends HighChartsPlotOptionsImpl {
public AreaSplineRangeChartPlotOptions() { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/AreaSplineRangeChartPlotOptions.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
/*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class AreaSplineRangeChartPlotOptions extends HighChartsPlotOptionsImpl {
public AreaSplineRangeChartPlotOptions() { | chartType = ChartType.AREASPLINERANGE; |
downdrown/VaadinHighChartsAPI | src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/AreaChartPlotOptions.java | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
| import at.downdrown.vaadinaddons.highchartsapi.model.ChartType; | /*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class AreaChartPlotOptions extends HighChartsPlotOptionsImpl {
public AreaChartPlotOptions() { | // Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/ChartType.java
// public enum ChartType implements HighchartsObject {
//
// AREA("area"),
// AREARANGE("arearange"),
// AREASPLINE("areaspline"),
// AREASPLINERANGE("areasplinerange"),
// BAR("bar"),
// BOXPLOT("boxplot"),
// BUBBLE("bubble"),
// COLUMN("column"),
// COLUMNRANGE("columnrange"),
// ERRORBAR("errorbar"),
// FUNNEL("funnel"),
// GAUGE("gauge"),
// HEATMAP("heatmap"),
// LINE("line"),
// PIE("pie"),
// POLYGON("polygon"),
// PYRAMID("pyramid"),
// SCATTER("scatter"),
// SOLIDGAUGE("solidgauge"),
// SPLINE("spline"),
// TREEMAP("treemap"),
// WATERFALL("waterfall");
//
// private String highchartsvalue;
//
// ChartType(String highchartsvalue) {
// this.highchartsvalue = highchartsvalue;
// }
//
// public String getHighChartValue() {
// return this.highchartsvalue;
// }
// }
// Path: src/main/java/at/downdrown/vaadinaddons/highchartsapi/model/plotoptions/AreaChartPlotOptions.java
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
/*
* Copyright (c) 2015 by Manfred Huber.
*/
package at.downdrown.vaadinaddons.highchartsapi.model.plotoptions;
public class AreaChartPlotOptions extends HighChartsPlotOptionsImpl {
public AreaChartPlotOptions() { | chartType = ChartType.AREA; |
automenta/netentionj | src/main/java/netention/core/Publish.java | // Path: src/main/java/netention/web/Bus.java
// final public class Bus {
// /** status of interactive sessions */
// public final static String SESSION = "session";
//
// /** declared interest in a topic, passively requests for more information */
// public final static String INTEREST = "interest";
// public final static String INTEREST_WIKIPEDIA = "interest.wikipedia";
//
// /** permanent knowledge to share */
// public final static String PUBLISH = "publish";
//
// /** transient knowledge to share */
// public final static String SAY = "say";
// }
| import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import java.util.List;
import java.util.Map;
import netention.web.Bus;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.impl.Json; | /*
* Copyright (C) 2014 me
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package netention.core;
/**
*
* @author me
*/
public class Publish implements Handler<Message> {
private final Core core;
private final EventBus bus;
public Publish(Core c, EventBus b) {
this.core = c;
this.bus = b; | // Path: src/main/java/netention/web/Bus.java
// final public class Bus {
// /** status of interactive sessions */
// public final static String SESSION = "session";
//
// /** declared interest in a topic, passively requests for more information */
// public final static String INTEREST = "interest";
// public final static String INTEREST_WIKIPEDIA = "interest.wikipedia";
//
// /** permanent knowledge to share */
// public final static String PUBLISH = "publish";
//
// /** transient knowledge to share */
// public final static String SAY = "say";
// }
// Path: src/main/java/netention/core/Publish.java
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import java.util.List;
import java.util.Map;
import netention.web.Bus;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.impl.Json;
/*
* Copyright (C) 2014 me
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package netention.core;
/**
*
* @author me
*/
public class Publish implements Handler<Message> {
private final Core core;
private final EventBus bus;
public Publish(Core c, EventBus b) {
this.core = c;
this.bus = b; | b.registerHandler(Bus.PUBLISH, this); |
automenta/netentionj | src/main/java/netention/util/IRC.java | // Path: src/main/java/netention/web/Bus.java
// final public class Bus {
// /** status of interactive sessions */
// public final static String SESSION = "session";
//
// /** declared interest in a topic, passively requests for more information */
// public final static String INTEREST = "interest";
// public final static String INTEREST_WIKIPEDIA = "interest.wikipedia";
//
// /** permanent knowledge to share */
// public final static String PUBLISH = "publish";
//
// /** transient knowledge to share */
// public final static String SAY = "say";
// }
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import netention.web.Bus;
import org.vertx.java.core.eventbus.EventBus; | writer.write("USER " + login + " 8 * : Java IRC Hacks Bot\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
System.out.println("Nickname is already in use.");
return;
}
}
// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );
// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
if (line.toLowerCase( ).startsWith("PING ")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.write("PRIVMSG " + channel + " :I got pinged!\r\n");
writer.flush( );
}
else {
// Print the raw line received by the bot. | // Path: src/main/java/netention/web/Bus.java
// final public class Bus {
// /** status of interactive sessions */
// public final static String SESSION = "session";
//
// /** declared interest in a topic, passively requests for more information */
// public final static String INTEREST = "interest";
// public final static String INTEREST_WIKIPEDIA = "interest.wikipedia";
//
// /** permanent knowledge to share */
// public final static String PUBLISH = "publish";
//
// /** transient knowledge to share */
// public final static String SAY = "say";
// }
// Path: src/main/java/netention/util/IRC.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import netention.web.Bus;
import org.vertx.java.core.eventbus.EventBus;
writer.write("USER " + login + " 8 * : Java IRC Hacks Bot\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
System.out.println("Nickname is already in use.");
return;
}
}
// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );
// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
if (line.toLowerCase( ).startsWith("PING ")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.write("PRIVMSG " + channel + " :I got pinged!\r\n");
writer.flush( );
}
else {
// Print the raw line received by the bot. | eventBus.publish(Bus.SAY, line); |
Sylvain-Bugat/RundeckMonitor | src/main/java/com/github/sbugat/rundeckmonitor/VersionChecker.java | // Path: src/main/java/com/github/sbugat/rundeckmonitor/tools/EnvironmentTools.java
// public final class EnvironmentTools {
//
// /** SLF4J XLogger. */
// private static final XLogger LOG = XLoggerFactory.getXLogger(EnvironmentTools.class);
//
// /** Windows OS name property. */
// private static final String OS_NAME_PROPERTY = "os.name"; //$NON-NLS-1$
// /** Windows name in OS name property. */
// private static final String WINDOWS_OS_NAME = "windows"; //$NON-NLS-1$
//
// /**
// * Private constructor to prevent Instantiating.
// */
// private EnvironmentTools() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Check if the operating system is a windows based on a property, otherwise it's a Linux/Mac-OS.
// *
// * @return true if the OS is a windows*
// */
// public static boolean isWindows() {
//
// LOG.entry();
// final String operatingSystem = System.getProperty(OS_NAME_PROPERTY);
//
// if (null == operatingSystem) {
// LOG.exit(false);
// return false;
// }
//
// final boolean isWindows = operatingSystem.toLowerCase(Locale.getDefault()).startsWith(WINDOWS_OS_NAME);
// LOG.exit(isWindows);
// return isWindows;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JOptionPane;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryTag;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import com.github.sbugat.rundeckmonitor.tools.EnvironmentTools; | /**
* Download a file/URL and write it to a destination file.
*
* @param inputStream source stream
* @param destinationFile destination file
* @throws IOException in case of copy error
*/
private static void downloadFile(final InputStream inputStream, final String destinationFile) throws IOException {
Files.copy(inputStream, Paths.get(destinationFile));
}
/**
* Get the java executable.
*
* @return absolte path to the java executable
* @throws NoSuchFileException if the java executable is not found
*/
private static String getJavaExecutable() throws NoSuchFileException {
LOG.entry();
final String javaDirectory = System.getProperty(JAVA_HOME_PROPERTY);
if (javaDirectory == null) {
throw new IllegalStateException(JAVA_HOME_PROPERTY);
}
final String javaExecutableFilePath;
// Add .exe extension on Windows OS | // Path: src/main/java/com/github/sbugat/rundeckmonitor/tools/EnvironmentTools.java
// public final class EnvironmentTools {
//
// /** SLF4J XLogger. */
// private static final XLogger LOG = XLoggerFactory.getXLogger(EnvironmentTools.class);
//
// /** Windows OS name property. */
// private static final String OS_NAME_PROPERTY = "os.name"; //$NON-NLS-1$
// /** Windows name in OS name property. */
// private static final String WINDOWS_OS_NAME = "windows"; //$NON-NLS-1$
//
// /**
// * Private constructor to prevent Instantiating.
// */
// private EnvironmentTools() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Check if the operating system is a windows based on a property, otherwise it's a Linux/Mac-OS.
// *
// * @return true if the OS is a windows*
// */
// public static boolean isWindows() {
//
// LOG.entry();
// final String operatingSystem = System.getProperty(OS_NAME_PROPERTY);
//
// if (null == operatingSystem) {
// LOG.exit(false);
// return false;
// }
//
// final boolean isWindows = operatingSystem.toLowerCase(Locale.getDefault()).startsWith(WINDOWS_OS_NAME);
// LOG.exit(isWindows);
// return isWindows;
// }
// }
// Path: src/main/java/com/github/sbugat/rundeckmonitor/VersionChecker.java
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JOptionPane;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryTag;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import com.github.sbugat.rundeckmonitor.tools.EnvironmentTools;
/**
* Download a file/URL and write it to a destination file.
*
* @param inputStream source stream
* @param destinationFile destination file
* @throws IOException in case of copy error
*/
private static void downloadFile(final InputStream inputStream, final String destinationFile) throws IOException {
Files.copy(inputStream, Paths.get(destinationFile));
}
/**
* Get the java executable.
*
* @return absolte path to the java executable
* @throws NoSuchFileException if the java executable is not found
*/
private static String getJavaExecutable() throws NoSuchFileException {
LOG.entry();
final String javaDirectory = System.getProperty(JAVA_HOME_PROPERTY);
if (javaDirectory == null) {
throw new IllegalStateException(JAVA_HOME_PROPERTY);
}
final String javaExecutableFilePath;
// Add .exe extension on Windows OS | if (EnvironmentTools.isWindows()) { |
sleroy/fakesmtp-junit-runner | src/main/java/com/github/sleroy/junit/mail/server/SMTPServerHandler.java | // Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/BindPortException.java
// public final class BindPortException extends AbstractPortException {
//
// private static final long serialVersionUID = -4019988153141714187L;
//
// public BindPortException(final Exception e, final int port) {
// super(e, port);
// }
// }
//
// Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/OutOfRangePortException.java
// public final class OutOfRangePortException extends AbstractPortException {
// private static final long serialVersionUID = -8357518994968551990L;
//
// public OutOfRangePortException(final Exception e, final int port) {
// super(e, port);
// }
// }
| import java.net.InetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.AuthenticationHandlerFactory;
import org.subethamail.smtp.helper.SimpleMessageListener;
import org.subethamail.smtp.helper.SimpleMessageListenerAdapter;
import org.subethamail.smtp.server.SMTPServer;
import com.github.sleroy.fakesmtp.core.exception.BindPortException;
import com.github.sleroy.fakesmtp.core.exception.OutOfRangePortException; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
/**
* Starts and stops the SMTP server.
*
* @author Nilhcem
* @since 1.0
*/
public class SMTPServerHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class);
private final SMTPServer smtpServer;
/**
* Instantiates a new SMTP server handler.
*
* @param mailListener
* the mail listener
* @param smtpAuthHandlerFactory
* the smtp auth handler factory
*/
public SMTPServerHandler(final SimpleMessageListener mailListener,
final AuthenticationHandlerFactory smtpAuthHandlerFactory) {
smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(mailListener), smtpAuthHandlerFactory);
}
/**
* Checks whether the server is running
*
* @return true, whether the server is running
*/
public boolean isRunning() {
return smtpServer.isRunning();
}
/**
* Starts the server on the port and address specified in parameters.
*
* @param port
* the SMTP port to be opened.
* @param bindAddress
* the address to bind to. null means bind to all.
* @throws BindPortException
* when the port can't be opened.
* @throws OutOfRangePortException
* when port is out of range.
* @throws IllegalArgumentException
* when port is out of range.
*/
public void startServer(final int port, final InetAddress bindAddress) | // Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/BindPortException.java
// public final class BindPortException extends AbstractPortException {
//
// private static final long serialVersionUID = -4019988153141714187L;
//
// public BindPortException(final Exception e, final int port) {
// super(e, port);
// }
// }
//
// Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/OutOfRangePortException.java
// public final class OutOfRangePortException extends AbstractPortException {
// private static final long serialVersionUID = -8357518994968551990L;
//
// public OutOfRangePortException(final Exception e, final int port) {
// super(e, port);
// }
// }
// Path: src/main/java/com/github/sleroy/junit/mail/server/SMTPServerHandler.java
import java.net.InetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.AuthenticationHandlerFactory;
import org.subethamail.smtp.helper.SimpleMessageListener;
import org.subethamail.smtp.helper.SimpleMessageListenerAdapter;
import org.subethamail.smtp.server.SMTPServer;
import com.github.sleroy.fakesmtp.core.exception.BindPortException;
import com.github.sleroy.fakesmtp.core.exception.OutOfRangePortException;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
/**
* Starts and stops the SMTP server.
*
* @author Nilhcem
* @since 1.0
*/
public class SMTPServerHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class);
private final SMTPServer smtpServer;
/**
* Instantiates a new SMTP server handler.
*
* @param mailListener
* the mail listener
* @param smtpAuthHandlerFactory
* the smtp auth handler factory
*/
public SMTPServerHandler(final SimpleMessageListener mailListener,
final AuthenticationHandlerFactory smtpAuthHandlerFactory) {
smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(mailListener), smtpAuthHandlerFactory);
}
/**
* Checks whether the server is running
*
* @return true, whether the server is running
*/
public boolean isRunning() {
return smtpServer.isRunning();
}
/**
* Starts the server on the port and address specified in parameters.
*
* @param port
* the SMTP port to be opened.
* @param bindAddress
* the address to bind to. null means bind to all.
* @throws BindPortException
* when the port can't be opened.
* @throws OutOfRangePortException
* when port is out of range.
* @throws IllegalArgumentException
* when port is out of range.
*/
public void startServer(final int port, final InetAddress bindAddress) | throws BindPortException, OutOfRangePortException { |
sleroy/fakesmtp-junit-runner | src/main/java/com/github/sleroy/junit/mail/server/SMTPServerHandler.java | // Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/BindPortException.java
// public final class BindPortException extends AbstractPortException {
//
// private static final long serialVersionUID = -4019988153141714187L;
//
// public BindPortException(final Exception e, final int port) {
// super(e, port);
// }
// }
//
// Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/OutOfRangePortException.java
// public final class OutOfRangePortException extends AbstractPortException {
// private static final long serialVersionUID = -8357518994968551990L;
//
// public OutOfRangePortException(final Exception e, final int port) {
// super(e, port);
// }
// }
| import java.net.InetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.AuthenticationHandlerFactory;
import org.subethamail.smtp.helper.SimpleMessageListener;
import org.subethamail.smtp.helper.SimpleMessageListenerAdapter;
import org.subethamail.smtp.server.SMTPServer;
import com.github.sleroy.fakesmtp.core.exception.BindPortException;
import com.github.sleroy.fakesmtp.core.exception.OutOfRangePortException; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
/**
* Starts and stops the SMTP server.
*
* @author Nilhcem
* @since 1.0
*/
public class SMTPServerHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class);
private final SMTPServer smtpServer;
/**
* Instantiates a new SMTP server handler.
*
* @param mailListener
* the mail listener
* @param smtpAuthHandlerFactory
* the smtp auth handler factory
*/
public SMTPServerHandler(final SimpleMessageListener mailListener,
final AuthenticationHandlerFactory smtpAuthHandlerFactory) {
smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(mailListener), smtpAuthHandlerFactory);
}
/**
* Checks whether the server is running
*
* @return true, whether the server is running
*/
public boolean isRunning() {
return smtpServer.isRunning();
}
/**
* Starts the server on the port and address specified in parameters.
*
* @param port
* the SMTP port to be opened.
* @param bindAddress
* the address to bind to. null means bind to all.
* @throws BindPortException
* when the port can't be opened.
* @throws OutOfRangePortException
* when port is out of range.
* @throws IllegalArgumentException
* when port is out of range.
*/
public void startServer(final int port, final InetAddress bindAddress) | // Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/BindPortException.java
// public final class BindPortException extends AbstractPortException {
//
// private static final long serialVersionUID = -4019988153141714187L;
//
// public BindPortException(final Exception e, final int port) {
// super(e, port);
// }
// }
//
// Path: src/main/java/com/github/sleroy/fakesmtp/core/exception/OutOfRangePortException.java
// public final class OutOfRangePortException extends AbstractPortException {
// private static final long serialVersionUID = -8357518994968551990L;
//
// public OutOfRangePortException(final Exception e, final int port) {
// super(e, port);
// }
// }
// Path: src/main/java/com/github/sleroy/junit/mail/server/SMTPServerHandler.java
import java.net.InetAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.AuthenticationHandlerFactory;
import org.subethamail.smtp.helper.SimpleMessageListener;
import org.subethamail.smtp.helper.SimpleMessageListenerAdapter;
import org.subethamail.smtp.server.SMTPServer;
import com.github.sleroy.fakesmtp.core.exception.BindPortException;
import com.github.sleroy.fakesmtp.core.exception.OutOfRangePortException;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
/**
* Starts and stops the SMTP server.
*
* @author Nilhcem
* @since 1.0
*/
public class SMTPServerHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class);
private final SMTPServer smtpServer;
/**
* Instantiates a new SMTP server handler.
*
* @param mailListener
* the mail listener
* @param smtpAuthHandlerFactory
* the smtp auth handler factory
*/
public SMTPServerHandler(final SimpleMessageListener mailListener,
final AuthenticationHandlerFactory smtpAuthHandlerFactory) {
smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(mailListener), smtpAuthHandlerFactory);
}
/**
* Checks whether the server is running
*
* @return true, whether the server is running
*/
public boolean isRunning() {
return smtpServer.isRunning();
}
/**
* Starts the server on the port and address specified in parameters.
*
* @param port
* the SMTP port to be opened.
* @param bindAddress
* the address to bind to. null means bind to all.
* @throws BindPortException
* when the port can't be opened.
* @throws OutOfRangePortException
* when port is out of range.
* @throws IllegalArgumentException
* when port is out of range.
*/
public void startServer(final int port, final InetAddress bindAddress) | throws BindPortException, OutOfRangePortException { |
sleroy/fakesmtp-junit-runner | src/test/java/com/github/sleroy/junit/mail/server/MailListenerTest.java | // Path: src/main/java/com/github/sleroy/junit/mail/server/MailListener.java
// public final class MailListener implements SimpleMessageListener {
// private final MailSaverInterface saver;
//
// /**
// * Creates the listener.
// *
// * @param saver
// * a {@code MailServer} object used to save emails and notify
// * components.
// */
// public MailListener(final MailSaverInterface saver) {
// this.saver = saver;
// }
//
// /**
// * Accepts all kind of email <i>(always return true)</i>.
// * <p>
// * Called once for every RCPT TO during a SMTP exchange.<br>
// * Each accepted recipient will result in a separate deliver() call later.
// * </p>
// *
// * @param from
// * the user who send the email.
// * @param recipient
// * the recipient of the email.
// * @return always return {@code true}
// */
// @Override
// public boolean accept(final String from, final String recipient) {
// return true;
// }
//
// /**
// * Receives emails and forwards them to the {@link MailSaver} object.
// */
// @Override
// public void deliver(final String from, final String recipient, final InputStream data) throws IOException {
// saver.saveEmailAndNotify(from, recipient, data);
// }
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/MailSaverInterface.java
// @FunctionalInterface
// public interface MailSaverInterface {
//
// /**
// * Saves incoming email in file system and notifies observers.
// *
// * @param from
// * the user who send the email.
// * @param to
// * the recipient of the email.
// * @param data
// * an InputStream object containing the email.
// * @see MailServerModel to see which observers will be notified
// */
// void saveEmailAndNotify(String from, String to, InputStream data);
//
// }
| import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.github.sleroy.junit.mail.server.MailListener;
import com.github.sleroy.junit.mail.server.MailSaverInterface; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
public class MailListenerTest {
@Test
public void testAccept() throws Exception { | // Path: src/main/java/com/github/sleroy/junit/mail/server/MailListener.java
// public final class MailListener implements SimpleMessageListener {
// private final MailSaverInterface saver;
//
// /**
// * Creates the listener.
// *
// * @param saver
// * a {@code MailServer} object used to save emails and notify
// * components.
// */
// public MailListener(final MailSaverInterface saver) {
// this.saver = saver;
// }
//
// /**
// * Accepts all kind of email <i>(always return true)</i>.
// * <p>
// * Called once for every RCPT TO during a SMTP exchange.<br>
// * Each accepted recipient will result in a separate deliver() call later.
// * </p>
// *
// * @param from
// * the user who send the email.
// * @param recipient
// * the recipient of the email.
// * @return always return {@code true}
// */
// @Override
// public boolean accept(final String from, final String recipient) {
// return true;
// }
//
// /**
// * Receives emails and forwards them to the {@link MailSaver} object.
// */
// @Override
// public void deliver(final String from, final String recipient, final InputStream data) throws IOException {
// saver.saveEmailAndNotify(from, recipient, data);
// }
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/MailSaverInterface.java
// @FunctionalInterface
// public interface MailSaverInterface {
//
// /**
// * Saves incoming email in file system and notifies observers.
// *
// * @param from
// * the user who send the email.
// * @param to
// * the recipient of the email.
// * @param data
// * an InputStream object containing the email.
// * @see MailServerModel to see which observers will be notified
// */
// void saveEmailAndNotify(String from, String to, InputStream data);
//
// }
// Path: src/test/java/com/github/sleroy/junit/mail/server/MailListenerTest.java
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.github.sleroy.junit.mail.server.MailListener;
import com.github.sleroy.junit.mail.server.MailSaverInterface;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
public class MailListenerTest {
@Test
public void testAccept() throws Exception { | MailListener mailListener = new MailListener(Mockito.mock(MailSaverInterface.class)); |
sleroy/fakesmtp-junit-runner | src/test/java/com/github/sleroy/junit/mail/server/MailListenerTest.java | // Path: src/main/java/com/github/sleroy/junit/mail/server/MailListener.java
// public final class MailListener implements SimpleMessageListener {
// private final MailSaverInterface saver;
//
// /**
// * Creates the listener.
// *
// * @param saver
// * a {@code MailServer} object used to save emails and notify
// * components.
// */
// public MailListener(final MailSaverInterface saver) {
// this.saver = saver;
// }
//
// /**
// * Accepts all kind of email <i>(always return true)</i>.
// * <p>
// * Called once for every RCPT TO during a SMTP exchange.<br>
// * Each accepted recipient will result in a separate deliver() call later.
// * </p>
// *
// * @param from
// * the user who send the email.
// * @param recipient
// * the recipient of the email.
// * @return always return {@code true}
// */
// @Override
// public boolean accept(final String from, final String recipient) {
// return true;
// }
//
// /**
// * Receives emails and forwards them to the {@link MailSaver} object.
// */
// @Override
// public void deliver(final String from, final String recipient, final InputStream data) throws IOException {
// saver.saveEmailAndNotify(from, recipient, data);
// }
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/MailSaverInterface.java
// @FunctionalInterface
// public interface MailSaverInterface {
//
// /**
// * Saves incoming email in file system and notifies observers.
// *
// * @param from
// * the user who send the email.
// * @param to
// * the recipient of the email.
// * @param data
// * an InputStream object containing the email.
// * @see MailServerModel to see which observers will be notified
// */
// void saveEmailAndNotify(String from, String to, InputStream data);
//
// }
| import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.github.sleroy.junit.mail.server.MailListener;
import com.github.sleroy.junit.mail.server.MailSaverInterface; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
public class MailListenerTest {
@Test
public void testAccept() throws Exception { | // Path: src/main/java/com/github/sleroy/junit/mail/server/MailListener.java
// public final class MailListener implements SimpleMessageListener {
// private final MailSaverInterface saver;
//
// /**
// * Creates the listener.
// *
// * @param saver
// * a {@code MailServer} object used to save emails and notify
// * components.
// */
// public MailListener(final MailSaverInterface saver) {
// this.saver = saver;
// }
//
// /**
// * Accepts all kind of email <i>(always return true)</i>.
// * <p>
// * Called once for every RCPT TO during a SMTP exchange.<br>
// * Each accepted recipient will result in a separate deliver() call later.
// * </p>
// *
// * @param from
// * the user who send the email.
// * @param recipient
// * the recipient of the email.
// * @return always return {@code true}
// */
// @Override
// public boolean accept(final String from, final String recipient) {
// return true;
// }
//
// /**
// * Receives emails and forwards them to the {@link MailSaver} object.
// */
// @Override
// public void deliver(final String from, final String recipient, final InputStream data) throws IOException {
// saver.saveEmailAndNotify(from, recipient, data);
// }
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/MailSaverInterface.java
// @FunctionalInterface
// public interface MailSaverInterface {
//
// /**
// * Saves incoming email in file system and notifies observers.
// *
// * @param from
// * the user who send the email.
// * @param to
// * the recipient of the email.
// * @param data
// * an InputStream object containing the email.
// * @see MailServerModel to see which observers will be notified
// */
// void saveEmailAndNotify(String from, String to, InputStream data);
//
// }
// Path: src/test/java/com/github/sleroy/junit/mail/server/MailListenerTest.java
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.github.sleroy.junit.mail.server.MailListener;
import com.github.sleroy.junit.mail.server.MailSaverInterface;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
public class MailListenerTest {
@Test
public void testAccept() throws Exception { | MailListener mailListener = new MailListener(Mockito.mock(MailSaverInterface.class)); |
sleroy/fakesmtp-junit-runner | src/test/java/com/github/sleroy/junit/mail/server/SMTPAuthHandlerFactoryTest.java | // Path: src/main/java/com/github/sleroy/junit/mail/server/SMTPAuthHandlerFactory.java
// final class SMTPAuthHandlerFactory implements AuthenticationHandlerFactory {
//
// /** The Constant LOGIN_MECHANISM. */
// public static final String LOGIN_MECHANISM = "LOGIN";
//
// /** The smtp auth handler. */
// private final AuthenticationHandler smtpAuthHandler;
//
// /**
// * Instantiates a new SMTP auth handler factory.
// *
// * @param smtpAuthHandler
// * the smtp auth handler
// */
// public SMTPAuthHandlerFactory(final AuthenticationHandler smtpAuthHandler) {
// super();
// this.smtpAuthHandler = smtpAuthHandler;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see org.subethamail.smtp.AuthenticationHandlerFactory#create()
// */
// @Override
// public AuthenticationHandler create() {
// return smtpAuthHandler;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see org.subethamail.smtp.AuthenticationHandlerFactory#
// * getAuthenticationMechanisms()
// */
// @Override
// public List<String> getAuthenticationMechanisms() {
// final List<String> result = new ArrayList<>();
// result.add(SMTPAuthHandlerFactory.LOGIN_MECHANISM);
// return result;
// }
// }
| import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.subethamail.smtp.AuthenticationHandler;
import com.github.sleroy.junit.mail.server.SMTPAuthHandlerFactory; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
@RunWith(MockitoJUnitRunner.class)
public class SMTPAuthHandlerFactoryTest {
@Mock
private AuthenticationHandler smtpAuthHandler;
@InjectMocks | // Path: src/main/java/com/github/sleroy/junit/mail/server/SMTPAuthHandlerFactory.java
// final class SMTPAuthHandlerFactory implements AuthenticationHandlerFactory {
//
// /** The Constant LOGIN_MECHANISM. */
// public static final String LOGIN_MECHANISM = "LOGIN";
//
// /** The smtp auth handler. */
// private final AuthenticationHandler smtpAuthHandler;
//
// /**
// * Instantiates a new SMTP auth handler factory.
// *
// * @param smtpAuthHandler
// * the smtp auth handler
// */
// public SMTPAuthHandlerFactory(final AuthenticationHandler smtpAuthHandler) {
// super();
// this.smtpAuthHandler = smtpAuthHandler;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see org.subethamail.smtp.AuthenticationHandlerFactory#create()
// */
// @Override
// public AuthenticationHandler create() {
// return smtpAuthHandler;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see org.subethamail.smtp.AuthenticationHandlerFactory#
// * getAuthenticationMechanisms()
// */
// @Override
// public List<String> getAuthenticationMechanisms() {
// final List<String> result = new ArrayList<>();
// result.add(SMTPAuthHandlerFactory.LOGIN_MECHANISM);
// return result;
// }
// }
// Path: src/test/java/com/github/sleroy/junit/mail/server/SMTPAuthHandlerFactoryTest.java
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.subethamail.smtp.AuthenticationHandler;
import com.github.sleroy.junit.mail.server.SMTPAuthHandlerFactory;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
@RunWith(MockitoJUnitRunner.class)
public class SMTPAuthHandlerFactoryTest {
@Mock
private AuthenticationHandler smtpAuthHandler;
@InjectMocks | private SMTPAuthHandlerFactory sMTPAuthHandlerFactory; |
sleroy/fakesmtp-junit-runner | src/main/java/com/github/sleroy/fakesmtp/model/MailServerModel.java | // Path: src/main/java/com/github/sleroy/junit/mail/server/events/DeleteAllMailEvent.java
// public class DeleteAllMailEvent {
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/NewMailEvent.java
// public class NewMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new new mail event.
// *
// * @param model
// * the model
// */
// public NewMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/RejectedMailEvent.java
// public class RejectedMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new rejected mail event.
// *
// * @param model
// * the model
// */
// public RejectedMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sleroy.junit.mail.server.events.DeleteAllMailEvent;
import com.github.sleroy.junit.mail.server.events.NewMailEvent;
import com.github.sleroy.junit.mail.server.events.RejectedMailEvent; | /*
*
*/
package com.github.sleroy.fakesmtp.model;
/**
* UI presentation model of the application.
* <p>
* The essence of a Presentation Model is of a fully self-contained class that
* represents all the data and behavior of the UI window, but without any of the
* controls used to render that UI on the screen.
* </p>
*
* @author Nilhcem
* @see <a href="link">http://martinfowler.com/eaaDev/PresentationModel.html</a>
* @since 1.0
*/
public class MailServerModel implements Observer {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(MailServerModel.class);
/** The email models. */
private final List<EmailModel> emailModels = new ArrayList<>(100);
/** The rejected mails. */
private final List<EmailModel> rejectedMails = new ArrayList<>(100);
/**
* Instantiates a new mail server model.
*/
public MailServerModel() {
super();
}
/**
* Delete all mails.
*/
public void deleteAllMails() {
LOGGER.info("Received event to delete all the mails");
emailModels.clear();
rejectedMails.clear();
}
/**
* Gets the email models.
*
* @return the email models
*/
public List<EmailModel> getEmailModels() {
return emailModels;
}
/**
* Gets the rejected mails.
*
* @return the rejected mails
*/
public List<EmailModel> getRejectedMails() {
return rejectedMails;
}
/**
* Rejects a mail.
*
* @param mail
* the mail
*/
public void rejectedMail(final EmailModel mail) {
LOGGER.info("A mail has been rejected : {}", mail);
rejectedMails.add(mail);
}
/**
* Save the mail.
*
* @param email
* the email
*/
public void saveMail(final EmailModel email) {
LOGGER.info("Has received mail : {}", email);
emailModels.add(email);
}
@Override
public String toString() {
return "MailServerModel [emailModels=" + emailModels + ", rejectedMails=" + rejectedMails + "]";
}
/*
* (non-Javadoc)
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(final Observable o, final Object arg) { | // Path: src/main/java/com/github/sleroy/junit/mail/server/events/DeleteAllMailEvent.java
// public class DeleteAllMailEvent {
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/NewMailEvent.java
// public class NewMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new new mail event.
// *
// * @param model
// * the model
// */
// public NewMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/RejectedMailEvent.java
// public class RejectedMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new rejected mail event.
// *
// * @param model
// * the model
// */
// public RejectedMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
// Path: src/main/java/com/github/sleroy/fakesmtp/model/MailServerModel.java
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sleroy.junit.mail.server.events.DeleteAllMailEvent;
import com.github.sleroy.junit.mail.server.events.NewMailEvent;
import com.github.sleroy.junit.mail.server.events.RejectedMailEvent;
/*
*
*/
package com.github.sleroy.fakesmtp.model;
/**
* UI presentation model of the application.
* <p>
* The essence of a Presentation Model is of a fully self-contained class that
* represents all the data and behavior of the UI window, but without any of the
* controls used to render that UI on the screen.
* </p>
*
* @author Nilhcem
* @see <a href="link">http://martinfowler.com/eaaDev/PresentationModel.html</a>
* @since 1.0
*/
public class MailServerModel implements Observer {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(MailServerModel.class);
/** The email models. */
private final List<EmailModel> emailModels = new ArrayList<>(100);
/** The rejected mails. */
private final List<EmailModel> rejectedMails = new ArrayList<>(100);
/**
* Instantiates a new mail server model.
*/
public MailServerModel() {
super();
}
/**
* Delete all mails.
*/
public void deleteAllMails() {
LOGGER.info("Received event to delete all the mails");
emailModels.clear();
rejectedMails.clear();
}
/**
* Gets the email models.
*
* @return the email models
*/
public List<EmailModel> getEmailModels() {
return emailModels;
}
/**
* Gets the rejected mails.
*
* @return the rejected mails
*/
public List<EmailModel> getRejectedMails() {
return rejectedMails;
}
/**
* Rejects a mail.
*
* @param mail
* the mail
*/
public void rejectedMail(final EmailModel mail) {
LOGGER.info("A mail has been rejected : {}", mail);
rejectedMails.add(mail);
}
/**
* Save the mail.
*
* @param email
* the email
*/
public void saveMail(final EmailModel email) {
LOGGER.info("Has received mail : {}", email);
emailModels.add(email);
}
@Override
public String toString() {
return "MailServerModel [emailModels=" + emailModels + ", rejectedMails=" + rejectedMails + "]";
}
/*
* (non-Javadoc)
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(final Observable o, final Object arg) { | if (arg instanceof NewMailEvent) { |
sleroy/fakesmtp-junit-runner | src/main/java/com/github/sleroy/fakesmtp/model/MailServerModel.java | // Path: src/main/java/com/github/sleroy/junit/mail/server/events/DeleteAllMailEvent.java
// public class DeleteAllMailEvent {
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/NewMailEvent.java
// public class NewMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new new mail event.
// *
// * @param model
// * the model
// */
// public NewMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/RejectedMailEvent.java
// public class RejectedMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new rejected mail event.
// *
// * @param model
// * the model
// */
// public RejectedMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sleroy.junit.mail.server.events.DeleteAllMailEvent;
import com.github.sleroy.junit.mail.server.events.NewMailEvent;
import com.github.sleroy.junit.mail.server.events.RejectedMailEvent; | LOGGER.info("A mail has been rejected : {}", mail);
rejectedMails.add(mail);
}
/**
* Save the mail.
*
* @param email
* the email
*/
public void saveMail(final EmailModel email) {
LOGGER.info("Has received mail : {}", email);
emailModels.add(email);
}
@Override
public String toString() {
return "MailServerModel [emailModels=" + emailModels + ", rejectedMails=" + rejectedMails + "]";
}
/*
* (non-Javadoc)
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(final Observable o, final Object arg) {
if (arg instanceof NewMailEvent) {
saveMail(((NewMailEvent) arg).getModel()); | // Path: src/main/java/com/github/sleroy/junit/mail/server/events/DeleteAllMailEvent.java
// public class DeleteAllMailEvent {
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/NewMailEvent.java
// public class NewMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new new mail event.
// *
// * @param model
// * the model
// */
// public NewMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/RejectedMailEvent.java
// public class RejectedMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new rejected mail event.
// *
// * @param model
// * the model
// */
// public RejectedMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
// Path: src/main/java/com/github/sleroy/fakesmtp/model/MailServerModel.java
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sleroy.junit.mail.server.events.DeleteAllMailEvent;
import com.github.sleroy.junit.mail.server.events.NewMailEvent;
import com.github.sleroy.junit.mail.server.events.RejectedMailEvent;
LOGGER.info("A mail has been rejected : {}", mail);
rejectedMails.add(mail);
}
/**
* Save the mail.
*
* @param email
* the email
*/
public void saveMail(final EmailModel email) {
LOGGER.info("Has received mail : {}", email);
emailModels.add(email);
}
@Override
public String toString() {
return "MailServerModel [emailModels=" + emailModels + ", rejectedMails=" + rejectedMails + "]";
}
/*
* (non-Javadoc)
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(final Observable o, final Object arg) {
if (arg instanceof NewMailEvent) {
saveMail(((NewMailEvent) arg).getModel()); | } else if (arg instanceof DeleteAllMailEvent) { |
sleroy/fakesmtp-junit-runner | src/main/java/com/github/sleroy/fakesmtp/model/MailServerModel.java | // Path: src/main/java/com/github/sleroy/junit/mail/server/events/DeleteAllMailEvent.java
// public class DeleteAllMailEvent {
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/NewMailEvent.java
// public class NewMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new new mail event.
// *
// * @param model
// * the model
// */
// public NewMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/RejectedMailEvent.java
// public class RejectedMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new rejected mail event.
// *
// * @param model
// * the model
// */
// public RejectedMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sleroy.junit.mail.server.events.DeleteAllMailEvent;
import com.github.sleroy.junit.mail.server.events.NewMailEvent;
import com.github.sleroy.junit.mail.server.events.RejectedMailEvent; |
}
/**
* Save the mail.
*
* @param email
* the email
*/
public void saveMail(final EmailModel email) {
LOGGER.info("Has received mail : {}", email);
emailModels.add(email);
}
@Override
public String toString() {
return "MailServerModel [emailModels=" + emailModels + ", rejectedMails=" + rejectedMails + "]";
}
/*
* (non-Javadoc)
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(final Observable o, final Object arg) {
if (arg instanceof NewMailEvent) {
saveMail(((NewMailEvent) arg).getModel());
} else if (arg instanceof DeleteAllMailEvent) {
deleteAllMails(); | // Path: src/main/java/com/github/sleroy/junit/mail/server/events/DeleteAllMailEvent.java
// public class DeleteAllMailEvent {
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/NewMailEvent.java
// public class NewMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new new mail event.
// *
// * @param model
// * the model
// */
// public NewMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
//
// Path: src/main/java/com/github/sleroy/junit/mail/server/events/RejectedMailEvent.java
// public class RejectedMailEvent {
//
// private final EmailModel model;
//
// /**
// * Instantiates a new rejected mail event.
// *
// * @param model
// * the model
// */
// public RejectedMailEvent(final EmailModel model) {
// this.model = model;
//
// }
//
// public EmailModel getModel() {
// return model;
// }
//
// }
// Path: src/main/java/com/github/sleroy/fakesmtp/model/MailServerModel.java
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sleroy.junit.mail.server.events.DeleteAllMailEvent;
import com.github.sleroy.junit.mail.server.events.NewMailEvent;
import com.github.sleroy.junit.mail.server.events.RejectedMailEvent;
}
/**
* Save the mail.
*
* @param email
* the email
*/
public void saveMail(final EmailModel email) {
LOGGER.info("Has received mail : {}", email);
emailModels.add(email);
}
@Override
public String toString() {
return "MailServerModel [emailModels=" + emailModels + ", rejectedMails=" + rejectedMails + "]";
}
/*
* (non-Javadoc)
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(final Observable o, final Object arg) {
if (arg instanceof NewMailEvent) {
saveMail(((NewMailEvent) arg).getModel());
} else if (arg instanceof DeleteAllMailEvent) {
deleteAllMails(); | } else if (arg instanceof RejectedMailEvent) { |
sleroy/fakesmtp-junit-runner | src/test/java/com/github/sleroy/junit/mail/server/SMTPAuthHandlerTest.java | // Path: src/main/java/com/github/sleroy/junit/mail/server/SMTPAuthHandler.java
// final class SMTPAuthHandler implements AuthenticationHandler {
// public static final String USER_IDENTITY = "User";
//
// private int pass = 0;
//
// private final String userName;
//
// private final String password;
//
// public SMTPAuthHandler(final String userName, final String password) {
// super();
// this.userName = userName;
// this.password = password;
// }
//
// /**
// * Simulates an authentication process.
// * <p>
// * <ul>
// * <li>first prompts for username;</li>
// * <li>then, prompts for password;</li>
// * <li>finally, returns {@code null} to finish the authentication
// * process;</li>
// * </ul>
// * </p>
// *
// * @return <code>null</code> if the authentication process is finished,
// * otherwise a string to hand back to the client.
// * @param clientInput
// * The client's input, eg "AUTH PLAIN dGVzdAB0ZXN0ADEyMzQ="
// */
// @Override
// public String auth(final String clientInput) {
// String prompt;
//
// if (++pass == 1) {
// prompt = userName;
// } else if (pass == 2) {
// prompt = password;
// } else {
// pass = 0;
// prompt = null;
// }
// return prompt;
// }
//
// /**
// * If the authentication process was successful, this returns the identity
// * of the user. The type defining the identity can vary depending on the
// * authentication mechanism used, but typically this returns a String
// * username. If authentication was not successful, the return value is
// * undefined.
// */
// @Override
// public Object getIdentity() {
// return SMTPAuthHandler.USER_IDENTITY;
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.github.sleroy.junit.mail.server.SMTPAuthHandler; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
@RunWith(MockitoJUnitRunner.class)
public class SMTPAuthHandlerTest {
private String password = "password";
private String userName = "username";
| // Path: src/main/java/com/github/sleroy/junit/mail/server/SMTPAuthHandler.java
// final class SMTPAuthHandler implements AuthenticationHandler {
// public static final String USER_IDENTITY = "User";
//
// private int pass = 0;
//
// private final String userName;
//
// private final String password;
//
// public SMTPAuthHandler(final String userName, final String password) {
// super();
// this.userName = userName;
// this.password = password;
// }
//
// /**
// * Simulates an authentication process.
// * <p>
// * <ul>
// * <li>first prompts for username;</li>
// * <li>then, prompts for password;</li>
// * <li>finally, returns {@code null} to finish the authentication
// * process;</li>
// * </ul>
// * </p>
// *
// * @return <code>null</code> if the authentication process is finished,
// * otherwise a string to hand back to the client.
// * @param clientInput
// * The client's input, eg "AUTH PLAIN dGVzdAB0ZXN0ADEyMzQ="
// */
// @Override
// public String auth(final String clientInput) {
// String prompt;
//
// if (++pass == 1) {
// prompt = userName;
// } else if (pass == 2) {
// prompt = password;
// } else {
// pass = 0;
// prompt = null;
// }
// return prompt;
// }
//
// /**
// * If the authentication process was successful, this returns the identity
// * of the user. The type defining the identity can vary depending on the
// * authentication mechanism used, but typically this returns a String
// * username. If authentication was not successful, the return value is
// * undefined.
// */
// @Override
// public Object getIdentity() {
// return SMTPAuthHandler.USER_IDENTITY;
// }
// }
// Path: src/test/java/com/github/sleroy/junit/mail/server/SMTPAuthHandlerTest.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.github.sleroy.junit.mail.server.SMTPAuthHandler;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.sleroy.junit.mail.server;
@RunWith(MockitoJUnitRunner.class)
public class SMTPAuthHandlerTest {
private String password = "password";
private String userName = "username";
| private SMTPAuthHandler SMTPAuthHandler = new SMTPAuthHandler(userName, password); |
xiaoshanlin000/SLTableView | library/src/main/java/com/shanlin/library/sltableview/adapter/SLStickyHeaderDecoration.java | // Path: library/src/main/java/com/shanlin/library/sltableview/SLTableViewCell.java
// public class SLTableViewCell extends RecyclerView.ViewHolder implements View.OnClickListener{
//
// private SLIndexPath indexPath;
// private SLCellViewClickListener clickListener;
// private Object userData;
// private String key;
// private boolean requiredValue;
// private ValueFilter valueFilter;
//
// public SLTableViewCell(View itemView) {
// super(itemView);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener){
// bindCellViewClick(view,clickListener,null);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// * @param userData 用户数据
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener,Object userData){
// view.setOnClickListener(this);
// this.clickListener = clickListener;
// this.userData = userData;
// }
//
// public SLTableViewCell setIndexPath(SLIndexPath indexPath) {
// this.indexPath = indexPath;
// return this;
// }
//
//
// public SLIndexPath getIndexPath() {
// return indexPath.clone();
// }
//
// @Override
// public void onClick(View v) {
// if (clickListener != null){
// clickListener.onCellViewClick(v,indexPath,userData);
// }
// }
//
// public boolean isRequiredValue() {
// return requiredValue;
// }
//
// public SLTableViewCell setRequiredValue(boolean requiredValue) {
// this.requiredValue = requiredValue;
// return this;
// }
//
// public String getKey() {
// return key;
// }
//
// public SLTableViewCell setKey(String key) {
// this.key = key;
// return this;
// }
//
// public HashMap<String,Object> keyValues(){
// HashMap<String,Object> result = new HashMap<String,Object>();
// String key = getKey();
// Object value = value();
// if (!TextUtils.isEmpty(key) && null != value){
// result.put(key,value);
// }
// return result;
// }
//
// // public ValueFilter getValueFilter() {
// // return valueFilter;
// // }
// //
// // public SLTableViewCell setValueFilter(ValueFilter valueFilter) {
// // this.valueFilter = valueFilter;
// // return this;
// // }
//
// // @Override
// // public boolean valueFilter(Object value){
// // if (null != getValueFilter()) {
// // return getValueFilter().valueFilter(value);
// // } else if (null == value) {
// // return false;
// // } else if (value instanceof String) {
// // return ((String)value).length() > 0;
// // }
// // return false;
// // }
//
// /**
// *
// * @return
// */
// public Object value(){
// return null;
// }
//
// // /**
// // * 当 requiredValue = true 和 value() 是空或者长度为0时, 显示的动画
// // * @return
// // */
// // public Animation animationWithNullValue(){
// // TranslateAnimation animation = new TranslateAnimation(-20, 20, 0, 0);
// // animation.setInterpolator(new AccelerateInterpolator());
// // animation.setDuration(100);
// // animation.setRepeatCount(3);
// // animation.setRepeatMode(Animation.REVERSE);
// // return animation;
// // }
//
// public interface SLCellViewClickListener{
// public void onCellViewClick(View view, SLIndexPath indexPath, Object userData);
// }
//
// }
| import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.shanlin.library.sltableview.SLTableViewCell;
import java.util.HashMap; | package com.shanlin.library.sltableview.adapter;
/**
* Created by Shanlin on 2016/12/29.
*/
public class SLStickyHeaderDecoration extends RecyclerView.ItemDecoration {
private SLTableViewStickyHeaderAdapter headerAdapter; | // Path: library/src/main/java/com/shanlin/library/sltableview/SLTableViewCell.java
// public class SLTableViewCell extends RecyclerView.ViewHolder implements View.OnClickListener{
//
// private SLIndexPath indexPath;
// private SLCellViewClickListener clickListener;
// private Object userData;
// private String key;
// private boolean requiredValue;
// private ValueFilter valueFilter;
//
// public SLTableViewCell(View itemView) {
// super(itemView);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener){
// bindCellViewClick(view,clickListener,null);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// * @param userData 用户数据
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener,Object userData){
// view.setOnClickListener(this);
// this.clickListener = clickListener;
// this.userData = userData;
// }
//
// public SLTableViewCell setIndexPath(SLIndexPath indexPath) {
// this.indexPath = indexPath;
// return this;
// }
//
//
// public SLIndexPath getIndexPath() {
// return indexPath.clone();
// }
//
// @Override
// public void onClick(View v) {
// if (clickListener != null){
// clickListener.onCellViewClick(v,indexPath,userData);
// }
// }
//
// public boolean isRequiredValue() {
// return requiredValue;
// }
//
// public SLTableViewCell setRequiredValue(boolean requiredValue) {
// this.requiredValue = requiredValue;
// return this;
// }
//
// public String getKey() {
// return key;
// }
//
// public SLTableViewCell setKey(String key) {
// this.key = key;
// return this;
// }
//
// public HashMap<String,Object> keyValues(){
// HashMap<String,Object> result = new HashMap<String,Object>();
// String key = getKey();
// Object value = value();
// if (!TextUtils.isEmpty(key) && null != value){
// result.put(key,value);
// }
// return result;
// }
//
// // public ValueFilter getValueFilter() {
// // return valueFilter;
// // }
// //
// // public SLTableViewCell setValueFilter(ValueFilter valueFilter) {
// // this.valueFilter = valueFilter;
// // return this;
// // }
//
// // @Override
// // public boolean valueFilter(Object value){
// // if (null != getValueFilter()) {
// // return getValueFilter().valueFilter(value);
// // } else if (null == value) {
// // return false;
// // } else if (value instanceof String) {
// // return ((String)value).length() > 0;
// // }
// // return false;
// // }
//
// /**
// *
// * @return
// */
// public Object value(){
// return null;
// }
//
// // /**
// // * 当 requiredValue = true 和 value() 是空或者长度为0时, 显示的动画
// // * @return
// // */
// // public Animation animationWithNullValue(){
// // TranslateAnimation animation = new TranslateAnimation(-20, 20, 0, 0);
// // animation.setInterpolator(new AccelerateInterpolator());
// // animation.setDuration(100);
// // animation.setRepeatCount(3);
// // animation.setRepeatMode(Animation.REVERSE);
// // return animation;
// // }
//
// public interface SLCellViewClickListener{
// public void onCellViewClick(View view, SLIndexPath indexPath, Object userData);
// }
//
// }
// Path: library/src/main/java/com/shanlin/library/sltableview/adapter/SLStickyHeaderDecoration.java
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.shanlin.library.sltableview.SLTableViewCell;
import java.util.HashMap;
package com.shanlin.library.sltableview.adapter;
/**
* Created by Shanlin on 2016/12/29.
*/
public class SLStickyHeaderDecoration extends RecyclerView.ItemDecoration {
private SLTableViewStickyHeaderAdapter headerAdapter; | private HashMap<Long, SLTableViewCell> headerCache; |
xiaoshanlin000/SLTableView | library/src/main/java/com/shanlin/library/sltableview/adapter/SLTableViewStickyHeaderAdapter.java | // Path: library/src/main/java/com/shanlin/library/sltableview/SLTableViewCell.java
// public class SLTableViewCell extends RecyclerView.ViewHolder implements View.OnClickListener{
//
// private SLIndexPath indexPath;
// private SLCellViewClickListener clickListener;
// private Object userData;
// private String key;
// private boolean requiredValue;
// private ValueFilter valueFilter;
//
// public SLTableViewCell(View itemView) {
// super(itemView);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener){
// bindCellViewClick(view,clickListener,null);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// * @param userData 用户数据
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener,Object userData){
// view.setOnClickListener(this);
// this.clickListener = clickListener;
// this.userData = userData;
// }
//
// public SLTableViewCell setIndexPath(SLIndexPath indexPath) {
// this.indexPath = indexPath;
// return this;
// }
//
//
// public SLIndexPath getIndexPath() {
// return indexPath.clone();
// }
//
// @Override
// public void onClick(View v) {
// if (clickListener != null){
// clickListener.onCellViewClick(v,indexPath,userData);
// }
// }
//
// public boolean isRequiredValue() {
// return requiredValue;
// }
//
// public SLTableViewCell setRequiredValue(boolean requiredValue) {
// this.requiredValue = requiredValue;
// return this;
// }
//
// public String getKey() {
// return key;
// }
//
// public SLTableViewCell setKey(String key) {
// this.key = key;
// return this;
// }
//
// public HashMap<String,Object> keyValues(){
// HashMap<String,Object> result = new HashMap<String,Object>();
// String key = getKey();
// Object value = value();
// if (!TextUtils.isEmpty(key) && null != value){
// result.put(key,value);
// }
// return result;
// }
//
// // public ValueFilter getValueFilter() {
// // return valueFilter;
// // }
// //
// // public SLTableViewCell setValueFilter(ValueFilter valueFilter) {
// // this.valueFilter = valueFilter;
// // return this;
// // }
//
// // @Override
// // public boolean valueFilter(Object value){
// // if (null != getValueFilter()) {
// // return getValueFilter().valueFilter(value);
// // } else if (null == value) {
// // return false;
// // } else if (value instanceof String) {
// // return ((String)value).length() > 0;
// // }
// // return false;
// // }
//
// /**
// *
// * @return
// */
// public Object value(){
// return null;
// }
//
// // /**
// // * 当 requiredValue = true 和 value() 是空或者长度为0时, 显示的动画
// // * @return
// // */
// // public Animation animationWithNullValue(){
// // TranslateAnimation animation = new TranslateAnimation(-20, 20, 0, 0);
// // animation.setInterpolator(new AccelerateInterpolator());
// // animation.setDuration(100);
// // animation.setRepeatCount(3);
// // animation.setRepeatMode(Animation.REVERSE);
// // return animation;
// // }
//
// public interface SLCellViewClickListener{
// public void onCellViewClick(View view, SLIndexPath indexPath, Object userData);
// }
//
// }
| import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import com.shanlin.library.sltableview.SLTableViewCell; | package com.shanlin.library.sltableview.adapter;
public interface SLTableViewStickyHeaderAdapter{
public int stickyHeaderType();
public boolean stickyHeader(int position);
public boolean showStickyHeader(int position);
public int getHeaderSectionByPosition(int position); | // Path: library/src/main/java/com/shanlin/library/sltableview/SLTableViewCell.java
// public class SLTableViewCell extends RecyclerView.ViewHolder implements View.OnClickListener{
//
// private SLIndexPath indexPath;
// private SLCellViewClickListener clickListener;
// private Object userData;
// private String key;
// private boolean requiredValue;
// private ValueFilter valueFilter;
//
// public SLTableViewCell(View itemView) {
// super(itemView);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener){
// bindCellViewClick(view,clickListener,null);
// }
//
// /**
// *
// * @param view 需要设置点击监听的view
// * @param clickListener 回调接口
// * @param userData 用户数据
// */
// public void bindCellViewClick(View view,SLCellViewClickListener clickListener,Object userData){
// view.setOnClickListener(this);
// this.clickListener = clickListener;
// this.userData = userData;
// }
//
// public SLTableViewCell setIndexPath(SLIndexPath indexPath) {
// this.indexPath = indexPath;
// return this;
// }
//
//
// public SLIndexPath getIndexPath() {
// return indexPath.clone();
// }
//
// @Override
// public void onClick(View v) {
// if (clickListener != null){
// clickListener.onCellViewClick(v,indexPath,userData);
// }
// }
//
// public boolean isRequiredValue() {
// return requiredValue;
// }
//
// public SLTableViewCell setRequiredValue(boolean requiredValue) {
// this.requiredValue = requiredValue;
// return this;
// }
//
// public String getKey() {
// return key;
// }
//
// public SLTableViewCell setKey(String key) {
// this.key = key;
// return this;
// }
//
// public HashMap<String,Object> keyValues(){
// HashMap<String,Object> result = new HashMap<String,Object>();
// String key = getKey();
// Object value = value();
// if (!TextUtils.isEmpty(key) && null != value){
// result.put(key,value);
// }
// return result;
// }
//
// // public ValueFilter getValueFilter() {
// // return valueFilter;
// // }
// //
// // public SLTableViewCell setValueFilter(ValueFilter valueFilter) {
// // this.valueFilter = valueFilter;
// // return this;
// // }
//
// // @Override
// // public boolean valueFilter(Object value){
// // if (null != getValueFilter()) {
// // return getValueFilter().valueFilter(value);
// // } else if (null == value) {
// // return false;
// // } else if (value instanceof String) {
// // return ((String)value).length() > 0;
// // }
// // return false;
// // }
//
// /**
// *
// * @return
// */
// public Object value(){
// return null;
// }
//
// // /**
// // * 当 requiredValue = true 和 value() 是空或者长度为0时, 显示的动画
// // * @return
// // */
// // public Animation animationWithNullValue(){
// // TranslateAnimation animation = new TranslateAnimation(-20, 20, 0, 0);
// // animation.setInterpolator(new AccelerateInterpolator());
// // animation.setDuration(100);
// // animation.setRepeatCount(3);
// // animation.setRepeatMode(Animation.REVERSE);
// // return animation;
// // }
//
// public interface SLCellViewClickListener{
// public void onCellViewClick(View view, SLIndexPath indexPath, Object userData);
// }
//
// }
// Path: library/src/main/java/com/shanlin/library/sltableview/adapter/SLTableViewStickyHeaderAdapter.java
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import com.shanlin.library.sltableview.SLTableViewCell;
package com.shanlin.library.sltableview.adapter;
public interface SLTableViewStickyHeaderAdapter{
public int stickyHeaderType();
public boolean stickyHeader(int position);
public boolean showStickyHeader(int position);
public int getHeaderSectionByPosition(int position); | public SLTableViewCell onCreateHeaderCell(RecyclerView parent, int position); |
xiaoshanlin000/SLTableView | pickerview/src/main/java/com/bigkoo/pickerview/lib/WheelTime.java | // Path: pickerview/src/main/java/com/bigkoo/pickerview/TimePopupWindow.java
// public enum Type {
// ALL, YEAR_MONTH_DAY, HOURS_MINS, MONTH_DAY_HOUR_MIN
// }// 四种选择模式,年月日时分,年月日,时分,月日时分
| import android.content.Context;
import android.view.View;
import com.bigkoo.pickerview.R;
import com.bigkoo.pickerview.TimePopupWindow.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
| package com.bigkoo.pickerview.lib;
public class WheelTime {
public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private View view;
private WheelView wv_year;
private WheelView wv_month;
private WheelView wv_day;
private WheelView wv_hours;
private WheelView wv_mins;
public int screenheight;
| // Path: pickerview/src/main/java/com/bigkoo/pickerview/TimePopupWindow.java
// public enum Type {
// ALL, YEAR_MONTH_DAY, HOURS_MINS, MONTH_DAY_HOUR_MIN
// }// 四种选择模式,年月日时分,年月日,时分,月日时分
// Path: pickerview/src/main/java/com/bigkoo/pickerview/lib/WheelTime.java
import android.content.Context;
import android.view.View;
import com.bigkoo.pickerview.R;
import com.bigkoo.pickerview.TimePopupWindow.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
package com.bigkoo.pickerview.lib;
public class WheelTime {
public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private View view;
private WheelView wv_year;
private WheelView wv_month;
private WheelView wv_day;
private WheelView wv_hours;
private WheelView wv_mins;
public int screenheight;
| private Type type;
|
cloudera/flume | flume-core/src/test/java/com/cloudera/flume/agent/TestNodeJersey.java | // Path: flume-core/src/test/java/com/cloudera/flume/master/TestMasterJersey.java
// public static String curl(String urlString) throws IOException {
// URL url = new URL(urlString);
// URLConnection urlConn = url.openConnection();
// urlConn.setDoInput(true);
// urlConn.setUseCaches(false);
//
// int len = urlConn.getContentLength();
// String type = urlConn.getContentType();
// LOG.info("pulled " + urlString + "[ type=" + type + " len=" + len + "]");
// InputStreamReader isr = new InputStreamReader(urlConn.getInputStream());
// BufferedReader br = new BufferedReader(isr);
// StringBuilder sb = new StringBuilder();
// String s;
// while ((s = br.readLine()) != null) {
// sb.append(s);
// sb.append('\n');
// }
// return sb.toString();
// }
| import org.slf4j.LoggerFactory;
import com.cloudera.flume.conf.FlumeSpecException;
import com.cloudera.util.NetUtils;
import static com.cloudera.flume.master.TestMasterJersey.curl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import org.slf4j.Logger; | /**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.flume.agent;
public class TestNodeJersey {
public static final Logger LOG = LoggerFactory
.getLogger(TestNodeJersey.class);
FlumeNode node;
@Before
public void setup() throws IOException {
node = FlumeNode.setup(new String[] { "-1" });
}
@After
public void tearDown() {
node.stop();
}
@Ignore
@Test
public void testNode() throws IOException, InterruptedException,
FlumeSpecException, JSONException { | // Path: flume-core/src/test/java/com/cloudera/flume/master/TestMasterJersey.java
// public static String curl(String urlString) throws IOException {
// URL url = new URL(urlString);
// URLConnection urlConn = url.openConnection();
// urlConn.setDoInput(true);
// urlConn.setUseCaches(false);
//
// int len = urlConn.getContentLength();
// String type = urlConn.getContentType();
// LOG.info("pulled " + urlString + "[ type=" + type + " len=" + len + "]");
// InputStreamReader isr = new InputStreamReader(urlConn.getInputStream());
// BufferedReader br = new BufferedReader(isr);
// StringBuilder sb = new StringBuilder();
// String s;
// while ((s = br.readLine()) != null) {
// sb.append(s);
// sb.append('\n');
// }
// return sb.toString();
// }
// Path: flume-core/src/test/java/com/cloudera/flume/agent/TestNodeJersey.java
import org.slf4j.LoggerFactory;
import com.cloudera.flume.conf.FlumeSpecException;
import com.cloudera.util.NetUtils;
import static com.cloudera.flume.master.TestMasterJersey.curl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import org.slf4j.Logger;
/**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.flume.agent;
public class TestNodeJersey {
public static final Logger LOG = LoggerFactory
.getLogger(TestNodeJersey.class);
FlumeNode node;
@Before
public void setup() throws IOException {
node = FlumeNode.setup(new String[] { "-1" });
}
@After
public void tearDown() {
node.stop();
}
@Ignore
@Test
public void testNode() throws IOException, InterruptedException,
FlumeSpecException, JSONException { | String content = curl("http://localhost:35862/node/reports"); |
cloudera/flume | flume-core/src/main/java/com/cloudera/flume/conf/FlumeSpecGen.java | // Path: flume-core/src/main/java/com/cloudera/flume/conf/FlumeBuilder.java
// enum ASTNODE {
// DEC, HEX, OCT, STRING, BOOL, FLOAT, // literals
// FUNC, // function node
// SINK, SOURCE, // sink or source
// KWARG, // kwarg support
// MULTI, DECO, BACKUP, ROLL, GEN, FAILCHAIN, // compound sinks
// NODE, // combination of sink and source
// };
| import java.util.ArrayList;
import java.util.List;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import com.cloudera.flume.conf.FlumeBuilder.ASTNODE;
import com.cloudera.flume.master.FlumeNodeSpec;
import com.google.common.base.Preconditions; | /**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.flume.conf;
/**
* This regenerates flume specs from parsed ASTs.
*
* The master node reads and parses commands. If they parse cleanly, this is
* used to regenerated the code as a string so it can be sent to the nodes.
*/
public class FlumeSpecGen {
static String genArg(CommonTree t) throws FlumeSpecException { | // Path: flume-core/src/main/java/com/cloudera/flume/conf/FlumeBuilder.java
// enum ASTNODE {
// DEC, HEX, OCT, STRING, BOOL, FLOAT, // literals
// FUNC, // function node
// SINK, SOURCE, // sink or source
// KWARG, // kwarg support
// MULTI, DECO, BACKUP, ROLL, GEN, FAILCHAIN, // compound sinks
// NODE, // combination of sink and source
// };
// Path: flume-core/src/main/java/com/cloudera/flume/conf/FlumeSpecGen.java
import java.util.ArrayList;
import java.util.List;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import com.cloudera.flume.conf.FlumeBuilder.ASTNODE;
import com.cloudera.flume.master.FlumeNodeSpec;
import com.google.common.base.Preconditions;
/**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.flume.conf;
/**
* This regenerates flume specs from parsed ASTs.
*
* The master node reads and parses commands. If they parse cleanly, this is
* used to regenerated the code as a string so it can be sent to the nodes.
*/
public class FlumeSpecGen {
static String genArg(CommonTree t) throws FlumeSpecException { | ASTNODE type = ASTNODE.valueOf(t.getText()); // convert to enum |
cloudera/flume | flume-core/src/main/java/org/apache/thrift/transport/TSaneServerSocket.java | // Path: flume-core/src/main/java/com/cloudera/flume/handlers/thrift/TBufferedSocket.java
// public class TBufferedSocket extends TSocket {
//
// public TBufferedSocket(Socket socket) throws TTransportException {
// super(socket);
// wrapStreams();
// }
//
// public TBufferedSocket(String host, int port, int timeout) {
// super(host, port, timeout);
// wrapStreams();
// }
//
// public TBufferedSocket(String host, int port) {
// super(host, port);
// wrapStreams();
// }
//
// @Override
// public void open() throws TTransportException {
// super.open();
// wrapStreams();
// }
//
// private void wrapStreams() {
// if (!isOpen() || inputStream_ == null) {
// return;
// }
// inputStream_ = new BufferedInputStream(inputStream_);
// outputStream_ = new BufferedOutputStream(outputStream_);
// }
//
// }
| import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cloudera.flume.handlers.thrift.TBufferedSocket; | serverSocket_.setReuseAddress(true);
// Bind to listening port
serverSocket_.bind(bindAddr);
} catch (IOException ioe) {
serverSocket_ = null;
throw new TTransportException("Could not create ServerSocket on address "
+ bindAddr.toString() + ".");
}
}
public void listen() throws TTransportException {
bind();
// Make sure not to block on accept
if (serverSocket_ != null) {
try {
serverSocket_.setSoTimeout(0);
} catch (SocketException sx) {
LOGGER.error("Could not set socket timeout.", sx);
}
}
}
protected TTransport acceptImpl() throws TTransportException {
if (serverSocket_ == null) {
throw new TTransportException(TTransportException.NOT_OPEN,
"No underlying server socket.");
}
try {
Socket result = serverSocket_.accept(); | // Path: flume-core/src/main/java/com/cloudera/flume/handlers/thrift/TBufferedSocket.java
// public class TBufferedSocket extends TSocket {
//
// public TBufferedSocket(Socket socket) throws TTransportException {
// super(socket);
// wrapStreams();
// }
//
// public TBufferedSocket(String host, int port, int timeout) {
// super(host, port, timeout);
// wrapStreams();
// }
//
// public TBufferedSocket(String host, int port) {
// super(host, port);
// wrapStreams();
// }
//
// @Override
// public void open() throws TTransportException {
// super.open();
// wrapStreams();
// }
//
// private void wrapStreams() {
// if (!isOpen() || inputStream_ == null) {
// return;
// }
// inputStream_ = new BufferedInputStream(inputStream_);
// outputStream_ = new BufferedOutputStream(outputStream_);
// }
//
// }
// Path: flume-core/src/main/java/org/apache/thrift/transport/TSaneServerSocket.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cloudera.flume.handlers.thrift.TBufferedSocket;
serverSocket_.setReuseAddress(true);
// Bind to listening port
serverSocket_.bind(bindAddr);
} catch (IOException ioe) {
serverSocket_ = null;
throw new TTransportException("Could not create ServerSocket on address "
+ bindAddr.toString() + ".");
}
}
public void listen() throws TTransportException {
bind();
// Make sure not to block on accept
if (serverSocket_ != null) {
try {
serverSocket_.setSoTimeout(0);
} catch (SocketException sx) {
LOGGER.error("Could not set socket timeout.", sx);
}
}
}
protected TTransport acceptImpl() throws TTransportException {
if (serverSocket_ == null) {
throw new TTransportException(TTransportException.NOT_OPEN,
"No underlying server socket.");
}
try {
Socket result = serverSocket_.accept(); | TSocket result2 = new TBufferedSocket(result); |
fuhoujun/e | demo/demo-service/src/main/java/com/xx/demo/test/repository/CustomerRepository.java | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CustomerEntity.java
// @Entity
// @Table(name = "demo_customer")
// public class CustomerEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @ManyToOne()
// private DictionaryEntity sex;
// @ManyToOne()
// private CompanyEntity company;
// @Column( nullable=true)
// private Boolean vip = false;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date dob;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public DictionaryEntity getSex() {
// return sex;
// }
//
// public void setSex(DictionaryEntity sex) {
// this.sex = sex;
// }
// public CompanyEntity getCompany() {
// return company;
// }
//
// public void setCompany(CompanyEntity company) {
// this.company = company;
// }
// public Boolean getVip() {
// return vip;
// }
//
// public void setVip(Boolean vip) {
// this.vip = vip;
// }
// public Date getDob() {
// return dob;
// }
//
// public void setDob(Date dob) {
// this.dob = dob;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CustomerQueryParam.java
// public class CustomerQueryParam extends DefaultDataPermissionQueryParam implements QueryParam {
// private String name;
// private String sexId;
// private Boolean vip;
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date dobStart;
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date dobEnd;
// private String phone;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSexId() {
// return sexId;
// }
//
// public void setSexId(String sexId) {
// this.sexId = sexId;
// }
//
// public Boolean getVip() {
// return vip;
// }
//
// public void setVip(Boolean vip) {
// this.vip = vip;
// }
//
// public Date getDobStart() {
// return dobStart;
// }
//
// public void setDobStart(Date dobStart) {
// this.dobStart = dobStart;
// }
//
// public Date getDobEnd() {
// return dobEnd;
// }
//
// public void setDobEnd(Date dobEnd) {
// this.dobEnd = dobEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
| import org.springframework.data.jpa.repository.Query;
import com.loy.e.core.query.annotation.DynamicQuery;
import com.xx.demo.test.domain.entity.CustomerEntity;
import org.springframework.data.domain.Pageable;
import com.xx.demo.test.domain.CustomerQueryParam;
import org.springframework.data.domain.Page;
import com.loy.e.core.repository.GenericRepository; | package com.xx.demo.test.repository;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
public interface CustomerRepository extends GenericRepository<CustomerEntity, String> {
@Query(value=" from CustomerEntity x where 1=1 <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='sexId'> and x.sex.id = :sexId </notEmpty><notEmpty name='vip'> and x.vip = :vip </notEmpty><notEmpty name='dobStart'> and x.dob >= :dobStart </notEmpty><notEmpty name='dobEnd'> and x.dob <= :dobEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty>")
@DynamicQuery | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CustomerEntity.java
// @Entity
// @Table(name = "demo_customer")
// public class CustomerEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @ManyToOne()
// private DictionaryEntity sex;
// @ManyToOne()
// private CompanyEntity company;
// @Column( nullable=true)
// private Boolean vip = false;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date dob;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public DictionaryEntity getSex() {
// return sex;
// }
//
// public void setSex(DictionaryEntity sex) {
// this.sex = sex;
// }
// public CompanyEntity getCompany() {
// return company;
// }
//
// public void setCompany(CompanyEntity company) {
// this.company = company;
// }
// public Boolean getVip() {
// return vip;
// }
//
// public void setVip(Boolean vip) {
// this.vip = vip;
// }
// public Date getDob() {
// return dob;
// }
//
// public void setDob(Date dob) {
// this.dob = dob;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CustomerQueryParam.java
// public class CustomerQueryParam extends DefaultDataPermissionQueryParam implements QueryParam {
// private String name;
// private String sexId;
// private Boolean vip;
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date dobStart;
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date dobEnd;
// private String phone;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSexId() {
// return sexId;
// }
//
// public void setSexId(String sexId) {
// this.sexId = sexId;
// }
//
// public Boolean getVip() {
// return vip;
// }
//
// public void setVip(Boolean vip) {
// this.vip = vip;
// }
//
// public Date getDobStart() {
// return dobStart;
// }
//
// public void setDobStart(Date dobStart) {
// this.dobStart = dobStart;
// }
//
// public Date getDobEnd() {
// return dobEnd;
// }
//
// public void setDobEnd(Date dobEnd) {
// this.dobEnd = dobEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CustomerRepository.java
import org.springframework.data.jpa.repository.Query;
import com.loy.e.core.query.annotation.DynamicQuery;
import com.xx.demo.test.domain.entity.CustomerEntity;
import org.springframework.data.domain.Pageable;
import com.xx.demo.test.domain.CustomerQueryParam;
import org.springframework.data.domain.Page;
import com.loy.e.core.repository.GenericRepository;
package com.xx.demo.test.repository;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
public interface CustomerRepository extends GenericRepository<CustomerEntity, String> {
@Query(value=" from CustomerEntity x where 1=1 <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='sexId'> and x.sex.id = :sexId </notEmpty><notEmpty name='vip'> and x.vip = :vip </notEmpty><notEmpty name='dobStart'> and x.dob >= :dobStart </notEmpty><notEmpty name='dobEnd'> and x.dob <= :dobEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty>")
@DynamicQuery | Page<CustomerEntity> findCustomerPage(CustomerQueryParam customerQueryParam, Pageable pageable); |
fuhoujun/e | demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
| import org.springframework.data.jpa.repository.Query;
import com.loy.e.core.query.annotation.DynamicQuery;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.domain.CompanyQueryParam;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import com.loy.e.core.repository.GenericRepository; | package com.xx.demo.test.repository;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
@Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
@DynamicQuery | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java
import org.springframework.data.jpa.repository.Query;
import com.loy.e.core.query.annotation.DynamicQuery;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.domain.CompanyQueryParam;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import com.loy.e.core.repository.GenericRepository;
package com.xx.demo.test.repository;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
@Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
@DynamicQuery | Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable); |
fuhoujun/e | demo/demo-service/src/main/java/com/xx/demo/test/service/impl/CompanyServiceImpl.java | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java
// public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
//
// @Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
// @DynamicQuery
// Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable);
//
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.loy.e.common.util.DateUtil;
import com.loy.e.core.annotation.ControllerLogExeTime;
import com.loy.e.core.query.Direction;
import com.loy.e.core.util.TableToExcelUtil;
import com.loy.e.data.permission.annotation.DataPermission;
import com.xx.demo.test.domain.CompanyQueryParam;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.repository.CompanyRepository; | package com.xx.demo.test.service.impl;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@RestController
@RequestMapping(value={"**/company"}, method={RequestMethod.POST, RequestMethod.GET})
@Transactional
public class CompanyServiceImpl{
@Autowired | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java
// public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
//
// @Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
// @DynamicQuery
// Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable);
//
// }
// Path: demo/demo-service/src/main/java/com/xx/demo/test/service/impl/CompanyServiceImpl.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.loy.e.common.util.DateUtil;
import com.loy.e.core.annotation.ControllerLogExeTime;
import com.loy.e.core.query.Direction;
import com.loy.e.core.util.TableToExcelUtil;
import com.loy.e.data.permission.annotation.DataPermission;
import com.xx.demo.test.domain.CompanyQueryParam;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.repository.CompanyRepository;
package com.xx.demo.test.service.impl;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@RestController
@RequestMapping(value={"**/company"}, method={RequestMethod.POST, RequestMethod.GET})
@Transactional
public class CompanyServiceImpl{
@Autowired | CompanyRepository companyRepository; |
fuhoujun/e | demo/demo-service/src/main/java/com/xx/demo/test/service/impl/CompanyServiceImpl.java | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java
// public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
//
// @Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
// @DynamicQuery
// Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable);
//
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.loy.e.common.util.DateUtil;
import com.loy.e.core.annotation.ControllerLogExeTime;
import com.loy.e.core.query.Direction;
import com.loy.e.core.util.TableToExcelUtil;
import com.loy.e.data.permission.annotation.DataPermission;
import com.xx.demo.test.domain.CompanyQueryParam;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.repository.CompanyRepository; | package com.xx.demo.test.service.impl;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@RestController
@RequestMapping(value={"**/company"}, method={RequestMethod.POST, RequestMethod.GET})
@Transactional
public class CompanyServiceImpl{
@Autowired
CompanyRepository companyRepository;
@RequestMapping({ "/page" })
@ControllerLogExeTime(description = "分页查询公司", log = false)
@DataPermission(uniqueKey="CompanyServiceImpl.queryPage",findAll=true) | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java
// public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
//
// @Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
// @DynamicQuery
// Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable);
//
// }
// Path: demo/demo-service/src/main/java/com/xx/demo/test/service/impl/CompanyServiceImpl.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.loy.e.common.util.DateUtil;
import com.loy.e.core.annotation.ControllerLogExeTime;
import com.loy.e.core.query.Direction;
import com.loy.e.core.util.TableToExcelUtil;
import com.loy.e.data.permission.annotation.DataPermission;
import com.xx.demo.test.domain.CompanyQueryParam;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.repository.CompanyRepository;
package com.xx.demo.test.service.impl;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@RestController
@RequestMapping(value={"**/company"}, method={RequestMethod.POST, RequestMethod.GET})
@Transactional
public class CompanyServiceImpl{
@Autowired
CompanyRepository companyRepository;
@RequestMapping({ "/page" })
@ControllerLogExeTime(description = "分页查询公司", log = false)
@DataPermission(uniqueKey="CompanyServiceImpl.queryPage",findAll=true) | public Page<CompanyEntity> queryPage(CompanyQueryParam companyQueryParam, Pageable pageable) { |
fuhoujun/e | demo/demo-service/src/main/java/com/xx/demo/test/service/impl/CompanyServiceImpl.java | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java
// public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
//
// @Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
// @DynamicQuery
// Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable);
//
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.loy.e.common.util.DateUtil;
import com.loy.e.core.annotation.ControllerLogExeTime;
import com.loy.e.core.query.Direction;
import com.loy.e.core.util.TableToExcelUtil;
import com.loy.e.data.permission.annotation.DataPermission;
import com.xx.demo.test.domain.CompanyQueryParam;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.repository.CompanyRepository; | package com.xx.demo.test.service.impl;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@RestController
@RequestMapping(value={"**/company"}, method={RequestMethod.POST, RequestMethod.GET})
@Transactional
public class CompanyServiceImpl{
@Autowired
CompanyRepository companyRepository;
@RequestMapping({ "/page" })
@ControllerLogExeTime(description = "分页查询公司", log = false)
@DataPermission(uniqueKey="CompanyServiceImpl.queryPage",findAll=true) | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/CompanyQueryParam.java
// public class CompanyQueryParam extends DefaultDataPermissionQueryParam {
// private String name;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateStart;
// @DateTimeFormat(pattern = "yyyy-MM-dd")
// private Date registerDateEnd;
// private String phone;
//
// String orderProperty = "";
//
// String direction = "";
//
// public String getOrderProperty() {
// return orderProperty;
// }
//
// public void setOrderProperty(String orderProperty) {
// this.orderProperty = orderProperty;
// }
//
// public String getDirection() {
// return direction;
// }
//
// public void setDirection(String direction) {
// this.direction = direction;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getRegisterDateStart() {
// return registerDateStart;
// }
//
// public void setRegisterDateStart(Date registerDateStart) {
// this.registerDateStart = registerDateStart;
// }
//
// public Date getRegisterDateEnd() {
// return registerDateEnd;
// }
//
// public void setRegisterDateEnd(Date registerDateEnd) {
// this.registerDateEnd = registerDateEnd;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
//
// Path: demo/demo-service/src/main/java/com/xx/demo/test/repository/CompanyRepository.java
// public interface CompanyRepository extends GenericRepository<CompanyEntity, String> {
//
// @Query(value=" from CompanyEntity x where 1=1 ${permissionQL} <notEmpty name='name'> and x.name like '%${name}%' </notEmpty><notEmpty name='registerDateStart'> and x.registerDate >= :registerDateStart </notEmpty><notEmpty name='registerDateEnd'> and x.registerDate <= :registerDateEnd </notEmpty><notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty><notEmpty name='orderProperty'> order by x.${orderProperty} ${direction} </notEmpty>")
// @DynamicQuery
// Page<CompanyEntity> findCompanyPage(CompanyQueryParam companyQueryParam, Pageable pageable);
//
// }
// Path: demo/demo-service/src/main/java/com/xx/demo/test/service/impl/CompanyServiceImpl.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.loy.e.common.util.DateUtil;
import com.loy.e.core.annotation.ControllerLogExeTime;
import com.loy.e.core.query.Direction;
import com.loy.e.core.util.TableToExcelUtil;
import com.loy.e.data.permission.annotation.DataPermission;
import com.xx.demo.test.domain.CompanyQueryParam;
import com.xx.demo.test.domain.entity.CompanyEntity;
import com.xx.demo.test.repository.CompanyRepository;
package com.xx.demo.test.service.impl;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@RestController
@RequestMapping(value={"**/company"}, method={RequestMethod.POST, RequestMethod.GET})
@Transactional
public class CompanyServiceImpl{
@Autowired
CompanyRepository companyRepository;
@RequestMapping({ "/page" })
@ControllerLogExeTime(description = "分页查询公司", log = false)
@DataPermission(uniqueKey="CompanyServiceImpl.queryPage",findAll=true) | public Page<CompanyEntity> queryPage(CompanyQueryParam companyQueryParam, Pageable pageable) { |
fuhoujun/e | demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CustomerEntity.java | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
| import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.loy.e.core.entity.BaseEntity;
import javax.persistence.ManyToOne;
import com.xx.demo.test.domain.entity.CompanyEntity;
import java.util.Date;
import com.loy.e.basic.data.domain.entity.DictionaryEntity;
import org.springframework.format.annotation.DateTimeFormat; | package com.xx.demo.test.domain.entity;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@Entity
@Table(name = "demo_customer")
public class CustomerEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
@Column( nullable=true)
private String name;
@ManyToOne()
private DictionaryEntity sex;
@ManyToOne() | // Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CompanyEntity.java
// @Entity
// @Table(name = "demo_company")
// public class CompanyEntity extends BaseEntity {
// private static final long serialVersionUID = 1L;
// @Column( nullable=true)
// private String name;
// @Column( nullable=true)
// private Integer registeredCapital;
// @Column( nullable=true)
// @DateTimeFormat(pattern="yyyy-MM-dd")
// private Date registerDate;
// @Column( nullable=true)
// private String contactName;
// @Column( nullable=true)
// private String phone;
// @Column( nullable=true)
// private String address;
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// public Integer getRegisteredCapital() {
// return registeredCapital;
// }
//
// public void setRegisteredCapital(Integer registeredCapital) {
// this.registeredCapital = registeredCapital;
// }
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// public String getContactName() {
// return contactName;
// }
//
// public void setContactName(String contactName) {
// this.contactName = contactName;
// }
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
// }
// Path: demo/demo-service/src/main/java/com/xx/demo/test/domain/entity/CustomerEntity.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.loy.e.core.entity.BaseEntity;
import javax.persistence.ManyToOne;
import com.xx.demo.test.domain.entity.CompanyEntity;
import java.util.Date;
import com.loy.e.basic.data.domain.entity.DictionaryEntity;
import org.springframework.format.annotation.DateTimeFormat;
package com.xx.demo.test.domain.entity;
/**
*
* @author Loy Fu qq群 540553957 website = http://www.17jee.com
*/
@Entity
@Table(name = "demo_customer")
public class CustomerEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
@Column( nullable=true)
private String name;
@ManyToOne()
private DictionaryEntity sex;
@ManyToOne() | private CompanyEntity company; |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/AuthenticationClientFactory.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import java.io.IOException;
import java.util.Map; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* Authentication Factory to return appropriate authentication client for
* FormsAuthenticationHandler implementation.
*/
public interface AuthenticationClientFactory {
public AuthenticationSoap newSharePointFormsAuthentication(
String virtualServer, String username, String password)
throws IOException;
| // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/AuthenticationClientFactory.java
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import java.io.IOException;
import java.util.Map;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* Authentication Factory to return appropriate authentication client for
* FormsAuthenticationHandler implementation.
*/
public interface AuthenticationClientFactory {
public AuthenticationSoap newSharePointFormsAuthentication(
String virtualServer, String username, String password)
throws IOException;
| public SamlHandshakeManager newAdfsAuthentication(String virtualServer, |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManager.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication
* to request Live authentication token and extract authentication cookie.
*/
public class LiveAuthenticationHandshakeManager
extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint;
private final String stsrealm; | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManager.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication
* to request Live authentication token and extract authentication cookie.
*/
public class LiveAuthenticationHandshakeManager
extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint;
private final String stsrealm; | private final HttpPostClient httpClient; |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManager.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication
* to request Live authentication token and extract authentication cookie.
*/
public class LiveAuthenticationHandshakeManager
extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint;
private final String stsrealm;
private final HttpPostClient httpClient;
private String login;
private String trustLocation;
public Builder(String sharePointUrl, String username, String password) { | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManager.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication
* to request Live authentication token and extract authentication cookie.
*/
public class LiveAuthenticationHandshakeManager
extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint;
private final String stsrealm;
private final HttpPostClient httpClient;
private String login;
private String trustLocation;
public Builder(String sharePointUrl, String username, String password) { | this(sharePointUrl, username, password, new HttpPostClientImpl()); |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandlerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
//
// Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
public class SamlAuthenticationHandlerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testBuilder() {
new SamlAuthenticationHandler.Builder("username", "password", | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
//
// Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandlerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
public class SamlAuthenticationHandlerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testBuilder() {
new SamlAuthenticationHandler.Builder("username", "password", | new UnsupportedScheduledExecutor(), |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandlerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
//
// Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | new SamlAuthenticationHandler.Builder("username", "password",
new UnsupportedScheduledExecutor(), null).build();
}
@Test
public void testIsFormsAutentication() throws IOException {
assertTrue(new SamlAuthenticationHandler.Builder("username", "password",
new UnsupportedScheduledExecutor(),
new UnsupportedSamlHandshakeManager()).build().isFormsAuthentication());
}
@Test
public void testNullToken() throws IOException {
SamlAuthenticationHandler handler = new SamlAuthenticationHandler.Builder(
"username", "password", new UnsupportedScheduledExecutor(),
new MockSamlHandshakeManager(null, null) {
@Override public String getAuthenticationCookie(String token) {
throw new UnsupportedOperationException();
}
}).build();
assertTrue(handler.isFormsAuthentication());
thrown.expect(IOException.class);
AuthenticationResult result = handler.authenticate();
}
@Test
public void testSAMLAutentication() throws IOException {
SamlAuthenticationHandler handler
= new SamlAuthenticationHandler.Builder("username", "password", | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
//
// Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandlerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
new SamlAuthenticationHandler.Builder("username", "password",
new UnsupportedScheduledExecutor(), null).build();
}
@Test
public void testIsFormsAutentication() throws IOException {
assertTrue(new SamlAuthenticationHandler.Builder("username", "password",
new UnsupportedScheduledExecutor(),
new UnsupportedSamlHandshakeManager()).build().isFormsAuthentication());
}
@Test
public void testNullToken() throws IOException {
SamlAuthenticationHandler handler = new SamlAuthenticationHandler.Builder(
"username", "password", new UnsupportedScheduledExecutor(),
new MockSamlHandshakeManager(null, null) {
@Override public String getAuthenticationCookie(String token) {
throw new UnsupportedOperationException();
}
}).build();
assertTrue(handler.isFormsAuthentication());
thrown.expect(IOException.class);
AuthenticationResult result = handler.authenticate();
}
@Test
public void testSAMLAutentication() throws IOException {
SamlAuthenticationHandler handler
= new SamlAuthenticationHandler.Builder("username", "password", | new MockScheduledExecutor(), |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandlerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
//
// Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | public void testNullToken() throws IOException {
SamlAuthenticationHandler handler = new SamlAuthenticationHandler.Builder(
"username", "password", new UnsupportedScheduledExecutor(),
new MockSamlHandshakeManager(null, null) {
@Override public String getAuthenticationCookie(String token) {
throw new UnsupportedOperationException();
}
}).build();
assertTrue(handler.isFormsAuthentication());
thrown.expect(IOException.class);
AuthenticationResult result = handler.authenticate();
}
@Test
public void testSAMLAutentication() throws IOException {
SamlAuthenticationHandler handler
= new SamlAuthenticationHandler.Builder("username", "password",
new MockScheduledExecutor(),
new MockSamlHandshakeManager("token", "AuthenticationCookie"))
.build();
assertTrue(handler.isFormsAuthentication());
AuthenticationResult result = handler.authenticate();
assertNotNull(result);
assertEquals("AuthenticationCookie", result.getCookie());
assertEquals(600, result.getCookieTimeOut());
assertEquals("NO_ERROR", result.getErrorCode());
}
private static class UnsupportedSamlHandshakeManager | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
//
// Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandlerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public void testNullToken() throws IOException {
SamlAuthenticationHandler handler = new SamlAuthenticationHandler.Builder(
"username", "password", new UnsupportedScheduledExecutor(),
new MockSamlHandshakeManager(null, null) {
@Override public String getAuthenticationCookie(String token) {
throw new UnsupportedOperationException();
}
}).build();
assertTrue(handler.isFormsAuthentication());
thrown.expect(IOException.class);
AuthenticationResult result = handler.authenticate();
}
@Test
public void testSAMLAutentication() throws IOException {
SamlAuthenticationHandler handler
= new SamlAuthenticationHandler.Builder("username", "password",
new MockScheduledExecutor(),
new MockSamlHandshakeManager("token", "AuthenticationCookie"))
.build();
assertTrue(handler.isFormsAuthentication());
AuthenticationResult result = handler.authenticate();
assertNotNull(result);
assertEquals("AuthenticationCookie", result.getCookie());
assertEquals(600, result.getCookieTimeOut());
assertEquals("NO_ERROR", result.getErrorCode());
}
private static class UnsupportedSamlHandshakeManager | implements SamlHandshakeManager { |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/SharePointFormsAuthenticationHandler.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SharePointAdaptor.java
// @VisibleForTesting
// static String getAdaptorUser(String username) {
// if (!"".equals(username)) {
// return username;
// }
//
// // USERNAME and USERDOMAIN environment variables are applicable for
// // Windows only. On non windows adaptor machine user name will
// // not be empty.
// // Using Ssytem.getenv instead on System.getProperty("user.name") because
// // System.getProperty("user.name") returns username without domain.
// if (System.getenv("USERDOMAIN") == null
// || System.getenv("USERNAME") == null) {
// return null;
// }
// return System.getenv("USERDOMAIN") + "\\" + System.getenv("USERNAME");
// }
| import static com.google.enterprise.adaptor.sharepoint.SharePointAdaptor.getAdaptorUser;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationMode;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginErrorCode;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginResult;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.MessageContext; | }
this.username = username;
this.password = password;
this.executor = executor;
this.authenticationClient = authenticationClient;
}
public SharePointFormsAuthenticationHandler build() {
SharePointFormsAuthenticationHandler authenticationHandler
= new SharePointFormsAuthenticationHandler(
username, password, executor, authenticationClient);
return authenticationHandler;
}
}
@Override
public AuthenticationResult authenticate() throws IOException {
if (!isFormsAuthentication()) {
return new AuthenticationResult(null, DEFAULT_COOKIE_TIMEOUT_SECONDS,
LoginErrorCode.NOT_IN_FORMS_AUTHENTICATION_MODE.toString());
}
LoginResult result;
try {
result = authenticationClient.login(username, password);
} catch (WebServiceException ex) {
log.log(Level.WARNING,
"Forms authentication failed.", ex);
log.log(Level.INFO, "Possible SharePoint environment configured to use "
+ "claims based windows integrated authentication. "
+ "Adaptor will fallback to use windows integrated authentication " | // Path: src/com/google/enterprise/adaptor/sharepoint/SharePointAdaptor.java
// @VisibleForTesting
// static String getAdaptorUser(String username) {
// if (!"".equals(username)) {
// return username;
// }
//
// // USERNAME and USERDOMAIN environment variables are applicable for
// // Windows only. On non windows adaptor machine user name will
// // not be empty.
// // Using Ssytem.getenv instead on System.getProperty("user.name") because
// // System.getProperty("user.name") returns username without domain.
// if (System.getenv("USERDOMAIN") == null
// || System.getenv("USERNAME") == null) {
// return null;
// }
// return System.getenv("USERDOMAIN") + "\\" + System.getenv("USERNAME");
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/SharePointFormsAuthenticationHandler.java
import static com.google.enterprise.adaptor.sharepoint.SharePointAdaptor.getAdaptorUser;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationMode;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginErrorCode;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginResult;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.MessageContext;
}
this.username = username;
this.password = password;
this.executor = executor;
this.authenticationClient = authenticationClient;
}
public SharePointFormsAuthenticationHandler build() {
SharePointFormsAuthenticationHandler authenticationHandler
= new SharePointFormsAuthenticationHandler(
username, password, executor, authenticationClient);
return authenticationHandler;
}
}
@Override
public AuthenticationResult authenticate() throws IOException {
if (!isFormsAuthentication()) {
return new AuthenticationResult(null, DEFAULT_COOKIE_TIMEOUT_SECONDS,
LoginErrorCode.NOT_IN_FORMS_AUTHENTICATION_MODE.toString());
}
LoginResult result;
try {
result = authenticationClient.login(username, password);
} catch (WebServiceException ex) {
log.log(Level.WARNING,
"Forms authentication failed.", ex);
log.log(Level.INFO, "Possible SharePoint environment configured to use "
+ "claims based windows integrated authentication. "
+ "Adaptor will fallback to use windows integrated authentication " | + "using username \"{0}\"", getAdaptorUser("")); |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManagerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
| import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | "https://sharepoint.example.com", "username", "password").build();
String tokenResponse = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
+ "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">"
+ "<data>Something went wrong this is invalid</data>"
+ "</S:Envelope>";
thrown.expect(IOException.class);
String extractedToken = manager.extractToken(tokenResponse);
}
@Test
public void testExtractTokenWithNullInput() throws IOException {
LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username", "password").build();
thrown.expect(IOException.class);
String extractedToken = manager.extractToken(null);
}
@Test
public void testAuthenticateInSamlHandlerWithLive() throws IOException{
MockHttpPostClient postClient = new MockHttpPostClient();
LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username@domain", "password&123",
postClient).build();
URL tokenRequest = new URL(
"https://login.microsoftonline.com/extSTS.srf");
postClient.responseMap.put(tokenRequest, | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManagerTest.java
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
"https://sharepoint.example.com", "username", "password").build();
String tokenResponse = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
+ "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">"
+ "<data>Something went wrong this is invalid</data>"
+ "</S:Envelope>";
thrown.expect(IOException.class);
String extractedToken = manager.extractToken(tokenResponse);
}
@Test
public void testExtractTokenWithNullInput() throws IOException {
LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username", "password").build();
thrown.expect(IOException.class);
String extractedToken = manager.extractToken(null);
}
@Test
public void testAuthenticateInSamlHandlerWithLive() throws IOException{
MockHttpPostClient postClient = new MockHttpPostClient();
LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username@domain", "password&123",
postClient).build();
URL tokenRequest = new URL(
"https://login.microsoftonline.com/extSTS.srf");
postClient.responseMap.put(tokenRequest, | new PostResponseInfo(LIVE_AUTHENTICATION_RESPONSE, null)); |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManagerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
| import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | = new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username", "password").build();
thrown.expect(IOException.class);
String extractedToken = manager.extractToken(null);
}
@Test
public void testAuthenticateInSamlHandlerWithLive() throws IOException{
MockHttpPostClient postClient = new MockHttpPostClient();
LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username@domain", "password&123",
postClient).build();
URL tokenRequest = new URL(
"https://login.microsoftonline.com/extSTS.srf");
postClient.responseMap.put(tokenRequest,
new PostResponseInfo(LIVE_AUTHENTICATION_RESPONSE, null));
URL submitToken = new URL(
"https://sharepoint.example.com/_forms/default.aspx?wa=wsignin1.0");
Map<String, List<String>> responseHeaders
= new HashMap<String, List<String>>();
responseHeaders.put("some-header", Arrays.asList("some value"));
responseHeaders.put("Set-Cookie",
Arrays.asList("FedAuth=AutheCookie", "rfta=rftaValue"));
postClient.responseMap.put(submitToken,
new PostResponseInfo(null, responseHeaders));
SamlAuthenticationHandler authenticationHandler
= new SamlAuthenticationHandler.Builder("username@domain", | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManagerTest.java
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username", "password").build();
thrown.expect(IOException.class);
String extractedToken = manager.extractToken(null);
}
@Test
public void testAuthenticateInSamlHandlerWithLive() throws IOException{
MockHttpPostClient postClient = new MockHttpPostClient();
LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username@domain", "password&123",
postClient).build();
URL tokenRequest = new URL(
"https://login.microsoftonline.com/extSTS.srf");
postClient.responseMap.put(tokenRequest,
new PostResponseInfo(LIVE_AUTHENTICATION_RESPONSE, null));
URL submitToken = new URL(
"https://sharepoint.example.com/_forms/default.aspx?wa=wsignin1.0");
Map<String, List<String>> responseHeaders
= new HashMap<String, List<String>>();
responseHeaders.put("some-header", Arrays.asList("some value"));
responseHeaders.put("Set-Cookie",
Arrays.asList("FedAuth=AutheCookie", "rfta=rftaValue"));
postClient.responseMap.put(submitToken,
new PostResponseInfo(null, responseHeaders));
SamlAuthenticationHandler authenticationHandler
= new SamlAuthenticationHandler.Builder("username@domain", | "password&123", new MockScheduledExecutor(), manager).build(); |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManagerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
| import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException; | LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username@domain", "password&123",
postClient).build();
URL tokenRequest = new URL(
"https://login.microsoftonline.com/extSTS.srf");
postClient.responseMap.put(tokenRequest,
new PostResponseInfo(LIVE_AUTHENTICATION_RESPONSE, null));
URL submitToken = new URL(
"https://sharepoint.example.com/_forms/default.aspx?wa=wsignin1.0");
Map<String, List<String>> responseHeaders
= new HashMap<String, List<String>>();
responseHeaders.put("some-header", Arrays.asList("some value"));
responseHeaders.put("Set-Cookie",
Arrays.asList("FedAuth=AutheCookie", "rfta=rftaValue"));
postClient.responseMap.put(submitToken,
new PostResponseInfo(null, responseHeaders));
SamlAuthenticationHandler authenticationHandler
= new SamlAuthenticationHandler.Builder("username@domain",
"password&123", new MockScheduledExecutor(), manager).build();
AuthenticationResult result = authenticationHandler.authenticate();
assertEquals("FedAuth=AutheCookie;rfta=rftaValue;", result.getCookie());
assertEquals("NO_ERROR", result.getErrorCode());
assertEquals(600, result.getCookieTimeOut());
}
| // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/LiveAuthenticationHandshakeManagerTest.java
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
LiveAuthenticationHandshakeManager manager
= new LiveAuthenticationHandshakeManager.Builder(
"https://sharepoint.example.com", "username@domain", "password&123",
postClient).build();
URL tokenRequest = new URL(
"https://login.microsoftonline.com/extSTS.srf");
postClient.responseMap.put(tokenRequest,
new PostResponseInfo(LIVE_AUTHENTICATION_RESPONSE, null));
URL submitToken = new URL(
"https://sharepoint.example.com/_forms/default.aspx?wa=wsignin1.0");
Map<String, List<String>> responseHeaders
= new HashMap<String, List<String>>();
responseHeaders.put("some-header", Arrays.asList("some value"));
responseHeaders.put("Set-Cookie",
Arrays.asList("FedAuth=AutheCookie", "rfta=rftaValue"));
postClient.responseMap.put(submitToken,
new PostResponseInfo(null, responseHeaders));
SamlAuthenticationHandler authenticationHandler
= new SamlAuthenticationHandler.Builder("username@domain",
"password&123", new MockScheduledExecutor(), manager).build();
AuthenticationResult result = authenticationHandler.authenticate();
assertEquals("FedAuth=AutheCookie;rfta=rftaValue;", result.getCookie());
assertEquals("NO_ERROR", result.getErrorCode());
assertEquals(600, result.getCookieTimeOut());
}
| private static class MockHttpPostClient implements HttpPostClient { |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManagerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
| import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
public class AdfsHandshakeManagerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
| // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManagerTest.java
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
public class AdfsHandshakeManagerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
| private static class UnsupportedHttpPostClient implements HttpPostClient { |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManagerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
| import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
public class AdfsHandshakeManagerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private static class UnsupportedHttpPostClient implements HttpPostClient {
@Override | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManagerTest.java
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
public class AdfsHandshakeManagerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private static class UnsupportedHttpPostClient implements HttpPostClient {
@Override | public SamlAuthenticationHandler.PostResponseInfo issuePostRequest( |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManagerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
| import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test; | MockHttpPostClient postClient = new MockHttpPostClient();
String username = "username@domain";
String password = "password&123";
AdfsHandshakeManager manager = new AdfsHandshakeManager.Builder(
"https://sharepoint.intranet.com", username, password,
"https://sts.dmain.com/adfs/services/trust/2005/usernamemixed",
"urn:realm:sharepoint", postClient).build();
URL tokenRequest = new URL(
"https://sts.dmain.com/adfs/services/trust/2005/usernamemixed");
String tokenResponse = "<s:Envelope "
+ "xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">"
+ "<s:Header>Some header</s:Header>"
+ "<t:RequestSecurityTokenResponse "
+ "xmlns:t=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">"
+ "This is requested token"
+ "</t:RequestSecurityTokenResponse>"
+ "</s:Envelope>";
postClient.responseMap.put(tokenRequest,
new PostResponseInfo(tokenResponse, null));
URL submitToken = new URL("https://sharepoint.intranet.com/_trust");
Map<String, List<String>> responseHeaders
= new HashMap<String, List<String>>();
responseHeaders.put("some-header", Arrays.asList("some value"));
responseHeaders.put("Set-Cookie", Arrays.asList("FedAuth=AutheCookie"));
postClient.responseMap.put(submitToken,
new PostResponseInfo(null, responseHeaders));
SamlAuthenticationHandler authenticationHandler
= new SamlAuthenticationHandler.Builder(username, password, | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class MockScheduledExecutor
// extends UnsupportedScheduledExecutor {
// long executionDelay;
// TimeUnit executionTimeUnit;
//
// @Override
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// executionDelay = delay;
// executionTimeUnit = unit;
// return null;
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManagerTest.java
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.MockScheduledExecutor;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
MockHttpPostClient postClient = new MockHttpPostClient();
String username = "username@domain";
String password = "password&123";
AdfsHandshakeManager manager = new AdfsHandshakeManager.Builder(
"https://sharepoint.intranet.com", username, password,
"https://sts.dmain.com/adfs/services/trust/2005/usernamemixed",
"urn:realm:sharepoint", postClient).build();
URL tokenRequest = new URL(
"https://sts.dmain.com/adfs/services/trust/2005/usernamemixed");
String tokenResponse = "<s:Envelope "
+ "xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">"
+ "<s:Header>Some header</s:Header>"
+ "<t:RequestSecurityTokenResponse "
+ "xmlns:t=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">"
+ "This is requested token"
+ "</t:RequestSecurityTokenResponse>"
+ "</s:Envelope>";
postClient.responseMap.put(tokenRequest,
new PostResponseInfo(tokenResponse, null));
URL submitToken = new URL("https://sharepoint.intranet.com/_trust");
Map<String, List<String>> responseHeaders
= new HashMap<String, List<String>>();
responseHeaders.put("some-header", Arrays.asList("some value"));
responseHeaders.put("Set-Cookie", Arrays.asList("FedAuth=AutheCookie"));
postClient.responseMap.put(submitToken,
new PostResponseInfo(null, responseHeaders));
SamlAuthenticationHandler authenticationHandler
= new SamlAuthenticationHandler.Builder(username, password, | new MockScheduledExecutor(), manager).build(); |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManager.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* SamlHandshakeManager implementation to support ADFS 2.0
* to request ADFS authentication token and extract authentication cookie.
*/
public class AdfsHandshakeManager implements SamlHandshakeManager {
private static final Logger log
= Logger.getLogger(AdfsHandshakeManager.class.getName());
private static final String DEFAULT_LOGIN = "/_layouts/Authenticate.aspx";
private static final String DEFAULT_TRUST = "/_trust";
protected final String login;
protected final String username;
protected final String password;
protected final String sharePointUrl;
protected final String stsendpoint;
protected final String stsrealm; | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManager.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* SamlHandshakeManager implementation to support ADFS 2.0
* to request ADFS authentication token and extract authentication cookie.
*/
public class AdfsHandshakeManager implements SamlHandshakeManager {
private static final Logger log
= Logger.getLogger(AdfsHandshakeManager.class.getName());
private static final String DEFAULT_LOGIN = "/_layouts/Authenticate.aspx";
private static final String DEFAULT_TRUST = "/_trust";
protected final String login;
protected final String username;
protected final String password;
protected final String sharePointUrl;
protected final String stsendpoint;
protected final String stsrealm; | protected final HttpPostClient httpClient; |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManager.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; | + "<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>"
+ "</t:RequestSecurityToken></s:Body></s:Envelope>";
@VisibleForTesting
AdfsHandshakeManager(String sharePointUrl, String username,
String password, String stsendpoint, String stsrealm, String login,
String trustLocation, HttpPostClient httpClient) {
this.sharePointUrl = sharePointUrl;
this.username = username;
this.password = password;
this.stsendpoint = stsendpoint;
this.stsrealm = stsrealm;
this.login = login;
this.trustLocation = trustLocation;
this.httpClient = httpClient;
}
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private final String stsendpoint;
private final String stsrealm;
private final HttpPostClient httpClient;
private String login;
private String trustLocation;
public Builder(String sharePointUrl, String username,
String password, String stsendpoint, String stsrealm) {
this(sharePointUrl, username, password, stsendpoint, stsrealm, | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManager.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
+ "<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>"
+ "</t:RequestSecurityToken></s:Body></s:Envelope>";
@VisibleForTesting
AdfsHandshakeManager(String sharePointUrl, String username,
String password, String stsendpoint, String stsrealm, String login,
String trustLocation, HttpPostClient httpClient) {
this.sharePointUrl = sharePointUrl;
this.username = username;
this.password = password;
this.stsendpoint = stsendpoint;
this.stsrealm = stsrealm;
this.login = login;
this.trustLocation = trustLocation;
this.httpClient = httpClient;
}
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private final String stsendpoint;
private final String stsrealm;
private final HttpPostClient httpClient;
private String login;
private String trustLocation;
public Builder(String sharePointUrl, String username,
String password, String stsendpoint, String stsrealm) {
this(sharePointUrl, username, password, stsendpoint, stsrealm, | new HttpPostClientImpl()); |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManager.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; | }
public Builder setLoginUrl(String login) {
this.login = login;
return this;
}
public Builder setTrustLocation(String trustLocation) {
this.trustLocation = trustLocation;
return this;
}
public AdfsHandshakeManager build() {
if (Strings.isNullOrEmpty(trustLocation)
|| Strings.isNullOrEmpty(login)) {
throw new NullPointerException();
}
return new AdfsHandshakeManager(sharePointUrl, username,
password, stsendpoint, stsrealm, login, trustLocation, httpClient);
}
}
@Override
public String requestToken() throws IOException {
String saml = generateSamlRequest();
URL u = new URL(stsendpoint);
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("SOAPAction", stsendpoint);
requestHeaders.put("Content-Type",
"application/soap+xml; charset=utf-8"); | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/AdfsHandshakeManager.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
}
public Builder setLoginUrl(String login) {
this.login = login;
return this;
}
public Builder setTrustLocation(String trustLocation) {
this.trustLocation = trustLocation;
return this;
}
public AdfsHandshakeManager build() {
if (Strings.isNullOrEmpty(trustLocation)
|| Strings.isNullOrEmpty(login)) {
throw new NullPointerException();
}
return new AdfsHandshakeManager(sharePointUrl, username,
password, stsendpoint, stsrealm, login, trustLocation, httpClient);
}
}
@Override
public String requestToken() throws IOException {
String saml = generateSamlRequest();
URL u = new URL(stsendpoint);
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("SOAPAction", stsendpoint);
requestHeaders.put("Content-Type",
"application/soap+xml; charset=utf-8"); | PostResponseInfo postResponse |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/AuthenticationClientFactoryImpl.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import javax.xml.ws.Service;
import javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.InvalidConfigurationException;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.EndpointReference; | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* Authentication Factory implementation to return appropriate
* authentication client for FormsAuthenticationHandler implementation.
*/
public class AuthenticationClientFactoryImpl
implements AuthenticationClientFactory {
/** SharePoint's namespace. */
private static final String XMLNS
= "http://schemas.microsoft.com/sharepoint/soap/";
private static final Logger log
= Logger.getLogger(AuthenticationClientFactoryImpl.class.getName());
private final Service authenticationService;
public AuthenticationClientFactoryImpl() {
this.authenticationService = Service.create(
AuthenticationSoap.class.getResource("Authentication.wsdl"),
new QName(XMLNS, "Authentication"));
}
private static String handleEncoding(String endpoint) {
// Handle Unicode. Java does not properly encode the POST path.
return URI.create(endpoint).toASCIIString();
}
private static URI spUrlToUri(String url) throws IOException {
// Because SP is silly, the path of the URI is unencoded, but the rest of
// the URI is correct. Thus, we split up the path from the host, and then
// turn them into URIs separately, and then turn everything into a
// properly-escaped string.
String[] parts = url.split("/", 4);
if (parts.length < 3) {
throw new IllegalArgumentException("Too few '/'s: " + url);
}
String host = parts[0] + "/" + parts[1] + "/" + parts[2];
// Host must be properly-encoded already.
URI hostUri = URI.create(host);
if (parts.length == 3) {
// There was no path.
return hostUri;
}
URI pathUri;
try {
pathUri = new URI(null, null, "/" + parts[3], null);
} catch (URISyntaxException ex) {
throw new IOException(ex);
}
return hostUri.resolve(pathUri);
}
@Override
public AuthenticationSoap newSharePointFormsAuthentication(
String virtualServer, String username, String password)
throws IOException {
String authenticationEndPoint = spUrlToUri(virtualServer
+ "/_vti_bin/Authentication.asmx").toString();
EndpointReference endpointRef = new W3CEndpointReferenceBuilder()
.address(handleEncoding(authenticationEndPoint)).build();
authenticationService.getPort(endpointRef, AuthenticationSoap.class);
return
authenticationService.getPort(endpointRef, AuthenticationSoap.class);
}
@Override | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/AuthenticationClientFactoryImpl.java
import javax.xml.ws.Service;
import javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.InvalidConfigurationException;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.EndpointReference;
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint;
/**
* Authentication Factory implementation to return appropriate
* authentication client for FormsAuthenticationHandler implementation.
*/
public class AuthenticationClientFactoryImpl
implements AuthenticationClientFactory {
/** SharePoint's namespace. */
private static final String XMLNS
= "http://schemas.microsoft.com/sharepoint/soap/";
private static final Logger log
= Logger.getLogger(AuthenticationClientFactoryImpl.class.getName());
private final Service authenticationService;
public AuthenticationClientFactoryImpl() {
this.authenticationService = Service.create(
AuthenticationSoap.class.getResource("Authentication.wsdl"),
new QName(XMLNS, "Authentication"));
}
private static String handleEncoding(String endpoint) {
// Handle Unicode. Java does not properly encode the POST path.
return URI.create(endpoint).toASCIIString();
}
private static URI spUrlToUri(String url) throws IOException {
// Because SP is silly, the path of the URI is unencoded, but the rest of
// the URI is correct. Thus, we split up the path from the host, and then
// turn them into URIs separately, and then turn everything into a
// properly-escaped string.
String[] parts = url.split("/", 4);
if (parts.length < 3) {
throw new IllegalArgumentException("Too few '/'s: " + url);
}
String host = parts[0] + "/" + parts[1] + "/" + parts[2];
// Host must be properly-encoded already.
URI hostUri = URI.create(host);
if (parts.length == 3) {
// There was no path.
return hostUri;
}
URI pathUri;
try {
pathUri = new URI(null, null, "/" + parts[3], null);
} catch (URISyntaxException ex) {
throw new IOException(ex);
}
return hostUri.resolve(pathUri);
}
@Override
public AuthenticationSoap newSharePointFormsAuthentication(
String virtualServer, String username, String password)
throws IOException {
String authenticationEndPoint = spUrlToUri(virtualServer
+ "/_vti_bin/Authentication.asmx").toString();
EndpointReference endpointRef = new W3CEndpointReferenceBuilder()
.address(handleEncoding(authenticationEndPoint)).build();
authenticationService.getPort(endpointRef, AuthenticationSoap.class);
return
authenticationService.getPort(endpointRef, AuthenticationSoap.class);
}
@Override | public SamlHandshakeManager newAdfsAuthentication(String virtualServer, |
googlegsa/sharepoint | src/com/google/enterprise/adaptor/sharepoint/experimental/LiveAdfsHandshakeManager.java | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.Config;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint.experimental;
// TODO: Move this class under examples directory once this implementation
// is finalized and validated in field.
/**
* SamlHandshakeManager implementation to support ADFS 2.0 +
* Live authentication to request ADFS authentication token and
* extract authentication cookie from Live authentication.
*/
public class LiveAdfsHandshakeManager implements SamlHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAdfsHandshakeManager.class.getName());
private static final String DEFAULT_LOGIN = "/_layouts/Authenticate.aspx";
private static final String DEFAULT_TRUST = "/_trust";
protected final String login;
protected final String username;
protected final String password;
protected final String sharePointUrl;
protected final String stsendpoint;
protected final String stsrealm; | // Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for(String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = IOHelper.readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if (headers == null || !headers.containsKey(header)) {
// return null;
// }
// if (headers.get(header) == null || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for(String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/com/google/enterprise/adaptor/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: src/com/google/enterprise/adaptor/sharepoint/experimental/LiveAdfsHandshakeManager.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.adaptor.Config;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.adaptor.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor.sharepoint.experimental;
// TODO: Move this class under examples directory once this implementation
// is finalized and validated in field.
/**
* SamlHandshakeManager implementation to support ADFS 2.0 +
* Live authentication to request ADFS authentication token and
* extract authentication cookie from Live authentication.
*/
public class LiveAdfsHandshakeManager implements SamlHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAdfsHandshakeManager.class.getName());
private static final String DEFAULT_LOGIN = "/_layouts/Authenticate.aspx";
private static final String DEFAULT_TRUST = "/_trust";
protected final String login;
protected final String username;
protected final String password;
protected final String sharePointUrl;
protected final String stsendpoint;
protected final String stsrealm; | protected final HttpPostClient httpClient; |
googlegsa/sharepoint | test/com/google/enterprise/adaptor/sharepoint/SharePointFormsAuthenticationHandlerTest.java | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationMode;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginErrorCode;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginResult;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.EndpointReference;
import javax.xml.ws.handler.MessageContext; | @Override
public AuthenticationMode mode() {
return AuthenticationMode.FORMS;
}
public Map<String, Object> getRequestContext() {
throw new UnsupportedOperationException();
}
public Map<String, Object> getResponseContext() {
throw new UnsupportedOperationException();
}
public Binding getBinding() {
throw new UnsupportedOperationException();
}
public EndpointReference getEndpointReference() {
throw new UnsupportedOperationException();
}
public <T extends EndpointReference> T
getEndpointReference(Class<T> clazz) {
throw new UnsupportedOperationException();
}
}
@Test
public void testBuilder() {
new SharePointFormsAuthenticationHandler.Builder("username", "password", | // Path: test/com/google/enterprise/adaptor/sharepoint/FormsAuthenticationHandlerTest.java
// static class UnsupportedScheduledExecutor extends CallerRunsExecutor
// implements ScheduledExecutorService {
//
// public ScheduledFuture<?> schedule(Runnable command, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay,
// TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
// long initialDelay, long period, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
// long initialDelay, long delay, TimeUnit unit) {
// throw new UnsupportedOperationException();
// }
//
// }
// Path: test/com/google/enterprise/adaptor/sharepoint/SharePointFormsAuthenticationHandlerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.enterprise.adaptor.sharepoint.FormsAuthenticationHandlerTest.UnsupportedScheduledExecutor;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationMode;
import com.microsoft.schemas.sharepoint.soap.authentication.AuthenticationSoap;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginErrorCode;
import com.microsoft.schemas.sharepoint.soap.authentication.LoginResult;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.EndpointReference;
import javax.xml.ws.handler.MessageContext;
@Override
public AuthenticationMode mode() {
return AuthenticationMode.FORMS;
}
public Map<String, Object> getRequestContext() {
throw new UnsupportedOperationException();
}
public Map<String, Object> getResponseContext() {
throw new UnsupportedOperationException();
}
public Binding getBinding() {
throw new UnsupportedOperationException();
}
public EndpointReference getEndpointReference() {
throw new UnsupportedOperationException();
}
public <T extends EndpointReference> T
getEndpointReference(Class<T> clazz) {
throw new UnsupportedOperationException();
}
}
@Test
public void testBuilder() {
new SharePointFormsAuthenticationHandler.Builder("username", "password", | new UnsupportedScheduledExecutor(), |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream; | package ch.icclab.cyclops.dashboard.errorreporting;
/**
* This class reports exceptions to a RabbitMQ instance. The RabbitMQ endpoint
* and credentials are configured in /WEB-INF/configuration.txt with the following fields:
*
* ERROR_REPORTER_HOST
* ERROR_REPORTER_PORT
* ERROR_REPORTER_VIRTUAL_HOST
* ERROR_REPORTER_USERNAME
* ERROR_REPORTER_PASSWORD
* ERROR_REPORTER_ENABLED
*
* Errors will only be reported if ERROR_REPORTER_ENABLED is set to "true"
*/
public class ErrorReporter {
private static final String EXCHANGE_NAME = "cyclops";
public static void reportException(Exception ex) {
if(isExceptionReportingEnabled()) {
try {
Connection conn = getConnection();
Channel channel = conn.createChannel();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(baos));
channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
channel.close();
} catch (IOException e) {
System.err.println("Failed to open connection for error reporting: " + e.getMessage());
}
}
}
public static boolean isExceptionReportingEnabled() { | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
package ch.icclab.cyclops.dashboard.errorreporting;
/**
* This class reports exceptions to a RabbitMQ instance. The RabbitMQ endpoint
* and credentials are configured in /WEB-INF/configuration.txt with the following fields:
*
* ERROR_REPORTER_HOST
* ERROR_REPORTER_PORT
* ERROR_REPORTER_VIRTUAL_HOST
* ERROR_REPORTER_USERNAME
* ERROR_REPORTER_PASSWORD
* ERROR_REPORTER_ENABLED
*
* Errors will only be reported if ERROR_REPORTER_ENABLED is set to "true"
*/
public class ErrorReporter {
private static final String EXCHANGE_NAME = "cyclops";
public static void reportException(Exception ex) {
if(isExceptionReportingEnabled()) {
try {
Connection conn = getConnection();
Channel channel = conn.createChannel();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(baos));
channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
channel.close();
} catch (IOException e) {
System.err.println("Failed to open connection for error reporting: " + e.getMessage());
}
}
}
public static boolean isExceptionReportingEnabled() { | String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED"); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/users/UserInfo.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.restlet.util.Series; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.users;
/**
* This class provides access to OpenAM user information
*/
public class UserInfo extends ServerResource{
@Get
public Representation getUserInfo(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String sessionId = query.getFirstValue("session_id", "");
String user = getRequest().getAttributes().get("user").toString(); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/users/UserInfo.java
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.restlet.util.Series;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.users;
/**
* This class provides access to OpenAM user information
*/
public class UserInfo extends ServerResource{
@Get
public Representation getUserInfo(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String sessionId = query.getFirstValue("session_id", "");
String user = getRequest().getAttributes().get("user").toString(); | String urlPattern = LoadConfiguration.configuration.get("OPENAM_LIST_USERINFO_URL"); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/charge/Charge.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.charge;
/**
* This class handles all requests concerning the Charge microservice
*/
public class Charge extends OAuthServerResource {
/**
* This method gets the charge data from the RC microservice.
*
* The method receives the the user's keystone ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the RC Endpoint, requesting the usage data during the given time frame. The
* RC Charge endpoint is configured in /WEB-INF/configuration.txt as RC_CHARGE_URL
*
* @return [description]
*/
@Get
public Representation getCharge() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader(); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/charge/Charge.java
import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.charge;
/**
* This class handles all requests concerning the Charge microservice
*/
public class Charge extends OAuthServerResource {
/**
* This method gets the charge data from the RC microservice.
*
* The method receives the the user's keystone ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the RC Endpoint, requesting the usage data during the given time frame. The
* RC Charge endpoint is configured in /WEB-INF/configuration.txt as RC_CHARGE_URL
*
* @return [description]
*/
@Get
public Representation getCharge() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader(); | String url = LoadConfiguration.configuration.get("RC_CHARGE_URL") + "?" + query; |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/charge/Charge.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.charge;
/**
* This class handles all requests concerning the Charge microservice
*/
public class Charge extends OAuthServerResource {
/**
* This method gets the charge data from the RC microservice.
*
* The method receives the the user's keystone ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the RC Endpoint, requesting the usage data during the given time frame. The
* RC Charge endpoint is configured in /WEB-INF/configuration.txt as RC_CHARGE_URL
*
* @return [description]
*/
@Get
public Representation getCharge() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader();
String url = LoadConfiguration.configuration.get("RC_CHARGE_URL") + "?" + query; | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/charge/Charge.java
import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.charge;
/**
* This class handles all requests concerning the Charge microservice
*/
public class Charge extends OAuthServerResource {
/**
* This method gets the charge data from the RC microservice.
*
* The method receives the the user's keystone ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the RC Endpoint, requesting the usage data during the given time frame. The
* RC Charge endpoint is configured in /WEB-INF/configuration.txt as RC_CHARGE_URL
*
* @return [description]
*/
@Get
public Representation getCharge() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader();
String url = LoadConfiguration.configuration.get("RC_CHARGE_URL") + "?" + query; | OAuthClientResource clientResource = new OAuthClientResource(url, oauthToken); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/users/Admin.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import java.io.IOException;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.users;
/**
* This class is responsible for requests to OpenAM that concern the administrator group
*/
public class Admin extends ServerResource{
/**
* This method updates gets information about the dashboard admin group from OpenAM
* <p>
* The method receives an OpenAM Session ID from the dashboard frontend and uses it to send a request to the OpenAM
* endpoint configured in /WEB-INF/configuration.txt as OPENAM_LIST_ADMINS_URL
* <p>
* The call will only succeed if the given Session ID belongs to an admin user. Otherwise, an error message is
* returned instead
*
* @return A representation of the untouched response
*/
@Get
public Representation getAdminGroupInfo(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String sessionId = query.getFirstValue("session_id", ""); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/users/Admin.java
import java.io.IOException;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.users;
/**
* This class is responsible for requests to OpenAM that concern the administrator group
*/
public class Admin extends ServerResource{
/**
* This method updates gets information about the dashboard admin group from OpenAM
* <p>
* The method receives an OpenAM Session ID from the dashboard frontend and uses it to send a request to the OpenAM
* endpoint configured in /WEB-INF/configuration.txt as OPENAM_LIST_ADMINS_URL
* <p>
* The call will only succeed if the given Session ID belongs to an admin user. Otherwise, an error message is
* returned instead
*
* @return A representation of the untouched response
*/
@Get
public Representation getAdminGroupInfo(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String sessionId = query.getFirstValue("session_id", ""); | ClientResource clientResource = new ClientResource(LoadConfiguration.configuration.get("OPENAM_LIST_ADMINS_URL")); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/users/Admin.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import java.io.IOException;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series; | String adminGroupName = LoadConfiguration.configuration.get("OPENAM_ADMIN_GROUP_NAME");
String adminEntryPattern = LoadConfiguration.configuration.get("OPENAM_ADMIN_USER_PATTERN");
updateObject.put("name", adminGroupName);
updateObject.put("realm", "/");
updateObject.put("cn", new JSONArray(new String[] { adminGroupName }));
updateObject.put("description", "");
for(int i = 0; i < admins.length(); i++) {
String adminName = admins.getString(i);
String uniqueMember = adminEntryPattern.replace("{{USERNAME}}", adminName);
uniqueMembers.put(uniqueMember);
}
updateObject.put("uniquemember", uniqueMembers);
String url = LoadConfiguration.configuration.get("OPENAM_LIST_ADMINS_URL");
ClientResource clientResource = new ClientResource(url);
Series<Header> headers = (Series<Header>) clientResource.getRequestAttributes().get("org.restlet.http.headers");
if (headers == null) {
headers = new Series<Header>(Header.class);
clientResource.getRequestAttributes().put("org.restlet.http.headers", headers);
}
headers.set("iPlanetDirectoryPro", sessionId);
return clientResource.put(updateObject);
}
catch (Exception e) { | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/users/Admin.java
import java.io.IOException;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series;
String adminGroupName = LoadConfiguration.configuration.get("OPENAM_ADMIN_GROUP_NAME");
String adminEntryPattern = LoadConfiguration.configuration.get("OPENAM_ADMIN_USER_PATTERN");
updateObject.put("name", adminGroupName);
updateObject.put("realm", "/");
updateObject.put("cn", new JSONArray(new String[] { adminGroupName }));
updateObject.put("description", "");
for(int i = 0; i < admins.length(); i++) {
String adminName = admins.getString(i);
String uniqueMember = adminEntryPattern.replace("{{USERNAME}}", adminName);
uniqueMembers.put(uniqueMember);
}
updateObject.put("uniquemember", uniqueMembers);
String url = LoadConfiguration.configuration.get("OPENAM_LIST_ADMINS_URL");
ClientResource clientResource = new ClientResource(url);
Series<Header> headers = (Series<Header>) clientResource.getRequestAttributes().get("org.restlet.http.headers");
if (headers == null) {
headers = new Series<Header>(Header.class);
clientResource.getRequestAttributes().put("org.restlet.http.headers", headers);
}
headers.set("iPlanetDirectoryPro", sessionId);
return clientResource.put(updateObject);
}
catch (Exception e) { | ErrorReporter.reportException(e); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/login/Login.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import java.io.IOException; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class handles requests meant to request an access token from OpenAM and log into the dashboard
*/
public class Login extends ServerResource{
/**
* This method requests an Oauth / OpenID Connect access token from OpenAM
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request to the OpenAM endpoint configured in OAUTH_TOKEN_URL. The response will then be sent
* to the frontend without modification.
* <p>
* Since the request requires an OAuth client username and password, these credentials need to be preconfigured
* in /WEB-INF/configuration.txt as OAUTH_CLIENT_NAME and OAUTH_CLIENT_PASS.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) { | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/login/Login.java
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import java.io.IOException;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class handles requests meant to request an access token from OpenAM and log into the dashboard
*/
public class Login extends ServerResource{
/**
* This method requests an Oauth / OpenID Connect access token from OpenAM
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request to the OpenAM endpoint configured in OAUTH_TOKEN_URL. The response will then be sent
* to the frontend without modification.
* <p>
* Since the request requires an OAuth client username and password, these credentials need to be preconfigured
* in /WEB-INF/configuration.txt as OAUTH_CLIENT_NAME and OAUTH_CLIENT_PASS.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) { | ErrorReporter.reportException(e); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/login/Login.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import java.io.IOException; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class handles requests meant to request an access token from OpenAM and log into the dashboard
*/
public class Login extends ServerResource{
/**
* This method requests an Oauth / OpenID Connect access token from OpenAM
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request to the OpenAM endpoint configured in OAUTH_TOKEN_URL. The response will then be sent
* to the frontend without modification.
* <p>
* Since the request requires an OAuth client username and password, these credentials need to be preconfigured
* in /WEB-INF/configuration.txt as OAUTH_CLIENT_NAME and OAUTH_CLIENT_PASS.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) {
ErrorReporter.reportException(e);
throw new ResourceException(500);
}
}
private Representation sendRequest(String username, String password) {
Form form = new Form();
form.add("grant_type", "password");
form.add("username", username);
form.add("password", password); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/login/Login.java
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import java.io.IOException;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class handles requests meant to request an access token from OpenAM and log into the dashboard
*/
public class Login extends ServerResource{
/**
* This method requests an Oauth / OpenID Connect access token from OpenAM
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request to the OpenAM endpoint configured in OAUTH_TOKEN_URL. The response will then be sent
* to the frontend without modification.
* <p>
* Since the request requires an OAuth client username and password, these credentials need to be preconfigured
* in /WEB-INF/configuration.txt as OAUTH_CLIENT_NAME and OAUTH_CLIENT_PASS.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) {
ErrorReporter.reportException(e);
throw new ResourceException(500);
}
}
private Representation sendRequest(String username, String password) {
Form form = new Form();
form.add("grant_type", "password");
form.add("username", username);
form.add("password", password); | form.add("scope", LoadConfiguration.configuration.get("OAUTH_SCOPE")); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/bills/Billing.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.bills;
/**
* This class handles / forwards the call concerning billing information to
* the billing microservice
*/
public class Billing extends OAuthServerResource {
/**
* This method gets the billing details from the billing microservice.
*
* The method receives the the user's ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the Billing Endpoint, requesting the billing data during the given time frame. The
* Billing endpoint is configured in /WEB-INF/configuration.txt as BILLING_INVOICE_URL
*
* @return A representation of the untouched response
*/
@Get
public Representation getBills() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader(); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/bills/Billing.java
import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.bills;
/**
* This class handles / forwards the call concerning billing information to
* the billing microservice
*/
public class Billing extends OAuthServerResource {
/**
* This method gets the billing details from the billing microservice.
*
* The method receives the the user's ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the Billing Endpoint, requesting the billing data during the given time frame. The
* Billing endpoint is configured in /WEB-INF/configuration.txt as BILLING_INVOICE_URL
*
* @return A representation of the untouched response
*/
@Get
public Representation getBills() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader(); | String url = LoadConfiguration.configuration.get("BILLING_INVOICE_URL") + "?" + query; |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/bills/Billing.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.bills;
/**
* This class handles / forwards the call concerning billing information to
* the billing microservice
*/
public class Billing extends OAuthServerResource {
/**
* This method gets the billing details from the billing microservice.
*
* The method receives the the user's ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the Billing Endpoint, requesting the billing data during the given time frame. The
* Billing endpoint is configured in /WEB-INF/configuration.txt as BILLING_INVOICE_URL
*
* @return A representation of the untouched response
*/
@Get
public Representation getBills() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader();
String url = LoadConfiguration.configuration.get("BILLING_INVOICE_URL") + "?" + query; | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/bills/Billing.java
import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.bills;
/**
* This class handles / forwards the call concerning billing information to
* the billing microservice
*/
public class Billing extends OAuthServerResource {
/**
* This method gets the billing details from the billing microservice.
*
* The method receives the the user's ID and two timestamps (from / to) from the dashboard frontend.
* It then sends this information to the Billing Endpoint, requesting the billing data during the given time frame. The
* Billing endpoint is configured in /WEB-INF/configuration.txt as BILLING_INVOICE_URL
*
* @return A representation of the untouched response
*/
@Get
public Representation getBills() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader();
String url = LoadConfiguration.configuration.get("BILLING_INVOICE_URL") + "?" + query; | OAuthClientResource clientResource = new OAuthClientResource(url, oauthToken); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/users/User.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.restlet.util.Series; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.users;
/**
* This class provides access to the OpenAM user list
*/
public class User extends ServerResource{
/**
* This method updates gets information about the dashboard users from OpenAM
* <p>
* The method receives an OpenAM Session ID from the dashboard frontend and uses it to send a request to the OpenAM
* endpoint configured in /WEB-INF/configuration.txt as OPENAM_LIST_USERS_URL
* <p>
* The call will only succeed if the given Session ID belongs to an admin user. Otherwise, an error message is
* returned instead
*
* @return A representation of the untouched response
*/
@Get
public Representation getUsers(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String sessionId = query.getFirstValue("session_id", ""); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/users/User.java
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.data.Form;
import org.restlet.data.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.restlet.util.Series;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.users;
/**
* This class provides access to the OpenAM user list
*/
public class User extends ServerResource{
/**
* This method updates gets information about the dashboard users from OpenAM
* <p>
* The method receives an OpenAM Session ID from the dashboard frontend and uses it to send a request to the OpenAM
* endpoint configured in /WEB-INF/configuration.txt as OPENAM_LIST_USERS_URL
* <p>
* The call will only succeed if the given Session ID belongs to an admin user. Otherwise, an error message is
* returned instead
*
* @return A representation of the untouched response
*/
@Get
public Representation getUsers(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String sessionId = query.getFirstValue("session_id", ""); | ClientResource clientResource = new ClientResource(LoadConfiguration.configuration.get("OPENAM_LIST_USERS_URL")); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/rate/Rate.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.rate;
public class Rate extends OAuthServerResource {
@Get
public Representation getRate() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader(); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/rate/Rate.java
import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.rate;
public class Rate extends OAuthServerResource {
@Get
public Representation getRate() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader(); | String url = LoadConfiguration.configuration.get("RC_RATE_URL") + "?" + query; |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/rate/Rate.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.rate;
public class Rate extends OAuthServerResource {
@Get
public Representation getRate() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader();
String url = LoadConfiguration.configuration.get("RC_RATE_URL") + "?" + query; | // Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthClientResource.java
// public class OAuthClientResource extends ClientResource {
// private String oauthToken;
//
// public OAuthClientResource(String url, String oauthToken) {
// super(url);
// this.oauthToken = oauthToken;
// }
//
// private void addTokenHeader() {
// ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
// challenge.setRawValue(oauthToken);
// setChallengeResponse(challenge);
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation get() {
// addTokenHeader();
// return super.get();
// }
//
// /**
// * This method adds the OAUTH header to the client resource before sending it.
// * Sending the request will be handled by the parent class.
// */
// @Override
// public Representation post(Representation rep) {
// addTokenHeader();
// return super.post(rep);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/oauth2/OAuthServerResource.java
// public class OAuthServerResource extends ServerResource {
//
// /**
// * This method returns the OAUTH header if availabe
// * @return OAUTH token or empty string
// */
// public String getOAuthTokenFromHeader() {
// Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers");
//
// if(headers == null) {
// return "";
// }
//
// return headers.getFirstValue("X-OAuth-Token", true, "");
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/rate/Rate.java
import ch.icclab.cyclops.dashboard.oauth2.OAuthClientResource;
import ch.icclab.cyclops.dashboard.oauth2.OAuthServerResource;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.rate;
public class Rate extends OAuthServerResource {
@Get
public Representation getRate() {
String query = getRequest().getResourceRef().getQuery();
String oauthToken = getOAuthTokenFromHeader();
String url = LoadConfiguration.configuration.get("RC_RATE_URL") + "?" + query; | OAuthClientResource clientResource = new OAuthClientResource(url, oauthToken); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/keystone/KeystoneAssociation.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/builder/KeystoneRequestBuilder.java
// public class KeystoneRequestBuilder {
//
// /**
// * This method builds the correct JSON object for a keystone authentication request
// *
// * @param username The keystone username
// * @param pwd The keystone password
// * @param domainName The keystone domain
// * @return A JSON representation
// */
// public static JsonRepresentation buildKeystoneAuthRequestBody(String username, String pwd, String domainName) throws JSONException {
// JSONObject wrapper = new JSONObject();
// JSONObject domain = new JSONObject();
// domain.put("name", domainName);
// JSONArray methods = new JSONArray();
// methods.put("password");
// JSONObject user = new JSONObject();
// user.put("domain", domain);
// user.put("name", username);
// user.put("password", pwd);
// JSONObject password = new JSONObject();
// password.put("user", user);
// JSONObject identity = new JSONObject();
// identity.put("methods", methods);
// identity.put("password", password);
// JSONObject auth = new JSONObject();
// auth.put("identity", identity);
// wrapper.put("auth", auth);
//
// return new JsonRepresentation(wrapper);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.builder.KeystoneRequestBuilder;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException; | headers = new Series<Header>(Header.class);
res.getRequestAttributes().put("org.restlet.http.headers", headers);
}
headers.set("iPlanetDirectoryPro", sessionId);
JSONObject data = new JSONObject();
data.put("keystoneid", keystoneId);
return res.put(new JsonRepresentation(data), MediaType.APPLICATION_JSON);
}
catch (Exception e) {
ErrorReporter.reportException(e);
throw new ResourceException(500);
}
}
private Representation findUserId(Representation rep) throws JSONException, IOException {
JSONObject response = new JSONObject();
JsonRepresentation jsonRep = new JsonRepresentation(rep);
JSONObject wrapper = jsonRep.getJsonObject();
String id = wrapper
.getJSONObject("token")
.getJSONObject("user")
.getString("id");
response.put("keystoneId", id);
return new JsonRepresentation(response);
}
private Representation sendRequest(String username, String pwd) throws JSONException, IOException { | // Path: dashboard/src/ch/icclab/cyclops/dashboard/builder/KeystoneRequestBuilder.java
// public class KeystoneRequestBuilder {
//
// /**
// * This method builds the correct JSON object for a keystone authentication request
// *
// * @param username The keystone username
// * @param pwd The keystone password
// * @param domainName The keystone domain
// * @return A JSON representation
// */
// public static JsonRepresentation buildKeystoneAuthRequestBody(String username, String pwd, String domainName) throws JSONException {
// JSONObject wrapper = new JSONObject();
// JSONObject domain = new JSONObject();
// domain.put("name", domainName);
// JSONArray methods = new JSONArray();
// methods.put("password");
// JSONObject user = new JSONObject();
// user.put("domain", domain);
// user.put("name", username);
// user.put("password", pwd);
// JSONObject password = new JSONObject();
// password.put("user", user);
// JSONObject identity = new JSONObject();
// identity.put("methods", methods);
// identity.put("password", password);
// JSONObject auth = new JSONObject();
// auth.put("identity", identity);
// wrapper.put("auth", auth);
//
// return new JsonRepresentation(wrapper);
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/keystone/KeystoneAssociation.java
import ch.icclab.cyclops.dashboard.builder.KeystoneRequestBuilder;
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException;
headers = new Series<Header>(Header.class);
res.getRequestAttributes().put("org.restlet.http.headers", headers);
}
headers.set("iPlanetDirectoryPro", sessionId);
JSONObject data = new JSONObject();
data.put("keystoneid", keystoneId);
return res.put(new JsonRepresentation(data), MediaType.APPLICATION_JSON);
}
catch (Exception e) {
ErrorReporter.reportException(e);
throw new ResourceException(500);
}
}
private Representation findUserId(Representation rep) throws JSONException, IOException {
JSONObject response = new JSONObject();
JsonRepresentation jsonRep = new JsonRepresentation(rep);
JSONObject wrapper = jsonRep.getJsonObject();
String id = wrapper
.getJSONObject("token")
.getJSONObject("user")
.getString("id");
response.put("keystoneId", id);
return new JsonRepresentation(response);
}
private Representation sendRequest(String username, String pwd) throws JSONException, IOException { | JsonRepresentation body = KeystoneRequestBuilder.buildKeystoneAuthRequestBody(username, pwd, "default"); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/login/Session.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class is responsible for requests that handle OpenAM Sessions
*/
public class Session extends ServerResource{
/**
* This method requests an OpenAM session ID to later make OpenAM API calls
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request with X-OpenAM-Username and X-OpenAM-Password headers.
* That request is then sent the appropriate OpenAM endpoint configured in OPENAM_AUTH_URL.
* Finally, the response will then be sent to the frontend without modification.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) { | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/login/Session.java
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class is responsible for requests that handle OpenAM Sessions
*/
public class Session extends ServerResource{
/**
* This method requests an OpenAM session ID to later make OpenAM API calls
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request with X-OpenAM-Username and X-OpenAM-Password headers.
* That request is then sent the appropriate OpenAM endpoint configured in OPENAM_AUTH_URL.
* Finally, the response will then be sent to the frontend without modification.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) { | ErrorReporter.reportException(e); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/login/Session.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class is responsible for requests that handle OpenAM Sessions
*/
public class Session extends ServerResource{
/**
* This method requests an OpenAM session ID to later make OpenAM API calls
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request with X-OpenAM-Username and X-OpenAM-Password headers.
* That request is then sent the appropriate OpenAM endpoint configured in OPENAM_AUTH_URL.
* Finally, the response will then be sent to the frontend without modification.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) {
ErrorReporter.reportException(e);
throw new ResourceException(500);
}
}
private Representation sendRequest(String username, String password) { | // Path: dashboard/src/ch/icclab/cyclops/dashboard/errorreporting/ErrorReporter.java
// public class ErrorReporter {
// private static final String EXCHANGE_NAME = "cyclops";
//
// public static void reportException(Exception ex) {
// if(isExceptionReportingEnabled()) {
// try {
// Connection conn = getConnection();
// Channel channel = conn.createChannel();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ex.printStackTrace(new PrintStream(baos));
// channel.basicPublish(EXCHANGE_NAME, "dashboard-errors", null, baos.toByteArray());
// channel.close();
//
// } catch (IOException e) {
// System.err.println("Failed to open connection for error reporting: " + e.getMessage());
// }
// }
// }
//
// public static boolean isExceptionReportingEnabled() {
// String enabled = LoadConfiguration.configuration.get("ERROR_REPORTER_ENABLED");
// return enabled.equals("true");
// }
//
// private static Connection getConnection() throws IOException {
// ConnectionFactory factory = new ConnectionFactory();
// factory.setHost(LoadConfiguration.configuration.get("ERROR_REPORTER_HOST"));
// factory.setPort(Integer.parseInt(LoadConfiguration.configuration.get("ERROR_REPORTER_PORT")));
// factory.setVirtualHost(LoadConfiguration.configuration.get("ERROR_REPORTER_VIRTUAL_HOST"));
// factory.setUsername(LoadConfiguration.configuration.get("ERROR_REPORTER_USERNAME"));
// factory.setPassword(LoadConfiguration.configuration.get("ERROR_REPORTER_PASSWORD"));
// return factory.newConnection();
// }
// }
//
// Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/login/Session.java
import ch.icclab.cyclops.dashboard.errorreporting.ErrorReporter;
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Header;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.*;
import org.restlet.util.Series;
import java.io.IOException;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.login;
/**
* This class is responsible for requests that handle OpenAM Sessions
*/
public class Session extends ServerResource{
/**
* This method requests an OpenAM session ID to later make OpenAM API calls
* <p>
* The method receives the user credentials from the dashboard frontend. Username and password are then used
* to build a new request with X-OpenAM-Username and X-OpenAM-Password headers.
* That request is then sent the appropriate OpenAM endpoint configured in OPENAM_AUTH_URL.
* Finally, the response will then be sent to the frontend without modification.
*
* @param entity The incoming request from the dashboard frontend containing username and password
* @return A representation of the untouched response
*/
@Post("json")
public Representation login(Representation entity) {
try {
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject json = represent.getJsonObject();
String user = json.getString("username");
String pass = json.getString("password");
return sendRequest(user, pass);
}
catch (Exception e) {
ErrorReporter.reportException(e);
throw new ResourceException(500);
}
}
private Representation sendRequest(String username, String password) { | ClientResource res = new ClientResource(LoadConfiguration.configuration.get("OPENAM_AUTH_URL")); |
icclab/cyclops-support | dashboard/src/ch/icclab/cyclops/dashboard/token/TokenInfo.java | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
| import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource; | /*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.token;
/**
* This class provides access to the OpenAM UserInfo endpoint
*/
public class TokenInfo extends ServerResource{
/**
* This method requests Token information from OpenAM.
* <p>
* The method receives an access token from the dashboard frontend. With this token, a request is sent to the
* appropriate OpenAM endpoint configured as OAUTH_TOKEN_INFO_URL. The response is then sent back to the dashboard.
*
* @return A representation of the untouched response
*/
@Get
public Representation userinfo(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String queryString = "?access_token=" + query.getFirstValue("access_token", ""); | // Path: dashboard/src/ch/icclab/cyclops/dashboard/util/LoadConfiguration.java
// public class LoadConfiguration extends ClientResource {
//
// //Instantiating the Instance variable for saving the config details
// public static HashMap<String,String> configuration;
//
// /**
// * Loads the configuration file
// *
// * Pseudo Code
// * 1. Create an instance of the ServletContext
// * 2. Get the relative path of the configuration.txt file
// * 3. Load the file and save the values into a static HashMap
// *
// * @param context
// * @throws IOException
// */
// public void run(Context context) throws IOException {
// configuration = new HashMap<String,String>();
// String nextLine;
//
// // Extract the ServletContext from the attributes of RestletContext
// ServletContext servlet = (ServletContext) context.getAttributes().get("org.restlet.ext.servlet.ServletContext");
// System.out.println("Reading the config file from " + servlet.getRealPath("/WEB-INF/configuration.txt"));
// // Get the path of the config file relative to the WAR
// String rootPath = servlet.getRealPath("/WEB-INF/configuration.txt");
//
// //Add WEB-INF path to access local images etc.
// String webInfPath = servlet.getRealPath("/WEB-INF");
// configuration.put("WEB-INF", webInfPath);
//
// Path path = Paths.get(rootPath);
// File configFile = new File(path.toString());
// FileRepresentation file = new FileRepresentation(configFile, MediaType.TEXT_PLAIN);
//
// // Read the values from the config file
// try {
// BufferedReader reader = new BufferedReader(file.getReader());
// while((nextLine = reader.readLine()) != null ) {
// String[] str = nextLine.split("==");
// configuration.put(str[0],str[1]);
// }
// } catch (IOException e) {
// System.out.println("Failed to load the Config file");
// e.printStackTrace();
// }
// }
// }
// Path: dashboard/src/ch/icclab/cyclops/dashboard/token/TokenInfo.java
import ch.icclab.cyclops.dashboard.util.LoadConfiguration;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/*
* Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package ch.icclab.cyclops.dashboard.token;
/**
* This class provides access to the OpenAM UserInfo endpoint
*/
public class TokenInfo extends ServerResource{
/**
* This method requests Token information from OpenAM.
* <p>
* The method receives an access token from the dashboard frontend. With this token, a request is sent to the
* appropriate OpenAM endpoint configured as OAUTH_TOKEN_INFO_URL. The response is then sent back to the dashboard.
*
* @return A representation of the untouched response
*/
@Get
public Representation userinfo(){
Form query = getRequest().getResourceRef().getQueryAsForm();
String queryString = "?access_token=" + query.getFirstValue("access_token", ""); | ClientResource clientResource = new ClientResource(LoadConfiguration.configuration.get("OAUTH_TOKEN_INFO_URL") + queryString); |
guigarage/ObserverPattern | tck/src/main/java/javax/observer/tck/CheckStringObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import java.util.Objects; | package javax.observer.tck;
/**
* @author Achim Meißner
*/
public class CheckStringObservable {
public static void checkStringObservableBasicMethods(final Observable<String> observable) {
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(null);
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
// Path: tck/src/main/java/javax/observer/tck/CheckStringObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import java.util.Objects;
package javax.observer.tck;
/**
* @author Achim Meißner
*/
public class CheckStringObservable {
public static void checkStringObservableBasicMethods(final Observable<String> observable) {
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(null);
| final Subscription willChangeSubscription = observable.onWillChange(e -> new RuntimeException("FAIL")); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/SwingBinding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier; | package com.guigarage.binding;
/**
* Provides Bindings for Swing. Swing attributes will automatically be handled in the EDT and properties will
* automatically be handled in a background thread.
*/
public class SwingBinding {
private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
package com.guigarage.binding;
/**
* Provides Bindings for Swing. Swing attributes will automatically be handled in the EDT and properties will
* automatically be handled in a background thread.
*/
public class SwingBinding {
private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
| public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) { |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/SwingBinding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier; | package com.guigarage.binding;
/**
* Provides Bindings for Swing. Swing attributes will automatically be handled in the EDT and properties will
* automatically be handled in a background thread.
*/
public class SwingBinding {
private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
return new ConvertableBidirectionalBindable<T>() {
private AtomicBoolean bindingCalled = new AtomicBoolean(false);
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private Lock bindingLock = new ReentrantLock();
private <U> U callLocked(Supplier<U> supplier) {
bindingLock.lock();
try {
return supplier.get();
} finally {
bindingLock.unlock();
}
}
private void callLocked(Runnable runnable) {
callLocked(() -> {
runnable.run();
return null;
});
}
@Override | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
package com.guigarage.binding;
/**
* Provides Bindings for Swing. Swing attributes will automatically be handled in the EDT and properties will
* automatically be handled in a background thread.
*/
public class SwingBinding {
private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
return new ConvertableBidirectionalBindable<T>() {
private AtomicBoolean bindingCalled = new AtomicBoolean(false);
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private Lock bindingLock = new ReentrantLock();
private <U> U callLocked(Supplier<U> supplier) {
bindingLock.lock();
try {
return supplier.get();
} finally {
bindingLock.unlock();
}
}
private void callLocked(Runnable runnable) {
callLocked(() -> {
runnable.run();
return null;
});
}
@Override | public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) { |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/SwingBinding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier; | package com.guigarage.binding;
/**
* Provides Bindings for Swing. Swing attributes will automatically be handled in the EDT and properties will
* automatically be handled in a background thread.
*/
public class SwingBinding {
private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
return new ConvertableBidirectionalBindable<T>() {
private AtomicBoolean bindingCalled = new AtomicBoolean(false);
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private Lock bindingLock = new ReentrantLock();
private <U> U callLocked(Supplier<U> supplier) {
bindingLock.lock();
try {
return supplier.get();
} finally {
bindingLock.unlock();
}
}
private void callLocked(Runnable runnable) {
callLocked(() -> {
runnable.run();
return null;
});
}
@Override | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
package com.guigarage.binding;
/**
* Provides Bindings for Swing. Swing attributes will automatically be handled in the EDT and properties will
* automatically be handled in a background thread.
*/
public class SwingBinding {
private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
return new ConvertableBidirectionalBindable<T>() {
private AtomicBoolean bindingCalled = new AtomicBoolean(false);
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private Lock bindingLock = new ReentrantLock();
private <U> U callLocked(Supplier<U> supplier) {
bindingLock.lock();
try {
return supplier.get();
} finally {
bindingLock.unlock();
}
}
private void callLocked(Runnable runnable) {
callLocked(() -> {
runnable.run();
return null;
});
}
@Override | public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) { |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/SwingBinding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier; | callLocked(() -> {
try {
property.setValue(converter2.apply((T) e.getNewValue()));
} catch (Exception ex) {
SwingUtilities.invokeLater(() -> {
errorHandler.accept(ex);
});
}
});
});
} catch (Exception e1) {
errorHandler.accept(e1);
} finally {
bindingCalled.set(false);
}
}
};
component.addPropertyChangeListener(listener);
return () -> {
component.removePropertyChangeListener(listener);
subscription.unsubscribe();
};
} catch (Exception e1) {
throw new RuntimeException("Can not bind!", e1);
}
}
@Override | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
callLocked(() -> {
try {
property.setValue(converter2.apply((T) e.getNewValue()));
} catch (Exception ex) {
SwingUtilities.invokeLater(() -> {
errorHandler.accept(ex);
});
}
});
});
} catch (Exception e1) {
errorHandler.accept(e1);
} finally {
bindingCalled.set(false);
}
}
};
component.addPropertyChangeListener(listener);
return () -> {
component.removePropertyChangeListener(listener);
subscription.unsubscribe();
};
} catch (Exception e1) {
throw new RuntimeException("Can not bind!", e1);
}
}
@Override | public <U> Subscription to(Observable<U> observable, Function<U, T> converter) { |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/SwingBinding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier; | throw new RuntimeException("Can not bind!", e1);
}
}
private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
return observable.onChanged(e -> {
callLocked(() -> {
try {
SwingUtilities.invokeAndWait(() -> {
if (!bindingCalled.get()) {
bindingCalled.set(true);
try {
propertyEditor.setValue(converter.apply(e.getValue()));
} catch (Exception e1) {
errorHandler.accept(e1);
} finally {
bindingCalled.set(false);
}
}
});
} catch (Exception e1) {
SwingUtilities.invokeLater(() -> {
errorHandler.accept(e1);
});
}
});
});
}
@Override | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
throw new RuntimeException("Can not bind!", e1);
}
}
private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
return observable.onChanged(e -> {
callLocked(() -> {
try {
SwingUtilities.invokeAndWait(() -> {
if (!bindingCalled.get()) {
bindingCalled.set(true);
try {
propertyEditor.setValue(converter.apply(e.getValue()));
} catch (Exception e1) {
errorHandler.accept(e1);
} finally {
bindingCalled.set(false);
}
}
});
} catch (Exception e1) {
SwingUtilities.invokeLater(() -> {
errorHandler.accept(e1);
});
}
});
});
}
@Override | public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) { |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/BindingExample.java | // Path: impl/src/main/java/com/guigarage/binding/Binding.java
// public class Binding {
//
// public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private boolean bindingCalled = false;
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
// Subscription subscription1 = to(toProperty, converter);
// Subscription subscription2 = bind(property, toProperty, converter2);
// return () -> {
// subscription1.unsubscribe();
// subscription2.unsubscribe();
// };
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// return bind(observable, property, converter);
// }
//
// private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
// return observable.onChanged(e -> {
// if(!bindingCalled) {
// bindingCalled = true;
// try {
// property.setValue(converter.apply(e.getValue()));
// } catch (Exception ex) {
// errorHandler.accept(ex);
// } finally {
// bindingCalled = false;
// }
// }
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = errorHandler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.binding.Binding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property; | package com.guigarage.examples;
public class BindingExample {
public static void main(String[] args) { | // Path: impl/src/main/java/com/guigarage/binding/Binding.java
// public class Binding {
//
// public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private boolean bindingCalled = false;
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
// Subscription subscription1 = to(toProperty, converter);
// Subscription subscription2 = bind(property, toProperty, converter2);
// return () -> {
// subscription1.unsubscribe();
// subscription2.unsubscribe();
// };
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// return bind(observable, property, converter);
// }
//
// private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
// return observable.onChanged(e -> {
// if(!bindingCalled) {
// bindingCalled = true;
// try {
// property.setValue(converter.apply(e.getValue()));
// } catch (Exception ex) {
// errorHandler.accept(ex);
// } finally {
// bindingCalled = false;
// }
// }
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = errorHandler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/BindingExample.java
import com.guigarage.binding.Binding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
package com.guigarage.examples;
public class BindingExample {
public static void main(String[] args) { | Property<String> stringProperty1 = new BasicProperty<>(); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/BindingExample.java | // Path: impl/src/main/java/com/guigarage/binding/Binding.java
// public class Binding {
//
// public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private boolean bindingCalled = false;
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
// Subscription subscription1 = to(toProperty, converter);
// Subscription subscription2 = bind(property, toProperty, converter2);
// return () -> {
// subscription1.unsubscribe();
// subscription2.unsubscribe();
// };
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// return bind(observable, property, converter);
// }
//
// private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
// return observable.onChanged(e -> {
// if(!bindingCalled) {
// bindingCalled = true;
// try {
// property.setValue(converter.apply(e.getValue()));
// } catch (Exception ex) {
// errorHandler.accept(ex);
// } finally {
// bindingCalled = false;
// }
// }
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = errorHandler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.binding.Binding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property; | package com.guigarage.examples;
public class BindingExample {
public static void main(String[] args) { | // Path: impl/src/main/java/com/guigarage/binding/Binding.java
// public class Binding {
//
// public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private boolean bindingCalled = false;
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
// Subscription subscription1 = to(toProperty, converter);
// Subscription subscription2 = bind(property, toProperty, converter2);
// return () -> {
// subscription1.unsubscribe();
// subscription2.unsubscribe();
// };
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// return bind(observable, property, converter);
// }
//
// private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
// return observable.onChanged(e -> {
// if(!bindingCalled) {
// bindingCalled = true;
// try {
// property.setValue(converter.apply(e.getValue()));
// } catch (Exception ex) {
// errorHandler.accept(ex);
// } finally {
// bindingCalled = false;
// }
// }
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = errorHandler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/BindingExample.java
import com.guigarage.binding.Binding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
package com.guigarage.examples;
public class BindingExample {
public static void main(String[] args) { | Property<String> stringProperty1 = new BasicProperty<>(); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/BindingExample.java | // Path: impl/src/main/java/com/guigarage/binding/Binding.java
// public class Binding {
//
// public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private boolean bindingCalled = false;
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
// Subscription subscription1 = to(toProperty, converter);
// Subscription subscription2 = bind(property, toProperty, converter2);
// return () -> {
// subscription1.unsubscribe();
// subscription2.unsubscribe();
// };
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// return bind(observable, property, converter);
// }
//
// private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
// return observable.onChanged(e -> {
// if(!bindingCalled) {
// bindingCalled = true;
// try {
// property.setValue(converter.apply(e.getValue()));
// } catch (Exception ex) {
// errorHandler.accept(ex);
// } finally {
// bindingCalled = false;
// }
// }
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = errorHandler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.binding.Binding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property; | package com.guigarage.examples;
public class BindingExample {
public static void main(String[] args) {
Property<String> stringProperty1 = new BasicProperty<>();
Property<String> stringProperty2 = new BasicProperty<>();
Property<Boolean> booleanProperty1 = new BasicProperty<>();
Property<Boolean> booleanProperty2 = new BasicProperty<>();
Property<Integer> intProperty1 = new BasicProperty<>();
Property<Integer> intProperty2 = new BasicProperty<>();
| // Path: impl/src/main/java/com/guigarage/binding/Binding.java
// public class Binding {
//
// public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private boolean bindingCalled = false;
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
// Subscription subscription1 = to(toProperty, converter);
// Subscription subscription2 = bind(property, toProperty, converter2);
// return () -> {
// subscription1.unsubscribe();
// subscription2.unsubscribe();
// };
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// return bind(observable, property, converter);
// }
//
// private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
// return observable.onChanged(e -> {
// if(!bindingCalled) {
// bindingCalled = true;
// try {
// property.setValue(converter.apply(e.getValue()));
// } catch (Exception ex) {
// errorHandler.accept(ex);
// } finally {
// bindingCalled = false;
// }
// }
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = errorHandler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/BindingExample.java
import com.guigarage.binding.Binding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
package com.guigarage.examples;
public class BindingExample {
public static void main(String[] args) {
Property<String> stringProperty1 = new BasicProperty<>();
Property<String> stringProperty2 = new BasicProperty<>();
Property<Boolean> booleanProperty1 = new BasicProperty<>();
Property<Boolean> booleanProperty2 = new BasicProperty<>();
Property<Integer> intProperty1 = new BasicProperty<>();
Property<Integer> intProperty2 = new BasicProperty<>();
| Binding.bind(stringProperty1).bidirectionalTo(stringProperty2); |
guigarage/ObserverPattern | tck/src/main/java/javax/observer/tck/CheckBooleanObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: tck/src/main/java/javax/observer/tck/util/ValueHolder.java
// public class ValueHolder<T> {
//
// T value;
//
// public ValueHolder() {
// }
//
// public ValueHolder(T value) {
// this.value = value;
// }
//
// public T getValue() {
// return value;
// }
//
// public void setValue(T value) {
// this.value = value;
// }
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.tck.util.ValueHolder;
import java.util.Objects;
import java.util.function.Consumer; | package javax.observer.tck;
public class CheckBooleanObservable {
public static void checkBooleanObservableBasicMethods(final Observable<Boolean> observable) {
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(true);
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: tck/src/main/java/javax/observer/tck/util/ValueHolder.java
// public class ValueHolder<T> {
//
// T value;
//
// public ValueHolder() {
// }
//
// public ValueHolder(T value) {
// this.value = value;
// }
//
// public T getValue() {
// return value;
// }
//
// public void setValue(T value) {
// this.value = value;
// }
// }
// Path: tck/src/main/java/javax/observer/tck/CheckBooleanObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.tck.util.ValueHolder;
import java.util.Objects;
import java.util.function.Consumer;
package javax.observer.tck;
public class CheckBooleanObservable {
public static void checkBooleanObservableBasicMethods(final Observable<Boolean> observable) {
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(true);
| Subscription willChangeSubscription = observable.onWillChange(e -> new RuntimeException("FAIL")); |
guigarage/ObserverPattern | tck/src/main/java/javax/observer/tck/CheckBooleanObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: tck/src/main/java/javax/observer/tck/util/ValueHolder.java
// public class ValueHolder<T> {
//
// T value;
//
// public ValueHolder() {
// }
//
// public ValueHolder(T value) {
// this.value = value;
// }
//
// public T getValue() {
// return value;
// }
//
// public void setValue(T value) {
// this.value = value;
// }
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.tck.util.ValueHolder;
import java.util.Objects;
import java.util.function.Consumer; | package javax.observer.tck;
public class CheckBooleanObservable {
public static void checkBooleanObservableBasicMethods(final Observable<Boolean> observable) {
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(true);
Subscription willChangeSubscription = observable.onWillChange(e -> new RuntimeException("FAIL"));
willChangeSubscription.unsubscribe();
Subscription changedSubscription = observable.onChanged(e -> new RuntimeException("FAIL"));
changedSubscription.unsubscribe();
}
public static void checkBooleanObservableChangeFromTrueToFalse(final Observable<Boolean> observable, final Consumer<Boolean> changeObservableValue) throws BadImplementationException {
Objects.requireNonNull(observable);
Objects.requireNonNull(changeObservableValue);
changeObservableValue.accept(Boolean.TRUE);
observable.value().orElseThrow(() -> new BadImplementationException("FAIL"));
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: tck/src/main/java/javax/observer/tck/util/ValueHolder.java
// public class ValueHolder<T> {
//
// T value;
//
// public ValueHolder() {
// }
//
// public ValueHolder(T value) {
// this.value = value;
// }
//
// public T getValue() {
// return value;
// }
//
// public void setValue(T value) {
// this.value = value;
// }
// }
// Path: tck/src/main/java/javax/observer/tck/CheckBooleanObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.tck.util.ValueHolder;
import java.util.Objects;
import java.util.function.Consumer;
package javax.observer.tck;
public class CheckBooleanObservable {
public static void checkBooleanObservableBasicMethods(final Observable<Boolean> observable) {
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(true);
Subscription willChangeSubscription = observable.onWillChange(e -> new RuntimeException("FAIL"));
willChangeSubscription.unsubscribe();
Subscription changedSubscription = observable.onChanged(e -> new RuntimeException("FAIL"));
changedSubscription.unsubscribe();
}
public static void checkBooleanObservableChangeFromTrueToFalse(final Observable<Boolean> observable, final Consumer<Boolean> changeObservableValue) throws BadImplementationException {
Objects.requireNonNull(observable);
Objects.requireNonNull(changeObservableValue);
changeObservableValue.accept(Boolean.TRUE);
observable.value().orElseThrow(() -> new BadImplementationException("FAIL"));
| final ValueHolder<Boolean> valeWillChangeHolder = new ValueHolder<>(false); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/observer/BasicObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
| package com.guigarage.observer;
public class BasicObservable<V> implements Observable<V> {
private V value;
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
// Path: impl/src/main/java/com/guigarage/observer/BasicObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
package com.guigarage.observer;
public class BasicObservable<V> implements Observable<V> {
private V value;
| private final List<ValueChangedListener<? super V>> changedListeners = new CopyOnWriteArrayList<>();
|
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/observer/BasicObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
| package com.guigarage.observer;
public class BasicObservable<V> implements Observable<V> {
private V value;
private final List<ValueChangedListener<? super V>> changedListeners = new CopyOnWriteArrayList<>();
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
// Path: impl/src/main/java/com/guigarage/observer/BasicObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
package com.guigarage.observer;
public class BasicObservable<V> implements Observable<V> {
private V value;
private final List<ValueChangedListener<? super V>> changedListeners = new CopyOnWriteArrayList<>();
| private final List<ValueWillChangeListener<? super V>> willChangeListeners = new CopyOnWriteArrayList<>();
|
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/observer/BasicObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
| if(inWillChangeEvent) {
throw new IllegalStateException("Value can not change while willChangeEvents are handled!");
}
if (this.value != value) {
boolean canChange = fireWillChangeEvent(value);
if(canChange) {
try {
this.value = value;
} finally {
fireChangedEvent(this.value);
}
}
}
}
private boolean fireWillChangeEvent(final V newValue) {
inWillChangeEvent = true;
try {
final ValueWillChangeEventImpl<V> event = new ValueWillChangeEventImpl<>(this, newValue);
Iterator<ValueWillChangeListener<? super V>> listenerIterator = willChangeListeners.iterator();
while (listenerIterator.hasNext() && !event.isVetoCalled()) {
listenerIterator.next().valueWillChange(event);
}
return !event.isVetoCalled();
} finally {
inWillChangeEvent = false;
}
}
private void fireChangedEvent(final V newValue) {
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
// Path: impl/src/main/java/com/guigarage/observer/BasicObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
if(inWillChangeEvent) {
throw new IllegalStateException("Value can not change while willChangeEvents are handled!");
}
if (this.value != value) {
boolean canChange = fireWillChangeEvent(value);
if(canChange) {
try {
this.value = value;
} finally {
fireChangedEvent(this.value);
}
}
}
}
private boolean fireWillChangeEvent(final V newValue) {
inWillChangeEvent = true;
try {
final ValueWillChangeEventImpl<V> event = new ValueWillChangeEventImpl<>(this, newValue);
Iterator<ValueWillChangeListener<? super V>> listenerIterator = willChangeListeners.iterator();
while (listenerIterator.hasNext() && !event.isVetoCalled()) {
listenerIterator.next().valueWillChange(event);
}
return !event.isVetoCalled();
} finally {
inWillChangeEvent = false;
}
}
private void fireChangedEvent(final V newValue) {
| final ValueChangedEvent<V> event = new ValueChangedEvent<V>() {
|
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/observer/BasicObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
| while (listenerIterator.hasNext() && !event.isVetoCalled()) {
listenerIterator.next().valueWillChange(event);
}
return !event.isVetoCalled();
} finally {
inWillChangeEvent = false;
}
}
private void fireChangedEvent(final V newValue) {
final ValueChangedEvent<V> event = new ValueChangedEvent<V>() {
@Override
public Observable<V> getObservable() {
return BasicObservable.this;
}
@Override
public V getValue() {
return newValue;
}
};
changedListeners.forEach(l -> l.valueChanged(event));
}
@Override
public V getValue() {
return value;
}
@Override
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedEvent.java
// public interface ValueChangedEvent<V> {
//
// Observable<V> getObservable();
//
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// V getValue();
// }
//
// Path: api/src/main/java/javax/observer/ValueChangedListener.java
// @FunctionalInterface
// public interface ValueChangedListener<V> extends EventListener {
//
// void valueChanged(ValueChangedEvent<? extends V> event);
//
// }
//
// Path: api/src/main/java/javax/observer/ValueWillChangeListener.java
// @FunctionalInterface
// public interface ValueWillChangeListener<V> extends EventListener {
//
// void valueWillChange(ValueWillChangeEvent<? extends V> event);
//
// }
// Path: impl/src/main/java/com/guigarage/observer/BasicObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import javax.observer.ValueChangedEvent;
import javax.observer.ValueChangedListener;
import javax.observer.ValueWillChangeListener;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
while (listenerIterator.hasNext() && !event.isVetoCalled()) {
listenerIterator.next().valueWillChange(event);
}
return !event.isVetoCalled();
} finally {
inWillChangeEvent = false;
}
}
private void fireChangedEvent(final V newValue) {
final ValueChangedEvent<V> event = new ValueChangedEvent<V>() {
@Override
public Observable<V> getObservable() {
return BasicObservable.this;
}
@Override
public V getValue() {
return newValue;
}
};
changedListeners.forEach(l -> l.valueChanged(event));
}
@Override
public V getValue() {
return value;
}
@Override
| public Subscription onChanged(final ValueChangedListener<? super V> listener) {
|
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/Binding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import java.util.function.Consumer;
import java.util.function.Function; | package com.guigarage.binding;
/**
* Class that provides basic functionallity for bindings wothout handling any thread issues, etc. This is not thread safe
* and should only be used for Bindings that will be handled on the same Thread.
*/
public class Binding {
public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
return new ConvertableBidirectionalBindable<T>() {
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private boolean bindingCalled = false;
@Override | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/Binding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import java.util.function.Consumer;
import java.util.function.Function;
package com.guigarage.binding;
/**
* Class that provides basic functionallity for bindings wothout handling any thread issues, etc. This is not thread safe
* and should only be used for Bindings that will be handled on the same Thread.
*/
public class Binding {
public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
return new ConvertableBidirectionalBindable<T>() {
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private boolean bindingCalled = false;
@Override | public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) { |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/Binding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import java.util.function.Consumer;
import java.util.function.Function; | package com.guigarage.binding;
/**
* Class that provides basic functionallity for bindings wothout handling any thread issues, etc. This is not thread safe
* and should only be used for Bindings that will be handled on the same Thread.
*/
public class Binding {
public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
return new ConvertableBidirectionalBindable<T>() {
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private boolean bindingCalled = false;
@Override
public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
Subscription subscription1 = to(toProperty, converter);
Subscription subscription2 = bind(property, toProperty, converter2);
return () -> {
subscription1.unsubscribe();
subscription2.unsubscribe();
};
}
@Override | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/Binding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import java.util.function.Consumer;
import java.util.function.Function;
package com.guigarage.binding;
/**
* Class that provides basic functionallity for bindings wothout handling any thread issues, etc. This is not thread safe
* and should only be used for Bindings that will be handled on the same Thread.
*/
public class Binding {
public static <T> ConvertableBidirectionalBindable<T> bind(Property<T> property) {
return new ConvertableBidirectionalBindable<T>() {
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private boolean bindingCalled = false;
@Override
public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
Subscription subscription1 = to(toProperty, converter);
Subscription subscription2 = bind(property, toProperty, converter2);
return () -> {
subscription1.unsubscribe();
subscription2.unsubscribe();
};
}
@Override | public <U> Subscription to(Observable<U> observable, Function<U, T> converter) { |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/binding/Binding.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
| import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import java.util.function.Consumer;
import java.util.function.Function; | public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
Subscription subscription1 = to(toProperty, converter);
Subscription subscription2 = bind(property, toProperty, converter2);
return () -> {
subscription1.unsubscribe();
subscription2.unsubscribe();
};
}
@Override
public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
return bind(observable, property, converter);
}
private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
return observable.onChanged(e -> {
if(!bindingCalled) {
bindingCalled = true;
try {
property.setValue(converter.apply(e.getValue()));
} catch (Exception ex) {
errorHandler.accept(ex);
} finally {
bindingCalled = false;
}
}
});
}
@Override | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBidirectionalBindable.java
// public interface ConvertableBidirectionalBindable<T> extends ConvertableBindable<T>, BidirectionalBindable<T> {
//
// /**
// *By defining a converter a bidirectional binding to an {@link Property} with a different value
// * type can be defined. For more information about binding see {@link BidirectionalBindable#bidirectionalTo(Property)}
// * @param property
// * @param converter the converter that will be used to convert any new value of the {@link Property}
// * to the correct value type
// * @param converter2 the converter that will be used to convert any new value to the value type of the {@link Property}
// * @param <U> value type of the {@link Property} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2);
//
// @Override
// default Subscription bidirectionalTo(Property<T> property) {
// return bidirectionalTo(property, v -> v, v -> v);
// }
// }
//
// Path: api/src/main/java/javax/observer/binding/ConvertableBindable.java
// public interface ConvertableBindable<T> extends Bindable<T> {
//
// /**
// * By defining a converter a unidirectional binding to an {@link Observable} with a different value
// * type can be defined. For more information about binding see {@link Bindable#to(Observable)}
// * @param observable the {@link Observable} to that this instance will be bound.
// * @param converter the converter that will be used to convert any new value of the {@link Observable}
// * to the correct value type
// * @param <U> value type of the {@link Observable} to that this instance will be bound.
// * @return a {@link Subscription} to unbind the binding that is created by calling this method
// */
// <U> Subscription to(Observable<U> observable, Function<U, T> converter);
//
// @Override
// default Subscription to(Observable<T> observable) {
// return to(observable, v -> v);
// }
//
// }
// Path: impl/src/main/java/com/guigarage/binding/Binding.java
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import javax.observer.binding.ConvertableBindable;
import java.util.function.Consumer;
import java.util.function.Function;
public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
Subscription subscription1 = to(toProperty, converter);
Subscription subscription2 = bind(property, toProperty, converter2);
return () -> {
subscription1.unsubscribe();
subscription2.unsubscribe();
};
}
@Override
public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
return bind(observable, property, converter);
}
private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
return observable.onChanged(e -> {
if(!bindingCalled) {
bindingCalled = true;
try {
property.setValue(converter.apply(e.getValue()));
} catch (Exception ex) {
errorHandler.accept(ex);
} finally {
bindingCalled = false;
}
}
});
}
@Override | public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) { |
guigarage/ObserverPattern | tck/src/main/java/javax/observer/tck/CheckLongObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import java.util.Objects; | package javax.observer.tck;
/**
*
* @author Thomas Zimmermann (https://github.com/zimmi)
*/
public class CheckLongObservable
{
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
// Path: tck/src/main/java/javax/observer/tck/CheckLongObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import java.util.Objects;
package javax.observer.tck;
/**
*
* @author Thomas Zimmermann (https://github.com/zimmi)
*/
public class CheckLongObservable
{
| public static void checkLongObservableBasicMethods(final Observable<Long> observable) |
guigarage/ObserverPattern | tck/src/main/java/javax/observer/tck/CheckLongObservable.java | // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
| import javax.observer.Observable;
import javax.observer.Subscription;
import java.util.Objects; | package javax.observer.tck;
/**
*
* @author Thomas Zimmermann (https://github.com/zimmi)
*/
public class CheckLongObservable
{
public static void checkLongObservableBasicMethods(final Observable<Long> observable)
{
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(0L);
| // Path: api/src/main/java/javax/observer/Observable.java
// public interface Observable<V> {
//
// /**
// * Returns the current value.
// * @return the value
// */
// V getValue();
//
// /**
// * Returns an {@link Optional} that contains the current value or {@code null}. This is a
// * convenience method that can be used to acces the value by using a fluent API based on
// * the {@link Optional} API.
// * @return an {@link Optional} that contains the current value or {@code null}
// */
// default Optional<V> value() {
// return Optional.ofNullable(getValue());
// }
//
// Subscription onChanged(ValueChangedListener<? super V> listener);
//
// default Subscription onChangedAndCall(final ValueChangedListener<? super V> listener) {
// final Subscription subscription = onChanged(listener);
// listener.valueChanged(new ValueChangedEvent<V>() {
// @Override
// public Observable<V> getObservable() {
// return Observable.this;
// }
//
// @Override
// public V getValue() {
// return Observable.this.getValue();
// }
// });
// return subscription;
// }
//
// Subscription onWillChange(ValueWillChangeListener<? super V> listener);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
// Path: tck/src/main/java/javax/observer/tck/CheckLongObservable.java
import javax.observer.Observable;
import javax.observer.Subscription;
import java.util.Objects;
package javax.observer.tck;
/**
*
* @author Thomas Zimmermann (https://github.com/zimmi)
*/
public class CheckLongObservable
{
public static void checkLongObservableBasicMethods(final Observable<Long> observable)
{
Objects.requireNonNull(observable);
observable.getValue();
observable.value();
observable.value().orElse(0L);
| final Subscription willChangeSubscription = observable.onWillChange(e -> new RuntimeException("FAIL")); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/WillChangeExample.java | // Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import java.time.LocalDateTime; | package com.guigarage.examples;
/**
* Created by hendrikebbers on 30.01.17.
*/
public class WillChangeExample {
public static void main(String[] args) {
//Defines a String property that only allows characters that are defined as digit | // Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/WillChangeExample.java
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import java.time.LocalDateTime;
package com.guigarage.examples;
/**
* Created by hendrikebbers on 30.01.17.
*/
public class WillChangeExample {
public static void main(String[] args) {
//Defines a String property that only allows characters that are defined as digit | Property<String> myProperty = new BasicProperty<>(); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/WillChangeExample.java | // Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import java.time.LocalDateTime; | package com.guigarage.examples;
/**
* Created by hendrikebbers on 30.01.17.
*/
public class WillChangeExample {
public static void main(String[] args) {
//Defines a String property that only allows characters that are defined as digit | // Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/WillChangeExample.java
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import java.time.LocalDateTime;
package com.guigarage.examples;
/**
* Created by hendrikebbers on 30.01.17.
*/
public class WillChangeExample {
public static void main(String[] args) {
//Defines a String property that only allows characters that are defined as digit | Property<String> myProperty = new BasicProperty<>(); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/OnChangedAndCallExample.java | // Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
| import com.guigarage.observer.BasicProperty; | package com.guigarage.examples;
/**
* Created by hendrikebbers on 30.01.17.
*/
public class OnChangedAndCallExample {
public void update(String value) {
System.out.println("The current value is: " + value);
}
public static void main(String[] args) { | // Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
// Path: impl/src/main/java/com/guigarage/examples/OnChangedAndCallExample.java
import com.guigarage.observer.BasicProperty;
package com.guigarage.examples;
/**
* Created by hendrikebbers on 30.01.17.
*/
public class OnChangedAndCallExample {
public void update(String value) {
System.out.println("The current value is: " + value);
}
public static void main(String[] args) { | BasicProperty<String> property = new BasicProperty<>(); |
guigarage/ObserverPattern | tck/src/main/java/javax/observer/tck/CheckBooleanProperty.java | // Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
| import javax.observer.Property;
import javax.observer.Subscription;
import java.util.Objects;
| package javax.observer.tck;
/**
* Created by hendrikebbers on 11.11.16.
*/
public class CheckBooleanProperty {
public static void checkBooleanPropertyBasicMethods(final Property<Boolean> property) {
Objects.requireNonNull(property);
property.getValue();
property.value();
property.value().orElse(true);
property.setValue(Boolean.FALSE);
property.setValue(Boolean.TRUE);
| // Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
//
// Path: api/src/main/java/javax/observer/Subscription.java
// @FunctionalInterface
// public interface Subscription {
//
// void unsubscribe();
// }
// Path: tck/src/main/java/javax/observer/tck/CheckBooleanProperty.java
import javax.observer.Property;
import javax.observer.Subscription;
import java.util.Objects;
package javax.observer.tck;
/**
* Created by hendrikebbers on 11.11.16.
*/
public class CheckBooleanProperty {
public static void checkBooleanPropertyBasicMethods(final Property<Boolean> property) {
Objects.requireNonNull(property);
property.getValue();
property.value();
property.value().orElse(true);
property.setValue(Boolean.FALSE);
property.setValue(Boolean.TRUE);
| final Subscription subscription = property.onChanged(e -> new RuntimeException("FAIL"));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.