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
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/fragments/ScatterChartFrag.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // }
import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.ScatterChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView;
package com.xxmassdeveloper.mpchartexample.fragments; public class ScatterChartFrag extends SimpleFragment { public static Fragment newInstance() { return new ScatterChartFrag(); } private ScatterChart mChart; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.frag_simple_scatter, container, false); mChart = (ScatterChart) v.findViewById(R.id.scatterChart1); mChart.setDescription(""); Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),"OpenSans-Light.ttf");
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/fragments/ScatterChartFrag.java import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.ScatterChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView; package com.xxmassdeveloper.mpchartexample.fragments; public class ScatterChartFrag extends SimpleFragment { public static Fragment newInstance() { return new ScatterChartFrag(); } private ScatterChart mChart; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.frag_simple_scatter, container, false); mChart = (ScatterChart) v.findViewById(R.id.scatterChart1); mChart.setDescription(""); Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),"OpenSans-Light.ttf");
MyMarkerView mv = new MyMarkerView(getActivity(), R.layout.custom_marker_view);
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/realm/RealmDatabaseActivityHorizontalBar.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/RealmDemoData.java // public class RealmDemoData extends RealmObject { // // private float value; // // private float open, close, high, low; // // private float bubbleSize; // // private RealmList<RealmFloat> stackValues; // // private int xIndex; // // private String xValue; // // private String someStringField; // // // ofc there could me more fields here... // // public RealmDemoData() { // // } // // public RealmDemoData(float value, int xIndex, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for stacked bars. // * // * @param stackValues // * @param xIndex // * @param xValue // */ // public RealmDemoData(float[] stackValues, int xIndex, String xValue) { // this.xIndex = xIndex; // this.xValue = xValue; // this.stackValues = new RealmList<RealmFloat>(); // // for (float val : stackValues) { // this.stackValues.add(new RealmFloat(val)); // } // } // // /** // * Constructor for candles. // * // * @param high // * @param low // * @param open // * @param close // * @param xIndex // */ // public RealmDemoData(float high, float low, float open, float close, int xIndex, String xValue) { // this.value = (high + low) / 2f; // this.high = high; // this.low = low; // this.open = open; // this.close = close; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for bubbles. // * // * @param value // * @param xIndex // * @param bubbleSize // * @param xValue // */ // public RealmDemoData(float value, int xIndex, float bubbleSize, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.bubbleSize = bubbleSize; // this.xValue = xValue; // } // // public float getValue() { // return value; // } // // public void setValue(float value) { // this.value = value; // } // // public RealmList<RealmFloat> getStackValues() { // return stackValues; // } // // public void setStackValues(RealmList<RealmFloat> stackValues) { // this.stackValues = stackValues; // } // // public int getxIndex() { // return xIndex; // } // // public void setxIndex(int xIndex) { // this.xIndex = xIndex; // } // // public String getxValue() { // return xValue; // } // // public void setxValue(String xValue) { // this.xValue = xValue; // } // // public float getOpen() { // return open; // } // // public void setOpen(float open) { // this.open = open; // } // // public float getClose() { // return close; // } // // public void setClose(float close) { // this.close = close; // } // // public float getHigh() { // return high; // } // // public void setHigh(float high) { // this.high = high; // } // // public float getLow() { // return low; // } // // public void setLow(float low) { // this.low = low; // } // // public float getBubbleSize() { // return bubbleSize; // } // // public void setBubbleSize(float bubbleSize) { // this.bubbleSize = bubbleSize; // } // // public String getSomeStringField() { // return someStringField; // } // // public void setSomeStringField(String someStringField) { // this.someStringField = someStringField; // } // }
import android.graphics.Color; import android.os.Bundle; import android.view.WindowManager; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.HorizontalBarChart; import com.github.mikephil.charting.data.realm.implementation.RealmBarData; import com.github.mikephil.charting.data.realm.implementation.RealmBarDataSet; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.RealmDemoData; import java.util.ArrayList; import io.realm.RealmResults;
package com.xxmassdeveloper.mpchartexample.realm; /** * Created by Philipp Jahoda on 21/10/15. */ public class RealmDatabaseActivityHorizontalBar extends RealmBaseActivity { private HorizontalBarChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_horizontalbarchart_noseekbar); mChart = (HorizontalBarChart) findViewById(R.id.chart1); setup(mChart); mChart.getAxisLeft().setAxisMinValue(0f); mChart.setDrawValueAboveBar(false); } @Override protected void onResume() { super.onResume(); // setup realm // write some demo-data into the realm.io database writeToDBStack(50); // add data to the chart setData(); } private void setData() {
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/RealmDemoData.java // public class RealmDemoData extends RealmObject { // // private float value; // // private float open, close, high, low; // // private float bubbleSize; // // private RealmList<RealmFloat> stackValues; // // private int xIndex; // // private String xValue; // // private String someStringField; // // // ofc there could me more fields here... // // public RealmDemoData() { // // } // // public RealmDemoData(float value, int xIndex, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for stacked bars. // * // * @param stackValues // * @param xIndex // * @param xValue // */ // public RealmDemoData(float[] stackValues, int xIndex, String xValue) { // this.xIndex = xIndex; // this.xValue = xValue; // this.stackValues = new RealmList<RealmFloat>(); // // for (float val : stackValues) { // this.stackValues.add(new RealmFloat(val)); // } // } // // /** // * Constructor for candles. // * // * @param high // * @param low // * @param open // * @param close // * @param xIndex // */ // public RealmDemoData(float high, float low, float open, float close, int xIndex, String xValue) { // this.value = (high + low) / 2f; // this.high = high; // this.low = low; // this.open = open; // this.close = close; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for bubbles. // * // * @param value // * @param xIndex // * @param bubbleSize // * @param xValue // */ // public RealmDemoData(float value, int xIndex, float bubbleSize, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.bubbleSize = bubbleSize; // this.xValue = xValue; // } // // public float getValue() { // return value; // } // // public void setValue(float value) { // this.value = value; // } // // public RealmList<RealmFloat> getStackValues() { // return stackValues; // } // // public void setStackValues(RealmList<RealmFloat> stackValues) { // this.stackValues = stackValues; // } // // public int getxIndex() { // return xIndex; // } // // public void setxIndex(int xIndex) { // this.xIndex = xIndex; // } // // public String getxValue() { // return xValue; // } // // public void setxValue(String xValue) { // this.xValue = xValue; // } // // public float getOpen() { // return open; // } // // public void setOpen(float open) { // this.open = open; // } // // public float getClose() { // return close; // } // // public void setClose(float close) { // this.close = close; // } // // public float getHigh() { // return high; // } // // public void setHigh(float high) { // this.high = high; // } // // public float getLow() { // return low; // } // // public void setLow(float low) { // this.low = low; // } // // public float getBubbleSize() { // return bubbleSize; // } // // public void setBubbleSize(float bubbleSize) { // this.bubbleSize = bubbleSize; // } // // public String getSomeStringField() { // return someStringField; // } // // public void setSomeStringField(String someStringField) { // this.someStringField = someStringField; // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/realm/RealmDatabaseActivityHorizontalBar.java import android.graphics.Color; import android.os.Bundle; import android.view.WindowManager; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.HorizontalBarChart; import com.github.mikephil.charting.data.realm.implementation.RealmBarData; import com.github.mikephil.charting.data.realm.implementation.RealmBarDataSet; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.RealmDemoData; import java.util.ArrayList; import io.realm.RealmResults; package com.xxmassdeveloper.mpchartexample.realm; /** * Created by Philipp Jahoda on 21/10/15. */ public class RealmDatabaseActivityHorizontalBar extends RealmBaseActivity { private HorizontalBarChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_horizontalbarchart_noseekbar); mChart = (HorizontalBarChart) findViewById(R.id.chart1); setup(mChart); mChart.getAxisLeft().setAxisMinValue(0f); mChart.setDrawValueAboveBar(false); } @Override protected void onResume() { super.onResume(); // setup realm // write some demo-data into the realm.io database writeToDBStack(50); // add data to the chart setData(); } private void setData() {
RealmResults<RealmDemoData> result = mRealm.allObjects(RealmDemoData.class);
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivity.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyYAxisValueFormatter.java // public class MyYAxisValueFormatter implements YAxisValueFormatter { // // private DecimalFormat mFormat; // // public MyYAxisValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, YAxis yAxis) { // return mFormat.format(value) + " $"; // } // }
import android.annotation.SuppressLint; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendForm; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.components.YAxis.AxisDependency; import com.github.mikephil.charting.components.YAxis.YAxisLabelPosition; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.filter.Approximator; import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType; import com.github.mikephil.charting.formatter.YAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.interfaces.datasets.IDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.xxmassdeveloper.mpchartexample.custom.MyYAxisValueFormatter; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList;
mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mChart = (BarChart) findViewById(R.id.chart1); mChart.setOnChartValueSelectedListener(this); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(true); mChart.setDescription(""); // if more than 60 entries are displayed in the chart, no values will be // drawn mChart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDrawGridBackground(false); // mChart.setDrawYLabels(false); mTf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); XAxis xAxis = mChart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setTypeface(mTf); xAxis.setDrawGridLines(false); xAxis.setSpaceBetweenLabels(2);
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyYAxisValueFormatter.java // public class MyYAxisValueFormatter implements YAxisValueFormatter { // // private DecimalFormat mFormat; // // public MyYAxisValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, YAxis yAxis) { // return mFormat.format(value) + " $"; // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivity.java import android.annotation.SuppressLint; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendForm; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.components.YAxis.AxisDependency; import com.github.mikephil.charting.components.YAxis.YAxisLabelPosition; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.filter.Approximator; import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType; import com.github.mikephil.charting.formatter.YAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.interfaces.datasets.IDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.xxmassdeveloper.mpchartexample.custom.MyYAxisValueFormatter; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList; mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mChart = (BarChart) findViewById(R.id.chart1); mChart.setOnChartValueSelectedListener(this); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(true); mChart.setDescription(""); // if more than 60 entries are displayed in the chart, no values will be // drawn mChart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDrawGridBackground(false); // mChart.setDrawYLabels(false); mTf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); XAxis xAxis = mChart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setTypeface(mTf); xAxis.setDrawGridLines(false); xAxis.setSpaceBetweenLabels(2);
YAxisValueFormatter custom = new MyYAxisValueFormatter();
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/StackedBarActivity.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyValueFormatter.java // public class MyValueFormatter implements ValueFormatter { // // private DecimalFormat mFormat; // // public MyValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { // return mFormat.format(value) + " $"; // } // } // // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyYAxisValueFormatter.java // public class MyYAxisValueFormatter implements YAxisValueFormatter { // // private DecimalFormat mFormat; // // public MyYAxisValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, YAxis yAxis) { // return mFormat.format(value) + " $"; // } // }
import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.filter.Approximator; import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.custom.MyValueFormatter; import com.xxmassdeveloper.mpchartexample.custom.MyYAxisValueFormatter; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList; import java.util.List;
package com.xxmassdeveloper.mpchartexample; public class StackedBarActivity extends DemoBase implements OnSeekBarChangeListener, OnChartValueSelectedListener { private BarChart mChart; private SeekBar mSeekBarX, mSeekBarY; private TextView tvX, tvY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_barchart); tvX = (TextView) findViewById(R.id.tvXMax); tvY = (TextView) findViewById(R.id.tvYMax); mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarX.setOnSeekBarChangeListener(this); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mSeekBarY.setOnSeekBarChangeListener(this); mChart = (BarChart) findViewById(R.id.chart1); mChart.setOnChartValueSelectedListener(this); mChart.setDescription(""); // if more than 60 entries are displayed in the chart, no values will be // drawn mChart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDrawGridBackground(false); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(false); // change the position of the y-labels YAxis leftAxis = mChart.getAxisLeft();
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyValueFormatter.java // public class MyValueFormatter implements ValueFormatter { // // private DecimalFormat mFormat; // // public MyValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { // return mFormat.format(value) + " $"; // } // } // // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyYAxisValueFormatter.java // public class MyYAxisValueFormatter implements YAxisValueFormatter { // // private DecimalFormat mFormat; // // public MyYAxisValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, YAxis yAxis) { // return mFormat.format(value) + " $"; // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/StackedBarActivity.java import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.filter.Approximator; import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.custom.MyValueFormatter; import com.xxmassdeveloper.mpchartexample.custom.MyYAxisValueFormatter; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList; import java.util.List; package com.xxmassdeveloper.mpchartexample; public class StackedBarActivity extends DemoBase implements OnSeekBarChangeListener, OnChartValueSelectedListener { private BarChart mChart; private SeekBar mSeekBarX, mSeekBarY; private TextView tvX, tvY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_barchart); tvX = (TextView) findViewById(R.id.tvXMax); tvY = (TextView) findViewById(R.id.tvYMax); mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarX.setOnSeekBarChangeListener(this); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mSeekBarY.setOnSeekBarChangeListener(this); mChart = (BarChart) findViewById(R.id.chart1); mChart.setOnChartValueSelectedListener(this); mChart.setDescription(""); // if more than 60 entries are displayed in the chart, no values will be // drawn mChart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDrawGridBackground(false); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(false); // change the position of the y-labels YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setValueFormatter(new MyYAxisValueFormatter());
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/StackedBarActivity.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyValueFormatter.java // public class MyValueFormatter implements ValueFormatter { // // private DecimalFormat mFormat; // // public MyValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { // return mFormat.format(value) + " $"; // } // } // // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyYAxisValueFormatter.java // public class MyYAxisValueFormatter implements YAxisValueFormatter { // // private DecimalFormat mFormat; // // public MyYAxisValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, YAxis yAxis) { // return mFormat.format(value) + " $"; // } // }
import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.filter.Approximator; import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.custom.MyValueFormatter; import com.xxmassdeveloper.mpchartexample.custom.MyYAxisValueFormatter; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList; import java.util.List;
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tvX.setText("" + (mSeekBarX.getProgress() + 1)); tvY.setText("" + (mSeekBarY.getProgress())); ArrayList<String> xVals = new ArrayList<String>(); for (int i = 0; i < mSeekBarX.getProgress() + 1; i++) { xVals.add(mMonths[i % mMonths.length]); } ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>(); for (int i = 0; i < mSeekBarX.getProgress() + 1; i++) { float mult = (mSeekBarY.getProgress() + 1); float val1 = (float) (Math.random() * mult) + mult / 3; float val2 = (float) (Math.random() * mult) + mult / 3; float val3 = (float) (Math.random() * mult) + mult / 3; yVals1.add(new BarEntry(new float[] { val1, val2, val3 }, i)); } BarDataSet set1 = new BarDataSet(yVals1, "Statistics Vienna 2014"); set1.setColors(getColors()); set1.setStackLabels(new String[] { "Births", "Divorces", "Marriages" }); ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>(); dataSets.add(set1); BarData data = new BarData(xVals, dataSets);
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyValueFormatter.java // public class MyValueFormatter implements ValueFormatter { // // private DecimalFormat mFormat; // // public MyValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { // return mFormat.format(value) + " $"; // } // } // // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyYAxisValueFormatter.java // public class MyYAxisValueFormatter implements YAxisValueFormatter { // // private DecimalFormat mFormat; // // public MyYAxisValueFormatter() { // mFormat = new DecimalFormat("###,###,###,##0.0"); // } // // @Override // public String getFormattedValue(float value, YAxis yAxis) { // return mFormat.format(value) + " $"; // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/StackedBarActivity.java import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.filter.Approximator; import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.custom.MyValueFormatter; import com.xxmassdeveloper.mpchartexample.custom.MyYAxisValueFormatter; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList; import java.util.List; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tvX.setText("" + (mSeekBarX.getProgress() + 1)); tvY.setText("" + (mSeekBarY.getProgress())); ArrayList<String> xVals = new ArrayList<String>(); for (int i = 0; i < mSeekBarX.getProgress() + 1; i++) { xVals.add(mMonths[i % mMonths.length]); } ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>(); for (int i = 0; i < mSeekBarX.getProgress() + 1; i++) { float mult = (mSeekBarY.getProgress() + 1); float val1 = (float) (Math.random() * mult) + mult / 3; float val2 = (float) (Math.random() * mult) + mult / 3; float val3 = (float) (Math.random() * mult) + mult / 3; yVals1.add(new BarEntry(new float[] { val1, val2, val3 }, i)); } BarDataSet set1 = new BarDataSet(yVals1, "Statistics Vienna 2014"); set1.setColors(getColors()); set1.setStackLabels(new String[] { "Births", "Divorces", "Marriages" }); ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>(); dataSets.add(set1); BarData data = new BarData(xVals, dataSets);
data.setValueFormatter(new MyValueFormatter());
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyFillFormatter.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/ILineDataSet.java // public interface ILineDataSet extends ILineRadarDataSet<Entry> { // // /** // * Returns the intensity of the cubic lines (the effect intensity). // * Max = 1f = very cubic, Min = 0.05f = low cubic effect, Default: 0.2f // * // * @return // */ // float getCubicIntensity(); // // /** // * Returns true if drawing cubic lines is enabled, false if not. // * // * @return // */ // boolean isDrawCubicEnabled(); // // /** // * Returns the size of the drawn circles. // */ // float getCircleRadius(); // // /** // * Returns the color at the given index of the DataSet's circle-color array. // * Performs a IndexOutOfBounds check by modulus. // * // * @param index // * @return // */ // int getCircleColor(int index); // // /** // * Returns true if drawing circles for this DataSet is enabled, false if not // * // * @return // */ // boolean isDrawCirclesEnabled(); // // /** // * Returns the color of the inner circle (the circle-hole). // * // * @return // */ // int getCircleHoleColor(); // // /** // * Returns true if drawing the circle-holes is enabled, false if not. // * // * @return // */ // boolean isDrawCircleHoleEnabled(); // // /** // * Returns the DashPathEffect that is used for drawing the lines. // * // * @return // */ // DashPathEffect getDashPathEffect(); // // /** // * Returns true if the dashed-line effect is enabled, false if not. // * If the DashPathEffect object is null, also return false here. // * // * @return // */ // boolean isDashedLineEnabled(); // // /** // * Returns the FillFormatter that is set for this DataSet. // * // * @return // */ // FillFormatter getFillFormatter(); // }
import com.github.mikephil.charting.formatter.FillFormatter; import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
package com.xxmassdeveloper.mpchartexample.custom; /** * Created by Philipp Jahoda on 12/09/15. */ public class MyFillFormatter implements FillFormatter { private float mFillPos = 0f; public MyFillFormatter(float fillpos) { this.mFillPos = fillpos; } @Override
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/ILineDataSet.java // public interface ILineDataSet extends ILineRadarDataSet<Entry> { // // /** // * Returns the intensity of the cubic lines (the effect intensity). // * Max = 1f = very cubic, Min = 0.05f = low cubic effect, Default: 0.2f // * // * @return // */ // float getCubicIntensity(); // // /** // * Returns true if drawing cubic lines is enabled, false if not. // * // * @return // */ // boolean isDrawCubicEnabled(); // // /** // * Returns the size of the drawn circles. // */ // float getCircleRadius(); // // /** // * Returns the color at the given index of the DataSet's circle-color array. // * Performs a IndexOutOfBounds check by modulus. // * // * @param index // * @return // */ // int getCircleColor(int index); // // /** // * Returns true if drawing circles for this DataSet is enabled, false if not // * // * @return // */ // boolean isDrawCirclesEnabled(); // // /** // * Returns the color of the inner circle (the circle-hole). // * // * @return // */ // int getCircleHoleColor(); // // /** // * Returns true if drawing the circle-holes is enabled, false if not. // * // * @return // */ // boolean isDrawCircleHoleEnabled(); // // /** // * Returns the DashPathEffect that is used for drawing the lines. // * // * @return // */ // DashPathEffect getDashPathEffect(); // // /** // * Returns true if the dashed-line effect is enabled, false if not. // * If the DashPathEffect object is null, also return false here. // * // * @return // */ // boolean isDashedLineEnabled(); // // /** // * Returns the FillFormatter that is set for this DataSet. // * // * @return // */ // FillFormatter getFillFormatter(); // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyFillFormatter.java import com.github.mikephil.charting.formatter.FillFormatter; import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider; package com.xxmassdeveloper.mpchartexample.custom; /** * Created by Philipp Jahoda on 12/09/15. */ public class MyFillFormatter implements FillFormatter { private float mFillPos = 0f; public MyFillFormatter(float fillpos) { this.mFillPos = fillpos; } @Override
public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/realm/RealmDatabaseActivityBar.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/RealmDemoData.java // public class RealmDemoData extends RealmObject { // // private float value; // // private float open, close, high, low; // // private float bubbleSize; // // private RealmList<RealmFloat> stackValues; // // private int xIndex; // // private String xValue; // // private String someStringField; // // // ofc there could me more fields here... // // public RealmDemoData() { // // } // // public RealmDemoData(float value, int xIndex, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for stacked bars. // * // * @param stackValues // * @param xIndex // * @param xValue // */ // public RealmDemoData(float[] stackValues, int xIndex, String xValue) { // this.xIndex = xIndex; // this.xValue = xValue; // this.stackValues = new RealmList<RealmFloat>(); // // for (float val : stackValues) { // this.stackValues.add(new RealmFloat(val)); // } // } // // /** // * Constructor for candles. // * // * @param high // * @param low // * @param open // * @param close // * @param xIndex // */ // public RealmDemoData(float high, float low, float open, float close, int xIndex, String xValue) { // this.value = (high + low) / 2f; // this.high = high; // this.low = low; // this.open = open; // this.close = close; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for bubbles. // * // * @param value // * @param xIndex // * @param bubbleSize // * @param xValue // */ // public RealmDemoData(float value, int xIndex, float bubbleSize, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.bubbleSize = bubbleSize; // this.xValue = xValue; // } // // public float getValue() { // return value; // } // // public void setValue(float value) { // this.value = value; // } // // public RealmList<RealmFloat> getStackValues() { // return stackValues; // } // // public void setStackValues(RealmList<RealmFloat> stackValues) { // this.stackValues = stackValues; // } // // public int getxIndex() { // return xIndex; // } // // public void setxIndex(int xIndex) { // this.xIndex = xIndex; // } // // public String getxValue() { // return xValue; // } // // public void setxValue(String xValue) { // this.xValue = xValue; // } // // public float getOpen() { // return open; // } // // public void setOpen(float open) { // this.open = open; // } // // public float getClose() { // return close; // } // // public void setClose(float close) { // this.close = close; // } // // public float getHigh() { // return high; // } // // public void setHigh(float high) { // this.high = high; // } // // public float getLow() { // return low; // } // // public void setLow(float low) { // this.low = low; // } // // public float getBubbleSize() { // return bubbleSize; // } // // public void setBubbleSize(float bubbleSize) { // this.bubbleSize = bubbleSize; // } // // public String getSomeStringField() { // return someStringField; // } // // public void setSomeStringField(String someStringField) { // this.someStringField = someStringField; // } // }
import android.os.Bundle; import android.view.WindowManager; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.data.realm.implementation.RealmBarData; import com.github.mikephil.charting.data.realm.implementation.RealmBarDataSet; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.RealmDemoData; import java.util.ArrayList; import io.realm.RealmResults;
package com.xxmassdeveloper.mpchartexample.realm; /** * Created by Philipp Jahoda on 21/10/15. */ public class RealmDatabaseActivityBar extends RealmBaseActivity { private BarChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_barchart_noseekbar); mChart = (BarChart) findViewById(R.id.chart1); setup(mChart); } @Override protected void onResume() { super.onResume(); // setup realm // write some demo-data into the realm.io database writeToDB(20); // add data to the chart setData(); } private void setData() {
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/RealmDemoData.java // public class RealmDemoData extends RealmObject { // // private float value; // // private float open, close, high, low; // // private float bubbleSize; // // private RealmList<RealmFloat> stackValues; // // private int xIndex; // // private String xValue; // // private String someStringField; // // // ofc there could me more fields here... // // public RealmDemoData() { // // } // // public RealmDemoData(float value, int xIndex, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for stacked bars. // * // * @param stackValues // * @param xIndex // * @param xValue // */ // public RealmDemoData(float[] stackValues, int xIndex, String xValue) { // this.xIndex = xIndex; // this.xValue = xValue; // this.stackValues = new RealmList<RealmFloat>(); // // for (float val : stackValues) { // this.stackValues.add(new RealmFloat(val)); // } // } // // /** // * Constructor for candles. // * // * @param high // * @param low // * @param open // * @param close // * @param xIndex // */ // public RealmDemoData(float high, float low, float open, float close, int xIndex, String xValue) { // this.value = (high + low) / 2f; // this.high = high; // this.low = low; // this.open = open; // this.close = close; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for bubbles. // * // * @param value // * @param xIndex // * @param bubbleSize // * @param xValue // */ // public RealmDemoData(float value, int xIndex, float bubbleSize, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.bubbleSize = bubbleSize; // this.xValue = xValue; // } // // public float getValue() { // return value; // } // // public void setValue(float value) { // this.value = value; // } // // public RealmList<RealmFloat> getStackValues() { // return stackValues; // } // // public void setStackValues(RealmList<RealmFloat> stackValues) { // this.stackValues = stackValues; // } // // public int getxIndex() { // return xIndex; // } // // public void setxIndex(int xIndex) { // this.xIndex = xIndex; // } // // public String getxValue() { // return xValue; // } // // public void setxValue(String xValue) { // this.xValue = xValue; // } // // public float getOpen() { // return open; // } // // public void setOpen(float open) { // this.open = open; // } // // public float getClose() { // return close; // } // // public void setClose(float close) { // this.close = close; // } // // public float getHigh() { // return high; // } // // public void setHigh(float high) { // this.high = high; // } // // public float getLow() { // return low; // } // // public void setLow(float low) { // this.low = low; // } // // public float getBubbleSize() { // return bubbleSize; // } // // public void setBubbleSize(float bubbleSize) { // this.bubbleSize = bubbleSize; // } // // public String getSomeStringField() { // return someStringField; // } // // public void setSomeStringField(String someStringField) { // this.someStringField = someStringField; // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/realm/RealmDatabaseActivityBar.java import android.os.Bundle; import android.view.WindowManager; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.data.realm.implementation.RealmBarData; import com.github.mikephil.charting.data.realm.implementation.RealmBarDataSet; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.RealmDemoData; import java.util.ArrayList; import io.realm.RealmResults; package com.xxmassdeveloper.mpchartexample.realm; /** * Created by Philipp Jahoda on 21/10/15. */ public class RealmDatabaseActivityBar extends RealmBaseActivity { private BarChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_barchart_noseekbar); mChart = (BarChart) findViewById(R.id.chart1); setup(mChart); } @Override protected void onResume() { super.onResume(); // setup realm // write some demo-data into the realm.io database writeToDB(20); // add data to the chart setData(); } private void setData() {
RealmResults<RealmDemoData> result = mRealm.allObjects(RealmDemoData.class);
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/CircleProgressBar.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType;
PADDING = padding; invalidate(); } public int getPadding() { return PADDING; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); left = 0 + strokeWidth / 2; top = 0 + strokeWidth / 2; right = min - strokeWidth / 2; bottom = min - strokeWidth / 2; rectF.set(left + PADDING, top + PADDING, right - PADDING, bottom - PADDING); } // *******************START POSITION FOR CIRCLE AND CIRCLE SEGMENT // VIEW****************** public int getProgressStartPosition() { return startPosInDegrees; } public void setStartPositionInDegrees(int degrees) { this.startPosInDegrees = degrees; }
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/CircleProgressBar.java import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType; PADDING = padding; invalidate(); } public int getPadding() { return PADDING; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); left = 0 + strokeWidth / 2; top = 0 + strokeWidth / 2; right = min - strokeWidth / 2; bottom = min - strokeWidth / 2; rectF.set(left + PADDING, top + PADDING, right - PADDING, bottom - PADDING); } // *******************START POSITION FOR CIRCLE AND CIRCLE SEGMENT // VIEW****************** public int getProgressStartPosition() { return startPosInDegrees; } public void setStartPositionInDegrees(int degrees) { this.startPosInDegrees = degrees; }
public void setStartPositionInDegrees(ProgressStartPoint position) {
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/CircleProgressBar.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType;
return PADDING; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); left = 0 + strokeWidth / 2; top = 0 + strokeWidth / 2; right = min - strokeWidth / 2; bottom = min - strokeWidth / 2; rectF.set(left + PADDING, top + PADDING, right - PADDING, bottom - PADDING); } // *******************START POSITION FOR CIRCLE AND CIRCLE SEGMENT // VIEW****************** public int getProgressStartPosition() { return startPosInDegrees; } public void setStartPositionInDegrees(int degrees) { this.startPosInDegrees = degrees; } public void setStartPositionInDegrees(ProgressStartPoint position) { this.startPosInDegrees = position.getValue(); } @Override
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/CircleProgressBar.java import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType; return PADDING; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); left = 0 + strokeWidth / 2; top = 0 + strokeWidth / 2; right = min - strokeWidth / 2; bottom = min - strokeWidth / 2; rectF.set(left + PADDING, top + PADDING, right - PADDING, bottom - PADDING); } // *******************START POSITION FOR CIRCLE AND CIRCLE SEGMENT // VIEW****************** public int getProgressStartPosition() { return startPosInDegrees; } public void setStartPositionInDegrees(int degrees) { this.startPosInDegrees = degrees; } public void setStartPositionInDegrees(ProgressStartPoint position) { this.startPosInDegrees = position.getValue(); } @Override
public ShapeType setType(ShapeType type) {
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/ProgressView.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/OnProgressViewListener.java // public interface OnProgressViewListener { // public void onFinish(); // // public void onProgressUpdate(float progress); // // void setProgress(float prog); // // int getprogress(); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressShape.java // public interface ProgressShape { // public ShapeType setType(ShapeType type); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // }
import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import com.natasa.progressviews.utils.OnProgressViewListener; import com.natasa.progressviews.utils.ProgressShape; import com.natasa.progressviews.utils.ProgressStartPoint; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.util.AttributeSet; import android.view.View;
/* * ProgressViews * Copyright (c) 2015 Natasa Misic * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.natasa.progressviews; abstract class ProgressView extends View implements ProgressShape { protected float progress = 0; protected float strokeWidth = getResources().getDimension( R.dimen.default_stroke_width); protected float backgroundStrokeWidth = getResources().getDimension( R.dimen.default_background_stroke_width); protected int backgroundColor = getResources().getColor(R.color.background_color); protected int color = getResources().getColor(R.color.progress_color); protected int height; protected int width; protected int min; protected Paint backgroundPaint; protected Paint foregroundPaint; private String PROGRESS = getResources().getString(R.string.progress);
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/OnProgressViewListener.java // public interface OnProgressViewListener { // public void onFinish(); // // public void onProgressUpdate(float progress); // // void setProgress(float prog); // // int getprogress(); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressShape.java // public interface ProgressShape { // public ShapeType setType(ShapeType type); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/ProgressView.java import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import com.natasa.progressviews.utils.OnProgressViewListener; import com.natasa.progressviews.utils.ProgressShape; import com.natasa.progressviews.utils.ProgressStartPoint; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.util.AttributeSet; import android.view.View; /* * ProgressViews * Copyright (c) 2015 Natasa Misic * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.natasa.progressviews; abstract class ProgressView extends View implements ProgressShape { protected float progress = 0; protected float strokeWidth = getResources().getDimension( R.dimen.default_stroke_width); protected float backgroundStrokeWidth = getResources().getDimension( R.dimen.default_background_stroke_width); protected int backgroundColor = getResources().getColor(R.color.background_color); protected int color = getResources().getColor(R.color.progress_color); protected int height; protected int width; protected int min; protected Paint backgroundPaint; protected Paint foregroundPaint; private String PROGRESS = getResources().getString(R.string.progress);
protected int startPosInDegrees = ProgressStartPoint.DEFAULT.ordinal();
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/ProgressView.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/OnProgressViewListener.java // public interface OnProgressViewListener { // public void onFinish(); // // public void onProgressUpdate(float progress); // // void setProgress(float prog); // // int getprogress(); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressShape.java // public interface ProgressShape { // public ShapeType setType(ShapeType type); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // }
import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import com.natasa.progressviews.utils.OnProgressViewListener; import com.natasa.progressviews.utils.ProgressShape; import com.natasa.progressviews.utils.ProgressStartPoint; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.util.AttributeSet; import android.view.View;
/* * ProgressViews * Copyright (c) 2015 Natasa Misic * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.natasa.progressviews; abstract class ProgressView extends View implements ProgressShape { protected float progress = 0; protected float strokeWidth = getResources().getDimension( R.dimen.default_stroke_width); protected float backgroundStrokeWidth = getResources().getDimension( R.dimen.default_background_stroke_width); protected int backgroundColor = getResources().getColor(R.color.background_color); protected int color = getResources().getColor(R.color.progress_color); protected int height; protected int width; protected int min; protected Paint backgroundPaint; protected Paint foregroundPaint; private String PROGRESS = getResources().getString(R.string.progress); protected int startPosInDegrees = ProgressStartPoint.DEFAULT.ordinal(); private ObjectAnimator objAnimator; protected ProgressViewTextData text_data = new ProgressViewTextData( Color.LTGRAY, 42);
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/OnProgressViewListener.java // public interface OnProgressViewListener { // public void onFinish(); // // public void onProgressUpdate(float progress); // // void setProgress(float prog); // // int getprogress(); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressShape.java // public interface ProgressShape { // public ShapeType setType(ShapeType type); // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/ProgressView.java import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import com.natasa.progressviews.utils.OnProgressViewListener; import com.natasa.progressviews.utils.ProgressShape; import com.natasa.progressviews.utils.ProgressStartPoint; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.util.AttributeSet; import android.view.View; /* * ProgressViews * Copyright (c) 2015 Natasa Misic * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.natasa.progressviews; abstract class ProgressView extends View implements ProgressShape { protected float progress = 0; protected float strokeWidth = getResources().getDimension( R.dimen.default_stroke_width); protected float backgroundStrokeWidth = getResources().getDimension( R.dimen.default_background_stroke_width); protected int backgroundColor = getResources().getColor(R.color.background_color); protected int color = getResources().getColor(R.color.progress_color); protected int height; protected int width; protected int min; protected Paint backgroundPaint; protected Paint foregroundPaint; private String PROGRESS = getResources().getString(R.string.progress); protected int startPosInDegrees = ProgressStartPoint.DEFAULT.ordinal(); private ObjectAnimator objAnimator; protected ProgressViewTextData text_data = new ProgressViewTextData( Color.LTGRAY, 42);
private OnProgressViewListener listenr;
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/CircleSegmentBar.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType;
/* * ProgressViews * Copyright (c) 2015 Natasa Misic * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.natasa.progressviews; public class CircleSegmentBar extends ProgressView { public static final int rad_360 = 360; private float SEGMENT_WIDTH = 3f; private int PADDING = 10; private Path progressPath; private Path backgroundPath; final RectF oval = new RectF(); private float radius; private float angle;
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/CircleSegmentBar.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType; /* * ProgressViews * Copyright (c) 2015 Natasa Misic * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.natasa.progressviews; public class CircleSegmentBar extends ProgressView { public static final int rad_360 = 360; private float SEGMENT_WIDTH = 3f; private int PADDING = 10; private Path progressPath; private Path backgroundPath; final RectF oval = new RectF(); private float radius; private float angle;
private int angleStartPoint = ProgressStartPoint.DEFAULT.getValue();
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/CircleSegmentBar.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType;
public void setStartPositionInDegrees(ProgressStartPoint position) { this.startPosInDegrees = position.getValue(); } private void drawGradientColor() { if (isGradientColor) setLinearGradientProgress(gradColors); } public void setLinearGradientProgress(boolean isGradientColor) { this.isGradientColor = isGradientColor; } public void setLinearGradientProgress(boolean isGradientColor, int[] colors) { this.isGradientColor = isGradientColor; gradColors = colors; } private void setLinearGradientProgress(int[] gradColors) { if (gradColors != null) colorHelper.setGradientPaint(foregroundPaint, left, top, right, bottom, gradColors); else colorHelper.setGradientPaint(foregroundPaint, left, top, right, bottom); } @Override
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressStartPoint.java // public enum ProgressStartPoint { // // DEFAULT(-90), LEFT(180), RIGHT(0), BOTTOM(90); // int value; // private ProgressStartPoint(int value) { // this.value = value; // } // public int getValue() { // return value; // } // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/CircleSegmentBar.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressStartPoint; import com.natasa.progressviews.utils.ShapeType; public void setStartPositionInDegrees(ProgressStartPoint position) { this.startPosInDegrees = position.getValue(); } private void drawGradientColor() { if (isGradientColor) setLinearGradientProgress(gradColors); } public void setLinearGradientProgress(boolean isGradientColor) { this.isGradientColor = isGradientColor; } public void setLinearGradientProgress(boolean isGradientColor, int[] colors) { this.isGradientColor = isGradientColor; gradColors = colors; } private void setLinearGradientProgress(int[] gradColors) { if (gradColors != null) colorHelper.setGradientPaint(foregroundPaint, left, top, right, bottom, gradColors); else colorHelper.setGradientPaint(foregroundPaint, left, top, right, bottom); } @Override
public ShapeType setType(ShapeType type) {
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivityMultiDataset.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // }
import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.LargeValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList;
package com.xxmassdeveloper.mpchartexample; public class BarChartActivityMultiDataset extends DemoBase implements OnSeekBarChangeListener, OnChartValueSelectedListener { private BarChart mChart; private SeekBar mSeekBarX, mSeekBarY; private TextView tvX, tvY; private Typeface tf; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_barchart); tvX = (TextView) findViewById(R.id.tvXMax); tvY = (TextView) findViewById(R.id.tvYMax); mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarX.setOnSeekBarChangeListener(this); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mSeekBarY.setOnSeekBarChangeListener(this); mChart = (BarChart) findViewById(R.id.chart1); mChart.setOnChartValueSelectedListener(this); mChart.setDescription(""); // mChart.setDrawBorders(true); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDrawBarShadow(false); mChart.setDrawGridBackground(false); // create a custom MarkerView (extend MarkerView) and specify the layout // to use for it
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivityMultiDataset.java import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.formatter.LargeValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList; package com.xxmassdeveloper.mpchartexample; public class BarChartActivityMultiDataset extends DemoBase implements OnSeekBarChangeListener, OnChartValueSelectedListener { private BarChart mChart; private SeekBar mSeekBarX, mSeekBarY; private TextView tvX, tvY; private Typeface tf; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_barchart); tvX = (TextView) findViewById(R.id.tvXMax); tvY = (TextView) findViewById(R.id.tvYMax); mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarX.setOnSeekBarChangeListener(this); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mSeekBarY.setOnSeekBarChangeListener(this); mChart = (BarChart) findViewById(R.id.chart1); mChart.setOnChartValueSelectedListener(this); mChart.setDescription(""); // mChart.setDrawBorders(true); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDrawBarShadow(false); mChart.setDrawGridBackground(false); // create a custom MarkerView (extend MarkerView) and specify the layout // to use for it
MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/LineProgressBar.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressLineOrientation.java // public enum ProgressLineOrientation { // HORIZONTAL(0), VERTICAL(1); // // int value; // // private ProgressLineOrientation(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // }
import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressLineOrientation; import com.natasa.progressviews.utils.ShapeType;
canvas.drawLine(0, nMiddle, progressX, nMiddle, foregroundPaint); } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); setMeasuredDimension(width, height); } /**** * @return int value for orientation. <li> * <i>HORIZONTAL=0 <li> VERTICAL=1</i></li> ***/ public int getLineOrientation() { return lineOrientation; } /*** * @param position ProgressLineOrientation value **/ public void setLineOrientation(ProgressLineOrientation position) { this.lineOrientation = position.getValue(); } @Override
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ProgressLineOrientation.java // public enum ProgressLineOrientation { // HORIZONTAL(0), VERTICAL(1); // // int value; // // private ProgressLineOrientation(int value) { // this.value = value; // } // // public int getValue() { // return value; // } // // } // // Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/LineProgressBar.java import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.natasa.progressviews.utils.ProgressLineOrientation; import com.natasa.progressviews.utils.ShapeType; canvas.drawLine(0, nMiddle, progressX, nMiddle, foregroundPaint); } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); setMeasuredDimension(width, height); } /**** * @return int value for orientation. <li> * <i>HORIZONTAL=0 <li> VERTICAL=1</i></li> ***/ public int getLineOrientation() { return lineOrientation; } /*** * @param position ProgressLineOrientation value **/ public void setLineOrientation(ProgressLineOrientation position) { this.lineOrientation = position.getValue(); } @Override
public ShapeType setType(ShapeType type) {
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/realm/RealmDatabaseActivityScatter.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/RealmDemoData.java // public class RealmDemoData extends RealmObject { // // private float value; // // private float open, close, high, low; // // private float bubbleSize; // // private RealmList<RealmFloat> stackValues; // // private int xIndex; // // private String xValue; // // private String someStringField; // // // ofc there could me more fields here... // // public RealmDemoData() { // // } // // public RealmDemoData(float value, int xIndex, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for stacked bars. // * // * @param stackValues // * @param xIndex // * @param xValue // */ // public RealmDemoData(float[] stackValues, int xIndex, String xValue) { // this.xIndex = xIndex; // this.xValue = xValue; // this.stackValues = new RealmList<RealmFloat>(); // // for (float val : stackValues) { // this.stackValues.add(new RealmFloat(val)); // } // } // // /** // * Constructor for candles. // * // * @param high // * @param low // * @param open // * @param close // * @param xIndex // */ // public RealmDemoData(float high, float low, float open, float close, int xIndex, String xValue) { // this.value = (high + low) / 2f; // this.high = high; // this.low = low; // this.open = open; // this.close = close; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for bubbles. // * // * @param value // * @param xIndex // * @param bubbleSize // * @param xValue // */ // public RealmDemoData(float value, int xIndex, float bubbleSize, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.bubbleSize = bubbleSize; // this.xValue = xValue; // } // // public float getValue() { // return value; // } // // public void setValue(float value) { // this.value = value; // } // // public RealmList<RealmFloat> getStackValues() { // return stackValues; // } // // public void setStackValues(RealmList<RealmFloat> stackValues) { // this.stackValues = stackValues; // } // // public int getxIndex() { // return xIndex; // } // // public void setxIndex(int xIndex) { // this.xIndex = xIndex; // } // // public String getxValue() { // return xValue; // } // // public void setxValue(String xValue) { // this.xValue = xValue; // } // // public float getOpen() { // return open; // } // // public void setOpen(float open) { // this.open = open; // } // // public float getClose() { // return close; // } // // public void setClose(float close) { // this.close = close; // } // // public float getHigh() { // return high; // } // // public void setHigh(float high) { // this.high = high; // } // // public float getLow() { // return low; // } // // public void setLow(float low) { // this.low = low; // } // // public float getBubbleSize() { // return bubbleSize; // } // // public void setBubbleSize(float bubbleSize) { // this.bubbleSize = bubbleSize; // } // // public String getSomeStringField() { // return someStringField; // } // // public void setSomeStringField(String someStringField) { // this.someStringField = someStringField; // } // }
import android.os.Bundle; import android.view.WindowManager; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.ScatterChart; import com.github.mikephil.charting.data.realm.implementation.RealmScatterData; import com.github.mikephil.charting.data.realm.implementation.RealmScatterDataSet; import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.RealmDemoData; import java.util.ArrayList; import io.realm.RealmResults;
package com.xxmassdeveloper.mpchartexample.realm; /** * Created by Philipp Jahoda on 21/10/15. */ public class RealmDatabaseActivityScatter extends RealmBaseActivity { private ScatterChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_scatterchart_noseekbar); mChart = (ScatterChart) findViewById(R.id.chart1); setup(mChart); mChart.getAxisLeft().setDrawGridLines(false); mChart.getXAxis().setDrawGridLines(false); mChart.setPinchZoom(true); } @Override protected void onResume() { super.onResume(); // setup realm // write some demo-data into the realm.io database writeToDB(45); // add data to the chart setData(); } private void setData() {
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/RealmDemoData.java // public class RealmDemoData extends RealmObject { // // private float value; // // private float open, close, high, low; // // private float bubbleSize; // // private RealmList<RealmFloat> stackValues; // // private int xIndex; // // private String xValue; // // private String someStringField; // // // ofc there could me more fields here... // // public RealmDemoData() { // // } // // public RealmDemoData(float value, int xIndex, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for stacked bars. // * // * @param stackValues // * @param xIndex // * @param xValue // */ // public RealmDemoData(float[] stackValues, int xIndex, String xValue) { // this.xIndex = xIndex; // this.xValue = xValue; // this.stackValues = new RealmList<RealmFloat>(); // // for (float val : stackValues) { // this.stackValues.add(new RealmFloat(val)); // } // } // // /** // * Constructor for candles. // * // * @param high // * @param low // * @param open // * @param close // * @param xIndex // */ // public RealmDemoData(float high, float low, float open, float close, int xIndex, String xValue) { // this.value = (high + low) / 2f; // this.high = high; // this.low = low; // this.open = open; // this.close = close; // this.xIndex = xIndex; // this.xValue = xValue; // } // // /** // * Constructor for bubbles. // * // * @param value // * @param xIndex // * @param bubbleSize // * @param xValue // */ // public RealmDemoData(float value, int xIndex, float bubbleSize, String xValue) { // this.value = value; // this.xIndex = xIndex; // this.bubbleSize = bubbleSize; // this.xValue = xValue; // } // // public float getValue() { // return value; // } // // public void setValue(float value) { // this.value = value; // } // // public RealmList<RealmFloat> getStackValues() { // return stackValues; // } // // public void setStackValues(RealmList<RealmFloat> stackValues) { // this.stackValues = stackValues; // } // // public int getxIndex() { // return xIndex; // } // // public void setxIndex(int xIndex) { // this.xIndex = xIndex; // } // // public String getxValue() { // return xValue; // } // // public void setxValue(String xValue) { // this.xValue = xValue; // } // // public float getOpen() { // return open; // } // // public void setOpen(float open) { // this.open = open; // } // // public float getClose() { // return close; // } // // public void setClose(float close) { // this.close = close; // } // // public float getHigh() { // return high; // } // // public void setHigh(float high) { // this.high = high; // } // // public float getLow() { // return low; // } // // public void setLow(float low) { // this.low = low; // } // // public float getBubbleSize() { // return bubbleSize; // } // // public void setBubbleSize(float bubbleSize) { // this.bubbleSize = bubbleSize; // } // // public String getSomeStringField() { // return someStringField; // } // // public void setSomeStringField(String someStringField) { // this.someStringField = someStringField; // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/realm/RealmDatabaseActivityScatter.java import android.os.Bundle; import android.view.WindowManager; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.ScatterChart; import com.github.mikephil.charting.data.realm.implementation.RealmScatterData; import com.github.mikephil.charting.data.realm.implementation.RealmScatterDataSet; import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.RealmDemoData; import java.util.ArrayList; import io.realm.RealmResults; package com.xxmassdeveloper.mpchartexample.realm; /** * Created by Philipp Jahoda on 21/10/15. */ public class RealmDatabaseActivityScatter extends RealmBaseActivity { private ScatterChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_scatterchart_noseekbar); mChart = (ScatterChart) findViewById(R.id.chart1); setup(mChart); mChart.getAxisLeft().setDrawGridLines(false); mChart.getXAxis().setDrawGridLines(false); mChart.setPinchZoom(true); } @Override protected void onResume() { super.onResume(); // setup realm // write some demo-data into the realm.io database writeToDB(45); // add data to the chart setData(); } private void setData() {
RealmResults<RealmDemoData> result = mRealm.allObjects(RealmDemoData.class);
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/RadarChartActivitry.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // }
import android.graphics.Typeface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.Toast; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.RadarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.RadarData; import com.github.mikephil.charting.data.RadarDataSet; import com.github.mikephil.charting.interfaces.datasets.IDataSet; import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList;
package com.xxmassdeveloper.mpchartexample; public class RadarChartActivitry extends DemoBase { private RadarChart mChart; private Typeface tf; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_radarchart); mChart = (RadarChart) findViewById(R.id.chart1); tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); mChart.setDescription(""); mChart.setWebLineWidth(1.5f); mChart.setWebLineWidthInner(0.75f); mChart.setWebAlpha(100); // create a custom MarkerView (extend MarkerView) and specify the layout // to use for it
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/RadarChartActivitry.java import android.graphics.Typeface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.Toast; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.RadarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.RadarData; import com.github.mikephil.charting.data.RadarDataSet; import com.github.mikephil.charting.interfaces.datasets.IDataSet; import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView; import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase; import java.util.ArrayList; package com.xxmassdeveloper.mpchartexample; public class RadarChartActivitry extends DemoBase { private RadarChart mChart; private Typeface tf; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_radarchart); mChart = (RadarChart) findViewById(R.id.chart1); tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); mChart.setDescription(""); mChart.setWebLineWidth(1.5f); mChart.setWebLineWidthInner(0.75f); mChart.setWebAlpha(100); // create a custom MarkerView (extend MarkerView) and specify the layout // to use for it
MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
rahulmaddineni/Stayfit
app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/fragments/BarChartFrag.java
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // }
import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.listener.ChartTouchListener; import com.github.mikephil.charting.listener.OnChartGestureListener; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView;
package com.xxmassdeveloper.mpchartexample.fragments; public class BarChartFrag extends SimpleFragment implements OnChartGestureListener { public static Fragment newInstance() { return new BarChartFrag(); } private BarChart mChart; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.frag_simple_bar, container, false); // create a new chart object mChart = new BarChart(getActivity()); mChart.setDescription(""); mChart.setOnChartGestureListener(this);
// Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/MyMarkerView.java // public class MyMarkerView extends MarkerView { // // private TextView tvContent; // // public MyMarkerView(Context context, int layoutResource) { // super(context, layoutResource); // // tvContent = (TextView) findViewById(R.id.tvContent); // } // // // callbacks everytime the MarkerView is redrawn, can be used to update the // // content (user-interface) // @Override // public void refreshContent(Entry e, Highlight highlight) { // // if (e instanceof CandleEntry) { // // CandleEntry ce = (CandleEntry) e; // // tvContent.setText("" + Utils.formatNumber(ce.getHigh(), 0, true)); // } else { // // tvContent.setText("" + Utils.formatNumber(e.getVal(), 0, true)); // } // } // // @Override // public int getXOffset(float xpos) { // // this will center the marker-view horizontally // return -(getWidth() / 2); // } // // @Override // public int getYOffset(float ypos) { // // this will cause the marker-view to be above the selected value // return -getHeight(); // } // } // Path: app/libs/MPAndroidChart-2.2.3/MPAndroidChart-2.2.3/MPChartExample/src/com/xxmassdeveloper/mpchartexample/fragments/BarChartFrag.java import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.listener.ChartTouchListener; import com.github.mikephil.charting.listener.OnChartGestureListener; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView; package com.xxmassdeveloper.mpchartexample.fragments; public class BarChartFrag extends SimpleFragment implements OnChartGestureListener { public static Fragment newInstance() { return new BarChartFrag(); } private BarChart mChart; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.frag_simple_bar, container, false); // create a new chart object mChart = new BarChart(getActivity()); mChart.setDescription(""); mChart.setOnChartGestureListener(this);
MyMarkerView mv = new MyMarkerView(getActivity(), R.layout.custom_marker_view);
rahulmaddineni/Stayfit
progressviewslib/src/main/java/com/natasa/progressviews/ArcProgressBar.java
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ShapeType;
left = 0 + strokeWidth / 2; top = 0 + strokeWidth / 2; right = min - strokeWidth / 2; bottom = min - strokeWidth / 2; oval.set(left + PADDING, top + PADDING, right - PADDING, bottom - PADDING); } public void setArcViewPadding(int padding) { PADDING = padding; invalidate(); } public void setLinearGradientProgress(boolean isGradientColor, int[] colors) { this.isGradientColor = isGradientColor; gradColors=colors; } private void setLinearGradientProgress(int[] gradColors) { if(gradColors!=null) colorHelper.setGradientPaint(foregroundPaint, left, top, right, top,gradColors); else colorHelper.setGradientPaint(foregroundPaint, left, top, right, top); } public int getPadding() { return PADDING; } @Override
// Path: progressviewslib/src/main/java/com/natasa/progressviews/utils/ShapeType.java // public enum ShapeType { // CIRCLE, ARC, LINE, SEGMENT_CIRCLE; // } // Path: progressviewslib/src/main/java/com/natasa/progressviews/ArcProgressBar.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.RectF; import android.util.AttributeSet; import com.natasa.progressviews.utils.ShapeType; left = 0 + strokeWidth / 2; top = 0 + strokeWidth / 2; right = min - strokeWidth / 2; bottom = min - strokeWidth / 2; oval.set(left + PADDING, top + PADDING, right - PADDING, bottom - PADDING); } public void setArcViewPadding(int padding) { PADDING = padding; invalidate(); } public void setLinearGradientProgress(boolean isGradientColor, int[] colors) { this.isGradientColor = isGradientColor; gradColors=colors; } private void setLinearGradientProgress(int[] gradColors) { if(gradColors!=null) colorHelper.setGradientPaint(foregroundPaint, left, top, right, top,gradColors); else colorHelper.setGradientPaint(foregroundPaint, left, top, right, top); } public int getPadding() { return PADDING; } @Override
public ShapeType setType(ShapeType type) {
struberg/juel
modules/impl/src/test/java/de/odysseus/el/tree/impl/ast/AstNullTest.java
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // }
import javax.el.ELException; import de.odysseus.el.TestCase; import de.odysseus.el.tree.Bindings;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public class AstNullTest extends TestCase { private Bindings bindings = new Bindings(null, null, null); AstNull parseNode(String expression) { return (AstNull)parse(expression).getRoot().getChild(0); } public void testEval() { assertNull(parseNode("${null}").eval(bindings, null)); } public void testAppendStructure() { StringBuilder s = new StringBuilder(); parseNode("${null}").appendStructure(s, bindings); assertEquals("null", s.toString()); } public void testIsLiteralText() { assertFalse(parseNode("${null}").isLiteralText()); } public void testIsLeftValue() { assertFalse(parseNode("${null}").isLeftValue()); } public void testGetType() { assertNull(parseNode("${null}").getType(bindings, null)); } public void testIsReadOnly() { assertTrue(parseNode("${null}").isReadOnly(bindings, null)); } public void testSetValue() {
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // } // Path: modules/impl/src/test/java/de/odysseus/el/tree/impl/ast/AstNullTest.java import javax.el.ELException; import de.odysseus.el.TestCase; import de.odysseus.el.tree.Bindings; /* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public class AstNullTest extends TestCase { private Bindings bindings = new Bindings(null, null, null); AstNull parseNode(String expression) { return (AstNull)parse(expression).getRoot().getChild(0); } public void testEval() { assertNull(parseNode("${null}").eval(bindings, null)); } public void testAppendStructure() { StringBuilder s = new StringBuilder(); parseNode("${null}").appendStructure(s, bindings); assertEquals("null", s.toString()); } public void testIsLiteralText() { assertFalse(parseNode("${null}").isLiteralText()); } public void testIsLeftValue() { assertFalse(parseNode("${null}").isLeftValue()); } public void testGetType() { assertNull(parseNode("${null}").getType(bindings, null)); } public void testIsReadOnly() { assertTrue(parseNode("${null}").isReadOnly(bindings, null)); } public void testSetValue() {
try { parseNode("${null}").setValue(bindings, null, null); fail(); } catch (ELException e) {}
struberg/juel
modules/impl/src/test/java/de/odysseus/el/tree/impl/ast/AstBooleanTest.java
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // }
import javax.el.ELException; import de.odysseus.el.TestCase; import de.odysseus.el.tree.Bindings;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public class AstBooleanTest extends TestCase { private Bindings bindings = new Bindings(null, null, null); AstBoolean parseNode(String expression) { return (AstBoolean)parse(expression).getRoot().getChild(0); } public void testEval() { assertEquals(true, parseNode("${true}").eval(bindings, null)); assertEquals(false, parseNode("${false}").eval(bindings, null)); } public void testAppendStructure() { StringBuilder s = new StringBuilder(); parseNode("${true}").appendStructure(s, bindings); parseNode("${false}").appendStructure(s, bindings); assertEquals("truefalse", s.toString()); } public void testIsLiteralText() { assertFalse(parseNode("${true}").isLiteralText()); } public void testIsLeftValue() { assertFalse(parseNode("${true}").isLeftValue()); } public void testGetType() { assertNull(parseNode("${true}").getType(bindings, null)); } public void testIsReadOnly() { assertTrue(parseNode("${true}").isReadOnly(bindings, null)); } public void testSetValue() {
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // } // Path: modules/impl/src/test/java/de/odysseus/el/tree/impl/ast/AstBooleanTest.java import javax.el.ELException; import de.odysseus.el.TestCase; import de.odysseus.el.tree.Bindings; /* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public class AstBooleanTest extends TestCase { private Bindings bindings = new Bindings(null, null, null); AstBoolean parseNode(String expression) { return (AstBoolean)parse(expression).getRoot().getChild(0); } public void testEval() { assertEquals(true, parseNode("${true}").eval(bindings, null)); assertEquals(false, parseNode("${false}").eval(bindings, null)); } public void testAppendStructure() { StringBuilder s = new StringBuilder(); parseNode("${true}").appendStructure(s, bindings); parseNode("${false}").appendStructure(s, bindings); assertEquals("truefalse", s.toString()); } public void testIsLiteralText() { assertFalse(parseNode("${true}").isLiteralText()); } public void testIsLeftValue() { assertFalse(parseNode("${true}").isLeftValue()); } public void testGetType() { assertNull(parseNode("${true}").getType(bindings, null)); } public void testIsReadOnly() { assertTrue(parseNode("${true}").isReadOnly(bindings, null)); } public void testSetValue() {
try { parseNode("${true}").setValue(bindings, null, null); fail(); } catch (ELException e) {}
struberg/juel
modules/impl/src/main/java/de/odysseus/el/misc/TypeConverterImpl.java
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // }
import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.math.BigDecimal; import java.math.BigInteger; import javax.el.ELException;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.misc; /** * Type Conversions as described in EL 2.1 specification (section 1.17). */ public class TypeConverterImpl implements TypeConverter { private static final long serialVersionUID = 1L; protected Boolean coerceToBoolean(Object value) { if (value == null || "".equals(value)) { return Boolean.FALSE; } if (value instanceof Boolean) { return (Boolean)value; } if (value instanceof String) { return Boolean.valueOf((String)value); }
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // } // Path: modules/impl/src/main/java/de/odysseus/el/misc/TypeConverterImpl.java import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.math.BigDecimal; import java.math.BigInteger; import javax.el.ELException; /* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.misc; /** * Type Conversions as described in EL 2.1 specification (section 1.17). */ public class TypeConverterImpl implements TypeConverter { private static final long serialVersionUID = 1L; protected Boolean coerceToBoolean(Object value) { if (value == null || "".equals(value)) { return Boolean.FALSE; } if (value instanceof Boolean) { return (Boolean)value; } if (value instanceof String) { return Boolean.valueOf((String)value); }
throw new ELException(LocalMessages.get("error.coerce.type", value.getClass(), Boolean.class));
struberg/juel
modules/impl/src/test/java/de/odysseus/el/ExpressionFactoryImplTest.java
// Path: modules/impl/src/main/java/de/odysseus/el/util/SimpleContext.java // public class SimpleContext extends ELContext { // static class Functions extends FunctionMapper { // Map<String, Method> map = Collections.emptyMap(); // // @Override // public Method resolveFunction(String prefix, String localName) { // return map.get(prefix + ":" + localName); // } // // public void setFunction(String prefix, String localName, Method method) { // if (map.isEmpty()) { // map = new HashMap<String, Method>(); // } // map.put(prefix + ":" + localName, method); // } // } // // static class Variables extends VariableMapper { // Map<String, ValueExpression> map = Collections.emptyMap(); // // @Override // public ValueExpression resolveVariable(String variable) { // return map.get(variable); // } // // @Override // public ValueExpression setVariable(String variable, ValueExpression expression) { // if (map.isEmpty()) { // map = new HashMap<String, ValueExpression>(); // } // return map.put(variable, expression); // } // } // // private Functions functions; // private Variables variables; // private ELResolver resolver; // // /** // * Create a context. // */ // public SimpleContext() { // this(null); // } // // /** // * Create a context, use the specified resolver. // */ // public SimpleContext(ELResolver resolver) { // this.resolver = resolver; // } // // /** // * Define a function. // */ // public void setFunction(String prefix, String localName, Method method) { // if (functions == null) { // functions = new Functions(); // } // functions.setFunction(prefix, localName, method); // } // // /** // * Define a variable. // */ // public ValueExpression setVariable(String name, ValueExpression expression) { // if (variables == null) { // variables = new Variables(); // } // return variables.setVariable(name, expression); // } // // /** // * Get our function mapper. // */ // @Override // public FunctionMapper getFunctionMapper() { // if (functions == null) { // functions = new Functions(); // } // return functions; // } // // /** // * Get our variable mapper. // */ // @Override // public VariableMapper getVariableMapper() { // if (variables == null) { // variables = new Variables(); // } // return variables; // } // // /** // * Get our resolver. Lazy initialize to a {@link SimpleResolver} if necessary. // */ // @Override // public ELResolver getELResolver() { // if (resolver == null) { // resolver = new SimpleResolver(); // } // return resolver; // } // // /** // * Set our resolver. // * // * @param resolver // */ // public void setELResolver(ELResolver resolver) { // this.resolver = resolver; // } // }
import de.odysseus.el.util.SimpleContext; import de.odysseus.el.util.SimpleResolver;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el; public class ExpressionFactoryImplTest extends TestCase { public static long bar() { return 1; } private ExpressionFactoryImpl factory = new ExpressionFactoryImpl(); public void testCoerceToType() { assertEquals("1", factory.coerceToType(1l, String.class)); } public void testCreateTreeValueExpression() {
// Path: modules/impl/src/main/java/de/odysseus/el/util/SimpleContext.java // public class SimpleContext extends ELContext { // static class Functions extends FunctionMapper { // Map<String, Method> map = Collections.emptyMap(); // // @Override // public Method resolveFunction(String prefix, String localName) { // return map.get(prefix + ":" + localName); // } // // public void setFunction(String prefix, String localName, Method method) { // if (map.isEmpty()) { // map = new HashMap<String, Method>(); // } // map.put(prefix + ":" + localName, method); // } // } // // static class Variables extends VariableMapper { // Map<String, ValueExpression> map = Collections.emptyMap(); // // @Override // public ValueExpression resolveVariable(String variable) { // return map.get(variable); // } // // @Override // public ValueExpression setVariable(String variable, ValueExpression expression) { // if (map.isEmpty()) { // map = new HashMap<String, ValueExpression>(); // } // return map.put(variable, expression); // } // } // // private Functions functions; // private Variables variables; // private ELResolver resolver; // // /** // * Create a context. // */ // public SimpleContext() { // this(null); // } // // /** // * Create a context, use the specified resolver. // */ // public SimpleContext(ELResolver resolver) { // this.resolver = resolver; // } // // /** // * Define a function. // */ // public void setFunction(String prefix, String localName, Method method) { // if (functions == null) { // functions = new Functions(); // } // functions.setFunction(prefix, localName, method); // } // // /** // * Define a variable. // */ // public ValueExpression setVariable(String name, ValueExpression expression) { // if (variables == null) { // variables = new Variables(); // } // return variables.setVariable(name, expression); // } // // /** // * Get our function mapper. // */ // @Override // public FunctionMapper getFunctionMapper() { // if (functions == null) { // functions = new Functions(); // } // return functions; // } // // /** // * Get our variable mapper. // */ // @Override // public VariableMapper getVariableMapper() { // if (variables == null) { // variables = new Variables(); // } // return variables; // } // // /** // * Get our resolver. Lazy initialize to a {@link SimpleResolver} if necessary. // */ // @Override // public ELResolver getELResolver() { // if (resolver == null) { // resolver = new SimpleResolver(); // } // return resolver; // } // // /** // * Set our resolver. // * // * @param resolver // */ // public void setELResolver(ELResolver resolver) { // this.resolver = resolver; // } // } // Path: modules/impl/src/test/java/de/odysseus/el/ExpressionFactoryImplTest.java import de.odysseus.el.util.SimpleContext; import de.odysseus.el.util.SimpleResolver; /* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el; public class ExpressionFactoryImplTest extends TestCase { public static long bar() { return 1; } private ExpressionFactoryImpl factory = new ExpressionFactoryImpl(); public void testCoerceToType() { assertEquals("1", factory.coerceToType(1l, String.class)); } public void testCreateTreeValueExpression() {
SimpleContext context = new SimpleContext(new SimpleResolver());
struberg/juel
modules/impl/src/test/java/de/odysseus/el/misc/TypeConverterImplTest.java
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // }
import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.beans.PropertyChangeListener; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import javax.el.ELException; import junit.framework.TestCase;
static { PropertyEditorManager.registerEditor(Date.class, DateEditor.class); } /** * Test enum type */ static enum Foo { BAR }; TypeConverterImpl converter = new TypeConverterImpl(); public void testToBoolean() { assertFalse(converter.coerceToBoolean(null)); assertFalse(converter.coerceToBoolean("")); assertTrue(converter.coerceToBoolean(Boolean.TRUE)); assertFalse(converter.coerceToBoolean(Boolean.FALSE)); assertTrue(converter.coerceToBoolean("true")); assertFalse(converter.coerceToBoolean("false")); assertFalse(converter.coerceToBoolean("yes")); // Boolean.valueOf(String) never throws an exception... } public void testToCharacter() { assertEquals(Character.valueOf((char)0), converter.coerceToCharacter(null)); assertEquals(Character.valueOf((char)0), converter.coerceToCharacter("")); Character c = Character.valueOf((char)99); assertSame(c, converter.coerceToCharacter(c)); try { converter.coerceToCharacter(Boolean.TRUE); fail();
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // } // Path: modules/impl/src/test/java/de/odysseus/el/misc/TypeConverterImplTest.java import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.beans.PropertyChangeListener; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import javax.el.ELException; import junit.framework.TestCase; static { PropertyEditorManager.registerEditor(Date.class, DateEditor.class); } /** * Test enum type */ static enum Foo { BAR }; TypeConverterImpl converter = new TypeConverterImpl(); public void testToBoolean() { assertFalse(converter.coerceToBoolean(null)); assertFalse(converter.coerceToBoolean("")); assertTrue(converter.coerceToBoolean(Boolean.TRUE)); assertFalse(converter.coerceToBoolean(Boolean.FALSE)); assertTrue(converter.coerceToBoolean("true")); assertFalse(converter.coerceToBoolean("false")); assertFalse(converter.coerceToBoolean("yes")); // Boolean.valueOf(String) never throws an exception... } public void testToCharacter() { assertEquals(Character.valueOf((char)0), converter.coerceToCharacter(null)); assertEquals(Character.valueOf((char)0), converter.coerceToCharacter("")); Character c = Character.valueOf((char)99); assertSame(c, converter.coerceToCharacter(c)); try { converter.coerceToCharacter(Boolean.TRUE); fail();
} catch (ELException e) {}
struberg/juel
modules/impl/src/main/java/de/odysseus/el/tree/impl/ast/AstString.java
// Path: modules/api/src/main/java/javax/el/ELContext.java // public abstract class ELContext { // private final Map<Class<?>, Object> context = new HashMap<Class<?>, Object>(); // // private Locale locale; // private boolean resolved; // // /** // * Returns the context object associated with the given key. The ELContext maintains a // * collection of context objects relevant to the evaluation of an expression. These context // * objects are used by ELResolvers. This method is used to retrieve the context with the given // * key from the collection. By convention, the object returned will be of the type specified by // * the key. However, this is not required and the key is used strictly as a unique identifier. // * // * @param key // * The unique identifier that was used to associate the context object with this // * ELContext. // * @return The context object associated with the given key, or null if no such context was // * found. // * @throws NullPointerException // * if key is null. // */ // public Object getContext(Class<?> key) { // return context.get(key); // } // // /** // * Retrieves the ELResolver associated with this context. The ELContext maintains a reference to // * the ELResolver that will be consulted to resolve variables and properties during an // * expression evaluation. This method retrieves the reference to the resolver. Once an ELContext // * is constructed, the reference to the ELResolver associated with the context cannot be // * changed. // * // * @return The resolver to be consulted for variable and property resolution during expression // * evaluation. // */ // public abstract ELResolver getELResolver(); // // /** // * Retrieves the FunctionMapper associated with this ELContext. // * // * @return The function mapper to be consulted for the resolution of EL functions. // */ // public abstract FunctionMapper getFunctionMapper(); // // /** // * Get the Locale stored by a previous invocation to {@link #setLocale(Locale)}. If this method // * returns non null, this Locale must be used for all localization needs in the implementation. // * The Locale must not be cached to allow for applications that change Locale dynamically. // * // * @return The Locale in which this instance is operating. Used primarily for message // * localization. // */ // public Locale getLocale() { // return locale; // } // // /** // * Retrieves the VariableMapper associated with this ELContext. // * // * @return The variable mapper to be consulted for the resolution of EL variables. // */ // public abstract VariableMapper getVariableMapper(); // // /** // * Returns whether an {@link ELResolver} has successfully resolved a given (base, property) // * pair. The {@link CompositeELResolver} checks this property to determine whether it should // * consider or skip other component resolvers. // * // * @return The variable mapper to be consulted for the resolution of EL variables. // * @see CompositeELResolver // */ // public boolean isPropertyResolved() { // return resolved; // } // // /** // * Associates a context object with this ELContext. The ELContext maintains a collection of // * context objects relevant to the evaluation of an expression. These context objects are used // * by ELResolvers. This method is used to add a context object to that collection. By // * convention, the contextObject will be of the type specified by the key. However, this is not // * required and the key is used strictly as a unique identifier. // * // * @param key // * The key used by an {@link ELResolver} to identify this context object. // * @param contextObject // * The context object to add to the collection. // * @throws NullPointerException // * if key is null or contextObject is null. // */ // public void putContext(Class<?> key, Object contextObject) { // context.put(key, contextObject); // } // // /** // * Set the Locale for this instance. This method may be called by the party creating the // * instance, such as JavaServer Faces or JSP, to enable the EL implementation to provide // * localized messages to the user. If no Locale is set, the implementation must use the locale // * returned by Locale.getDefault( ). // * // * @param locale // * The Locale in which this instance is operating. Used primarily for message // * localization. // */ // public void setLocale(Locale locale) { // this.locale = locale; // } // // /** // * Called to indicate that a ELResolver has successfully resolved a given (base, property) pair. // * The {@link CompositeELResolver} checks this property to determine whether it should consider // * or skip other component resolvers. // * // * @param resolved // * true if the property has been resolved, or false if not. // * @see CompositeELResolver // */ // public void setPropertyResolved(boolean resolved) { // this.resolved = resolved; // } // }
import javax.el.ELContext; import de.odysseus.el.tree.Bindings;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public final class AstString extends AstLiteral { private final String value; public AstString(String value) { this.value = value; } @Override
// Path: modules/api/src/main/java/javax/el/ELContext.java // public abstract class ELContext { // private final Map<Class<?>, Object> context = new HashMap<Class<?>, Object>(); // // private Locale locale; // private boolean resolved; // // /** // * Returns the context object associated with the given key. The ELContext maintains a // * collection of context objects relevant to the evaluation of an expression. These context // * objects are used by ELResolvers. This method is used to retrieve the context with the given // * key from the collection. By convention, the object returned will be of the type specified by // * the key. However, this is not required and the key is used strictly as a unique identifier. // * // * @param key // * The unique identifier that was used to associate the context object with this // * ELContext. // * @return The context object associated with the given key, or null if no such context was // * found. // * @throws NullPointerException // * if key is null. // */ // public Object getContext(Class<?> key) { // return context.get(key); // } // // /** // * Retrieves the ELResolver associated with this context. The ELContext maintains a reference to // * the ELResolver that will be consulted to resolve variables and properties during an // * expression evaluation. This method retrieves the reference to the resolver. Once an ELContext // * is constructed, the reference to the ELResolver associated with the context cannot be // * changed. // * // * @return The resolver to be consulted for variable and property resolution during expression // * evaluation. // */ // public abstract ELResolver getELResolver(); // // /** // * Retrieves the FunctionMapper associated with this ELContext. // * // * @return The function mapper to be consulted for the resolution of EL functions. // */ // public abstract FunctionMapper getFunctionMapper(); // // /** // * Get the Locale stored by a previous invocation to {@link #setLocale(Locale)}. If this method // * returns non null, this Locale must be used for all localization needs in the implementation. // * The Locale must not be cached to allow for applications that change Locale dynamically. // * // * @return The Locale in which this instance is operating. Used primarily for message // * localization. // */ // public Locale getLocale() { // return locale; // } // // /** // * Retrieves the VariableMapper associated with this ELContext. // * // * @return The variable mapper to be consulted for the resolution of EL variables. // */ // public abstract VariableMapper getVariableMapper(); // // /** // * Returns whether an {@link ELResolver} has successfully resolved a given (base, property) // * pair. The {@link CompositeELResolver} checks this property to determine whether it should // * consider or skip other component resolvers. // * // * @return The variable mapper to be consulted for the resolution of EL variables. // * @see CompositeELResolver // */ // public boolean isPropertyResolved() { // return resolved; // } // // /** // * Associates a context object with this ELContext. The ELContext maintains a collection of // * context objects relevant to the evaluation of an expression. These context objects are used // * by ELResolvers. This method is used to add a context object to that collection. By // * convention, the contextObject will be of the type specified by the key. However, this is not // * required and the key is used strictly as a unique identifier. // * // * @param key // * The key used by an {@link ELResolver} to identify this context object. // * @param contextObject // * The context object to add to the collection. // * @throws NullPointerException // * if key is null or contextObject is null. // */ // public void putContext(Class<?> key, Object contextObject) { // context.put(key, contextObject); // } // // /** // * Set the Locale for this instance. This method may be called by the party creating the // * instance, such as JavaServer Faces or JSP, to enable the EL implementation to provide // * localized messages to the user. If no Locale is set, the implementation must use the locale // * returned by Locale.getDefault( ). // * // * @param locale // * The Locale in which this instance is operating. Used primarily for message // * localization. // */ // public void setLocale(Locale locale) { // this.locale = locale; // } // // /** // * Called to indicate that a ELResolver has successfully resolved a given (base, property) pair. // * The {@link CompositeELResolver} checks this property to determine whether it should consider // * or skip other component resolvers. // * // * @param resolved // * true if the property has been resolved, or false if not. // * @see CompositeELResolver // */ // public void setPropertyResolved(boolean resolved) { // this.resolved = resolved; // } // } // Path: modules/impl/src/main/java/de/odysseus/el/tree/impl/ast/AstString.java import javax.el.ELContext; import de.odysseus.el.tree.Bindings; /* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public final class AstString extends AstLiteral { private final String value; public AstString(String value) { this.value = value; } @Override
public Object eval(Bindings bindings, ELContext context) {
struberg/juel
modules/impl/src/main/java/de/odysseus/el/tree/impl/Scanner.java
// Path: modules/impl/src/main/java/de/odysseus/el/misc/LocalMessages.java // public final class LocalMessages { // private static final String BUNDLE_NAME = "de.odysseus.el.misc.LocalStrings"; // private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); // // public static String get(String key, Object... args) { // String template = null; // try { // template = RESOURCE_BUNDLE.getString(key); // } catch (MissingResourceException e) { // StringBuilder b = new StringBuilder(); // try { // b.append(RESOURCE_BUNDLE.getString("message.unknown")); // b.append(": "); // } catch (MissingResourceException e2) {} // b.append(key); // if (args != null && args.length > 0) { // b.append("("); // b.append(args[0]); // for (int i = 1; i < args.length; i++) { // b.append(", "); // b.append(args[i]); // } // b.append(")"); // } // return b.toString(); // } // return MessageFormat.format(template, args); // } // }
import java.util.HashMap; import de.odysseus.el.misc.LocalMessages;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl; /** * Handcrafted scanner. * * @author Christoph Beck */ public class Scanner { /** * Scan exception type */ @SuppressWarnings("serial") public static class ScanException extends Exception { final int position; final String encountered; final String expected; public ScanException(int position, String encountered, String expected) {
// Path: modules/impl/src/main/java/de/odysseus/el/misc/LocalMessages.java // public final class LocalMessages { // private static final String BUNDLE_NAME = "de.odysseus.el.misc.LocalStrings"; // private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); // // public static String get(String key, Object... args) { // String template = null; // try { // template = RESOURCE_BUNDLE.getString(key); // } catch (MissingResourceException e) { // StringBuilder b = new StringBuilder(); // try { // b.append(RESOURCE_BUNDLE.getString("message.unknown")); // b.append(": "); // } catch (MissingResourceException e2) {} // b.append(key); // if (args != null && args.length > 0) { // b.append("("); // b.append(args[0]); // for (int i = 1; i < args.length; i++) { // b.append(", "); // b.append(args[i]); // } // b.append(")"); // } // return b.toString(); // } // return MessageFormat.format(template, args); // } // } // Path: modules/impl/src/main/java/de/odysseus/el/tree/impl/Scanner.java import java.util.HashMap; import de.odysseus.el.misc.LocalMessages; /* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl; /** * Handcrafted scanner. * * @author Christoph Beck */ public class Scanner { /** * Scan exception type */ @SuppressWarnings("serial") public static class ScanException extends Exception { final int position; final String encountered; final String expected; public ScanException(int position, String encountered, String expected) {
super(LocalMessages.get("error.scan", position, encountered, expected));
struberg/juel
modules/impl/src/test/java/de/odysseus/el/tree/impl/ast/AstCompositeTest.java
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // }
import javax.el.ELException; import de.odysseus.el.TestCase; import de.odysseus.el.tree.Bindings;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public class AstCompositeTest extends TestCase { private Bindings bindings = new Bindings(null, null, null); AstComposite parseNode(String expression) { return (AstComposite)parse(expression).getRoot(); } public void testEval() { assertEquals("101", parseNode("${1}0${1}").eval(bindings, null)); } public void testAppendStructure() { StringBuilder s = new StringBuilder(); parseNode("${1}0${1}").appendStructure(s, bindings); assertEquals("${1}0${1}", s.toString()); } public void testIsLiteralText() { assertFalse(parseNode("${1}0${1}").isLiteralText()); } public void testIsLeftValue() { assertFalse(parseNode("${1}0${1}").isLeftValue()); } public void testGetType() { assertNull(parseNode("${1}0${1}").getType(bindings, null)); } public void testIsReadOnly() { assertTrue(parseNode("${1}0${1}").isReadOnly(bindings, null)); } public void testSetValue() {
// Path: modules/api/src/main/java/javax/el/ELException.java // public class ELException extends RuntimeException { // private static final long serialVersionUID = 1L; // // /** // * Creates an ELException with no detail message. // */ // public ELException() { // super(); // } // // /** // * Creates an ELException with the provided detail message. // * // * @param message // * the detail message // */ // public ELException(String message) { // super(message); // } // // /** // * Creates an ELException with the given cause. // * // * @param cause // * the originating cause of this exception // */ // public ELException(Throwable cause) { // super(cause); // } // // /** // * Creates an ELException with the given detail message and root cause. // * // * @param message // * the detail message // * @param cause // * the originating cause of this exception // */ // public ELException(String message, Throwable cause) { // super(message, cause); // } // } // Path: modules/impl/src/test/java/de/odysseus/el/tree/impl/ast/AstCompositeTest.java import javax.el.ELException; import de.odysseus.el.TestCase; import de.odysseus.el.tree.Bindings; /* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public class AstCompositeTest extends TestCase { private Bindings bindings = new Bindings(null, null, null); AstComposite parseNode(String expression) { return (AstComposite)parse(expression).getRoot(); } public void testEval() { assertEquals("101", parseNode("${1}0${1}").eval(bindings, null)); } public void testAppendStructure() { StringBuilder s = new StringBuilder(); parseNode("${1}0${1}").appendStructure(s, bindings); assertEquals("${1}0${1}", s.toString()); } public void testIsLiteralText() { assertFalse(parseNode("${1}0${1}").isLiteralText()); } public void testIsLeftValue() { assertFalse(parseNode("${1}0${1}").isLeftValue()); } public void testGetType() { assertNull(parseNode("${1}0${1}").getType(bindings, null)); } public void testIsReadOnly() { assertTrue(parseNode("${1}0${1}").isReadOnly(bindings, null)); } public void testSetValue() {
try { parseNode("${1}0${1}").setValue(bindings, null, null); fail(); } catch (ELException e) {}
owagner/logic4mqtt
src/main/java/com/tellerulam/logic4mqtt/api/Events.java
// Path: src/main/java/com/tellerulam/logic4mqtt/TopicCache.java // static public class TopicValue // { // private TopicValue(Object value, Date ts,Object fullValue) // { // this.value=value; // this.ts=ts; // this.lastRefresh=ts; // this.fullValue=fullValue; // } // public final Object value,fullValue; // public final Date ts; // public Date lastRefresh; // void markAsRefreshed() // { // lastRefresh=new Date(); // } // }
import java.util.*; import com.tellerulam.logic4mqtt.*; import com.tellerulam.logic4mqtt.TopicCache.TopicValue;
} public void queueStore(String timespec,String topic,Map<String,Object> value) { internalQueueSet(timespec,topic,ScriptEngineTools.encodeAsJSON(value),true); } /** * Clears possibly queued value sets for the given topic * * @param topic the topic to clear the queue for * @return number of removed queued set */ public int clearQueue(String topic) { return LogicTimer.remTimer("_SET_"+TopicCache.convertSetTopic(topic)); } /** * * Get a cached last value of a topic, or null if the topic or the specified * generation is not known. * * @param topic * @param generation (0 = current, 1 = previous, ...) * @return the value, or null */ public Object getValue(String topic,int generation) { topic=TopicCache.convertStatusTopic(topic);
// Path: src/main/java/com/tellerulam/logic4mqtt/TopicCache.java // static public class TopicValue // { // private TopicValue(Object value, Date ts,Object fullValue) // { // this.value=value; // this.ts=ts; // this.lastRefresh=ts; // this.fullValue=fullValue; // } // public final Object value,fullValue; // public final Date ts; // public Date lastRefresh; // void markAsRefreshed() // { // lastRefresh=new Date(); // } // } // Path: src/main/java/com/tellerulam/logic4mqtt/api/Events.java import java.util.*; import com.tellerulam.logic4mqtt.*; import com.tellerulam.logic4mqtt.TopicCache.TopicValue; } public void queueStore(String timespec,String topic,Map<String,Object> value) { internalQueueSet(timespec,topic,ScriptEngineTools.encodeAsJSON(value),true); } /** * Clears possibly queued value sets for the given topic * * @param topic the topic to clear the queue for * @return number of removed queued set */ public int clearQueue(String topic) { return LogicTimer.remTimer("_SET_"+TopicCache.convertSetTopic(topic)); } /** * * Get a cached last value of a topic, or null if the topic or the specified * generation is not known. * * @param topic * @param generation (0 = current, 1 = previous, ...) * @return the value, or null */ public Object getValue(String topic,int generation) { topic=TopicCache.convertStatusTopic(topic);
TopicValue tv=TopicCache.getTopicValue(topic, generation);
trygvis/javax-usb-libusb1
javalibusb1/src/main/java/javalibusb1/Libusb1Utils.java
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // }
import static javax.usb.UsbHostManager.*; import javax.usb.*; import java.io.*; import java.util.*;
package javalibusb1; public class Libusb1Utils { private static final Properties javaxUsbProperties = new Properties(); static {
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // } // Path: javalibusb1/src/main/java/javalibusb1/Libusb1Utils.java import static javax.usb.UsbHostManager.*; import javax.usb.*; import java.io.*; import java.util.*; package javalibusb1; public class Libusb1Utils { private static final Properties javaxUsbProperties = new Properties(); static {
InputStream stream = UsbHostManager.class.getClassLoader().
trygvis/javax-usb-libusb1
javalibusb1/src/main/java/javalibusb1/Libusb1UsbDevice.java
// Path: javalibusb1/src/main/java/javalibusb1/Libusb1UsbControlIrp.java // public static Libusb1UsbControlIrp createControlIrp(UsbControlIrp irp) { // if(irp instanceof Libusb1UsbControlIrp) { // return (Libusb1UsbControlIrp) irp; // } // // checkIrp(irp); // checkControlIrp(irp); // // return new Libusb1UsbControlIrp(irp); // }
import static javalibusb1.Libusb1UsbControlIrp.createControlIrp; import javax.usb.*; import javax.usb.event.*; import javax.usb.util.*; import java.io.*; import java.util.*;
public boolean isUsbHub() { return false; } public void addUsbDeviceListener(UsbDeviceListener listener) { deviceListeners.add(listener); } public void removeUsbDeviceListener(UsbDeviceListener listener) { deviceListeners.remove(listener); } public UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex) { return new DefaultUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); } public void asyncSubmit(List<UsbControlIrp> list) { throw new RuntimeException("Not implemented"); } public void asyncSubmit(UsbControlIrp irp) { throw new RuntimeException("Not implemented"); } public void syncSubmit(List<UsbControlIrp> list) { throw new RuntimeException("Not implemented"); } public void syncSubmit(UsbControlIrp irp) throws UsbException {
// Path: javalibusb1/src/main/java/javalibusb1/Libusb1UsbControlIrp.java // public static Libusb1UsbControlIrp createControlIrp(UsbControlIrp irp) { // if(irp instanceof Libusb1UsbControlIrp) { // return (Libusb1UsbControlIrp) irp; // } // // checkIrp(irp); // checkControlIrp(irp); // // return new Libusb1UsbControlIrp(irp); // } // Path: javalibusb1/src/main/java/javalibusb1/Libusb1UsbDevice.java import static javalibusb1.Libusb1UsbControlIrp.createControlIrp; import javax.usb.*; import javax.usb.event.*; import javax.usb.util.*; import java.io.*; import java.util.*; public boolean isUsbHub() { return false; } public void addUsbDeviceListener(UsbDeviceListener listener) { deviceListeners.add(listener); } public void removeUsbDeviceListener(UsbDeviceListener listener) { deviceListeners.remove(listener); } public UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex) { return new DefaultUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); } public void asyncSubmit(List<UsbControlIrp> list) { throw new RuntimeException("Not implemented"); } public void asyncSubmit(UsbControlIrp irp) { throw new RuntimeException("Not implemented"); } public void syncSubmit(List<UsbControlIrp> list) { throw new RuntimeException("Not implemented"); } public void syncSubmit(UsbControlIrp irp) throws UsbException {
internalSyncSubmitControl(libusb_device_ptr, createControlIrp(irp));
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java
// Path: javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java // public class ExtraUsbUtil { // /** // * @param a Least significant byte // * @param b Most significant byte // */ // public static short toShort(byte a, byte b) { // return (short)(b << 8 | a); // } // // /** // * @param a Least significant byte // * @param b // * @param c // * @param d Most significant byte // * @return // */ // public static int toInt(byte a, byte b, byte c, byte d) { // return d << 24 | c << 16 | b << 8 | a; // } // // public static boolean isUsbDevice(UsbDeviceDescriptor descriptor, short idVendor, short idProduct) { // return descriptor.idVendor() == idVendor && descriptor.idProduct() == idProduct; // } // // public static UsbDevice findUsbDevice(UsbHub usbHub, short idVendor, short idProduct) { // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (isUsbDevice(deviceDescriptor, idVendor, idProduct)) { // return device; // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // UsbDevice foundDevice = findUsbDevice((UsbHub) device, idVendor, idProduct); // // if (foundDevice != null) { // return foundDevice; // } // } // // return null; // } // // public static List<UsbDevice> findUsbDevices(UsbHub usbHub, short idVendor, short idProduct) { // List<UsbDevice> devices = new ArrayList<UsbDevice>(); // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (deviceDescriptor.idVendor() == idVendor && deviceDescriptor.idProduct() == idProduct) { // devices.add(device); // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // List<UsbDevice> foundDevices = findUsbDevices((UsbHub) device, idVendor, idProduct); // // devices.addAll(foundDevices); // } // // return devices; // } // // public static List<UsbDevice> listUsbDevices(UsbHub usbHub) { // List<UsbDevice> devices = new ArrayList<UsbDevice>(); // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // devices.add(device); // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // devices.addAll(listUsbDevices(usbHub)); // } // // return devices; // } // // public static String deviceIdToString(UsbDeviceDescriptor descriptor) { // return toHexString(descriptor.idVendor()) + ":" + toHexString(descriptor.idProduct()); // } // // public static String deviceIdToString(short idVendor, short idProduct) { // return toHexString(idVendor) + ":" + toHexString(idProduct); // } // } // // Path: javax.usb/src/main/java/javax/usb/util/UsbUtil.java // public static String toHexString(byte b) { // int i = unsignedInt(b); // return new String(new char[]{ // hexDigits[i >> 4], // hexDigits[i & 0x0f], // }); // }
import static java.lang.Integer.*; import static javax.usb.extra.ExtraUsbUtil.*; import static javax.usb.util.UsbUtil.toHexString; import javax.usb.*; import java.util.*;
System.err.println("'id' parameter is out of range."); return null; } return devices.get(index); } else if (idProduct != null && idVendor != null) { UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); if (usbDevice == null) { System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); } return usbDevice; } return null; } public static void listDevices(UsbHub hub, short idVendor, short idProduct) { listDevices("0", hub, idVendor, idProduct); } private static void listDevices(String prefix, UsbHub hub, short idVendor, short idProduct) { List<UsbDevice> list = hub.getAttachedUsbDevices(); for (int i = 0; i < list.size(); i++) { UsbDevice device = list.get(i); if (device.isUsbHub()) { listDevices(prefix + "." + i, (UsbHub) device, idVendor, idProduct); } else { UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor();
// Path: javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java // public class ExtraUsbUtil { // /** // * @param a Least significant byte // * @param b Most significant byte // */ // public static short toShort(byte a, byte b) { // return (short)(b << 8 | a); // } // // /** // * @param a Least significant byte // * @param b // * @param c // * @param d Most significant byte // * @return // */ // public static int toInt(byte a, byte b, byte c, byte d) { // return d << 24 | c << 16 | b << 8 | a; // } // // public static boolean isUsbDevice(UsbDeviceDescriptor descriptor, short idVendor, short idProduct) { // return descriptor.idVendor() == idVendor && descriptor.idProduct() == idProduct; // } // // public static UsbDevice findUsbDevice(UsbHub usbHub, short idVendor, short idProduct) { // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (isUsbDevice(deviceDescriptor, idVendor, idProduct)) { // return device; // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // UsbDevice foundDevice = findUsbDevice((UsbHub) device, idVendor, idProduct); // // if (foundDevice != null) { // return foundDevice; // } // } // // return null; // } // // public static List<UsbDevice> findUsbDevices(UsbHub usbHub, short idVendor, short idProduct) { // List<UsbDevice> devices = new ArrayList<UsbDevice>(); // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (deviceDescriptor.idVendor() == idVendor && deviceDescriptor.idProduct() == idProduct) { // devices.add(device); // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // List<UsbDevice> foundDevices = findUsbDevices((UsbHub) device, idVendor, idProduct); // // devices.addAll(foundDevices); // } // // return devices; // } // // public static List<UsbDevice> listUsbDevices(UsbHub usbHub) { // List<UsbDevice> devices = new ArrayList<UsbDevice>(); // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // devices.add(device); // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // devices.addAll(listUsbDevices(usbHub)); // } // // return devices; // } // // public static String deviceIdToString(UsbDeviceDescriptor descriptor) { // return toHexString(descriptor.idVendor()) + ":" + toHexString(descriptor.idProduct()); // } // // public static String deviceIdToString(short idVendor, short idProduct) { // return toHexString(idVendor) + ":" + toHexString(idProduct); // } // } // // Path: javax.usb/src/main/java/javax/usb/util/UsbUtil.java // public static String toHexString(byte b) { // int i = unsignedInt(b); // return new String(new char[]{ // hexDigits[i >> 4], // hexDigits[i & 0x0f], // }); // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java import static java.lang.Integer.*; import static javax.usb.extra.ExtraUsbUtil.*; import static javax.usb.util.UsbUtil.toHexString; import javax.usb.*; import java.util.*; System.err.println("'id' parameter is out of range."); return null; } return devices.get(index); } else if (idProduct != null && idVendor != null) { UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); if (usbDevice == null) { System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); } return usbDevice; } return null; } public static void listDevices(UsbHub hub, short idVendor, short idProduct) { listDevices("0", hub, idVendor, idProduct); } private static void listDevices(String prefix, UsbHub hub, short idVendor, short idProduct) { List<UsbDevice> list = hub.getAttachedUsbDevices(); for (int i = 0; i < list.size(); i++) { UsbDevice device = list.get(i); if (device.isUsbHub()) { listDevices(prefix + "." + i, (UsbHub) device, idVendor, idProduct); } else { UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor();
System.err.print(prefix + "." + i + " " + toHexString(deviceDescriptor.idVendor()) + ":" + toHexString(deviceDescriptor.idProduct()));
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/ztex/MemTest.java
// Path: javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java // public static UsbDevice findUsbDevice(UsbHub usbHub, short idVendor, short idProduct) { // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (isUsbDevice(deviceDescriptor, idVendor, idProduct)) { // return device; // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // UsbDevice foundDevice = findUsbDevice((UsbHub) device, idVendor, idProduct); // // if (foundDevice != null) { // return foundDevice; // } // } // // return null; // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static void listDevices(UsbHub hub, short idVendor, short idProduct) { // listDevices("0", hub, idVendor, idProduct); // }
import static java.util.Arrays.asList; import static javax.usb.extra.ExtraUsbUtil.findUsbDevice; import static io.trygvis.usb.tools.UsbCliUtil.listDevices; import javax.usb.*; import java.util.*;
package io.trygvis.usb.tools.ztex; public class MemTest { public static final short idVendor = (short)0x221a; public static final short idProduct = (short)0x0100; public static void main(String[] a) throws UsbException { UsbServices usbServices = UsbHostManager.getUsbServices(); UsbHub hub = usbServices.getRootUsbHub(); System.out.println("MemTest"); List<String> args = new ArrayList<String>(asList(a)); Iterator<String> it = args.iterator(); while (it.hasNext()) { String arg = it.next(); if (arg.equals("--list")) {
// Path: javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java // public static UsbDevice findUsbDevice(UsbHub usbHub, short idVendor, short idProduct) { // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (isUsbDevice(deviceDescriptor, idVendor, idProduct)) { // return device; // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // UsbDevice foundDevice = findUsbDevice((UsbHub) device, idVendor, idProduct); // // if (foundDevice != null) { // return foundDevice; // } // } // // return null; // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static void listDevices(UsbHub hub, short idVendor, short idProduct) { // listDevices("0", hub, idVendor, idProduct); // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/ztex/MemTest.java import static java.util.Arrays.asList; import static javax.usb.extra.ExtraUsbUtil.findUsbDevice; import static io.trygvis.usb.tools.UsbCliUtil.listDevices; import javax.usb.*; import java.util.*; package io.trygvis.usb.tools.ztex; public class MemTest { public static final short idVendor = (short)0x221a; public static final short idProduct = (short)0x0100; public static void main(String[] a) throws UsbException { UsbServices usbServices = UsbHostManager.getUsbServices(); UsbHub hub = usbServices.getRootUsbHub(); System.out.println("MemTest"); List<String> args = new ArrayList<String>(asList(a)); Iterator<String> it = args.iterator(); while (it.hasNext()) { String arg = it.next(); if (arg.equals("--list")) {
listDevices(hub, idVendor, idProduct);
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/ztex/MemTest.java
// Path: javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java // public static UsbDevice findUsbDevice(UsbHub usbHub, short idVendor, short idProduct) { // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (isUsbDevice(deviceDescriptor, idVendor, idProduct)) { // return device; // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // UsbDevice foundDevice = findUsbDevice((UsbHub) device, idVendor, idProduct); // // if (foundDevice != null) { // return foundDevice; // } // } // // return null; // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static void listDevices(UsbHub hub, short idVendor, short idProduct) { // listDevices("0", hub, idVendor, idProduct); // }
import static java.util.Arrays.asList; import static javax.usb.extra.ExtraUsbUtil.findUsbDevice; import static io.trygvis.usb.tools.UsbCliUtil.listDevices; import javax.usb.*; import java.util.*;
package io.trygvis.usb.tools.ztex; public class MemTest { public static final short idVendor = (short)0x221a; public static final short idProduct = (short)0x0100; public static void main(String[] a) throws UsbException { UsbServices usbServices = UsbHostManager.getUsbServices(); UsbHub hub = usbServices.getRootUsbHub(); System.out.println("MemTest"); List<String> args = new ArrayList<String>(asList(a)); Iterator<String> it = args.iterator(); while (it.hasNext()) { String arg = it.next(); if (arg.equals("--list")) { listDevices(hub, idVendor, idProduct); break; } else {
// Path: javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java // public static UsbDevice findUsbDevice(UsbHub usbHub, short idVendor, short idProduct) { // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (device.isUsbHub()) { // continue; // } // // UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor(); // // if (isUsbDevice(deviceDescriptor, idVendor, idProduct)) { // return device; // } // } // // for (UsbDevice device : usbHub.getAttachedUsbDevices()) { // if (!device.isUsbHub()) { // continue; // } // // UsbDevice foundDevice = findUsbDevice((UsbHub) device, idVendor, idProduct); // // if (foundDevice != null) { // return foundDevice; // } // } // // return null; // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static void listDevices(UsbHub hub, short idVendor, short idProduct) { // listDevices("0", hub, idVendor, idProduct); // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/ztex/MemTest.java import static java.util.Arrays.asList; import static javax.usb.extra.ExtraUsbUtil.findUsbDevice; import static io.trygvis.usb.tools.UsbCliUtil.listDevices; import javax.usb.*; import java.util.*; package io.trygvis.usb.tools.ztex; public class MemTest { public static final short idVendor = (short)0x221a; public static final short idProduct = (short)0x0100; public static void main(String[] a) throws UsbException { UsbServices usbServices = UsbHostManager.getUsbServices(); UsbHub hub = usbServices.getRootUsbHub(); System.out.println("MemTest"); List<String> args = new ArrayList<String>(asList(a)); Iterator<String> it = args.iterator(); while (it.hasNext()) { String arg = it.next(); if (arg.equals("--list")) { listDevices(hub, idVendor, idProduct); break; } else {
UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct);
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/IntelHex.java
// Path: usbtools/src/main/java/io/trygvis/usb/tools/IntelHex.java // public static enum RecordType { // DATA(0), // END_OF_FILE(1); // //EXTENDED_SEGMENT_ADDRESS_RECORD, // //START_SEGMENT_ADDRESS_RECORD, // //EXTENDED_LINEAR_ADDRESS_RECORD, // //START_LINEAR_ADDRESS_RECORD; // // byte id; // // RecordType(int id) { // this.id = (byte)id; // } // // public static RecordType lookup(int i) throws IOException { // for (RecordType recordType : values()) { // if (recordType.id == i) { // return recordType; // } // } // // throw new IOException("Unknown record type: " + i + "."); // } // }
import static java.lang.Integer.*; import static io.trygvis.usb.tools.IntelHex.RecordType.*; import javax.usb.util.*; import java.io.*; import java.util.*;
package io.trygvis.usb.tools; public class IntelHex { public static List<IntelHexPacket> openIntelHexFile(final File file) throws IOException { return openIntelHexFile(new FileInputStream(file)); } public static List<IntelHexPacket> openIntelHexFile(final InputStream is) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "ascii")); String line = reader.readLine(); if (line == null) { throw new IOException("The Intel hex file must contain at least one line"); } IntelHexPacket packet = parseLine(0, line); List<IntelHexPacket> list = new ArrayList<IntelHexPacket>(); while (true) { list.add(packet); line = reader.readLine(); if (line == null) { break; } packet = parseLine(packet.lineNo, line); } return list; }
// Path: usbtools/src/main/java/io/trygvis/usb/tools/IntelHex.java // public static enum RecordType { // DATA(0), // END_OF_FILE(1); // //EXTENDED_SEGMENT_ADDRESS_RECORD, // //START_SEGMENT_ADDRESS_RECORD, // //EXTENDED_LINEAR_ADDRESS_RECORD, // //START_LINEAR_ADDRESS_RECORD; // // byte id; // // RecordType(int id) { // this.id = (byte)id; // } // // public static RecordType lookup(int i) throws IOException { // for (RecordType recordType : values()) { // if (recordType.id == i) { // return recordType; // } // } // // throw new IOException("Unknown record type: " + i + "."); // } // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/IntelHex.java import static java.lang.Integer.*; import static io.trygvis.usb.tools.IntelHex.RecordType.*; import javax.usb.util.*; import java.io.*; import java.util.*; package io.trygvis.usb.tools; public class IntelHex { public static List<IntelHexPacket> openIntelHexFile(final File file) throws IOException { return openIntelHexFile(new FileInputStream(file)); } public static List<IntelHexPacket> openIntelHexFile(final InputStream is) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "ascii")); String line = reader.readLine(); if (line == null) { throw new IOException("The Intel hex file must contain at least one line"); } IntelHexPacket packet = parseLine(0, line); List<IntelHexPacket> list = new ArrayList<IntelHexPacket>(); while (true) { list.add(packet); line = reader.readLine(); if (line == null) { break; } packet = parseLine(packet.lineNo, line); } return list; }
public static enum RecordType {
trygvis/javax-usb-libusb1
javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java
// Path: javax.usb/src/main/java/javax/usb/util/UsbUtil.java // public static String toHexString(byte b) { // int i = unsignedInt(b); // return new String(new char[]{ // hexDigits[i >> 4], // hexDigits[i & 0x0f], // }); // }
import static javax.usb.util.UsbUtil.toHexString; import javax.usb.*; import java.util.*;
devices.addAll(foundDevices); } return devices; } public static List<UsbDevice> listUsbDevices(UsbHub usbHub) { List<UsbDevice> devices = new ArrayList<UsbDevice>(); for (UsbDevice device : usbHub.getAttachedUsbDevices()) { if (device.isUsbHub()) { continue; } devices.add(device); } for (UsbDevice device : usbHub.getAttachedUsbDevices()) { if (!device.isUsbHub()) { continue; } devices.addAll(listUsbDevices(usbHub)); } return devices; } public static String deviceIdToString(UsbDeviceDescriptor descriptor) {
// Path: javax.usb/src/main/java/javax/usb/util/UsbUtil.java // public static String toHexString(byte b) { // int i = unsignedInt(b); // return new String(new char[]{ // hexDigits[i >> 4], // hexDigits[i & 0x0f], // }); // } // Path: javax.usb-extra/src/main/java/javax/usb/extra/ExtraUsbUtil.java import static javax.usb.util.UsbUtil.toHexString; import javax.usb.*; import java.util.*; devices.addAll(foundDevices); } return devices; } public static List<UsbDevice> listUsbDevices(UsbHub usbHub) { List<UsbDevice> devices = new ArrayList<UsbDevice>(); for (UsbDevice device : usbHub.getAttachedUsbDevices()) { if (device.isUsbHub()) { continue; } devices.add(device); } for (UsbDevice device : usbHub.getAttachedUsbDevices()) { if (!device.isUsbHub()) { continue; } devices.addAll(listUsbDevices(usbHub)); } return devices; } public static String deviceIdToString(UsbDeviceDescriptor descriptor) {
return toHexString(descriptor.idVendor()) + ":" + toHexString(descriptor.idProduct());
trygvis/javax-usb-libusb1
javax.usb/src/main/java/javax/usb/event/UsbPipeErrorEvent.java
// Path: javax.usb/src/main/java/javax/usb/UsbException.java // public class UsbException extends Exception { // public UsbException() { // } // // public UsbException(String message) { // super(message); // } // } // // Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // }
import javax.usb.UsbException; import javax.usb.UsbIrp; import javax.usb.UsbPipe;
package javax.usb.event; public class UsbPipeErrorEvent extends UsbPipeEvent { private UsbException usbException;
// Path: javax.usb/src/main/java/javax/usb/UsbException.java // public class UsbException extends Exception { // public UsbException() { // } // // public UsbException(String message) { // super(message); // } // } // // Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // } // Path: javax.usb/src/main/java/javax/usb/event/UsbPipeErrorEvent.java import javax.usb.UsbException; import javax.usb.UsbIrp; import javax.usb.UsbPipe; package javax.usb.event; public class UsbPipeErrorEvent extends UsbPipeEvent { private UsbException usbException;
public UsbPipeErrorEvent(UsbPipe source, UsbException usbException) {
trygvis/javax-usb-libusb1
javax.usb/src/main/java/javax/usb/event/UsbPipeErrorEvent.java
// Path: javax.usb/src/main/java/javax/usb/UsbException.java // public class UsbException extends Exception { // public UsbException() { // } // // public UsbException(String message) { // super(message); // } // } // // Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // }
import javax.usb.UsbException; import javax.usb.UsbIrp; import javax.usb.UsbPipe;
package javax.usb.event; public class UsbPipeErrorEvent extends UsbPipeEvent { private UsbException usbException; public UsbPipeErrorEvent(UsbPipe source, UsbException usbException) { super(source); this.usbException = usbException; }
// Path: javax.usb/src/main/java/javax/usb/UsbException.java // public class UsbException extends Exception { // public UsbException() { // } // // public UsbException(String message) { // super(message); // } // } // // Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // } // Path: javax.usb/src/main/java/javax/usb/event/UsbPipeErrorEvent.java import javax.usb.UsbException; import javax.usb.UsbIrp; import javax.usb.UsbPipe; package javax.usb.event; public class UsbPipeErrorEvent extends UsbPipeEvent { private UsbException usbException; public UsbPipeErrorEvent(UsbPipe source, UsbException usbException) { super(source); this.usbException = usbException; }
public UsbPipeErrorEvent(UsbPipe source, UsbIrp usbIrp) {
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/ztex/ZtexDevice.java
// Path: usbtools/src/main/java/io/trygvis/usb/tools/ztex/ZtexFpgaState.java // public class ZtexFpgaState { // public final boolean configured; // public final byte checksum; // public final int bytesTransferred; // public final int initB; // // public ZtexFpgaState(boolean configured, byte checksum, int bytesTransferred, int initB) { // this.configured = configured; // this.checksum = checksum; // this.bytesTransferred = bytesTransferred; // this.initB = initB; // } // // public static ZtexFpgaState ztexFpgaStateFromBytes(byte[] bytes) { // if(bytes.length < 7) { // throw new RuntimeException("Invalid FPGA state descriptor, expected at least 7 bytes, got " + bytes.length + " bytes."); // } // return new ZtexFpgaState(bytes[0] == 0, // bytes[1], // toInt(bytes[2], bytes[3], bytes[4], bytes[5]), // UsbUtil.unsignedInt(bytes[6])); // } // // public String toString() { // if(!configured) { // return "Configured: no, checksum=" + toHexString(checksum) + ", bytesTransferred=" + bytesTransferred + ", initB=" + initB + "."; // } // return "Configured: yes, checksum=" + toHexString(checksum) + ", bytesTransferred=" + bytesTransferred + ", initB=" + initB + "."; // } // }
import static java.lang.System.*; import static io.trygvis.usb.tools.ztex.ZtexFpgaState.*; import javax.usb.*; import javax.usb.util.*; import java.io.*;
int size = vendorRequest(usbDevice, (byte) 0x22, (short) 0, (short) 0, buf); if (size != 40) { throw new ZtexException("Invalid Ztex device descriptor: expected the descriptor to be 40 bytes, was " + size + "."); } try { byte[] productId = new byte[4]; arraycopy(buf, 6, productId, 0, 4); byte[] intefaceCapabilities = new byte[6]; arraycopy(buf, 12, intefaceCapabilities, 0, 6); ZtexDeviceDescriptor deviceDescriptor = new ZtexDeviceDescriptor(buf[0], buf[1], new String(buf, 2, 4, "ascii"), productId, buf[10], buf[11], intefaceCapabilities); return new ZtexDevice(usbDevice, deviceDescriptor); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } // ----------------------------------------------------------------------- // FPGA Configuration // -----------------------------------------------------------------------
// Path: usbtools/src/main/java/io/trygvis/usb/tools/ztex/ZtexFpgaState.java // public class ZtexFpgaState { // public final boolean configured; // public final byte checksum; // public final int bytesTransferred; // public final int initB; // // public ZtexFpgaState(boolean configured, byte checksum, int bytesTransferred, int initB) { // this.configured = configured; // this.checksum = checksum; // this.bytesTransferred = bytesTransferred; // this.initB = initB; // } // // public static ZtexFpgaState ztexFpgaStateFromBytes(byte[] bytes) { // if(bytes.length < 7) { // throw new RuntimeException("Invalid FPGA state descriptor, expected at least 7 bytes, got " + bytes.length + " bytes."); // } // return new ZtexFpgaState(bytes[0] == 0, // bytes[1], // toInt(bytes[2], bytes[3], bytes[4], bytes[5]), // UsbUtil.unsignedInt(bytes[6])); // } // // public String toString() { // if(!configured) { // return "Configured: no, checksum=" + toHexString(checksum) + ", bytesTransferred=" + bytesTransferred + ", initB=" + initB + "."; // } // return "Configured: yes, checksum=" + toHexString(checksum) + ", bytesTransferred=" + bytesTransferred + ", initB=" + initB + "."; // } // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/ztex/ZtexDevice.java import static java.lang.System.*; import static io.trygvis.usb.tools.ztex.ZtexFpgaState.*; import javax.usb.*; import javax.usb.util.*; import java.io.*; int size = vendorRequest(usbDevice, (byte) 0x22, (short) 0, (short) 0, buf); if (size != 40) { throw new ZtexException("Invalid Ztex device descriptor: expected the descriptor to be 40 bytes, was " + size + "."); } try { byte[] productId = new byte[4]; arraycopy(buf, 6, productId, 0, 4); byte[] intefaceCapabilities = new byte[6]; arraycopy(buf, 12, intefaceCapabilities, 0, 6); ZtexDeviceDescriptor deviceDescriptor = new ZtexDeviceDescriptor(buf[0], buf[1], new String(buf, 2, 4, "ascii"), productId, buf[10], buf[11], intefaceCapabilities); return new ZtexDevice(usbDevice, deviceDescriptor); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } // ----------------------------------------------------------------------- // FPGA Configuration // -----------------------------------------------------------------------
public ZtexFpgaState getFpgaState() throws UsbException {
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/UsbEcho.java
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/HexFormatter.java // public static void writeBytes(PrintStream print, byte[] bytes) { // writeBytes(print, bytes, 0, bytes.length); // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static UsbDevice findDevice(UsbHub hub, Short idVendor, Short idProduct, String id) { // // TODO: Parse out --id=VVVV.PPPP[.N] and --device=[device path] // // if (id != null) { // int i = id.indexOf(':'); // if (i == 4) { // // this is an id on the form VVVV.PPPP // idVendor = (short) parseInt(id.substring(0, 4), 16); // idProduct = (short) parseInt(id.substring(5, 9), 16); // // id = null; // } // } // // if (id != null) { // // As this library is implemented with libusb which returns // // everything in a single, flat list for now just do this simple search. // // int index; // try { // index = parseInt(id); // } catch (NumberFormatException e) { // System.err.println("Invalid 'id' parameter, has to be an integer."); // return null; // } // // List<UsbDevice> devices = hub.getAttachedUsbDevices(); // // if (index >= devices.size() || index < 0) { // System.err.println("'id' parameter is out of range."); // return null; // } // // return devices.get(index); // } else if (idProduct != null && idVendor != null) { // UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); // // if (usbDevice == null) { // System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); // } // // return usbDevice; // } // return null; // }
import static java.lang.Byte.parseByte; import static javax.usb.UsbHostManager.*; import static io.trygvis.usb.tools.HexFormatter.writeBytes; import static io.trygvis.usb.tools.UsbCliUtil.findDevice; import javax.usb.*;
package io.trygvis.usb.tools; /** * Stream stdin to and endpoint and an endpoint to stdout. * * For now it required that the enpoints have the same packet size and that * the device sends one packet for each received. */ public class UsbEcho { public static final short idVendor = 0x0547; public static final short idProduct = (short) 0xff01; public static void main(String[] args) throws Exception { String id = null; byte configuration = 1; byte interfaceId = 0; Byte inEp = null; Byte outEp = null; for (String arg : args) { if(arg.startsWith("--id=")) { id = arg.substring(5); } else if(arg.startsWith("--in=")) { inEp = parseByte(arg.substring(5)); } else if(arg.startsWith("--out=")) { outEp = parseByte(arg.substring(6)); } } if(inEp == null || outEp == null) { System.err.println("Usage: --in=<in ep> --out=<out ep> [--id=VVVV:PPPP | --id=path]"); return; }
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/HexFormatter.java // public static void writeBytes(PrintStream print, byte[] bytes) { // writeBytes(print, bytes, 0, bytes.length); // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static UsbDevice findDevice(UsbHub hub, Short idVendor, Short idProduct, String id) { // // TODO: Parse out --id=VVVV.PPPP[.N] and --device=[device path] // // if (id != null) { // int i = id.indexOf(':'); // if (i == 4) { // // this is an id on the form VVVV.PPPP // idVendor = (short) parseInt(id.substring(0, 4), 16); // idProduct = (short) parseInt(id.substring(5, 9), 16); // // id = null; // } // } // // if (id != null) { // // As this library is implemented with libusb which returns // // everything in a single, flat list for now just do this simple search. // // int index; // try { // index = parseInt(id); // } catch (NumberFormatException e) { // System.err.println("Invalid 'id' parameter, has to be an integer."); // return null; // } // // List<UsbDevice> devices = hub.getAttachedUsbDevices(); // // if (index >= devices.size() || index < 0) { // System.err.println("'id' parameter is out of range."); // return null; // } // // return devices.get(index); // } else if (idProduct != null && idVendor != null) { // UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); // // if (usbDevice == null) { // System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); // } // // return usbDevice; // } // return null; // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbEcho.java import static java.lang.Byte.parseByte; import static javax.usb.UsbHostManager.*; import static io.trygvis.usb.tools.HexFormatter.writeBytes; import static io.trygvis.usb.tools.UsbCliUtil.findDevice; import javax.usb.*; package io.trygvis.usb.tools; /** * Stream stdin to and endpoint and an endpoint to stdout. * * For now it required that the enpoints have the same packet size and that * the device sends one packet for each received. */ public class UsbEcho { public static final short idVendor = 0x0547; public static final short idProduct = (short) 0xff01; public static void main(String[] args) throws Exception { String id = null; byte configuration = 1; byte interfaceId = 0; Byte inEp = null; Byte outEp = null; for (String arg : args) { if(arg.startsWith("--id=")) { id = arg.substring(5); } else if(arg.startsWith("--in=")) { inEp = parseByte(arg.substring(5)); } else if(arg.startsWith("--out=")) { outEp = parseByte(arg.substring(6)); } } if(inEp == null || outEp == null) { System.err.println("Usage: --in=<in ep> --out=<out ep> [--id=VVVV:PPPP | --id=path]"); return; }
UsbDevice device = findDevice(getUsbServices().getRootUsbHub(), idVendor, idProduct, id);
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/UsbEcho.java
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/HexFormatter.java // public static void writeBytes(PrintStream print, byte[] bytes) { // writeBytes(print, bytes, 0, bytes.length); // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static UsbDevice findDevice(UsbHub hub, Short idVendor, Short idProduct, String id) { // // TODO: Parse out --id=VVVV.PPPP[.N] and --device=[device path] // // if (id != null) { // int i = id.indexOf(':'); // if (i == 4) { // // this is an id on the form VVVV.PPPP // idVendor = (short) parseInt(id.substring(0, 4), 16); // idProduct = (short) parseInt(id.substring(5, 9), 16); // // id = null; // } // } // // if (id != null) { // // As this library is implemented with libusb which returns // // everything in a single, flat list for now just do this simple search. // // int index; // try { // index = parseInt(id); // } catch (NumberFormatException e) { // System.err.println("Invalid 'id' parameter, has to be an integer."); // return null; // } // // List<UsbDevice> devices = hub.getAttachedUsbDevices(); // // if (index >= devices.size() || index < 0) { // System.err.println("'id' parameter is out of range."); // return null; // } // // return devices.get(index); // } else if (idProduct != null && idVendor != null) { // UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); // // if (usbDevice == null) { // System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); // } // // return usbDevice; // } // return null; // }
import static java.lang.Byte.parseByte; import static javax.usb.UsbHostManager.*; import static io.trygvis.usb.tools.HexFormatter.writeBytes; import static io.trygvis.usb.tools.UsbCliUtil.findDevice; import javax.usb.*;
return; } UsbEndpointDescriptor outED = outEndpoint.getUsbEndpointDescriptor(); UsbEndpoint inEndpoint = usbInterface.getUsbEndpoint((byte) (0x80 | inEp)); if(inEndpoint == null) { System.err.println("Could not find in endpoint: " + inEp + "."); return; } UsbEndpointDescriptor inED = inEndpoint.getUsbEndpointDescriptor(); if(outED.wMaxPacketSize() != inED.wMaxPacketSize()) { System.err.println("The max packet size of out and in endpoint has to be equal."); return; } byte[] data = new byte[outED.wMaxPacketSize()]; UsbPipe outPipe = outEndpoint.getUsbPipe(); outPipe.open(); UsbPipe inPipe = inEndpoint.getUsbPipe(); inPipe.open(); int read = System.in.read(data); while (read != -1) { System.out.println("Sending " + read + " bytes...");
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/HexFormatter.java // public static void writeBytes(PrintStream print, byte[] bytes) { // writeBytes(print, bytes, 0, bytes.length); // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static UsbDevice findDevice(UsbHub hub, Short idVendor, Short idProduct, String id) { // // TODO: Parse out --id=VVVV.PPPP[.N] and --device=[device path] // // if (id != null) { // int i = id.indexOf(':'); // if (i == 4) { // // this is an id on the form VVVV.PPPP // idVendor = (short) parseInt(id.substring(0, 4), 16); // idProduct = (short) parseInt(id.substring(5, 9), 16); // // id = null; // } // } // // if (id != null) { // // As this library is implemented with libusb which returns // // everything in a single, flat list for now just do this simple search. // // int index; // try { // index = parseInt(id); // } catch (NumberFormatException e) { // System.err.println("Invalid 'id' parameter, has to be an integer."); // return null; // } // // List<UsbDevice> devices = hub.getAttachedUsbDevices(); // // if (index >= devices.size() || index < 0) { // System.err.println("'id' parameter is out of range."); // return null; // } // // return devices.get(index); // } else if (idProduct != null && idVendor != null) { // UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); // // if (usbDevice == null) { // System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); // } // // return usbDevice; // } // return null; // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbEcho.java import static java.lang.Byte.parseByte; import static javax.usb.UsbHostManager.*; import static io.trygvis.usb.tools.HexFormatter.writeBytes; import static io.trygvis.usb.tools.UsbCliUtil.findDevice; import javax.usb.*; return; } UsbEndpointDescriptor outED = outEndpoint.getUsbEndpointDescriptor(); UsbEndpoint inEndpoint = usbInterface.getUsbEndpoint((byte) (0x80 | inEp)); if(inEndpoint == null) { System.err.println("Could not find in endpoint: " + inEp + "."); return; } UsbEndpointDescriptor inED = inEndpoint.getUsbEndpointDescriptor(); if(outED.wMaxPacketSize() != inED.wMaxPacketSize()) { System.err.println("The max packet size of out and in endpoint has to be equal."); return; } byte[] data = new byte[outED.wMaxPacketSize()]; UsbPipe outPipe = outEndpoint.getUsbPipe(); outPipe.open(); UsbPipe inPipe = inEndpoint.getUsbPipe(); inPipe.open(); int read = System.in.read(data); while (read != -1) { System.out.println("Sending " + read + " bytes...");
writeBytes(System.out, data, 0, read);
trygvis/javax-usb-libusb1
javax.usb/src/main/java/javax/usb/util/DefaultUsbIrp.java
// Path: javax.usb/src/main/java/javax/usb/UsbException.java // public class UsbException extends Exception { // public UsbException() { // } // // public UsbException(String message) { // super(message); // } // } // // Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // }
import javax.usb.UsbException; import javax.usb.UsbIrp;
package javax.usb.util; public class DefaultUsbIrp implements UsbIrp { protected boolean acceptShortPacket; protected int actualLength; protected boolean complete; protected byte[] data; protected int length; protected int offset;
// Path: javax.usb/src/main/java/javax/usb/UsbException.java // public class UsbException extends Exception { // public UsbException() { // } // // public UsbException(String message) { // super(message); // } // } // // Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // Path: javax.usb/src/main/java/javax/usb/util/DefaultUsbIrp.java import javax.usb.UsbException; import javax.usb.UsbIrp; package javax.usb.util; public class DefaultUsbIrp implements UsbIrp { protected boolean acceptShortPacket; protected int actualLength; protected boolean complete; protected byte[] data; protected int length; protected int offset;
protected UsbException usbException;
trygvis/javax-usb-libusb1
usbtools/src/test/java/io/trygvis/usb/tools/HexFormatterTest.java
// Path: usbtools/src/main/java/io/trygvis/usb/tools/HexFormatter.java // public static void writeBytes(PrintStream print, byte[] bytes) { // writeBytes(print, bytes, 0, bytes.length); // }
import static io.trygvis.usb.tools.HexFormatter.writeBytes; import static org.junit.Assert.*; import org.junit.*; import java.io.*;
package io.trygvis.usb.tools; public class HexFormatterTest { static String EOL = System.getProperty("line.separator"); ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream print = new PrintStream(os); @Test public void testEmptyBuffer() {
// Path: usbtools/src/main/java/io/trygvis/usb/tools/HexFormatter.java // public static void writeBytes(PrintStream print, byte[] bytes) { // writeBytes(print, bytes, 0, bytes.length); // } // Path: usbtools/src/test/java/io/trygvis/usb/tools/HexFormatterTest.java import static io.trygvis.usb.tools.HexFormatter.writeBytes; import static org.junit.Assert.*; import org.junit.*; import java.io.*; package io.trygvis.usb.tools; public class HexFormatterTest { static String EOL = System.getProperty("line.separator"); ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream print = new PrintStream(os); @Test public void testEmptyBuffer() {
writeBytes(print, new byte[0]);
trygvis/javax-usb-libusb1
usbtools/src/main/java/io/trygvis/usb/tools/UsbWrite.java
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static UsbDevice findDevice(UsbHub hub, Short idVendor, Short idProduct, String id) { // // TODO: Parse out --id=VVVV.PPPP[.N] and --device=[device path] // // if (id != null) { // int i = id.indexOf(':'); // if (i == 4) { // // this is an id on the form VVVV.PPPP // idVendor = (short) parseInt(id.substring(0, 4), 16); // idProduct = (short) parseInt(id.substring(5, 9), 16); // // id = null; // } // } // // if (id != null) { // // As this library is implemented with libusb which returns // // everything in a single, flat list for now just do this simple search. // // int index; // try { // index = parseInt(id); // } catch (NumberFormatException e) { // System.err.println("Invalid 'id' parameter, has to be an integer."); // return null; // } // // List<UsbDevice> devices = hub.getAttachedUsbDevices(); // // if (index >= devices.size() || index < 0) { // System.err.println("'id' parameter is out of range."); // return null; // } // // return devices.get(index); // } else if (idProduct != null && idVendor != null) { // UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); // // if (usbDevice == null) { // System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); // } // // return usbDevice; // } // return null; // }
import static java.lang.Byte.parseByte; import static java.lang.Integer.parseInt; import static javax.usb.UsbHostManager.*; import static io.trygvis.usb.tools.UsbCliUtil.findDevice; import javax.usb.*;
package io.trygvis.usb.tools; /** * Stream an endpoint from stdin. */ public class UsbWrite { public static final short idVendor = 0x0547; public static final short idProduct = (short) 0xff01; public static void main(String[] args) throws Exception { String id = null; Byte endpointId = null; System.setProperty("javax.usb.libusb.trace", "true"); for (String arg : args) { if(arg.startsWith("--id=")) { id = arg.substring(5); } else if(arg.startsWith("--ep=")) { endpointId = parseByte(arg.substring(5)); } } if(id == null || endpointId == null) { System.err.println("Usage: --ep=<ep> --id=VVVV:PPPP"); return; }
// Path: javax.usb/src/main/java/javax/usb/UsbHostManager.java // public final class UsbHostManager { // // public static final String JAVAX_USB_USBSERVICES_PROPERTY = "javax.usb.services"; // // public static final String JAVAX_USB_PROPERTIES_FILE = "javax.usb.properties"; // // private static UsbServices usbServices; // // private final static Object lock = new Object(); // // private UsbHostManager() { // } // // public static UsbServices getUsbServices() throws UsbException, SecurityException { // synchronized (lock) { // if (usbServices == null) { // usbServices = initialize(); // } // return usbServices; // } // } // // private static UsbServices initialize() throws UsbException, SecurityException { // Properties properties = getProperties(); // // String services = properties.getProperty(JAVAX_USB_USBSERVICES_PROPERTY); // // if (services == null) { // throw new UsbException("Missing required property '" + JAVAX_USB_USBSERVICES_PROPERTY + "' from configuration file."); // } // // // TODO: Use the thread's current context class loader? // // Class<?> usbServicesClass; // // try { // usbServicesClass = UsbHostManager.class.getClassLoader().loadClass(services); // // return (UsbServices) usbServicesClass.newInstance(); // } catch (ClassNotFoundException e) { // throw new UsbPlatformException("Unable to load UsbServices class '" + services + "'.", e); // } catch (InstantiationException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (IllegalAccessException e) { // throw new UsbPlatformException("Unable to instantiate class '" + services + "'.", e); // } catch (ClassCastException e) { // throw new UsbPlatformException("Class " + services + " is not an instance of javax.usb.UsbServices."); // } // } // // public static Properties getProperties() throws UsbException, SecurityException { // InputStream stream = UsbHostManager.class.getClassLoader(). // getResourceAsStream(JAVAX_USB_PROPERTIES_FILE); // // if (stream == null) { // throw new UsbException("Unable to load configuration file '" + JAVAX_USB_PROPERTIES_FILE + "'."); // } // // Properties properties; // try { // properties = new Properties(); // properties.load(stream); // } catch (IOException e) { // throw new UsbPlatformException("Error while reading configuration file.", e); // } finally { // try { // stream.close(); // } catch (IOException e) { // // ignore // } // } // return properties; // } // } // // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbCliUtil.java // public static UsbDevice findDevice(UsbHub hub, Short idVendor, Short idProduct, String id) { // // TODO: Parse out --id=VVVV.PPPP[.N] and --device=[device path] // // if (id != null) { // int i = id.indexOf(':'); // if (i == 4) { // // this is an id on the form VVVV.PPPP // idVendor = (short) parseInt(id.substring(0, 4), 16); // idProduct = (short) parseInt(id.substring(5, 9), 16); // // id = null; // } // } // // if (id != null) { // // As this library is implemented with libusb which returns // // everything in a single, flat list for now just do this simple search. // // int index; // try { // index = parseInt(id); // } catch (NumberFormatException e) { // System.err.println("Invalid 'id' parameter, has to be an integer."); // return null; // } // // List<UsbDevice> devices = hub.getAttachedUsbDevices(); // // if (index >= devices.size() || index < 0) { // System.err.println("'id' parameter is out of range."); // return null; // } // // return devices.get(index); // } else if (idProduct != null && idVendor != null) { // UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct); // // if (usbDevice == null) { // System.err.println("Could not find device with id " + deviceIdToString(idVendor, idProduct) + "."); // } // // return usbDevice; // } // return null; // } // Path: usbtools/src/main/java/io/trygvis/usb/tools/UsbWrite.java import static java.lang.Byte.parseByte; import static java.lang.Integer.parseInt; import static javax.usb.UsbHostManager.*; import static io.trygvis.usb.tools.UsbCliUtil.findDevice; import javax.usb.*; package io.trygvis.usb.tools; /** * Stream an endpoint from stdin. */ public class UsbWrite { public static final short idVendor = 0x0547; public static final short idProduct = (short) 0xff01; public static void main(String[] args) throws Exception { String id = null; Byte endpointId = null; System.setProperty("javax.usb.libusb.trace", "true"); for (String arg : args) { if(arg.startsWith("--id=")) { id = arg.substring(5); } else if(arg.startsWith("--ep=")) { endpointId = parseByte(arg.substring(5)); } } if(id == null || endpointId == null) { System.err.println("Usage: --ep=<ep> --id=VVVV:PPPP"); return; }
UsbDevice device = findDevice(getUsbServices().getRootUsbHub(), idVendor, idProduct, id);
trygvis/javax-usb-libusb1
javax.usb/src/main/java/javax/usb/event/UsbPipeDataEvent.java
// Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // }
import javax.usb.UsbIrp; import javax.usb.UsbPipe;
package javax.usb.event; public class UsbPipeDataEvent extends UsbPipeEvent { private byte[] data; private int actualLength;
// Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // } // Path: javax.usb/src/main/java/javax/usb/event/UsbPipeDataEvent.java import javax.usb.UsbIrp; import javax.usb.UsbPipe; package javax.usb.event; public class UsbPipeDataEvent extends UsbPipeEvent { private byte[] data; private int actualLength;
public UsbPipeDataEvent(UsbPipe source, byte[] data, int actualLength) {
trygvis/javax-usb-libusb1
javax.usb/src/main/java/javax/usb/event/UsbPipeDataEvent.java
// Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // }
import javax.usb.UsbIrp; import javax.usb.UsbPipe;
package javax.usb.event; public class UsbPipeDataEvent extends UsbPipeEvent { private byte[] data; private int actualLength; public UsbPipeDataEvent(UsbPipe source, byte[] data, int actualLength) { super(source); this.data = data; this.actualLength = actualLength; }
// Path: javax.usb/src/main/java/javax/usb/UsbIrp.java // public interface UsbIrp { // void complete(); // // boolean getAcceptShortPacket(); // // int getActualLength(); // // byte[] getData(); // // int getLength(); // // int getOffset(); // // UsbException getUsbException(); // // boolean isComplete(); // // boolean isUsbException(); // // void setAcceptShortPacket(boolean accept); // // void setActualLength(int length); // // void setComplete(boolean complete); // // void setData(byte[] data); // // void setData(byte[] data, int offset, int length); // // void setLength(int length); // // void setOffset(int offset); // // void setUsbException(UsbException usbException); // // void waitUntilComplete(); // // void waitUntilComplete(long timeout); // } // // Path: javax.usb/src/main/java/javax/usb/UsbPipe.java // public interface UsbPipe { // void abortAllSubmissions() throws UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // void addUsbPipeListener(UsbPipeListener listener); // // UsbIrp asyncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(List list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void asyncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void close() throws UsbException, UsbNotActiveException, UsbNotOpenException, UsbDisconnectedException; // // UsbControlIrp createUsbControlIrp(byte bmRequestType, byte bRequest, short wValue, short wIndex); // // UsbIrp createUsbIrp(); // // UsbEndpoint getUsbEndpoint(); // // boolean isActive(); // // boolean isOpen(); // // void open() throws UsbException, UsbNotActiveException, UsbNotClaimedException, UsbDisconnectedException; // // void removeUsbPipeListener(UsbPipeListener listener); // // int syncSubmit(byte[] data) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(List<UsbIrp> list) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // // void syncSubmit(UsbIrp irp) throws UsbException, UsbNotActiveException, UsbNotOpenException, IllegalArgumentException, UsbDisconnectedException; // } // Path: javax.usb/src/main/java/javax/usb/event/UsbPipeDataEvent.java import javax.usb.UsbIrp; import javax.usb.UsbPipe; package javax.usb.event; public class UsbPipeDataEvent extends UsbPipeEvent { private byte[] data; private int actualLength; public UsbPipeDataEvent(UsbPipe source, byte[] data, int actualLength) { super(source); this.data = data; this.actualLength = actualLength; }
public UsbPipeDataEvent(UsbPipe source, UsbIrp usbIrp) {
achan/android-reddit
src/com/pocketreddit/library/authentication/LiveAuthenticator.java
// Path: src/com/pocketreddit/library/net/HttpHelper.java // public class HttpHelper { // private static final String TAG = HttpHelper.class.getName(); // private static final String SCHEME_SSL = "https"; // private static final int SCHEME_PORT_SSL = 443; // // private static HttpHelper instance; // // private HttpHelper() { // } // // public static HttpHelper getInstance() { // if (instance == null) // instance = new HttpHelper(); // // return instance; // } // // public JSONObject getJsonObjectFromGet(String uri, List<Cookie> cookies) throws NetException { // HttpClient client = buildHttpClient(cookies); // // try { // return getJsonObjectFromResponse(client.execute(new HttpGet(uri))); // } catch (Exception e) { // throw new NetException("Error while parsing GET response from " + uri // + " into JSON object: " + e.getMessage(), e); // } // } // // private HttpClient buildHttpClient(List<Cookie> cookies) { // DefaultHttpClient client = new DefaultHttpClient(); // // String userAgent = System.getProperty(Constants.SYSTEM_PROPERTY_USER_AGENT); // // if (userAgent != null) // client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent); // // if (cookies != null && !cookies.isEmpty()) { // client.setCookieStore(buildCookieStore(cookies)); // } // // return client; // } // // private CookieStore buildCookieStore(List<Cookie> cookies) { // Cookie[] cookieArray = new Cookie[cookies.size()]; // return buildCookieStore(cookies.toArray(cookieArray)); // } // // private CookieStore buildCookieStore(Cookie... cookies) { // CookieStore cookieStore = new BasicCookieStore(); // for (Cookie cookie : cookies) { // cookieStore.addCookie(cookie); // } // // return cookieStore; // } // // private JSONArray getJsonArrayFromResponse(HttpResponse response) throws IllegalStateException, // JSONException, IOException, UtilsException { // return new JSONArray(responseToString(response)); // } // // private String responseToString(HttpResponse response) throws IOException, // IllegalStateException, UtilsException { // InputStream is = null; // try { // is = response.getEntity().getContent(); // String content = StreamUtils.getInstance().convertStreamToString(is); // // String contentSnippet; // if (content.length() > 250) { // contentSnippet = content.substring(0, 100) + "###SNIPPET###" // + content.substring(content.length() - 100); // } else { // contentSnippet = content; // } // // Log.v(TAG, "stream content: " + contentSnippet); // return content; // } finally { // if (is != null) // is.close(); // } // } // // private JSONObject getJsonObjectFromResponse(HttpResponse response) // throws IllegalStateException, IOException, JSONException, UtilsException { // return new JSONObject(responseToString(response)); // } // // public JSONArray getJsonArrayFromGet(String uri, List<Cookie> cookies) throws NetException { // HttpClient client = buildHttpClient(cookies); // // try { // return getJsonArrayFromResponse(client.execute(new HttpGet(uri))); // } catch (Exception e) { // throw new NetException("Could not parse response into JSON array.", e); // } // } // // public JSONArray getJsonArrayFromGet(String uri) throws NetException { // return getJsonArrayFromGet(uri, null); // } // // public JSONObject getJsonObjectFromGet(String uri) throws NetException { // return getJsonObjectFromGet(uri, null); // } // // public JSONObject getJsonObjectFromPost(URI uri, List<NameValuePair> params) // throws NetException { // return getJsonObjectFromPost(uri, params, null); // } // // public JSONObject getJsonObjectFromPost(URI uri, List<NameValuePair> params, // List<Cookie> cookies) throws NetException { // HttpClient httpClient = buildHttpClient(cookies); // // if (SCHEME_SSL.equals(uri.getScheme())) { // HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; // // SchemeRegistry registry = new SchemeRegistry(); // SSLSocketFactory sslFactory = SSLSocketFactory.getSocketFactory(); // sslFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); // registry.register(new Scheme(SCHEME_SSL, sslFactory, SCHEME_PORT_SSL)); // SingleClientConnManager connectManager = new SingleClientConnManager( // httpClient.getParams(), registry); // // httpClient = new DefaultHttpClient(connectManager, httpClient.getParams()); // HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); // } // // HttpPost post = new HttpPost(uri); // // try { // post.setEntity(new UrlEncodedFormEntity(params)); // return getJsonObjectFromResponse(httpClient.execute(post)); // } catch (Exception e) { // throw new NetException("Error while parsing POST response from " + uri // + " into JSON object.", e); // } // } // }
import java.net.URI; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import android.util.Log; import com.pocketreddit.library.net.HttpHelper;
package com.pocketreddit.library.authentication; public class LiveAuthenticator implements Authenticator { private static final String TAG = LiveAuthenticator.class.getName(); private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; private static final String PARAM_USERNAME = "user"; private static final String PARAM_PASSWORD = "passwd"; private static final String PARAM_API_TYPE = "api_type"; private static final String API_TYPE_JSON = "json"; public LoginResult authenticate(String username, String password) throws AuthenticationException { try {
// Path: src/com/pocketreddit/library/net/HttpHelper.java // public class HttpHelper { // private static final String TAG = HttpHelper.class.getName(); // private static final String SCHEME_SSL = "https"; // private static final int SCHEME_PORT_SSL = 443; // // private static HttpHelper instance; // // private HttpHelper() { // } // // public static HttpHelper getInstance() { // if (instance == null) // instance = new HttpHelper(); // // return instance; // } // // public JSONObject getJsonObjectFromGet(String uri, List<Cookie> cookies) throws NetException { // HttpClient client = buildHttpClient(cookies); // // try { // return getJsonObjectFromResponse(client.execute(new HttpGet(uri))); // } catch (Exception e) { // throw new NetException("Error while parsing GET response from " + uri // + " into JSON object: " + e.getMessage(), e); // } // } // // private HttpClient buildHttpClient(List<Cookie> cookies) { // DefaultHttpClient client = new DefaultHttpClient(); // // String userAgent = System.getProperty(Constants.SYSTEM_PROPERTY_USER_AGENT); // // if (userAgent != null) // client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent); // // if (cookies != null && !cookies.isEmpty()) { // client.setCookieStore(buildCookieStore(cookies)); // } // // return client; // } // // private CookieStore buildCookieStore(List<Cookie> cookies) { // Cookie[] cookieArray = new Cookie[cookies.size()]; // return buildCookieStore(cookies.toArray(cookieArray)); // } // // private CookieStore buildCookieStore(Cookie... cookies) { // CookieStore cookieStore = new BasicCookieStore(); // for (Cookie cookie : cookies) { // cookieStore.addCookie(cookie); // } // // return cookieStore; // } // // private JSONArray getJsonArrayFromResponse(HttpResponse response) throws IllegalStateException, // JSONException, IOException, UtilsException { // return new JSONArray(responseToString(response)); // } // // private String responseToString(HttpResponse response) throws IOException, // IllegalStateException, UtilsException { // InputStream is = null; // try { // is = response.getEntity().getContent(); // String content = StreamUtils.getInstance().convertStreamToString(is); // // String contentSnippet; // if (content.length() > 250) { // contentSnippet = content.substring(0, 100) + "###SNIPPET###" // + content.substring(content.length() - 100); // } else { // contentSnippet = content; // } // // Log.v(TAG, "stream content: " + contentSnippet); // return content; // } finally { // if (is != null) // is.close(); // } // } // // private JSONObject getJsonObjectFromResponse(HttpResponse response) // throws IllegalStateException, IOException, JSONException, UtilsException { // return new JSONObject(responseToString(response)); // } // // public JSONArray getJsonArrayFromGet(String uri, List<Cookie> cookies) throws NetException { // HttpClient client = buildHttpClient(cookies); // // try { // return getJsonArrayFromResponse(client.execute(new HttpGet(uri))); // } catch (Exception e) { // throw new NetException("Could not parse response into JSON array.", e); // } // } // // public JSONArray getJsonArrayFromGet(String uri) throws NetException { // return getJsonArrayFromGet(uri, null); // } // // public JSONObject getJsonObjectFromGet(String uri) throws NetException { // return getJsonObjectFromGet(uri, null); // } // // public JSONObject getJsonObjectFromPost(URI uri, List<NameValuePair> params) // throws NetException { // return getJsonObjectFromPost(uri, params, null); // } // // public JSONObject getJsonObjectFromPost(URI uri, List<NameValuePair> params, // List<Cookie> cookies) throws NetException { // HttpClient httpClient = buildHttpClient(cookies); // // if (SCHEME_SSL.equals(uri.getScheme())) { // HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; // // SchemeRegistry registry = new SchemeRegistry(); // SSLSocketFactory sslFactory = SSLSocketFactory.getSocketFactory(); // sslFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); // registry.register(new Scheme(SCHEME_SSL, sslFactory, SCHEME_PORT_SSL)); // SingleClientConnManager connectManager = new SingleClientConnManager( // httpClient.getParams(), registry); // // httpClient = new DefaultHttpClient(connectManager, httpClient.getParams()); // HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); // } // // HttpPost post = new HttpPost(uri); // // try { // post.setEntity(new UrlEncodedFormEntity(params)); // return getJsonObjectFromResponse(httpClient.execute(post)); // } catch (Exception e) { // throw new NetException("Error while parsing POST response from " + uri // + " into JSON object.", e); // } // } // } // Path: src/com/pocketreddit/library/authentication/LiveAuthenticator.java import java.net.URI; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import android.util.Log; import com.pocketreddit.library.net.HttpHelper; package com.pocketreddit.library.authentication; public class LiveAuthenticator implements Authenticator { private static final String TAG = LiveAuthenticator.class.getName(); private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; private static final String PARAM_USERNAME = "user"; private static final String PARAM_PASSWORD = "passwd"; private static final String PARAM_API_TYPE = "api_type"; private static final String API_TYPE_JSON = "json"; public LoginResult authenticate(String username, String password) throws AuthenticationException { try {
return new LoginResult(HttpHelper.getInstance().getJsonObjectFromPost(
achan/android-reddit
src/com/pocketreddit/library/things/Link.java
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/UserSubmittedContent.java // public abstract class UserSubmittedContent extends Thing implements Created, Votable { // private static final long serialVersionUID = 1L; // // private String id; // private int upvotes; // private int downvotes; // private Boolean liked; // private double created; // private double createdUtc; // private String name; // // private String author; // private String authorFlairCssClass; // private String authorFlairText; // private String body; // private String bodyHtml; // private boolean edited; // private int numReports; // // private Subreddit subreddit; // // public int getUpvotes() { // return upvotes; // } // // public int getDownvotes() { // return downvotes; // } // // public Boolean isLiked() { // return liked; // } // // public double getCreated() { // // TODO Auto-generated method stub // return created; // } // // public double getCreatedUtc() { // return createdUtc; // } // // public Subreddit getSubreddit() { // return subreddit; // } // // public void setSubreddit(Subreddit subreddit) { // this.subreddit = subreddit; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getAuthorFlairCssClass() { // return authorFlairCssClass; // } // // public void setAuthorFlairCssClass(String authorFlairCssClass) { // this.authorFlairCssClass = authorFlairCssClass; // } // // public String getAuthorFlairText() { // return authorFlairText; // } // // public void setAuthorFlairText(String authorFlairText) { // this.authorFlairText = authorFlairText; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getBodyHtml() { // return bodyHtml; // } // // public void setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // } // // public boolean isEdited() { // return edited; // } // // public void setEdited(boolean edited) { // this.edited = edited; // } // // public void setCreated(double created) { // this.created = created; // } // // public void setCreatedUtc(double createdUtc) { // this.createdUtc = createdUtc; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public void setDownvotes(int downvotes) { // this.downvotes = downvotes; // } // // public Boolean getLiked() { // return liked; // } // // public void setLiked(Boolean liked) { // this.liked = liked; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public int getNumReports() { // return numReports; // } // // public void setNumReports(int numReports) { // this.numReports = numReports; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/com/pocketreddit/library/JsonParsingException.java // public class JsonParsingException extends Exception { // private static final long serialVersionUID = 1L; // // public JsonParsingException(String message, Throwable throwable) { // super(message, throwable); // } // // public JsonParsingException(String message) { // super(message); // } // // public JsonParsingException(JSONException e) { // super(e); // } // }
import java.net.URL; import org.json.JSONObject; import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.UserSubmittedContent; import com.pocketreddit.library.JsonParsingException;
package com.pocketreddit.library.things; public class Link extends UserSubmittedContent { private static final long serialVersionUID = 1L; private boolean clicked; private String domain; private boolean hidden; private boolean selfPost; private Object media; private Object mediaEmbed; private int numComments; private boolean over18; private String permalink; private boolean saved; private int score; private URL thumbnail; private String title; private String url; private String modHash; public Link() { }
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/UserSubmittedContent.java // public abstract class UserSubmittedContent extends Thing implements Created, Votable { // private static final long serialVersionUID = 1L; // // private String id; // private int upvotes; // private int downvotes; // private Boolean liked; // private double created; // private double createdUtc; // private String name; // // private String author; // private String authorFlairCssClass; // private String authorFlairText; // private String body; // private String bodyHtml; // private boolean edited; // private int numReports; // // private Subreddit subreddit; // // public int getUpvotes() { // return upvotes; // } // // public int getDownvotes() { // return downvotes; // } // // public Boolean isLiked() { // return liked; // } // // public double getCreated() { // // TODO Auto-generated method stub // return created; // } // // public double getCreatedUtc() { // return createdUtc; // } // // public Subreddit getSubreddit() { // return subreddit; // } // // public void setSubreddit(Subreddit subreddit) { // this.subreddit = subreddit; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getAuthorFlairCssClass() { // return authorFlairCssClass; // } // // public void setAuthorFlairCssClass(String authorFlairCssClass) { // this.authorFlairCssClass = authorFlairCssClass; // } // // public String getAuthorFlairText() { // return authorFlairText; // } // // public void setAuthorFlairText(String authorFlairText) { // this.authorFlairText = authorFlairText; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getBodyHtml() { // return bodyHtml; // } // // public void setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // } // // public boolean isEdited() { // return edited; // } // // public void setEdited(boolean edited) { // this.edited = edited; // } // // public void setCreated(double created) { // this.created = created; // } // // public void setCreatedUtc(double createdUtc) { // this.createdUtc = createdUtc; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public void setDownvotes(int downvotes) { // this.downvotes = downvotes; // } // // public Boolean getLiked() { // return liked; // } // // public void setLiked(Boolean liked) { // this.liked = liked; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public int getNumReports() { // return numReports; // } // // public void setNumReports(int numReports) { // this.numReports = numReports; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/com/pocketreddit/library/JsonParsingException.java // public class JsonParsingException extends Exception { // private static final long serialVersionUID = 1L; // // public JsonParsingException(String message, Throwable throwable) { // super(message, throwable); // } // // public JsonParsingException(String message) { // super(message); // } // // public JsonParsingException(JSONException e) { // super(e); // } // } // Path: src/com/pocketreddit/library/things/Link.java import java.net.URL; import org.json.JSONObject; import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.UserSubmittedContent; import com.pocketreddit.library.JsonParsingException; package com.pocketreddit.library.things; public class Link extends UserSubmittedContent { private static final long serialVersionUID = 1L; private boolean clicked; private String domain; private boolean hidden; private boolean selfPost; private Object media; private Object mediaEmbed; private int numComments; private boolean over18; private String permalink; private boolean saved; private int score; private URL thumbnail; private String title; private String url; private String modHash; public Link() { }
public Link(JSONObject json) throws JsonParsingException {
achan/android-reddit
src/com/pocketreddit/library/things/Link.java
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/UserSubmittedContent.java // public abstract class UserSubmittedContent extends Thing implements Created, Votable { // private static final long serialVersionUID = 1L; // // private String id; // private int upvotes; // private int downvotes; // private Boolean liked; // private double created; // private double createdUtc; // private String name; // // private String author; // private String authorFlairCssClass; // private String authorFlairText; // private String body; // private String bodyHtml; // private boolean edited; // private int numReports; // // private Subreddit subreddit; // // public int getUpvotes() { // return upvotes; // } // // public int getDownvotes() { // return downvotes; // } // // public Boolean isLiked() { // return liked; // } // // public double getCreated() { // // TODO Auto-generated method stub // return created; // } // // public double getCreatedUtc() { // return createdUtc; // } // // public Subreddit getSubreddit() { // return subreddit; // } // // public void setSubreddit(Subreddit subreddit) { // this.subreddit = subreddit; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getAuthorFlairCssClass() { // return authorFlairCssClass; // } // // public void setAuthorFlairCssClass(String authorFlairCssClass) { // this.authorFlairCssClass = authorFlairCssClass; // } // // public String getAuthorFlairText() { // return authorFlairText; // } // // public void setAuthorFlairText(String authorFlairText) { // this.authorFlairText = authorFlairText; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getBodyHtml() { // return bodyHtml; // } // // public void setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // } // // public boolean isEdited() { // return edited; // } // // public void setEdited(boolean edited) { // this.edited = edited; // } // // public void setCreated(double created) { // this.created = created; // } // // public void setCreatedUtc(double createdUtc) { // this.createdUtc = createdUtc; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public void setDownvotes(int downvotes) { // this.downvotes = downvotes; // } // // public Boolean getLiked() { // return liked; // } // // public void setLiked(Boolean liked) { // this.liked = liked; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public int getNumReports() { // return numReports; // } // // public void setNumReports(int numReports) { // this.numReports = numReports; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/com/pocketreddit/library/JsonParsingException.java // public class JsonParsingException extends Exception { // private static final long serialVersionUID = 1L; // // public JsonParsingException(String message, Throwable throwable) { // super(message, throwable); // } // // public JsonParsingException(String message) { // super(message); // } // // public JsonParsingException(JSONException e) { // super(e); // } // }
import java.net.URL; import org.json.JSONObject; import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.UserSubmittedContent; import com.pocketreddit.library.JsonParsingException;
public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "Link [clicked=" + clicked + ", domain=" + domain + ", hidden=" + hidden + ", selfPost=" + selfPost + ", media=" + media + ", mediaEmbed=" + mediaEmbed + ", numComments=" + numComments + ", over18=" + over18 + ", permalink=" + permalink + ", saved=" + saved + ", score=" + score + ", thumbnail=" + thumbnail + ", title=" + title + ", url=" + url + ", modHash=" + modHash + "]"; } public String getModHash() { return modHash; } public void setModHash(String modHash) { this.modHash = modHash; } @Override
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/UserSubmittedContent.java // public abstract class UserSubmittedContent extends Thing implements Created, Votable { // private static final long serialVersionUID = 1L; // // private String id; // private int upvotes; // private int downvotes; // private Boolean liked; // private double created; // private double createdUtc; // private String name; // // private String author; // private String authorFlairCssClass; // private String authorFlairText; // private String body; // private String bodyHtml; // private boolean edited; // private int numReports; // // private Subreddit subreddit; // // public int getUpvotes() { // return upvotes; // } // // public int getDownvotes() { // return downvotes; // } // // public Boolean isLiked() { // return liked; // } // // public double getCreated() { // // TODO Auto-generated method stub // return created; // } // // public double getCreatedUtc() { // return createdUtc; // } // // public Subreddit getSubreddit() { // return subreddit; // } // // public void setSubreddit(Subreddit subreddit) { // this.subreddit = subreddit; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getAuthorFlairCssClass() { // return authorFlairCssClass; // } // // public void setAuthorFlairCssClass(String authorFlairCssClass) { // this.authorFlairCssClass = authorFlairCssClass; // } // // public String getAuthorFlairText() { // return authorFlairText; // } // // public void setAuthorFlairText(String authorFlairText) { // this.authorFlairText = authorFlairText; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getBodyHtml() { // return bodyHtml; // } // // public void setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // } // // public boolean isEdited() { // return edited; // } // // public void setEdited(boolean edited) { // this.edited = edited; // } // // public void setCreated(double created) { // this.created = created; // } // // public void setCreatedUtc(double createdUtc) { // this.createdUtc = createdUtc; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public void setDownvotes(int downvotes) { // this.downvotes = downvotes; // } // // public Boolean getLiked() { // return liked; // } // // public void setLiked(Boolean liked) { // this.liked = liked; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public int getNumReports() { // return numReports; // } // // public void setNumReports(int numReports) { // this.numReports = numReports; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/com/pocketreddit/library/JsonParsingException.java // public class JsonParsingException extends Exception { // private static final long serialVersionUID = 1L; // // public JsonParsingException(String message, Throwable throwable) { // super(message, throwable); // } // // public JsonParsingException(String message) { // super(message); // } // // public JsonParsingException(JSONException e) { // super(e); // } // } // Path: src/com/pocketreddit/library/things/Link.java import java.net.URL; import org.json.JSONObject; import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.UserSubmittedContent; import com.pocketreddit.library.JsonParsingException; public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "Link [clicked=" + clicked + ", domain=" + domain + ", hidden=" + hidden + ", selfPost=" + selfPost + ", media=" + media + ", mediaEmbed=" + mediaEmbed + ", numComments=" + numComments + ", over18=" + over18 + ", permalink=" + permalink + ", saved=" + saved + ", score=" + score + ", thumbnail=" + thumbnail + ", title=" + title + ", url=" + url + ", modHash=" + modHash + "]"; } public String getModHash() { return modHash; } public void setModHash(String modHash) { this.modHash = modHash; } @Override
public Kind getKind() {
achan/android-reddit
src/com/pocketreddit/library/things/Listing.java
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // }
import java.util.List; import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.Thing;
public void setChildren(List<T> children) { this.children = children; } public String getBefore() { return before; } public void setBefore(String before) { this.before = before; } public String getAfter() { return after; } public void setAfter(String after) { this.after = after; } public String getModHash() { return modHash; } public void setModHash(String modHash) { this.modHash = modHash; } @Override
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // Path: src/com/pocketreddit/library/things/Listing.java import java.util.List; import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.Thing; public void setChildren(List<T> children) { this.children = children; } public String getBefore() { return before; } public void setBefore(String before) { this.before = before; } public String getAfter() { return after; } public void setAfter(String after) { this.after = after; } public String getModHash() { return modHash; } public void setModHash(String modHash) { this.modHash = modHash; } @Override
public Kind getKind() {
achan/android-reddit
tests/src/com/pocketreddit/library/authentication/TestLoginResult.java
// Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // }
import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log;
package com.pocketreddit.library.authentication; public class TestLoginResult extends AndroidTestCase { private static final String TAG = TestLoginResult.class.getName(); private final String successfulLoginJson = "{\"json\": {\"errors\": [], \"data\": {\"modhash\": \"7l7jf0fzvt9556d747b9ef00409e1a90d2fbdc328cd26b599b\", \"cookie\": \"13829964,2012-07-05T10:56:57,3acfec8427be44b0b90970d59a56e1b50ff74adf\"}}}"; private final String badPasswordJson = "{\"json\": {\"errors\": [[\"WRONG_PASSWORD\", \"invalid password\", \"passwd\"]]}}"; public void testLoginResultFromSuccess() { try {
// Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // } // Path: tests/src/com/pocketreddit/library/authentication/TestLoginResult.java import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log; package com.pocketreddit.library.authentication; public class TestLoginResult extends AndroidTestCase { private static final String TAG = TestLoginResult.class.getName(); private final String successfulLoginJson = "{\"json\": {\"errors\": [], \"data\": {\"modhash\": \"7l7jf0fzvt9556d747b9ef00409e1a90d2fbdc328cd26b599b\", \"cookie\": \"13829964,2012-07-05T10:56:57,3acfec8427be44b0b90970d59a56e1b50ff74adf\"}}}"; private final String badPasswordJson = "{\"json\": {\"errors\": [[\"WRONG_PASSWORD\", \"invalid password\", \"passwd\"]]}}"; public void testLoginResultFromSuccess() { try {
LoginResult login = new LoginResult(successfulLoginJson);
achan/android-reddit
src/com/pocketreddit/library/things/factories/ListingFactory.java
// Path: src/com/pocketreddit/library/things/Listing.java // public class Listing<T extends Thing> extends Thing { // private static final long serialVersionUID = 1L; // // /** // * A list of things that this Listing wraps. // */ // private List<T> children; // // /** // * The full name of the listing that precedes this page. Null, if there is // * no previous. // */ // private String before; // // /** // * The fullname of the listing that follows after this page. null if there // * is no next page. // */ // private String after; // // /** // * This modhash is not the same modhash provided upon login. You do not need // * to update your user's modhash everytime you get a new modhash. You can // * reuse the modhash given upon login. // */ // private String modHash; // // public List<T> getChildren() { // return children; // } // // public void setChildren(List<T> children) { // this.children = children; // } // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // @Override // public Kind getKind() { // return Kind.LISTING; // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: src/com/pocketreddit/library/things/utils/JsonToThingConverter.java // public class JsonToThingConverter<T extends Thing> { // public JsonToThingConverter() { // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public T convert(JSONObject json) throws ThingFactoryException { // Kind kind; // try { // kind = Kind.toKind(json.getString("kind")); // } catch (JSONException e) { // throw new ThingFactoryException( // "An error occurred trying to parse the kind of thing in provided json", e); // } // // ThingFactory thingFactory = null; // // switch (kind) { // case SUBREDDIT: // thingFactory = new SubredditFactory(json); // break; // case LISTING: // thingFactory = new ListingFactory(json); // break; // case THREAD: // try { // thingFactory = json.getJSONObject("data").isNull("domain") ? new CommentFactory( // json) : new LinkFactory(json); // } catch (JSONException e) { // throw new ThingFactoryException("Could not parse data for Thread thing.", e); // } // break; // case COMMENT: // thingFactory = new CommentFactory(json); // break; // case MORE: // return (T) new More(); // default: // throw new UnsupportedOperationException("Kind: " + kind // + " conversion not yet supported."); // } // // return (T) thingFactory.createThing(); // } // }
import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Listing; import com.pocketreddit.library.things.Thing; import com.pocketreddit.library.things.utils.JsonToThingConverter;
package com.pocketreddit.library.things.factories; public class ListingFactory<T extends Thing> implements ThingFactory { private JSONObject json; public ListingFactory(JSONObject json) { this.json = json; }
// Path: src/com/pocketreddit/library/things/Listing.java // public class Listing<T extends Thing> extends Thing { // private static final long serialVersionUID = 1L; // // /** // * A list of things that this Listing wraps. // */ // private List<T> children; // // /** // * The full name of the listing that precedes this page. Null, if there is // * no previous. // */ // private String before; // // /** // * The fullname of the listing that follows after this page. null if there // * is no next page. // */ // private String after; // // /** // * This modhash is not the same modhash provided upon login. You do not need // * to update your user's modhash everytime you get a new modhash. You can // * reuse the modhash given upon login. // */ // private String modHash; // // public List<T> getChildren() { // return children; // } // // public void setChildren(List<T> children) { // this.children = children; // } // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // @Override // public Kind getKind() { // return Kind.LISTING; // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: src/com/pocketreddit/library/things/utils/JsonToThingConverter.java // public class JsonToThingConverter<T extends Thing> { // public JsonToThingConverter() { // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public T convert(JSONObject json) throws ThingFactoryException { // Kind kind; // try { // kind = Kind.toKind(json.getString("kind")); // } catch (JSONException e) { // throw new ThingFactoryException( // "An error occurred trying to parse the kind of thing in provided json", e); // } // // ThingFactory thingFactory = null; // // switch (kind) { // case SUBREDDIT: // thingFactory = new SubredditFactory(json); // break; // case LISTING: // thingFactory = new ListingFactory(json); // break; // case THREAD: // try { // thingFactory = json.getJSONObject("data").isNull("domain") ? new CommentFactory( // json) : new LinkFactory(json); // } catch (JSONException e) { // throw new ThingFactoryException("Could not parse data for Thread thing.", e); // } // break; // case COMMENT: // thingFactory = new CommentFactory(json); // break; // case MORE: // return (T) new More(); // default: // throw new UnsupportedOperationException("Kind: " + kind // + " conversion not yet supported."); // } // // return (T) thingFactory.createThing(); // } // } // Path: src/com/pocketreddit/library/things/factories/ListingFactory.java import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Listing; import com.pocketreddit.library.things.Thing; import com.pocketreddit.library.things.utils.JsonToThingConverter; package com.pocketreddit.library.things.factories; public class ListingFactory<T extends Thing> implements ThingFactory { private JSONObject json; public ListingFactory(JSONObject json) { this.json = json; }
public Listing<T> createThing() throws ThingFactoryException {
achan/android-reddit
src/com/pocketreddit/library/things/factories/ListingFactory.java
// Path: src/com/pocketreddit/library/things/Listing.java // public class Listing<T extends Thing> extends Thing { // private static final long serialVersionUID = 1L; // // /** // * A list of things that this Listing wraps. // */ // private List<T> children; // // /** // * The full name of the listing that precedes this page. Null, if there is // * no previous. // */ // private String before; // // /** // * The fullname of the listing that follows after this page. null if there // * is no next page. // */ // private String after; // // /** // * This modhash is not the same modhash provided upon login. You do not need // * to update your user's modhash everytime you get a new modhash. You can // * reuse the modhash given upon login. // */ // private String modHash; // // public List<T> getChildren() { // return children; // } // // public void setChildren(List<T> children) { // this.children = children; // } // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // @Override // public Kind getKind() { // return Kind.LISTING; // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: src/com/pocketreddit/library/things/utils/JsonToThingConverter.java // public class JsonToThingConverter<T extends Thing> { // public JsonToThingConverter() { // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public T convert(JSONObject json) throws ThingFactoryException { // Kind kind; // try { // kind = Kind.toKind(json.getString("kind")); // } catch (JSONException e) { // throw new ThingFactoryException( // "An error occurred trying to parse the kind of thing in provided json", e); // } // // ThingFactory thingFactory = null; // // switch (kind) { // case SUBREDDIT: // thingFactory = new SubredditFactory(json); // break; // case LISTING: // thingFactory = new ListingFactory(json); // break; // case THREAD: // try { // thingFactory = json.getJSONObject("data").isNull("domain") ? new CommentFactory( // json) : new LinkFactory(json); // } catch (JSONException e) { // throw new ThingFactoryException("Could not parse data for Thread thing.", e); // } // break; // case COMMENT: // thingFactory = new CommentFactory(json); // break; // case MORE: // return (T) new More(); // default: // throw new UnsupportedOperationException("Kind: " + kind // + " conversion not yet supported."); // } // // return (T) thingFactory.createThing(); // } // }
import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Listing; import com.pocketreddit.library.things.Thing; import com.pocketreddit.library.things.utils.JsonToThingConverter;
package com.pocketreddit.library.things.factories; public class ListingFactory<T extends Thing> implements ThingFactory { private JSONObject json; public ListingFactory(JSONObject json) { this.json = json; } public Listing<T> createThing() throws ThingFactoryException { Listing<T> listing = new Listing<T>(); List<T> children = new ArrayList<T>(); try { JSONObject data = json.getJSONObject("data"); JSONArray jsonChildren = data.getJSONArray("children"); for (int i = 0; i < jsonChildren.length(); i++) {
// Path: src/com/pocketreddit/library/things/Listing.java // public class Listing<T extends Thing> extends Thing { // private static final long serialVersionUID = 1L; // // /** // * A list of things that this Listing wraps. // */ // private List<T> children; // // /** // * The full name of the listing that precedes this page. Null, if there is // * no previous. // */ // private String before; // // /** // * The fullname of the listing that follows after this page. null if there // * is no next page. // */ // private String after; // // /** // * This modhash is not the same modhash provided upon login. You do not need // * to update your user's modhash everytime you get a new modhash. You can // * reuse the modhash given upon login. // */ // private String modHash; // // public List<T> getChildren() { // return children; // } // // public void setChildren(List<T> children) { // this.children = children; // } // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // @Override // public Kind getKind() { // return Kind.LISTING; // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: src/com/pocketreddit/library/things/utils/JsonToThingConverter.java // public class JsonToThingConverter<T extends Thing> { // public JsonToThingConverter() { // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public T convert(JSONObject json) throws ThingFactoryException { // Kind kind; // try { // kind = Kind.toKind(json.getString("kind")); // } catch (JSONException e) { // throw new ThingFactoryException( // "An error occurred trying to parse the kind of thing in provided json", e); // } // // ThingFactory thingFactory = null; // // switch (kind) { // case SUBREDDIT: // thingFactory = new SubredditFactory(json); // break; // case LISTING: // thingFactory = new ListingFactory(json); // break; // case THREAD: // try { // thingFactory = json.getJSONObject("data").isNull("domain") ? new CommentFactory( // json) : new LinkFactory(json); // } catch (JSONException e) { // throw new ThingFactoryException("Could not parse data for Thread thing.", e); // } // break; // case COMMENT: // thingFactory = new CommentFactory(json); // break; // case MORE: // return (T) new More(); // default: // throw new UnsupportedOperationException("Kind: " + kind // + " conversion not yet supported."); // } // // return (T) thingFactory.createThing(); // } // } // Path: src/com/pocketreddit/library/things/factories/ListingFactory.java import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Listing; import com.pocketreddit.library.things.Thing; import com.pocketreddit.library.things.utils.JsonToThingConverter; package com.pocketreddit.library.things.factories; public class ListingFactory<T extends Thing> implements ThingFactory { private JSONObject json; public ListingFactory(JSONObject json) { this.json = json; } public Listing<T> createThing() throws ThingFactoryException { Listing<T> listing = new Listing<T>(); List<T> children = new ArrayList<T>(); try { JSONObject data = json.getJSONObject("data"); JSONArray jsonChildren = data.getJSONArray("children"); for (int i = 0; i < jsonChildren.length(); i++) {
JsonToThingConverter<T> converter = new JsonToThingConverter<T>();
achan/android-reddit
src/com/pocketreddit/library/things/UserSubmittedContent.java
// Path: src/com/pocketreddit/library/things/Subreddit.java // public class Subreddit extends Thing { // private static final long serialVersionUID = 1L; // // private String title; // private String id; // private String description; // private String displayName; // private boolean over18; // private long numSubscribers; // // // private static String CLASS_NAME = Subreddit.class.getSimpleName(); // // /** // * The relative URL of the subreddit. Ex: "/r/pics/" // */ // private String url; // // @Override // public String toString() { // return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url // + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " // + title + "\nid: " + id + "\n=====\n"; // } // // @Override // public Kind getKind() { // return Kind.SUBREDDIT; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSubredditId() { // return id; // } // // public void setSubredditId(String subredditId) { // this.id = subredditId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public long getNumSubscribers() { // return numSubscribers; // } // // public void setNumSubscribers(long numSubscribers) { // this.numSubscribers = numSubscribers; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: src/com/pocketreddit/library/Created.java // public interface Created { // public double getCreated(); // public double getCreatedUtc(); // } // // Path: src/com/pocketreddit/library/Votable.java // public interface Votable { // public int getUpvotes(); // // public int getDownvotes(); // // /** // * @return true if thing is liked by the user. false if thing is disliked. // * null if the user is neutral on the thing. // */ // public Boolean isLiked(); // }
import com.pocketreddit.library.things.Subreddit; import com.pocketreddit.library.things.Thing; import com.pocketreddit.library.Created; import com.pocketreddit.library.Votable;
package com.pocketreddit.library.things; public abstract class UserSubmittedContent extends Thing implements Created, Votable { private static final long serialVersionUID = 1L; private String id; private int upvotes; private int downvotes; private Boolean liked; private double created; private double createdUtc; private String name; private String author; private String authorFlairCssClass; private String authorFlairText; private String body; private String bodyHtml; private boolean edited; private int numReports;
// Path: src/com/pocketreddit/library/things/Subreddit.java // public class Subreddit extends Thing { // private static final long serialVersionUID = 1L; // // private String title; // private String id; // private String description; // private String displayName; // private boolean over18; // private long numSubscribers; // // // private static String CLASS_NAME = Subreddit.class.getSimpleName(); // // /** // * The relative URL of the subreddit. Ex: "/r/pics/" // */ // private String url; // // @Override // public String toString() { // return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url // + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " // + title + "\nid: " + id + "\n=====\n"; // } // // @Override // public Kind getKind() { // return Kind.SUBREDDIT; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSubredditId() { // return id; // } // // public void setSubredditId(String subredditId) { // this.id = subredditId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public long getNumSubscribers() { // return numSubscribers; // } // // public void setNumSubscribers(long numSubscribers) { // this.numSubscribers = numSubscribers; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: src/com/pocketreddit/library/Created.java // public interface Created { // public double getCreated(); // public double getCreatedUtc(); // } // // Path: src/com/pocketreddit/library/Votable.java // public interface Votable { // public int getUpvotes(); // // public int getDownvotes(); // // /** // * @return true if thing is liked by the user. false if thing is disliked. // * null if the user is neutral on the thing. // */ // public Boolean isLiked(); // } // Path: src/com/pocketreddit/library/things/UserSubmittedContent.java import com.pocketreddit.library.things.Subreddit; import com.pocketreddit.library.things.Thing; import com.pocketreddit.library.Created; import com.pocketreddit.library.Votable; package com.pocketreddit.library.things; public abstract class UserSubmittedContent extends Thing implements Created, Votable { private static final long serialVersionUID = 1L; private String id; private int upvotes; private int downvotes; private Boolean liked; private double created; private double createdUtc; private String name; private String author; private String authorFlairCssClass; private String authorFlairText; private String body; private String bodyHtml; private boolean edited; private int numReports;
private Subreddit subreddit;
achan/android-reddit
tests/src/com/pocketreddit/library/datasources/MockDataSource.java
// Path: src/com/pocketreddit/library/datasources/DataSourceException.java // public class DataSourceException extends Exception { // private static final long serialVersionUID = 1L; // // public DataSourceException(String message) { // super(message); // } // // public DataSourceException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/datasources/JsonDataSource.java // public interface JsonDataSource { // public JSONObject getSubreddits(String sessionId) throws DataSourceException; // // public JSONObject getLinks(String subreddit) throws DataSourceException; // // public JSONObject getComments(String permalink) throws DataSourceException; // // public JSONObject getSubreddit(String subreddit) throws DataSourceException; // // public JSONObject getDefaultSubreddits() throws DataSourceException; // // public JSONObject getLinksForFrontPage() throws DataSourceException; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // }
import java.io.IOException; import java.io.InputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.pocketreddit.library.datasources.DataSourceException; import com.pocketreddit.library.datasources.JsonDataSource; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException;
package com.pocketreddit.library.datasources; public class MockDataSource implements JsonDataSource { private Context context; public MockDataSource(Context context) { this.context = context; }
// Path: src/com/pocketreddit/library/datasources/DataSourceException.java // public class DataSourceException extends Exception { // private static final long serialVersionUID = 1L; // // public DataSourceException(String message) { // super(message); // } // // public DataSourceException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/datasources/JsonDataSource.java // public interface JsonDataSource { // public JSONObject getSubreddits(String sessionId) throws DataSourceException; // // public JSONObject getLinks(String subreddit) throws DataSourceException; // // public JSONObject getComments(String permalink) throws DataSourceException; // // public JSONObject getSubreddit(String subreddit) throws DataSourceException; // // public JSONObject getDefaultSubreddits() throws DataSourceException; // // public JSONObject getLinksForFrontPage() throws DataSourceException; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // } // Path: tests/src/com/pocketreddit/library/datasources/MockDataSource.java import java.io.IOException; import java.io.InputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.pocketreddit.library.datasources.DataSourceException; import com.pocketreddit.library.datasources.JsonDataSource; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException; package com.pocketreddit.library.datasources; public class MockDataSource implements JsonDataSource { private Context context; public MockDataSource(Context context) { this.context = context; }
public JSONObject getSubreddits(String sessionId) throws DataSourceException {
achan/android-reddit
tests/src/com/pocketreddit/library/datasources/MockDataSource.java
// Path: src/com/pocketreddit/library/datasources/DataSourceException.java // public class DataSourceException extends Exception { // private static final long serialVersionUID = 1L; // // public DataSourceException(String message) { // super(message); // } // // public DataSourceException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/datasources/JsonDataSource.java // public interface JsonDataSource { // public JSONObject getSubreddits(String sessionId) throws DataSourceException; // // public JSONObject getLinks(String subreddit) throws DataSourceException; // // public JSONObject getComments(String permalink) throws DataSourceException; // // public JSONObject getSubreddit(String subreddit) throws DataSourceException; // // public JSONObject getDefaultSubreddits() throws DataSourceException; // // public JSONObject getLinksForFrontPage() throws DataSourceException; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // }
import java.io.IOException; import java.io.InputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.pocketreddit.library.datasources.DataSourceException; import com.pocketreddit.library.datasources.JsonDataSource; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException;
package com.pocketreddit.library.datasources; public class MockDataSource implements JsonDataSource { private Context context; public MockDataSource(Context context) { this.context = context; } public JSONObject getSubreddits(String sessionId) throws DataSourceException { InputStream is = buildInputStream("/reddits/mine.json"); try {
// Path: src/com/pocketreddit/library/datasources/DataSourceException.java // public class DataSourceException extends Exception { // private static final long serialVersionUID = 1L; // // public DataSourceException(String message) { // super(message); // } // // public DataSourceException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/datasources/JsonDataSource.java // public interface JsonDataSource { // public JSONObject getSubreddits(String sessionId) throws DataSourceException; // // public JSONObject getLinks(String subreddit) throws DataSourceException; // // public JSONObject getComments(String permalink) throws DataSourceException; // // public JSONObject getSubreddit(String subreddit) throws DataSourceException; // // public JSONObject getDefaultSubreddits() throws DataSourceException; // // public JSONObject getLinksForFrontPage() throws DataSourceException; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // } // Path: tests/src/com/pocketreddit/library/datasources/MockDataSource.java import java.io.IOException; import java.io.InputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.pocketreddit.library.datasources.DataSourceException; import com.pocketreddit.library.datasources.JsonDataSource; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException; package com.pocketreddit.library.datasources; public class MockDataSource implements JsonDataSource { private Context context; public MockDataSource(Context context) { this.context = context; } public JSONObject getSubreddits(String sessionId) throws DataSourceException { InputStream is = buildInputStream("/reddits/mine.json"); try {
return new JSONObject(StreamUtils.getInstance().convertStreamToString(is));
achan/android-reddit
tests/src/com/pocketreddit/library/datasources/MockDataSource.java
// Path: src/com/pocketreddit/library/datasources/DataSourceException.java // public class DataSourceException extends Exception { // private static final long serialVersionUID = 1L; // // public DataSourceException(String message) { // super(message); // } // // public DataSourceException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/datasources/JsonDataSource.java // public interface JsonDataSource { // public JSONObject getSubreddits(String sessionId) throws DataSourceException; // // public JSONObject getLinks(String subreddit) throws DataSourceException; // // public JSONObject getComments(String permalink) throws DataSourceException; // // public JSONObject getSubreddit(String subreddit) throws DataSourceException; // // public JSONObject getDefaultSubreddits() throws DataSourceException; // // public JSONObject getLinksForFrontPage() throws DataSourceException; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // }
import java.io.IOException; import java.io.InputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.pocketreddit.library.datasources.DataSourceException; import com.pocketreddit.library.datasources.JsonDataSource; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException;
package com.pocketreddit.library.datasources; public class MockDataSource implements JsonDataSource { private Context context; public MockDataSource(Context context) { this.context = context; } public JSONObject getSubreddits(String sessionId) throws DataSourceException { InputStream is = buildInputStream("/reddits/mine.json"); try { return new JSONObject(StreamUtils.getInstance().convertStreamToString(is)); } catch (JSONException e) { throw new DataSourceException("Could not parse the JSON file.", e);
// Path: src/com/pocketreddit/library/datasources/DataSourceException.java // public class DataSourceException extends Exception { // private static final long serialVersionUID = 1L; // // public DataSourceException(String message) { // super(message); // } // // public DataSourceException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/datasources/JsonDataSource.java // public interface JsonDataSource { // public JSONObject getSubreddits(String sessionId) throws DataSourceException; // // public JSONObject getLinks(String subreddit) throws DataSourceException; // // public JSONObject getComments(String permalink) throws DataSourceException; // // public JSONObject getSubreddit(String subreddit) throws DataSourceException; // // public JSONObject getDefaultSubreddits() throws DataSourceException; // // public JSONObject getLinksForFrontPage() throws DataSourceException; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // } // Path: tests/src/com/pocketreddit/library/datasources/MockDataSource.java import java.io.IOException; import java.io.InputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.pocketreddit.library.datasources.DataSourceException; import com.pocketreddit.library.datasources.JsonDataSource; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException; package com.pocketreddit.library.datasources; public class MockDataSource implements JsonDataSource { private Context context; public MockDataSource(Context context) { this.context = context; } public JSONObject getSubreddits(String sessionId) throws DataSourceException { InputStream is = buildInputStream("/reddits/mine.json"); try { return new JSONObject(StreamUtils.getInstance().convertStreamToString(is)); } catch (JSONException e) { throw new DataSourceException("Could not parse the JSON file.", e);
} catch (UtilsException e) {
achan/android-reddit
src/com/pocketreddit/library/things/Message.java
// Path: src/com/pocketreddit/library/things/Message.java // public class Message { // private String author; // private String body; // private String bodyHtml; // private Message firstMessage; // private String context; // private String name; // private boolean read; // private String parentId; // private String replies; // private String subject; // private Subreddit subreddit; // private boolean comment; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getBodyHtml() { // return bodyHtml; // } // // public void setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // } // // public Message getFirstMessage() { // return firstMessage; // } // // public void setFirstMessage(Message firstMessage) { // this.firstMessage = firstMessage; // } // // public String getContext() { // return context; // } // // public void setContext(String context) { // this.context = context; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isRead() { // return read; // } // // public void setRead(boolean read) { // this.read = read; // } // // public String getParentId() { // return parentId; // } // // public void setParentId(String parentId) { // this.parentId = parentId; // } // // public String getReplies() { // return replies; // } // // public void setReplies(String replies) { // this.replies = replies; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public Subreddit getSubreddit() { // return subreddit; // } // // public void setSubreddit(Subreddit subreddit) { // this.subreddit = subreddit; // } // // public boolean isComment() { // return comment; // } // // public void setComment(boolean comment) { // this.comment = comment; // } // } // // Path: src/com/pocketreddit/library/things/Subreddit.java // public class Subreddit extends Thing { // private static final long serialVersionUID = 1L; // // private String title; // private String id; // private String description; // private String displayName; // private boolean over18; // private long numSubscribers; // // // private static String CLASS_NAME = Subreddit.class.getSimpleName(); // // /** // * The relative URL of the subreddit. Ex: "/r/pics/" // */ // private String url; // // @Override // public String toString() { // return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url // + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " // + title + "\nid: " + id + "\n=====\n"; // } // // @Override // public Kind getKind() { // return Kind.SUBREDDIT; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSubredditId() { // return id; // } // // public void setSubredditId(String subredditId) { // this.id = subredditId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public long getNumSubscribers() { // return numSubscribers; // } // // public void setNumSubscribers(long numSubscribers) { // this.numSubscribers = numSubscribers; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // }
import com.pocketreddit.library.things.Message; import com.pocketreddit.library.things.Subreddit;
package com.pocketreddit.library.things; public class Message { private String author; private String body; private String bodyHtml; private Message firstMessage; private String context; private String name; private boolean read; private String parentId; private String replies; private String subject;
// Path: src/com/pocketreddit/library/things/Message.java // public class Message { // private String author; // private String body; // private String bodyHtml; // private Message firstMessage; // private String context; // private String name; // private boolean read; // private String parentId; // private String replies; // private String subject; // private Subreddit subreddit; // private boolean comment; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getBodyHtml() { // return bodyHtml; // } // // public void setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // } // // public Message getFirstMessage() { // return firstMessage; // } // // public void setFirstMessage(Message firstMessage) { // this.firstMessage = firstMessage; // } // // public String getContext() { // return context; // } // // public void setContext(String context) { // this.context = context; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isRead() { // return read; // } // // public void setRead(boolean read) { // this.read = read; // } // // public String getParentId() { // return parentId; // } // // public void setParentId(String parentId) { // this.parentId = parentId; // } // // public String getReplies() { // return replies; // } // // public void setReplies(String replies) { // this.replies = replies; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public Subreddit getSubreddit() { // return subreddit; // } // // public void setSubreddit(Subreddit subreddit) { // this.subreddit = subreddit; // } // // public boolean isComment() { // return comment; // } // // public void setComment(boolean comment) { // this.comment = comment; // } // } // // Path: src/com/pocketreddit/library/things/Subreddit.java // public class Subreddit extends Thing { // private static final long serialVersionUID = 1L; // // private String title; // private String id; // private String description; // private String displayName; // private boolean over18; // private long numSubscribers; // // // private static String CLASS_NAME = Subreddit.class.getSimpleName(); // // /** // * The relative URL of the subreddit. Ex: "/r/pics/" // */ // private String url; // // @Override // public String toString() { // return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url // + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " // + title + "\nid: " + id + "\n=====\n"; // } // // @Override // public Kind getKind() { // return Kind.SUBREDDIT; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSubredditId() { // return id; // } // // public void setSubredditId(String subredditId) { // this.id = subredditId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public long getNumSubscribers() { // return numSubscribers; // } // // public void setNumSubscribers(long numSubscribers) { // this.numSubscribers = numSubscribers; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // Path: src/com/pocketreddit/library/things/Message.java import com.pocketreddit.library.things.Message; import com.pocketreddit.library.things.Subreddit; package com.pocketreddit.library.things; public class Message { private String author; private String body; private String bodyHtml; private Message firstMessage; private String context; private String name; private boolean read; private String parentId; private String replies; private String subject;
private Subreddit subreddit;
achan/android-reddit
src/com/pocketreddit/library/things/Subreddit.java
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // }
import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.Thing;
package com.pocketreddit.library.things; public class Subreddit extends Thing { private static final long serialVersionUID = 1L; private String title; private String id; private String description; private String displayName; private boolean over18; private long numSubscribers; // private static String CLASS_NAME = Subreddit.class.getSimpleName(); /** * The relative URL of the subreddit. Ex: "/r/pics/" */ private String url; @Override public String toString() { return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " + title + "\nid: " + id + "\n=====\n"; } @Override
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // Path: src/com/pocketreddit/library/things/Subreddit.java import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.Thing; package com.pocketreddit.library.things; public class Subreddit extends Thing { private static final long serialVersionUID = 1L; private String title; private String id; private String description; private String displayName; private boolean over18; private long numSubscribers; // private static String CLASS_NAME = Subreddit.class.getSimpleName(); /** * The relative URL of the subreddit. Ex: "/r/pics/" */ private String url; @Override public String toString() { return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " + title + "\nid: " + id + "\n=====\n"; } @Override
public Kind getKind() {
achan/android-reddit
src/com/pocketreddit/library/net/HttpHelper.java
// Path: src/com/pocketreddit/library/Constants.java // public class Constants { // private Constants() { // } // // public static final String SYSTEM_PROPERTY_USER_AGENT = "com.pocketreddit.library.useragent"; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // }
import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.CoreProtocolPNames; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.pocketreddit.library.Constants; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException;
package com.pocketreddit.library.net; public class HttpHelper { private static final String TAG = HttpHelper.class.getName(); private static final String SCHEME_SSL = "https"; private static final int SCHEME_PORT_SSL = 443; private static HttpHelper instance; private HttpHelper() { } public static HttpHelper getInstance() { if (instance == null) instance = new HttpHelper(); return instance; } public JSONObject getJsonObjectFromGet(String uri, List<Cookie> cookies) throws NetException { HttpClient client = buildHttpClient(cookies); try { return getJsonObjectFromResponse(client.execute(new HttpGet(uri))); } catch (Exception e) { throw new NetException("Error while parsing GET response from " + uri + " into JSON object: " + e.getMessage(), e); } } private HttpClient buildHttpClient(List<Cookie> cookies) { DefaultHttpClient client = new DefaultHttpClient();
// Path: src/com/pocketreddit/library/Constants.java // public class Constants { // private Constants() { // } // // public static final String SYSTEM_PROPERTY_USER_AGENT = "com.pocketreddit.library.useragent"; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // } // Path: src/com/pocketreddit/library/net/HttpHelper.java import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.CoreProtocolPNames; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.pocketreddit.library.Constants; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException; package com.pocketreddit.library.net; public class HttpHelper { private static final String TAG = HttpHelper.class.getName(); private static final String SCHEME_SSL = "https"; private static final int SCHEME_PORT_SSL = 443; private static HttpHelper instance; private HttpHelper() { } public static HttpHelper getInstance() { if (instance == null) instance = new HttpHelper(); return instance; } public JSONObject getJsonObjectFromGet(String uri, List<Cookie> cookies) throws NetException { HttpClient client = buildHttpClient(cookies); try { return getJsonObjectFromResponse(client.execute(new HttpGet(uri))); } catch (Exception e) { throw new NetException("Error while parsing GET response from " + uri + " into JSON object: " + e.getMessage(), e); } } private HttpClient buildHttpClient(List<Cookie> cookies) { DefaultHttpClient client = new DefaultHttpClient();
String userAgent = System.getProperty(Constants.SYSTEM_PROPERTY_USER_AGENT);
achan/android-reddit
src/com/pocketreddit/library/net/HttpHelper.java
// Path: src/com/pocketreddit/library/Constants.java // public class Constants { // private Constants() { // } // // public static final String SYSTEM_PROPERTY_USER_AGENT = "com.pocketreddit.library.useragent"; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // }
import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.CoreProtocolPNames; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.pocketreddit.library.Constants; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException;
private HttpClient buildHttpClient(List<Cookie> cookies) { DefaultHttpClient client = new DefaultHttpClient(); String userAgent = System.getProperty(Constants.SYSTEM_PROPERTY_USER_AGENT); if (userAgent != null) client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent); if (cookies != null && !cookies.isEmpty()) { client.setCookieStore(buildCookieStore(cookies)); } return client; } private CookieStore buildCookieStore(List<Cookie> cookies) { Cookie[] cookieArray = new Cookie[cookies.size()]; return buildCookieStore(cookies.toArray(cookieArray)); } private CookieStore buildCookieStore(Cookie... cookies) { CookieStore cookieStore = new BasicCookieStore(); for (Cookie cookie : cookies) { cookieStore.addCookie(cookie); } return cookieStore; } private JSONArray getJsonArrayFromResponse(HttpResponse response) throws IllegalStateException,
// Path: src/com/pocketreddit/library/Constants.java // public class Constants { // private Constants() { // } // // public static final String SYSTEM_PROPERTY_USER_AGENT = "com.pocketreddit.library.useragent"; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // } // Path: src/com/pocketreddit/library/net/HttpHelper.java import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.CoreProtocolPNames; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.pocketreddit.library.Constants; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException; private HttpClient buildHttpClient(List<Cookie> cookies) { DefaultHttpClient client = new DefaultHttpClient(); String userAgent = System.getProperty(Constants.SYSTEM_PROPERTY_USER_AGENT); if (userAgent != null) client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent); if (cookies != null && !cookies.isEmpty()) { client.setCookieStore(buildCookieStore(cookies)); } return client; } private CookieStore buildCookieStore(List<Cookie> cookies) { Cookie[] cookieArray = new Cookie[cookies.size()]; return buildCookieStore(cookies.toArray(cookieArray)); } private CookieStore buildCookieStore(Cookie... cookies) { CookieStore cookieStore = new BasicCookieStore(); for (Cookie cookie : cookies) { cookieStore.addCookie(cookie); } return cookieStore; } private JSONArray getJsonArrayFromResponse(HttpResponse response) throws IllegalStateException,
JSONException, IOException, UtilsException {
achan/android-reddit
src/com/pocketreddit/library/net/HttpHelper.java
// Path: src/com/pocketreddit/library/Constants.java // public class Constants { // private Constants() { // } // // public static final String SYSTEM_PROPERTY_USER_AGENT = "com.pocketreddit.library.useragent"; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // }
import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.CoreProtocolPNames; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.pocketreddit.library.Constants; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException;
client.setCookieStore(buildCookieStore(cookies)); } return client; } private CookieStore buildCookieStore(List<Cookie> cookies) { Cookie[] cookieArray = new Cookie[cookies.size()]; return buildCookieStore(cookies.toArray(cookieArray)); } private CookieStore buildCookieStore(Cookie... cookies) { CookieStore cookieStore = new BasicCookieStore(); for (Cookie cookie : cookies) { cookieStore.addCookie(cookie); } return cookieStore; } private JSONArray getJsonArrayFromResponse(HttpResponse response) throws IllegalStateException, JSONException, IOException, UtilsException { return new JSONArray(responseToString(response)); } private String responseToString(HttpResponse response) throws IOException, IllegalStateException, UtilsException { InputStream is = null; try { is = response.getEntity().getContent();
// Path: src/com/pocketreddit/library/Constants.java // public class Constants { // private Constants() { // } // // public static final String SYSTEM_PROPERTY_USER_AGENT = "com.pocketreddit.library.useragent"; // } // // Path: src/com/pocketreddit/library/utils/StreamUtils.java // public class StreamUtils { // private static StreamUtils instance; // // private StreamUtils() { // } // // public static StreamUtils getInstance() { // if (instance == null) { // instance = new StreamUtils(); // } // // return instance; // } // // public String convertStreamToString(InputStream is) throws UtilsException { // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // String line; // StringBuilder sb = new StringBuilder(); // // try { // while ((line = reader.readLine()) != null) { // sb.append(line + "\n"); // } // } catch (IOException e) { // throw new UtilsException("Couldn't read line from stream.", e); // } finally { // try { // if (is != null) // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return sb.toString(); // } // } // // Path: src/com/pocketreddit/library/utils/UtilsException.java // public class UtilsException extends Exception { // private static final long serialVersionUID = 1L; // // public UtilsException(String message) { // super(message); // } // // public UtilsException(String message, Throwable throwable) { // super(message, throwable); // } // } // Path: src/com/pocketreddit/library/net/HttpHelper.java import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.CoreProtocolPNames; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.pocketreddit.library.Constants; import com.pocketreddit.library.utils.StreamUtils; import com.pocketreddit.library.utils.UtilsException; client.setCookieStore(buildCookieStore(cookies)); } return client; } private CookieStore buildCookieStore(List<Cookie> cookies) { Cookie[] cookieArray = new Cookie[cookies.size()]; return buildCookieStore(cookies.toArray(cookieArray)); } private CookieStore buildCookieStore(Cookie... cookies) { CookieStore cookieStore = new BasicCookieStore(); for (Cookie cookie : cookies) { cookieStore.addCookie(cookie); } return cookieStore; } private JSONArray getJsonArrayFromResponse(HttpResponse response) throws IllegalStateException, JSONException, IOException, UtilsException { return new JSONArray(responseToString(response)); } private String responseToString(HttpResponse response) throws IOException, IllegalStateException, UtilsException { InputStream is = null; try { is = response.getEntity().getContent();
String content = StreamUtils.getInstance().convertStreamToString(is);
achan/android-reddit
src/com/pocketreddit/library/things/Thing.java
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // }
import java.io.Serializable; import com.pocketreddit.library.things.Kind;
package com.pocketreddit.library.things; public abstract class Thing implements Serializable { private static final long serialVersionUID = 1L; private String id; private String name;
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // Path: src/com/pocketreddit/library/things/Thing.java import java.io.Serializable; import com.pocketreddit.library.things.Kind; package com.pocketreddit.library.things; public abstract class Thing implements Serializable { private static final long serialVersionUID = 1L; private String id; private String name;
public abstract Kind getKind();
achan/android-reddit
tests/src/com/pocketreddit/library/authentication/IntegrationLiveAuthenticationTest.java
// Path: src/com/pocketreddit/library/authentication/AuthenticationException.java // public class AuthenticationException extends Exception { // private static final long serialVersionUID = 1L; // // public AuthenticationException(String message) { // super(message); // } // // public AuthenticationException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/authentication/LiveAuthenticator.java // public class LiveAuthenticator implements Authenticator { // private static final String TAG = LiveAuthenticator.class.getName(); // // private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; // private static final String PARAM_USERNAME = "user"; // private static final String PARAM_PASSWORD = "passwd"; // // private static final String PARAM_API_TYPE = "api_type"; // private static final String API_TYPE_JSON = "json"; // // public LoginResult authenticate(String username, String password) // throws AuthenticationException { // try { // return new LoginResult(HttpHelper.getInstance().getJsonObjectFromPost( // new URI(LOGIN_URI + "/" + username), // nameValuePairs(PARAM_USERNAME, username, PARAM_PASSWORD, password, // PARAM_API_TYPE, API_TYPE_JSON))); // } catch (Exception e) { // Log.e(TAG, "Unable to authenticate user: " + username, e); // throw new AuthenticationException("Unable to authenticate user: " + username, e); // } // } // // private List<NameValuePair> nameValuePairs(String... keysAndValues) { // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Must contain keys and values, length cannot be odd"); // } // // List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // // for (int i = 0; i < keysAndValues.length; i += 2) { // pairs.add(new BasicNameValuePair(keysAndValues[i], keysAndValues[i + 1])); // } // // return pairs; // } // } // // Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // }
import com.pocketreddit.library.authentication.AuthenticationException; import com.pocketreddit.library.authentication.LiveAuthenticator; import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log;
package com.pocketreddit.library.authentication; public class IntegrationLiveAuthenticationTest extends AndroidTestCase { private static final String TAG = IntegrationLiveAuthenticationTest.class.getName(); public void testLoginWithBadPw() {
// Path: src/com/pocketreddit/library/authentication/AuthenticationException.java // public class AuthenticationException extends Exception { // private static final long serialVersionUID = 1L; // // public AuthenticationException(String message) { // super(message); // } // // public AuthenticationException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/authentication/LiveAuthenticator.java // public class LiveAuthenticator implements Authenticator { // private static final String TAG = LiveAuthenticator.class.getName(); // // private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; // private static final String PARAM_USERNAME = "user"; // private static final String PARAM_PASSWORD = "passwd"; // // private static final String PARAM_API_TYPE = "api_type"; // private static final String API_TYPE_JSON = "json"; // // public LoginResult authenticate(String username, String password) // throws AuthenticationException { // try { // return new LoginResult(HttpHelper.getInstance().getJsonObjectFromPost( // new URI(LOGIN_URI + "/" + username), // nameValuePairs(PARAM_USERNAME, username, PARAM_PASSWORD, password, // PARAM_API_TYPE, API_TYPE_JSON))); // } catch (Exception e) { // Log.e(TAG, "Unable to authenticate user: " + username, e); // throw new AuthenticationException("Unable to authenticate user: " + username, e); // } // } // // private List<NameValuePair> nameValuePairs(String... keysAndValues) { // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Must contain keys and values, length cannot be odd"); // } // // List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // // for (int i = 0; i < keysAndValues.length; i += 2) { // pairs.add(new BasicNameValuePair(keysAndValues[i], keysAndValues[i + 1])); // } // // return pairs; // } // } // // Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // } // Path: tests/src/com/pocketreddit/library/authentication/IntegrationLiveAuthenticationTest.java import com.pocketreddit.library.authentication.AuthenticationException; import com.pocketreddit.library.authentication.LiveAuthenticator; import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log; package com.pocketreddit.library.authentication; public class IntegrationLiveAuthenticationTest extends AndroidTestCase { private static final String TAG = IntegrationLiveAuthenticationTest.class.getName(); public void testLoginWithBadPw() {
LiveAuthenticator authenticator = new LiveAuthenticator();
achan/android-reddit
tests/src/com/pocketreddit/library/authentication/IntegrationLiveAuthenticationTest.java
// Path: src/com/pocketreddit/library/authentication/AuthenticationException.java // public class AuthenticationException extends Exception { // private static final long serialVersionUID = 1L; // // public AuthenticationException(String message) { // super(message); // } // // public AuthenticationException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/authentication/LiveAuthenticator.java // public class LiveAuthenticator implements Authenticator { // private static final String TAG = LiveAuthenticator.class.getName(); // // private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; // private static final String PARAM_USERNAME = "user"; // private static final String PARAM_PASSWORD = "passwd"; // // private static final String PARAM_API_TYPE = "api_type"; // private static final String API_TYPE_JSON = "json"; // // public LoginResult authenticate(String username, String password) // throws AuthenticationException { // try { // return new LoginResult(HttpHelper.getInstance().getJsonObjectFromPost( // new URI(LOGIN_URI + "/" + username), // nameValuePairs(PARAM_USERNAME, username, PARAM_PASSWORD, password, // PARAM_API_TYPE, API_TYPE_JSON))); // } catch (Exception e) { // Log.e(TAG, "Unable to authenticate user: " + username, e); // throw new AuthenticationException("Unable to authenticate user: " + username, e); // } // } // // private List<NameValuePair> nameValuePairs(String... keysAndValues) { // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Must contain keys and values, length cannot be odd"); // } // // List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // // for (int i = 0; i < keysAndValues.length; i += 2) { // pairs.add(new BasicNameValuePair(keysAndValues[i], keysAndValues[i + 1])); // } // // return pairs; // } // } // // Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // }
import com.pocketreddit.library.authentication.AuthenticationException; import com.pocketreddit.library.authentication.LiveAuthenticator; import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log;
package com.pocketreddit.library.authentication; public class IntegrationLiveAuthenticationTest extends AndroidTestCase { private static final String TAG = IntegrationLiveAuthenticationTest.class.getName(); public void testLoginWithBadPw() { LiveAuthenticator authenticator = new LiveAuthenticator(); try {
// Path: src/com/pocketreddit/library/authentication/AuthenticationException.java // public class AuthenticationException extends Exception { // private static final long serialVersionUID = 1L; // // public AuthenticationException(String message) { // super(message); // } // // public AuthenticationException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/authentication/LiveAuthenticator.java // public class LiveAuthenticator implements Authenticator { // private static final String TAG = LiveAuthenticator.class.getName(); // // private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; // private static final String PARAM_USERNAME = "user"; // private static final String PARAM_PASSWORD = "passwd"; // // private static final String PARAM_API_TYPE = "api_type"; // private static final String API_TYPE_JSON = "json"; // // public LoginResult authenticate(String username, String password) // throws AuthenticationException { // try { // return new LoginResult(HttpHelper.getInstance().getJsonObjectFromPost( // new URI(LOGIN_URI + "/" + username), // nameValuePairs(PARAM_USERNAME, username, PARAM_PASSWORD, password, // PARAM_API_TYPE, API_TYPE_JSON))); // } catch (Exception e) { // Log.e(TAG, "Unable to authenticate user: " + username, e); // throw new AuthenticationException("Unable to authenticate user: " + username, e); // } // } // // private List<NameValuePair> nameValuePairs(String... keysAndValues) { // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Must contain keys and values, length cannot be odd"); // } // // List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // // for (int i = 0; i < keysAndValues.length; i += 2) { // pairs.add(new BasicNameValuePair(keysAndValues[i], keysAndValues[i + 1])); // } // // return pairs; // } // } // // Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // } // Path: tests/src/com/pocketreddit/library/authentication/IntegrationLiveAuthenticationTest.java import com.pocketreddit.library.authentication.AuthenticationException; import com.pocketreddit.library.authentication.LiveAuthenticator; import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log; package com.pocketreddit.library.authentication; public class IntegrationLiveAuthenticationTest extends AndroidTestCase { private static final String TAG = IntegrationLiveAuthenticationTest.class.getName(); public void testLoginWithBadPw() { LiveAuthenticator authenticator = new LiveAuthenticator(); try {
LoginResult result = authenticator.authenticate("testachan", "baddpw");
achan/android-reddit
tests/src/com/pocketreddit/library/authentication/IntegrationLiveAuthenticationTest.java
// Path: src/com/pocketreddit/library/authentication/AuthenticationException.java // public class AuthenticationException extends Exception { // private static final long serialVersionUID = 1L; // // public AuthenticationException(String message) { // super(message); // } // // public AuthenticationException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/authentication/LiveAuthenticator.java // public class LiveAuthenticator implements Authenticator { // private static final String TAG = LiveAuthenticator.class.getName(); // // private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; // private static final String PARAM_USERNAME = "user"; // private static final String PARAM_PASSWORD = "passwd"; // // private static final String PARAM_API_TYPE = "api_type"; // private static final String API_TYPE_JSON = "json"; // // public LoginResult authenticate(String username, String password) // throws AuthenticationException { // try { // return new LoginResult(HttpHelper.getInstance().getJsonObjectFromPost( // new URI(LOGIN_URI + "/" + username), // nameValuePairs(PARAM_USERNAME, username, PARAM_PASSWORD, password, // PARAM_API_TYPE, API_TYPE_JSON))); // } catch (Exception e) { // Log.e(TAG, "Unable to authenticate user: " + username, e); // throw new AuthenticationException("Unable to authenticate user: " + username, e); // } // } // // private List<NameValuePair> nameValuePairs(String... keysAndValues) { // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Must contain keys and values, length cannot be odd"); // } // // List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // // for (int i = 0; i < keysAndValues.length; i += 2) { // pairs.add(new BasicNameValuePair(keysAndValues[i], keysAndValues[i + 1])); // } // // return pairs; // } // } // // Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // }
import com.pocketreddit.library.authentication.AuthenticationException; import com.pocketreddit.library.authentication.LiveAuthenticator; import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log;
package com.pocketreddit.library.authentication; public class IntegrationLiveAuthenticationTest extends AndroidTestCase { private static final String TAG = IntegrationLiveAuthenticationTest.class.getName(); public void testLoginWithBadPw() { LiveAuthenticator authenticator = new LiveAuthenticator(); try { LoginResult result = authenticator.authenticate("testachan", "baddpw"); assertFalse("LoginResult should produce errors when there is a bad pw.", result .getErrors().isEmpty());
// Path: src/com/pocketreddit/library/authentication/AuthenticationException.java // public class AuthenticationException extends Exception { // private static final long serialVersionUID = 1L; // // public AuthenticationException(String message) { // super(message); // } // // public AuthenticationException(String message, Throwable throwable) { // super(message, throwable); // } // } // // Path: src/com/pocketreddit/library/authentication/LiveAuthenticator.java // public class LiveAuthenticator implements Authenticator { // private static final String TAG = LiveAuthenticator.class.getName(); // // private static final String LOGIN_URI = "https://ssl.reddit.com/api/login"; // private static final String PARAM_USERNAME = "user"; // private static final String PARAM_PASSWORD = "passwd"; // // private static final String PARAM_API_TYPE = "api_type"; // private static final String API_TYPE_JSON = "json"; // // public LoginResult authenticate(String username, String password) // throws AuthenticationException { // try { // return new LoginResult(HttpHelper.getInstance().getJsonObjectFromPost( // new URI(LOGIN_URI + "/" + username), // nameValuePairs(PARAM_USERNAME, username, PARAM_PASSWORD, password, // PARAM_API_TYPE, API_TYPE_JSON))); // } catch (Exception e) { // Log.e(TAG, "Unable to authenticate user: " + username, e); // throw new AuthenticationException("Unable to authenticate user: " + username, e); // } // } // // private List<NameValuePair> nameValuePairs(String... keysAndValues) { // if (keysAndValues.length % 2 != 0) { // throw new IllegalArgumentException("Must contain keys and values, length cannot be odd"); // } // // List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // // for (int i = 0; i < keysAndValues.length; i += 2) { // pairs.add(new BasicNameValuePair(keysAndValues[i], keysAndValues[i + 1])); // } // // return pairs; // } // } // // Path: src/com/pocketreddit/library/authentication/LoginResult.java // public class LoginResult { // private String modHash; // private String cookie; // private List<List<String>> errors; // // public LoginResult(String json) throws AuthenticationException, JSONException { // this(new JSONObject(json)); // } // // public LoginResult(JSONObject json) throws AuthenticationException { // try { // errors = new ArrayList<List<String>>(); // json = json.getJSONObject("json"); // // JSONArray jsonErrors = json.getJSONArray("errors"); // for (int i = 0; i < jsonErrors.length(); i++) { // JSONArray currentError = jsonErrors.getJSONArray(i); // List<String> errorKeys = new ArrayList<String>(); // for (int j = 0; j < currentError.length(); j++) { // errorKeys.add(currentError.getString(j)); // } // // errors.add(errorKeys); // } // // if (jsonErrors.length() == 0) { // JSONObject data = json.getJSONObject("data"); // setModHash(data.getString("modhash")); // setCookie(data.getString("cookie")); // } // } catch (JSONException e) { // throw new AuthenticationException("Could not parse login response.", e); // } // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // public String getCookie() { // return cookie; // } // // public void setCookie(String cookie) { // this.cookie = cookie; // } // // public List<List<String>> getErrors() { // return errors; // } // // public void setErrors(List<List<String>> errors) { // this.errors = errors; // } // } // Path: tests/src/com/pocketreddit/library/authentication/IntegrationLiveAuthenticationTest.java import com.pocketreddit.library.authentication.AuthenticationException; import com.pocketreddit.library.authentication.LiveAuthenticator; import com.pocketreddit.library.authentication.LoginResult; import android.test.AndroidTestCase; import android.util.Log; package com.pocketreddit.library.authentication; public class IntegrationLiveAuthenticationTest extends AndroidTestCase { private static final String TAG = IntegrationLiveAuthenticationTest.class.getName(); public void testLoginWithBadPw() { LiveAuthenticator authenticator = new LiveAuthenticator(); try { LoginResult result = authenticator.authenticate("testachan", "baddpw"); assertFalse("LoginResult should produce errors when there is a bad pw.", result .getErrors().isEmpty());
} catch (AuthenticationException e) {
achan/android-reddit
src/com/pocketreddit/library/things/factories/LinkFactory.java
// Path: src/com/pocketreddit/library/things/Link.java // public class Link extends UserSubmittedContent { // private static final long serialVersionUID = 1L; // // private boolean clicked; // private String domain; // private boolean hidden; // private boolean selfPost; // private Object media; // private Object mediaEmbed; // private int numComments; // private boolean over18; // private String permalink; // private boolean saved; // private int score; // private URL thumbnail; // private String title; // private String url; // private String modHash; // // public Link() { // } // // public Link(JSONObject json) throws JsonParsingException { // // } // // public boolean isClicked() { // return clicked; // } // // public void setClicked(boolean clicked) { // this.clicked = clicked; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public boolean isSelfPost() { // return selfPost; // } // // public void setSelfPost(boolean selfPost) { // this.selfPost = selfPost; // } // // public Object getMedia() { // return media; // } // // public void setMedia(Object media) { // this.media = media; // } // // public Object getMediaEmbed() { // return mediaEmbed; // } // // public void setMediaEmbed(Object mediaEmbed) { // this.mediaEmbed = mediaEmbed; // } // // public int getNumComments() { // return numComments; // } // // public void setNumComments(int numComments) { // this.numComments = numComments; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public String getPermalink() { // return permalink; // } // // public void setPermalink(String permalink) { // this.permalink = permalink; // } // // public boolean isSaved() { // return saved; // } // // public void setSaved(boolean saved) { // this.saved = saved; // } // // public int getScore() { // return score; // } // // public void setScore(int score) { // this.score = score; // } // // public URL getThumbnail() { // return thumbnail; // } // // public void setThumbnail(URL thumbnail) { // this.thumbnail = thumbnail; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public String toString() { // return "Link [clicked=" + clicked + ", domain=" + domain + ", hidden=" + hidden // + ", selfPost=" + selfPost + ", media=" + media + ", mediaEmbed=" + mediaEmbed // + ", numComments=" + numComments + ", over18=" + over18 + ", permalink=" // + permalink + ", saved=" + saved + ", score=" + score + ", thumbnail=" + thumbnail // + ", title=" + title + ", url=" + url + ", modHash=" + modHash + "]"; // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // @Override // public Kind getKind() { // return Kind.THREAD; // } // }
import java.net.MalformedURLException; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Link;
package com.pocketreddit.library.things.factories; public class LinkFactory implements ThingFactory { private JSONObject json; public LinkFactory(JSONObject json) { this.json = json; }
// Path: src/com/pocketreddit/library/things/Link.java // public class Link extends UserSubmittedContent { // private static final long serialVersionUID = 1L; // // private boolean clicked; // private String domain; // private boolean hidden; // private boolean selfPost; // private Object media; // private Object mediaEmbed; // private int numComments; // private boolean over18; // private String permalink; // private boolean saved; // private int score; // private URL thumbnail; // private String title; // private String url; // private String modHash; // // public Link() { // } // // public Link(JSONObject json) throws JsonParsingException { // // } // // public boolean isClicked() { // return clicked; // } // // public void setClicked(boolean clicked) { // this.clicked = clicked; // } // // public String getDomain() { // return domain; // } // // public void setDomain(String domain) { // this.domain = domain; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public boolean isSelfPost() { // return selfPost; // } // // public void setSelfPost(boolean selfPost) { // this.selfPost = selfPost; // } // // public Object getMedia() { // return media; // } // // public void setMedia(Object media) { // this.media = media; // } // // public Object getMediaEmbed() { // return mediaEmbed; // } // // public void setMediaEmbed(Object mediaEmbed) { // this.mediaEmbed = mediaEmbed; // } // // public int getNumComments() { // return numComments; // } // // public void setNumComments(int numComments) { // this.numComments = numComments; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public String getPermalink() { // return permalink; // } // // public void setPermalink(String permalink) { // this.permalink = permalink; // } // // public boolean isSaved() { // return saved; // } // // public void setSaved(boolean saved) { // this.saved = saved; // } // // public int getScore() { // return score; // } // // public void setScore(int score) { // this.score = score; // } // // public URL getThumbnail() { // return thumbnail; // } // // public void setThumbnail(URL thumbnail) { // this.thumbnail = thumbnail; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public String toString() { // return "Link [clicked=" + clicked + ", domain=" + domain + ", hidden=" + hidden // + ", selfPost=" + selfPost + ", media=" + media + ", mediaEmbed=" + mediaEmbed // + ", numComments=" + numComments + ", over18=" + over18 + ", permalink=" // + permalink + ", saved=" + saved + ", score=" + score + ", thumbnail=" + thumbnail // + ", title=" + title + ", url=" + url + ", modHash=" + modHash + "]"; // } // // public String getModHash() { // return modHash; // } // // public void setModHash(String modHash) { // this.modHash = modHash; // } // // @Override // public Kind getKind() { // return Kind.THREAD; // } // } // Path: src/com/pocketreddit/library/things/factories/LinkFactory.java import java.net.MalformedURLException; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Link; package com.pocketreddit.library.things.factories; public class LinkFactory implements ThingFactory { private JSONObject json; public LinkFactory(JSONObject json) { this.json = json; }
public Link createThing() throws ThingFactoryException {
achan/android-reddit
src/com/pocketreddit/library/things/factories/SubredditFactory.java
// Path: src/com/pocketreddit/library/things/Subreddit.java // public class Subreddit extends Thing { // private static final long serialVersionUID = 1L; // // private String title; // private String id; // private String description; // private String displayName; // private boolean over18; // private long numSubscribers; // // // private static String CLASS_NAME = Subreddit.class.getSimpleName(); // // /** // * The relative URL of the subreddit. Ex: "/r/pics/" // */ // private String url; // // @Override // public String toString() { // return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url // + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " // + title + "\nid: " + id + "\n=====\n"; // } // // @Override // public Kind getKind() { // return Kind.SUBREDDIT; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSubredditId() { // return id; // } // // public void setSubredditId(String subredditId) { // this.id = subredditId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public long getNumSubscribers() { // return numSubscribers; // } // // public void setNumSubscribers(long numSubscribers) { // this.numSubscribers = numSubscribers; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // }
import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Subreddit;
package com.pocketreddit.library.things.factories; public class SubredditFactory implements ThingFactory { private JSONObject json; public SubredditFactory(JSONObject json) { this.json = json; }
// Path: src/com/pocketreddit/library/things/Subreddit.java // public class Subreddit extends Thing { // private static final long serialVersionUID = 1L; // // private String title; // private String id; // private String description; // private String displayName; // private boolean over18; // private long numSubscribers; // // // private static String CLASS_NAME = Subreddit.class.getSimpleName(); // // /** // * The relative URL of the subreddit. Ex: "/r/pics/" // */ // private String url; // // @Override // public String toString() { // return "Subreddit:\n=====\ndisplayName: " + displayName + "\nurl: " + url // + "\nnumSubscribers: " + numSubscribers + "\nover18: " + over18 + "\ntitle: " // + title + "\nid: " + id + "\n=====\n"; // } // // @Override // public Kind getKind() { // return Kind.SUBREDDIT; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getSubredditId() { // return id; // } // // public void setSubredditId(String subredditId) { // this.id = subredditId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public boolean isOver18() { // return over18; // } // // public void setOver18(boolean over18) { // this.over18 = over18; // } // // public long getNumSubscribers() { // return numSubscribers; // } // // public void setNumSubscribers(long numSubscribers) { // this.numSubscribers = numSubscribers; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // Path: src/com/pocketreddit/library/things/factories/SubredditFactory.java import org.json.JSONException; import org.json.JSONObject; import com.pocketreddit.library.things.Subreddit; package com.pocketreddit.library.things.factories; public class SubredditFactory implements ThingFactory { private JSONObject json; public SubredditFactory(JSONObject json) { this.json = json; }
public Subreddit createThing() throws ThingFactoryException {
achan/android-reddit
src/com/pocketreddit/library/things/More.java
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // }
import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.Thing;
package com.pocketreddit.library.things; public class More extends Thing { private static final long serialVersionUID = 1L; @Override
// Path: src/com/pocketreddit/library/things/Kind.java // public enum Kind { // COMMENT("t1"), THREAD("t3"), MESSAGE("t4"), SUBREDDIT("t5"), MORE("more"), LISTING("Listing"); // // private String id; // // private Kind(String id) { // this.id = id; // } // // public String getId() { // return id; // } // // public static Kind toKind(String id) { // for (Kind kind : Kind.values()) { // if (kind.id.equals(id)) // return kind; // } // // throw new IllegalArgumentException("Could not find kind for id: " + id); // } // } // // Path: src/com/pocketreddit/library/things/Thing.java // public abstract class Thing implements Serializable { // private static final long serialVersionUID = 1L; // // private String id; // private String name; // // public abstract Kind getKind(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // Path: src/com/pocketreddit/library/things/More.java import com.pocketreddit.library.things.Kind; import com.pocketreddit.library.things.Thing; package com.pocketreddit.library.things; public class More extends Thing { private static final long serialVersionUID = 1L; @Override
public Kind getKind() {
sivaprasadreddy/jcart
jcart-core/src/main/java/com/sivalabs/jcart/common/services/EmailService.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/JCartException.java // public class JCartException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // public JCartException() // { // super(); // } // // public JCartException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public JCartException(String message, Throwable cause) // { // super(message, cause); // } // // public JCartException(String message) // { // super(message); // } // // public JCartException(Throwable cause) // { // super(cause); // } // // }
import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import com.sivalabs.jcart.JCartException;
/** * */ package com.sivalabs.jcart.common.services; /** * @author Siva * */ @Component public class EmailService { private static final JCLogger logger = JCLogger.getLogger(EmailService.class); @Autowired JavaMailSender javaMailSender; @Value("${support.email}") String supportEmail; public void sendEmail(String to, String subject, String content) { try { // Prepare message using a Spring helper final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); message.setSubject(subject); message.setFrom(supportEmail); message.setTo(to); message.setText(content, true /* isHtml */); javaMailSender.send(message.getMimeMessage()); } catch (MailException | MessagingException e) { logger.error(e);
// Path: jcart-core/src/main/java/com/sivalabs/jcart/JCartException.java // public class JCartException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // public JCartException() // { // super(); // } // // public JCartException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public JCartException(String message, Throwable cause) // { // super(message, cause); // } // // public JCartException(String message) // { // super(message); // } // // public JCartException(Throwable cause) // { // super(cause); // } // // } // Path: jcart-core/src/main/java/com/sivalabs/jcart/common/services/EmailService.java import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import com.sivalabs.jcart.JCartException; /** * */ package com.sivalabs.jcart.common.services; /** * @author Siva * */ @Component public class EmailService { private static final JCLogger logger = JCLogger.getLogger(EmailService.class); @Autowired JavaMailSender javaMailSender; @Value("${support.email}") String supportEmail; public void sendEmail(String to, String subject, String content) { try { // Prepare message using a Spring helper final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); message.setSubject(subject); message.setFrom(supportEmail); message.setTo(to); message.setText(content, true /* isHtml */); javaMailSender.send(message.getMimeMessage()); } catch (MailException | MessagingException e) { logger.error(e);
throw new JCartException("Unable to send email");
sivaprasadreddy/jcart
jcart-site/src/main/java/com/sivalabs/jcart/site/web/models/LineItem.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // }
import java.math.BigDecimal; import com.sivalabs.jcart.entities.Product;
/** * */ package com.sivalabs.jcart.site.web.models; /** * @author Siva * */ public class LineItem {
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // } // Path: jcart-site/src/main/java/com/sivalabs/jcart/site/web/models/LineItem.java import java.math.BigDecimal; import com.sivalabs.jcart.entities.Product; /** * */ package com.sivalabs.jcart.site.web.models; /** * @author Siva * */ public class LineItem {
private Product product;
sivaprasadreddy/jcart
jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Order.java // @Entity // @Table(name="orders") // public class Order implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(nullable=false, unique=true) // private String orderNumber; // @OneToMany(cascade=CascadeType.ALL, mappedBy="order") // private Set<OrderItem> items; // @ManyToOne(cascade=CascadeType.MERGE) // @JoinColumn(name="cust_id") // private Customer customer; // @OneToOne(cascade=CascadeType.PERSIST) // @JoinColumn(name="delivery_addr_id") // private Address deliveryAddress; // @OneToOne(cascade=CascadeType.PERSIST) // @JoinColumn(name="billing_addr_id") // private Address billingAddress; // @OneToOne(cascade=CascadeType.PERSIST) // @JoinColumn(name="payment_id") // private Payment payment; // @Enumerated(EnumType.STRING) // private OrderStatus status; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn; // // public Order() // { // this.items = new HashSet<OrderItem>(); // this.status = OrderStatus.NEW; // this.createdOn = new Date(); // } // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getOrderNumber() // { // return orderNumber; // } // // public void setOrderNumber(String orderNumber) // { // this.orderNumber = orderNumber; // } // // public Set<OrderItem> getItems() // { // return items; // } // public void setItems(Set<OrderItem> items) // { // this.items = items; // } // public Customer getCustomer() // { // return customer; // } // public void setCustomer(Customer customer) // { // this.customer = customer; // } // public Address getDeliveryAddress() // { // return deliveryAddress; // } // public void setDeliveryAddress(Address deliveryAddress) // { // this.deliveryAddress = deliveryAddress; // } // public Payment getPayment() // { // return payment; // } // public void setPayment(Payment payment) // { // this.payment = payment; // } // public OrderStatus getStatus() // { // return status; // } // public void setStatus(OrderStatus status) // { // this.status = status; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Address getBillingAddress() { // return billingAddress; // } // // public void setBillingAddress(Address billingAddress) { // this.billingAddress = billingAddress; // } // // // public BigDecimal getTotalAmount() // { // BigDecimal amount = new BigDecimal("0.0"); // for (OrderItem item : items) // { // amount = amount.add(item.getSubTotal()); // } // return amount; // } // // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.entities.Customer; import com.sivalabs.jcart.entities.Order;
/** * */ package com.sivalabs.jcart.customers; /** * @author Siva * */ @Service @Transactional public class CustomerService { @Autowired CustomerRepository customerRepository;
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Order.java // @Entity // @Table(name="orders") // public class Order implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(nullable=false, unique=true) // private String orderNumber; // @OneToMany(cascade=CascadeType.ALL, mappedBy="order") // private Set<OrderItem> items; // @ManyToOne(cascade=CascadeType.MERGE) // @JoinColumn(name="cust_id") // private Customer customer; // @OneToOne(cascade=CascadeType.PERSIST) // @JoinColumn(name="delivery_addr_id") // private Address deliveryAddress; // @OneToOne(cascade=CascadeType.PERSIST) // @JoinColumn(name="billing_addr_id") // private Address billingAddress; // @OneToOne(cascade=CascadeType.PERSIST) // @JoinColumn(name="payment_id") // private Payment payment; // @Enumerated(EnumType.STRING) // private OrderStatus status; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn; // // public Order() // { // this.items = new HashSet<OrderItem>(); // this.status = OrderStatus.NEW; // this.createdOn = new Date(); // } // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getOrderNumber() // { // return orderNumber; // } // // public void setOrderNumber(String orderNumber) // { // this.orderNumber = orderNumber; // } // // public Set<OrderItem> getItems() // { // return items; // } // public void setItems(Set<OrderItem> items) // { // this.items = items; // } // public Customer getCustomer() // { // return customer; // } // public void setCustomer(Customer customer) // { // this.customer = customer; // } // public Address getDeliveryAddress() // { // return deliveryAddress; // } // public void setDeliveryAddress(Address deliveryAddress) // { // this.deliveryAddress = deliveryAddress; // } // public Payment getPayment() // { // return payment; // } // public void setPayment(Payment payment) // { // this.payment = payment; // } // public OrderStatus getStatus() // { // return status; // } // public void setStatus(OrderStatus status) // { // this.status = status; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Address getBillingAddress() { // return billingAddress; // } // // public void setBillingAddress(Address billingAddress) { // this.billingAddress = billingAddress; // } // // // public BigDecimal getTotalAmount() // { // BigDecimal amount = new BigDecimal("0.0"); // for (OrderItem item : items) // { // amount = amount.add(item.getSubTotal()); // } // return amount; // } // // } // Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.entities.Customer; import com.sivalabs.jcart.entities.Order; /** * */ package com.sivalabs.jcart.customers; /** * @author Siva * */ @Service @Transactional public class CustomerService { @Autowired CustomerRepository customerRepository;
public Customer getCustomerByEmail(String email) {
sivaprasadreddy/jcart
jcart-site/src/main/java/com/sivalabs/jcart/site/security/AuthenticatedUser.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // }
import com.sivalabs.jcart.entities.Customer; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils;
/** * */ package com.sivalabs.jcart.site.security; public class AuthenticatedUser extends org.springframework.security.core.userdetails.User { private static final long serialVersionUID = 1L;
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // Path: jcart-site/src/main/java/com/sivalabs/jcart/site/security/AuthenticatedUser.java import com.sivalabs.jcart.entities.Customer; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; /** * */ package com.sivalabs.jcart.site.security; public class AuthenticatedUser extends org.springframework.security.core.userdetails.User { private static final long serialVersionUID = 1L;
private Customer customer;
sivaprasadreddy/jcart
jcart-site/src/main/java/com/sivalabs/jcart/site/security/CustomUserDetailsService.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer;
/** * */ package com.sivalabs.jcart.site.security; /** * @author Siva * */ @Service @Transactional public class CustomUserDetailsService implements UserDetailsService {
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // Path: jcart-site/src/main/java/com/sivalabs/jcart/site/security/CustomUserDetailsService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer; /** * */ package com.sivalabs.jcart.site.security; /** * @author Siva * */ @Service @Transactional public class CustomUserDetailsService implements UserDetailsService {
@Autowired CustomerService customerService;
sivaprasadreddy/jcart
jcart-site/src/main/java/com/sivalabs/jcart/site/security/CustomUserDetailsService.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer;
/** * */ package com.sivalabs.jcart.site.security; /** * @author Siva * */ @Service @Transactional public class CustomUserDetailsService implements UserDetailsService { @Autowired CustomerService customerService; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // Path: jcart-site/src/main/java/com/sivalabs/jcart/site/security/CustomUserDetailsService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer; /** * */ package com.sivalabs.jcart.site.security; /** * @author Siva * */ @Service @Transactional public class CustomUserDetailsService implements UserDetailsService { @Autowired CustomerService customerService; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Customer customer = customerService.getCustomerByEmail(email);
sivaprasadreddy/jcart
jcart-site/src/main/java/com/sivalabs/jcart/site/web/validators/CustomerValidator.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer;
/** * */ package com.sivalabs.jcart.site.web.validators; /** * @author Siva * */ @Component public class CustomerValidator implements Validator {
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // Path: jcart-site/src/main/java/com/sivalabs/jcart/site/web/validators/CustomerValidator.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer; /** * */ package com.sivalabs.jcart.site.web.validators; /** * @author Siva * */ @Component public class CustomerValidator implements Validator {
@Autowired private CustomerService custmoerService;
sivaprasadreddy/jcart
jcart-site/src/main/java/com/sivalabs/jcart/site/web/validators/CustomerValidator.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer;
/** * */ package com.sivalabs.jcart.site.web.validators; /** * @author Siva * */ @Component public class CustomerValidator implements Validator { @Autowired private CustomerService custmoerService; @Override public boolean supports(Class<?> clazz) {
// Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // Path: jcart-site/src/main/java/com/sivalabs/jcart/site/web/validators/CustomerValidator.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer; /** * */ package com.sivalabs.jcart.site.web.validators; /** * @author Siva * */ @Component public class CustomerValidator implements Validator { @Autowired private CustomerService custmoerService; @Override public boolean supports(Class<?> clazz) {
return Customer.class.isAssignableFrom(clazz);
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/models/ProductForm.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // }
import java.math.BigDecimal; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.web.multipart.MultipartFile; import com.sivalabs.jcart.entities.Category; import com.sivalabs.jcart.entities.Product;
return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; }
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/models/ProductForm.java import java.math.BigDecimal; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.web.multipart.MultipartFile; import com.sivalabs.jcart.entities.Category; import com.sivalabs.jcart.entities.Product; return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; }
public Product toProduct() {
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/models/ProductForm.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // }
import java.math.BigDecimal; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.web.multipart.MultipartFile; import com.sivalabs.jcart.entities.Category; import com.sivalabs.jcart.entities.Product;
} public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Product toProduct() { Product p = new Product(); p.setId(id); p.setName(name); p.setDescription(description); p.setDisabled(disabled); p.setPrice(price); p.setSku(sku);
// Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/models/ProductForm.java import java.math.BigDecimal; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.web.multipart.MultipartFile; import com.sivalabs.jcart.entities.Category; import com.sivalabs.jcart.entities.Product; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Product toProduct() { Product p = new Product(); p.setId(id); p.setName(name); p.setDescription(description); p.setDisabled(disabled); p.setPrice(price); p.setSku(sku);
Category category = new Category();
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/JCartAdminBaseController.java
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/AuthenticatedUser.java // public class AuthenticatedUser extends org.springframework.security.core.userdetails.User // { // // private static final long serialVersionUID = 1L; // private User user; // // public AuthenticatedUser(User user) // { // super(user.getEmail(), user.getPassword(), getAuthorities(user)); // this.user = user; // } // // public User getUser() // { // return user; // } // // private static Collection<? extends GrantedAuthority> getAuthorities(User user) // { // Set<String> roleAndPermissions = new HashSet<>(); // List<Role> roles = user.getRoles(); // // for (Role role : roles) // { // roleAndPermissions.add(role.getName()); // List<Permission> permissions = role.getPermissions(); // for (Permission permission : permissions) // { // roleAndPermissions.add("ROLE_"+permission.getName()); // } // } // String[] roleNames = new String[roleAndPermissions.size()]; // Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roleAndPermissions.toArray(roleNames)); // return authorities; // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/common/services/JCLogger.java // public class JCLogger // { // private Logger logger; // // public JCLogger(Class<?> clazz) // { // this.logger = LoggerFactory.getLogger(clazz); // } // // public static final JCLogger getLogger(Class<?> clazz) // { // return new JCLogger(clazz); // } // // public void info(String msg) // { // this.logger.info(msg); // } // public void info(String format, Object...args) // { // this.logger.info(format, args); // } // // public void debug(String msg) // { // this.logger.debug(msg); // } // // public void debug(String format, Object...args) // { // this.logger.info(format, args); // } // // public void warn(String msg) // { // this.logger.info(msg); // } // // public void warn(String format, Object...args) // { // this.logger.info(format, args); // } // // public void error(String msg) // { // this.logger.error(msg); // } // // public void error(String format, Object...args) // { // this.logger.error(format, args); // } // // public void error(Throwable t) // { // this.logger.error(t.getMessage(), t); // } // // public void error(String msg, Throwable t) // { // this.logger.error(msg, t); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ModelAttribute; import com.sivalabs.jcart.admin.security.AuthenticatedUser; import com.sivalabs.jcart.common.services.JCLogger;
/** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ public abstract class JCartAdminBaseController {
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/AuthenticatedUser.java // public class AuthenticatedUser extends org.springframework.security.core.userdetails.User // { // // private static final long serialVersionUID = 1L; // private User user; // // public AuthenticatedUser(User user) // { // super(user.getEmail(), user.getPassword(), getAuthorities(user)); // this.user = user; // } // // public User getUser() // { // return user; // } // // private static Collection<? extends GrantedAuthority> getAuthorities(User user) // { // Set<String> roleAndPermissions = new HashSet<>(); // List<Role> roles = user.getRoles(); // // for (Role role : roles) // { // roleAndPermissions.add(role.getName()); // List<Permission> permissions = role.getPermissions(); // for (Permission permission : permissions) // { // roleAndPermissions.add("ROLE_"+permission.getName()); // } // } // String[] roleNames = new String[roleAndPermissions.size()]; // Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roleAndPermissions.toArray(roleNames)); // return authorities; // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/common/services/JCLogger.java // public class JCLogger // { // private Logger logger; // // public JCLogger(Class<?> clazz) // { // this.logger = LoggerFactory.getLogger(clazz); // } // // public static final JCLogger getLogger(Class<?> clazz) // { // return new JCLogger(clazz); // } // // public void info(String msg) // { // this.logger.info(msg); // } // public void info(String format, Object...args) // { // this.logger.info(format, args); // } // // public void debug(String msg) // { // this.logger.debug(msg); // } // // public void debug(String format, Object...args) // { // this.logger.info(format, args); // } // // public void warn(String msg) // { // this.logger.info(msg); // } // // public void warn(String format, Object...args) // { // this.logger.info(format, args); // } // // public void error(String msg) // { // this.logger.error(msg); // } // // public void error(String format, Object...args) // { // this.logger.error(format, args); // } // // public void error(Throwable t) // { // this.logger.error(t.getMessage(), t); // } // // public void error(String msg, Throwable t) // { // this.logger.error(msg, t); // } // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/JCartAdminBaseController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ModelAttribute; import com.sivalabs.jcart.admin.security.AuthenticatedUser; import com.sivalabs.jcart.common.services.JCLogger; /** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ public abstract class JCartAdminBaseController {
protected final JCLogger logger = JCLogger.getLogger(getClass());
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/JCartAdminBaseController.java
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/AuthenticatedUser.java // public class AuthenticatedUser extends org.springframework.security.core.userdetails.User // { // // private static final long serialVersionUID = 1L; // private User user; // // public AuthenticatedUser(User user) // { // super(user.getEmail(), user.getPassword(), getAuthorities(user)); // this.user = user; // } // // public User getUser() // { // return user; // } // // private static Collection<? extends GrantedAuthority> getAuthorities(User user) // { // Set<String> roleAndPermissions = new HashSet<>(); // List<Role> roles = user.getRoles(); // // for (Role role : roles) // { // roleAndPermissions.add(role.getName()); // List<Permission> permissions = role.getPermissions(); // for (Permission permission : permissions) // { // roleAndPermissions.add("ROLE_"+permission.getName()); // } // } // String[] roleNames = new String[roleAndPermissions.size()]; // Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roleAndPermissions.toArray(roleNames)); // return authorities; // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/common/services/JCLogger.java // public class JCLogger // { // private Logger logger; // // public JCLogger(Class<?> clazz) // { // this.logger = LoggerFactory.getLogger(clazz); // } // // public static final JCLogger getLogger(Class<?> clazz) // { // return new JCLogger(clazz); // } // // public void info(String msg) // { // this.logger.info(msg); // } // public void info(String format, Object...args) // { // this.logger.info(format, args); // } // // public void debug(String msg) // { // this.logger.debug(msg); // } // // public void debug(String format, Object...args) // { // this.logger.info(format, args); // } // // public void warn(String msg) // { // this.logger.info(msg); // } // // public void warn(String format, Object...args) // { // this.logger.info(format, args); // } // // public void error(String msg) // { // this.logger.error(msg); // } // // public void error(String format, Object...args) // { // this.logger.error(format, args); // } // // public void error(Throwable t) // { // this.logger.error(t.getMessage(), t); // } // // public void error(String msg, Throwable t) // { // this.logger.error(msg, t); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ModelAttribute; import com.sivalabs.jcart.admin.security.AuthenticatedUser; import com.sivalabs.jcart.common.services.JCLogger;
/** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ public abstract class JCartAdminBaseController { protected final JCLogger logger = JCLogger.getLogger(getClass()); @Autowired protected MessageSource messageSource; protected abstract String getHeaderTitle(); public String getMessage(String code) { return messageSource.getMessage(code, null, null); } public String getMessage(String code, String defaultMsg) { return messageSource.getMessage(code, null, defaultMsg, null); } @ModelAttribute("authenticatedUser")
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/AuthenticatedUser.java // public class AuthenticatedUser extends org.springframework.security.core.userdetails.User // { // // private static final long serialVersionUID = 1L; // private User user; // // public AuthenticatedUser(User user) // { // super(user.getEmail(), user.getPassword(), getAuthorities(user)); // this.user = user; // } // // public User getUser() // { // return user; // } // // private static Collection<? extends GrantedAuthority> getAuthorities(User user) // { // Set<String> roleAndPermissions = new HashSet<>(); // List<Role> roles = user.getRoles(); // // for (Role role : roles) // { // roleAndPermissions.add(role.getName()); // List<Permission> permissions = role.getPermissions(); // for (Permission permission : permissions) // { // roleAndPermissions.add("ROLE_"+permission.getName()); // } // } // String[] roleNames = new String[roleAndPermissions.size()]; // Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roleAndPermissions.toArray(roleNames)); // return authorities; // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/common/services/JCLogger.java // public class JCLogger // { // private Logger logger; // // public JCLogger(Class<?> clazz) // { // this.logger = LoggerFactory.getLogger(clazz); // } // // public static final JCLogger getLogger(Class<?> clazz) // { // return new JCLogger(clazz); // } // // public void info(String msg) // { // this.logger.info(msg); // } // public void info(String format, Object...args) // { // this.logger.info(format, args); // } // // public void debug(String msg) // { // this.logger.debug(msg); // } // // public void debug(String format, Object...args) // { // this.logger.info(format, args); // } // // public void warn(String msg) // { // this.logger.info(msg); // } // // public void warn(String format, Object...args) // { // this.logger.info(format, args); // } // // public void error(String msg) // { // this.logger.error(msg); // } // // public void error(String format, Object...args) // { // this.logger.error(format, args); // } // // public void error(Throwable t) // { // this.logger.error(t.getMessage(), t); // } // // public void error(String msg, Throwable t) // { // this.logger.error(msg, t); // } // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/JCartAdminBaseController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ModelAttribute; import com.sivalabs.jcart.admin.security.AuthenticatedUser; import com.sivalabs.jcart.common.services.JCLogger; /** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ public abstract class JCartAdminBaseController { protected final JCLogger logger = JCLogger.getLogger(getClass()); @Autowired protected MessageSource messageSource; protected abstract String getHeaderTitle(); public String getMessage(String code) { return messageSource.getMessage(code, null, null); } public String getMessage(String code, String defaultMsg) { return messageSource.getMessage(code, null, defaultMsg, null); } @ModelAttribute("authenticatedUser")
public AuthenticatedUser authenticatedUser(@AuthenticationPrincipal AuthenticatedUser authenticatedUser)
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/validators/CategoryValidator.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/catalog/CatalogService.java // @Service // @Transactional // public class CatalogService { // @Autowired CategoryRepository categoryRepository; // @Autowired ProductRepository productRepository; // // public List<Category> getAllCategories() { // // return categoryRepository.findAll(); // } // // public List<Product> getAllProducts() { // // return productRepository.findAll(); // } // // public Category getCategoryByName(String name) { // return categoryRepository.getByName(name); // } // // public Category getCategoryById(Integer id) { // return categoryRepository.findOne(id); // } // // public Category createCategory(Category category) { // Category persistedCategory = getCategoryByName(category.getName()); // if(persistedCategory != null){ // throw new JCartException("Category "+category.getName()+" already exist"); // } // return categoryRepository.save(category); // } // // public Category updateCategory(Category category) { // Category persistedCategory = getCategoryById(category.getId()); // if(persistedCategory == null){ // throw new JCartException("Category "+category.getId()+" doesn't exist"); // } // persistedCategory.setDescription(category.getDescription()); // persistedCategory.setDisplayOrder(category.getDisplayOrder()); // persistedCategory.setDisabled(category.isDisabled()); // return categoryRepository.save(persistedCategory); // } // // public Product getProductById(Integer id) { // return productRepository.findOne(id); // } // // public Product getProductBySku(String sku) { // return productRepository.findBySku(sku); // } // // public Product createProduct(Product product) { // Product persistedProduct = getProductBySku(product.getName()); // if(persistedProduct != null){ // throw new JCartException("Product SKU "+product.getSku()+" already exist"); // } // return productRepository.save(product); // } // // public Product updateProduct(Product product) { // Product persistedProduct = getProductById(product.getId()); // if(persistedProduct == null){ // throw new JCartException("Product "+product.getId()+" doesn't exist"); // } // persistedProduct.setDescription(product.getDescription()); // persistedProduct.setDisabled(product.isDisabled()); // persistedProduct.setPrice(product.getPrice()); // persistedProduct.setCategory(getCategoryById(product.getCategory().getId())); // return productRepository.save(persistedProduct); // } // // public List<Product> searchProducts(String query) { // return productRepository.search("%"+query+"%"); // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.catalog.CatalogService; import com.sivalabs.jcart.entities.Category;
/** * */ package com.sivalabs.jcart.admin.web.validators; /** * @author Siva * */ @Component public class CategoryValidator implements Validator { @Autowired protected MessageSource messageSource;
// Path: jcart-core/src/main/java/com/sivalabs/jcart/catalog/CatalogService.java // @Service // @Transactional // public class CatalogService { // @Autowired CategoryRepository categoryRepository; // @Autowired ProductRepository productRepository; // // public List<Category> getAllCategories() { // // return categoryRepository.findAll(); // } // // public List<Product> getAllProducts() { // // return productRepository.findAll(); // } // // public Category getCategoryByName(String name) { // return categoryRepository.getByName(name); // } // // public Category getCategoryById(Integer id) { // return categoryRepository.findOne(id); // } // // public Category createCategory(Category category) { // Category persistedCategory = getCategoryByName(category.getName()); // if(persistedCategory != null){ // throw new JCartException("Category "+category.getName()+" already exist"); // } // return categoryRepository.save(category); // } // // public Category updateCategory(Category category) { // Category persistedCategory = getCategoryById(category.getId()); // if(persistedCategory == null){ // throw new JCartException("Category "+category.getId()+" doesn't exist"); // } // persistedCategory.setDescription(category.getDescription()); // persistedCategory.setDisplayOrder(category.getDisplayOrder()); // persistedCategory.setDisabled(category.isDisabled()); // return categoryRepository.save(persistedCategory); // } // // public Product getProductById(Integer id) { // return productRepository.findOne(id); // } // // public Product getProductBySku(String sku) { // return productRepository.findBySku(sku); // } // // public Product createProduct(Product product) { // Product persistedProduct = getProductBySku(product.getName()); // if(persistedProduct != null){ // throw new JCartException("Product SKU "+product.getSku()+" already exist"); // } // return productRepository.save(product); // } // // public Product updateProduct(Product product) { // Product persistedProduct = getProductById(product.getId()); // if(persistedProduct == null){ // throw new JCartException("Product "+product.getId()+" doesn't exist"); // } // persistedProduct.setDescription(product.getDescription()); // persistedProduct.setDisabled(product.isDisabled()); // persistedProduct.setPrice(product.getPrice()); // persistedProduct.setCategory(getCategoryById(product.getCategory().getId())); // return productRepository.save(persistedProduct); // } // // public List<Product> searchProducts(String query) { // return productRepository.search("%"+query+"%"); // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/validators/CategoryValidator.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.catalog.CatalogService; import com.sivalabs.jcart.entities.Category; /** * */ package com.sivalabs.jcart.admin.web.validators; /** * @author Siva * */ @Component public class CategoryValidator implements Validator { @Autowired protected MessageSource messageSource;
@Autowired protected CatalogService catalogService;
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/validators/CategoryValidator.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/catalog/CatalogService.java // @Service // @Transactional // public class CatalogService { // @Autowired CategoryRepository categoryRepository; // @Autowired ProductRepository productRepository; // // public List<Category> getAllCategories() { // // return categoryRepository.findAll(); // } // // public List<Product> getAllProducts() { // // return productRepository.findAll(); // } // // public Category getCategoryByName(String name) { // return categoryRepository.getByName(name); // } // // public Category getCategoryById(Integer id) { // return categoryRepository.findOne(id); // } // // public Category createCategory(Category category) { // Category persistedCategory = getCategoryByName(category.getName()); // if(persistedCategory != null){ // throw new JCartException("Category "+category.getName()+" already exist"); // } // return categoryRepository.save(category); // } // // public Category updateCategory(Category category) { // Category persistedCategory = getCategoryById(category.getId()); // if(persistedCategory == null){ // throw new JCartException("Category "+category.getId()+" doesn't exist"); // } // persistedCategory.setDescription(category.getDescription()); // persistedCategory.setDisplayOrder(category.getDisplayOrder()); // persistedCategory.setDisabled(category.isDisabled()); // return categoryRepository.save(persistedCategory); // } // // public Product getProductById(Integer id) { // return productRepository.findOne(id); // } // // public Product getProductBySku(String sku) { // return productRepository.findBySku(sku); // } // // public Product createProduct(Product product) { // Product persistedProduct = getProductBySku(product.getName()); // if(persistedProduct != null){ // throw new JCartException("Product SKU "+product.getSku()+" already exist"); // } // return productRepository.save(product); // } // // public Product updateProduct(Product product) { // Product persistedProduct = getProductById(product.getId()); // if(persistedProduct == null){ // throw new JCartException("Product "+product.getId()+" doesn't exist"); // } // persistedProduct.setDescription(product.getDescription()); // persistedProduct.setDisabled(product.isDisabled()); // persistedProduct.setPrice(product.getPrice()); // persistedProduct.setCategory(getCategoryById(product.getCategory().getId())); // return productRepository.save(persistedProduct); // } // // public List<Product> searchProducts(String query) { // return productRepository.search("%"+query+"%"); // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.catalog.CatalogService; import com.sivalabs.jcart.entities.Category;
/** * */ package com.sivalabs.jcart.admin.web.validators; /** * @author Siva * */ @Component public class CategoryValidator implements Validator { @Autowired protected MessageSource messageSource; @Autowired protected CatalogService catalogService; @Override public boolean supports(Class<?> clazz) {
// Path: jcart-core/src/main/java/com/sivalabs/jcart/catalog/CatalogService.java // @Service // @Transactional // public class CatalogService { // @Autowired CategoryRepository categoryRepository; // @Autowired ProductRepository productRepository; // // public List<Category> getAllCategories() { // // return categoryRepository.findAll(); // } // // public List<Product> getAllProducts() { // // return productRepository.findAll(); // } // // public Category getCategoryByName(String name) { // return categoryRepository.getByName(name); // } // // public Category getCategoryById(Integer id) { // return categoryRepository.findOne(id); // } // // public Category createCategory(Category category) { // Category persistedCategory = getCategoryByName(category.getName()); // if(persistedCategory != null){ // throw new JCartException("Category "+category.getName()+" already exist"); // } // return categoryRepository.save(category); // } // // public Category updateCategory(Category category) { // Category persistedCategory = getCategoryById(category.getId()); // if(persistedCategory == null){ // throw new JCartException("Category "+category.getId()+" doesn't exist"); // } // persistedCategory.setDescription(category.getDescription()); // persistedCategory.setDisplayOrder(category.getDisplayOrder()); // persistedCategory.setDisabled(category.isDisabled()); // return categoryRepository.save(persistedCategory); // } // // public Product getProductById(Integer id) { // return productRepository.findOne(id); // } // // public Product getProductBySku(String sku) { // return productRepository.findBySku(sku); // } // // public Product createProduct(Product product) { // Product persistedProduct = getProductBySku(product.getName()); // if(persistedProduct != null){ // throw new JCartException("Product SKU "+product.getSku()+" already exist"); // } // return productRepository.save(product); // } // // public Product updateProduct(Product product) { // Product persistedProduct = getProductById(product.getId()); // if(persistedProduct == null){ // throw new JCartException("Product "+product.getId()+" doesn't exist"); // } // persistedProduct.setDescription(product.getDescription()); // persistedProduct.setDisabled(product.isDisabled()); // persistedProduct.setPrice(product.getPrice()); // persistedProduct.setCategory(getCategoryById(product.getCategory().getId())); // return productRepository.save(persistedProduct); // } // // public List<Product> searchProducts(String query) { // return productRepository.search("%"+query+"%"); // } // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/validators/CategoryValidator.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sivalabs.jcart.catalog.CatalogService; import com.sivalabs.jcart.entities.Category; /** * */ package com.sivalabs.jcart.admin.web.validators; /** * @author Siva * */ @Component public class CategoryValidator implements Validator { @Autowired protected MessageSource messageSource; @Autowired protected CatalogService catalogService; @Override public boolean supports(Class<?> clazz) {
return Category.class.isAssignableFrom(clazz);
sivaprasadreddy/jcart
jcart-core/src/test/java/com/sivalabs/jcart/JCartCoreApplicationTest.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/common/services/EmailService.java // @Component // public class EmailService // { // private static final JCLogger logger = JCLogger.getLogger(EmailService.class); // // @Autowired JavaMailSender javaMailSender; // // @Value("${support.email}") String supportEmail; // // public void sendEmail(String to, String subject, String content) // { // try // { // // Prepare message using a Spring helper // final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage(); // final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); // message.setSubject(subject); // message.setFrom(supportEmail); // message.setTo(to); // message.setText(content, true /* isHtml */); // // javaMailSender.send(message.getMimeMessage()); // } // catch (MailException | MessagingException e) // { // logger.error(e); // throw new JCartException("Unable to send email"); // } // } // // // }
import static org.junit.Assert.*; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.sivalabs.jcart.common.services.EmailService;
/** * */ package com.sivalabs.jcart; /** * @author Siva * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = JCartCoreApplication.class) public class JCartCoreApplicationTest { @Autowired DataSource dataSource;
// Path: jcart-core/src/main/java/com/sivalabs/jcart/common/services/EmailService.java // @Component // public class EmailService // { // private static final JCLogger logger = JCLogger.getLogger(EmailService.class); // // @Autowired JavaMailSender javaMailSender; // // @Value("${support.email}") String supportEmail; // // public void sendEmail(String to, String subject, String content) // { // try // { // // Prepare message using a Spring helper // final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage(); // final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); // message.setSubject(subject); // message.setFrom(supportEmail); // message.setTo(to); // message.setText(content, true /* isHtml */); // // javaMailSender.send(message.getMimeMessage()); // } // catch (MailException | MessagingException e) // { // logger.error(e); // throw new JCartException("Unable to send email"); // } // } // // // } // Path: jcart-core/src/test/java/com/sivalabs/jcart/JCartCoreApplicationTest.java import static org.junit.Assert.*; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.sivalabs.jcart.common.services.EmailService; /** * */ package com.sivalabs.jcart; /** * @author Siva * */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = JCartCoreApplication.class) public class JCartCoreApplicationTest { @Autowired DataSource dataSource;
@Autowired EmailService emailService;
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/config/WebConfig.java
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/PostAuthorizationFilter.java // @Component // public class PostAuthorizationFilter extends OncePerRequestFilter // { // @Autowired SecurityService securityService; // // protected String[] IGNORE_URIS = { // "/assets/" // }; // // @Override // protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) // throws ServletException, IOException // { // String uri = request.getRequestURI(); // if(!isIgnorableURI(uri)){ // String menu = MenuConfiguration.getMatchingMenu(uri); // request.setAttribute("CURRENT_MENU", menu); // } // chain.doFilter(request, response); // } // // private boolean isIgnorableURI(String uri) // { // for (String u : IGNORE_URIS) // { // if(uri.startsWith(u)) // { // return true; // } // } // return false; // } // }
import javax.servlet.Filter; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import com.sivalabs.jcart.admin.security.PostAuthorizationFilter;
/** * */ package com.sivalabs.jcart.admin.config; /** * @author Siva * */ @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Value("${server.port:9443}") private int serverPort; @Autowired
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/PostAuthorizationFilter.java // @Component // public class PostAuthorizationFilter extends OncePerRequestFilter // { // @Autowired SecurityService securityService; // // protected String[] IGNORE_URIS = { // "/assets/" // }; // // @Override // protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) // throws ServletException, IOException // { // String uri = request.getRequestURI(); // if(!isIgnorableURI(uri)){ // String menu = MenuConfiguration.getMatchingMenu(uri); // request.setAttribute("CURRENT_MENU", menu); // } // chain.doFilter(request, response); // } // // private boolean isIgnorableURI(String uri) // { // for (String u : IGNORE_URIS) // { // if(uri.startsWith(u)) // { // return true; // } // } // return false; // } // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/config/WebConfig.java import javax.servlet.Filter; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import com.sivalabs.jcart.admin.security.PostAuthorizationFilter; /** * */ package com.sivalabs.jcart.admin.config; /** * @author Siva * */ @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Value("${server.port:9443}") private int serverPort; @Autowired
private PostAuthorizationFilter postAuthorizationFilter;
sivaprasadreddy/jcart
jcart-core/src/main/java/com/sivalabs/jcart/catalog/CatalogService.java
// Path: jcart-core/src/main/java/com/sivalabs/jcart/JCartException.java // public class JCartException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // public JCartException() // { // super(); // } // // public JCartException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public JCartException(String message, Throwable cause) // { // super(message, cause); // } // // public JCartException(String message) // { // super(message); // } // // public JCartException(Throwable cause) // { // super(cause); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.JCartException; import com.sivalabs.jcart.entities.Category; import com.sivalabs.jcart.entities.Product;
/** * */ package com.sivalabs.jcart.catalog; /** * @author Siva * */ @Service @Transactional public class CatalogService { @Autowired CategoryRepository categoryRepository; @Autowired ProductRepository productRepository;
// Path: jcart-core/src/main/java/com/sivalabs/jcart/JCartException.java // public class JCartException extends RuntimeException // { // private static final long serialVersionUID = 1L; // // public JCartException() // { // super(); // } // // public JCartException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public JCartException(String message, Throwable cause) // { // super(message, cause); // } // // public JCartException(String message) // { // super(message); // } // // public JCartException(Throwable cause) // { // super(cause); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Category.java // @Entity // @Table(name="categories") // public class Category // { // @Id @GeneratedValue(strategy=GenerationType.AUTO) // private Integer id; // @Column(nullable=false, unique=true) // @NotEmpty // private String name; // @Column(length=1024) // private String description; // @Column(name="disp_order") // private Integer displayOrder; // private boolean disabled; // @OneToMany(mappedBy="category") // private Set<Product> products; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public Integer getDisplayOrder() // { // return displayOrder; // } // public void setDisplayOrder(Integer displayOrder) // { // this.displayOrder = displayOrder; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Set<Product> getProducts() // { // return products; // } // public void setProducts(Set<Product> products) // { // this.products = products; // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Product.java // @Entity // @Table(name="products") // public class Product implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // @Column(name="id") // private Integer id; // @Column(nullable=false, unique=true) // private String sku; // @Column(nullable=false) // private String name; // private String description; // @Column(nullable=false) // private BigDecimal price = new BigDecimal("0.0"); // private String imageUrl; // private boolean disabled; // @Temporal(TemporalType.TIMESTAMP) // @Column(name="created_on") // private Date createdOn = new Date(); // // @ManyToOne // @JoinColumn(name="cat_id") // private Category category; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // // public String getSku() // { // return sku; // } // public void setSku(String sku) // { // this.sku = sku; // } // public String getName() // { // return name; // } // public void setName(String name) // { // this.name = name; // } // public String getDescription() // { // return description; // } // public void setDescription(String description) // { // this.description = description; // } // public BigDecimal getPrice() // { // return price; // } // public void setPrice(BigDecimal price) // { // this.price = price; // } // public String getImageUrl() // { // return imageUrl; // } // public void setImageUrl(String imageUrl) // { // this.imageUrl = imageUrl; // } // // public boolean isDisabled() // { // return disabled; // } // public void setDisabled(boolean disabled) // { // this.disabled = disabled; // } // public Date getCreatedOn() // { // return createdOn; // } // public void setCreatedOn(Date createdOn) // { // this.createdOn = createdOn; // } // // public Category getCategory() // { // return category; // } // public void setCategory(Category category) // { // this.category = category; // } // // } // Path: jcart-core/src/main/java/com/sivalabs/jcart/catalog/CatalogService.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.jcart.JCartException; import com.sivalabs.jcart.entities.Category; import com.sivalabs.jcart.entities.Product; /** * */ package com.sivalabs.jcart.catalog; /** * @author Siva * */ @Service @Transactional public class CatalogService { @Autowired CategoryRepository categoryRepository; @Autowired ProductRepository productRepository;
public List<Category> getAllCategories() {
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/CustomerController.java
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/SecurityUtil.java // public class SecurityUtil // { // // public static final String MANAGE_CATEGORIES = "ROLE_MANAGE_CATEGORIES"; // public static final String MANAGE_PRODUCTS = "ROLE_MANAGE_PRODUCTS"; // public static final String MANAGE_ORDERS = "ROLE_MANAGE_ORDERS"; // public static final String MANAGE_CUSTOMERS = "ROLE_MANAGE_CUSTOMERS"; // public static final String MANAGE_PAYMENT_SYSTEMS = "ROLE_MANAGE_PAYMENT_SYSTEMS"; // public static final String MANAGE_USERS = "ROLE_MANAGE_USERS"; // public static final String MANAGE_ROLES = "ROLE_MANAGE_ROLES"; // public static final String MANAGE_PERMISSIONS = "ROLE_MANAGE_PERMISSIONS"; // public static final String MANAGE_SETTINGS = "ROLE_MANAGE_SETTINGS"; // // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.sivalabs.jcart.admin.security.SecurityUtil; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer;
/** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ @Controller @Secured(SecurityUtil.MANAGE_CUSTOMERS) public class CustomerController extends JCartAdminBaseController { private static final String viewPrefix = "customers/"; @Autowired
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/SecurityUtil.java // public class SecurityUtil // { // // public static final String MANAGE_CATEGORIES = "ROLE_MANAGE_CATEGORIES"; // public static final String MANAGE_PRODUCTS = "ROLE_MANAGE_PRODUCTS"; // public static final String MANAGE_ORDERS = "ROLE_MANAGE_ORDERS"; // public static final String MANAGE_CUSTOMERS = "ROLE_MANAGE_CUSTOMERS"; // public static final String MANAGE_PAYMENT_SYSTEMS = "ROLE_MANAGE_PAYMENT_SYSTEMS"; // public static final String MANAGE_USERS = "ROLE_MANAGE_USERS"; // public static final String MANAGE_ROLES = "ROLE_MANAGE_ROLES"; // public static final String MANAGE_PERMISSIONS = "ROLE_MANAGE_PERMISSIONS"; // public static final String MANAGE_SETTINGS = "ROLE_MANAGE_SETTINGS"; // // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/CustomerController.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.sivalabs.jcart.admin.security.SecurityUtil; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer; /** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ @Controller @Secured(SecurityUtil.MANAGE_CUSTOMERS) public class CustomerController extends JCartAdminBaseController { private static final String viewPrefix = "customers/"; @Autowired
private CustomerService customerService;
sivaprasadreddy/jcart
jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/CustomerController.java
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/SecurityUtil.java // public class SecurityUtil // { // // public static final String MANAGE_CATEGORIES = "ROLE_MANAGE_CATEGORIES"; // public static final String MANAGE_PRODUCTS = "ROLE_MANAGE_PRODUCTS"; // public static final String MANAGE_ORDERS = "ROLE_MANAGE_ORDERS"; // public static final String MANAGE_CUSTOMERS = "ROLE_MANAGE_CUSTOMERS"; // public static final String MANAGE_PAYMENT_SYSTEMS = "ROLE_MANAGE_PAYMENT_SYSTEMS"; // public static final String MANAGE_USERS = "ROLE_MANAGE_USERS"; // public static final String MANAGE_ROLES = "ROLE_MANAGE_ROLES"; // public static final String MANAGE_PERMISSIONS = "ROLE_MANAGE_PERMISSIONS"; // public static final String MANAGE_SETTINGS = "ROLE_MANAGE_SETTINGS"; // // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.sivalabs.jcart.admin.security.SecurityUtil; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer;
/** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ @Controller @Secured(SecurityUtil.MANAGE_CUSTOMERS) public class CustomerController extends JCartAdminBaseController { private static final String viewPrefix = "customers/"; @Autowired private CustomerService customerService; @Override protected String getHeaderTitle() { return "Manage Customers"; } @RequestMapping(value="/customers", method=RequestMethod.GET) public String listCustomers(Model model) {
// Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/SecurityUtil.java // public class SecurityUtil // { // // public static final String MANAGE_CATEGORIES = "ROLE_MANAGE_CATEGORIES"; // public static final String MANAGE_PRODUCTS = "ROLE_MANAGE_PRODUCTS"; // public static final String MANAGE_ORDERS = "ROLE_MANAGE_ORDERS"; // public static final String MANAGE_CUSTOMERS = "ROLE_MANAGE_CUSTOMERS"; // public static final String MANAGE_PAYMENT_SYSTEMS = "ROLE_MANAGE_PAYMENT_SYSTEMS"; // public static final String MANAGE_USERS = "ROLE_MANAGE_USERS"; // public static final String MANAGE_ROLES = "ROLE_MANAGE_ROLES"; // public static final String MANAGE_PERMISSIONS = "ROLE_MANAGE_PERMISSIONS"; // public static final String MANAGE_SETTINGS = "ROLE_MANAGE_SETTINGS"; // // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/customers/CustomerService.java // @Service // @Transactional // public class CustomerService { // @Autowired CustomerRepository customerRepository; // // public Customer getCustomerByEmail(String email) { // return customerRepository.findByEmail(email); // } // // public Customer createCustomer(Customer customer) { // return customerRepository.save(customer); // } // // public List<Customer> getAllCustomers() { // return customerRepository.findAll(); // } // // public Customer getCustomerById(Integer id) { // return customerRepository.findOne(id); // } // // public List<Order> getCustomerOrders(String email) { // return customerRepository.getCustomerOrders(email); // } // // } // // Path: jcart-core/src/main/java/com/sivalabs/jcart/entities/Customer.java // @Entity // @Table(name="customers") // public class Customer implements Serializable // { // private static final long serialVersionUID = 1L; // @Id @GeneratedValue(strategy=GenerationType.IDENTITY) // private Integer id; // @Column(name="firstname", nullable=false) // @NotEmpty // private String firstName; // @Column(name="lastname") // private String lastName; // @NotEmpty // @Email // @Column(name="email", nullable=false, unique=true) // private String email; // @NotEmpty // @Column(name="password", nullable=false) // private String password; // private String phone; // // public Integer getId() // { // return id; // } // public void setId(Integer id) // { // this.id = id; // } // public String getFirstName() // { // return firstName; // } // public void setFirstName(String firstName) // { // this.firstName = firstName; // } // public String getLastName() // { // return lastName; // } // public void setLastName(String lastName) // { // this.lastName = lastName; // } // public String getEmail() // { // return email; // } // public void setEmail(String email) // { // this.email = email; // } // public String getPhone() // { // return phone; // } // public void setPhone(String phone) // { // this.phone = phone; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // // } // Path: jcart-admin/src/main/java/com/sivalabs/jcart/admin/web/controllers/CustomerController.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.sivalabs.jcart.admin.security.SecurityUtil; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.entities.Customer; /** * */ package com.sivalabs.jcart.admin.web.controllers; /** * @author Siva * */ @Controller @Secured(SecurityUtil.MANAGE_CUSTOMERS) public class CustomerController extends JCartAdminBaseController { private static final String viewPrefix = "customers/"; @Autowired private CustomerService customerService; @Override protected String getHeaderTitle() { return "Manage Customers"; } @RequestMapping(value="/customers", method=RequestMethod.GET) public String listCustomers(Model model) {
List<Customer> list = customerService.getAllCustomers();
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // }
import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*;
package com.jaquadro.minecraft.chameleon.resources; @SideOnly(Side.CLIENT) public class ModelRegistry {
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // } // Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*; package com.jaquadro.minecraft.chameleon.resources; @SideOnly(Side.CLIENT) public class ModelRegistry {
private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>();
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // }
import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*;
package com.jaquadro.minecraft.chameleon.resources; @SideOnly(Side.CLIENT) public class ModelRegistry { private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>();
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // } // Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*; package com.jaquadro.minecraft.chameleon.resources; @SideOnly(Side.CLIENT) public class ModelRegistry { private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>();
private final Set<IItemModelRegister> itemRegistry = new HashSet<IItemModelRegister>();
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // }
import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*;
package com.jaquadro.minecraft.chameleon.resources; @SideOnly(Side.CLIENT) public class ModelRegistry { private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>(); private final Set<IItemModelRegister> itemRegistry = new HashSet<IItemModelRegister>(); public final ChamModelLoader loader = new ChamModelLoader(); public void registerModel (IBlockModelRegister modelRegister) { if (modelRegister != null) blockRegistry.add(modelRegister); } public void registerModel (IItemModelRegister modelRegister) { if (modelRegister != null) { itemRegistry.add(modelRegister); registerItemVariants(modelRegister.getItem()); } }
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // } // Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*; package com.jaquadro.minecraft.chameleon.resources; @SideOnly(Side.CLIENT) public class ModelRegistry { private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>(); private final Set<IItemModelRegister> itemRegistry = new HashSet<IItemModelRegister>(); public final ChamModelLoader loader = new ChamModelLoader(); public void registerModel (IBlockModelRegister modelRegister) { if (modelRegister != null) blockRegistry.add(modelRegister); } public void registerModel (IItemModelRegister modelRegister) { if (modelRegister != null) { itemRegistry.add(modelRegister); registerItemVariants(modelRegister.getItem()); } }
public void registerModel (IUnifiedRegister modelRegister) {
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // }
import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*;
registerItemMapping(item, register); } } } private void registerItemMapping (Item item) { registerItemMapping(item, null); } private void registerItemMapping (Item item, IItemModelRegister register) { if (item instanceof IItemMeshResolver) ModelLoader.setCustomMeshDefinition(item, ((IItemMeshResolver) item).getMeshResolver()); else if (register != null) { for (ItemStack stack : register.getItemVariants()) ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack)); } else if (item instanceof IItemMeshMapper) { for (Pair<ItemStack, ModelResourceLocation> pair : ((IItemMeshMapper) item).getMeshMappings()) ModelLoader.setCustomModelResourceLocation(item, pair.getKey().getMetadata(), pair.getValue()); } else { NonNullList<ItemStack> variants = NonNullList.create(); item.getSubItems(item.getCreativeTab(), variants); for (ItemStack stack : variants) ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack)); } } private void registerTextureResources (List<ResourceLocation> resources) { for (ResourceLocation resource : resources)
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java // public interface IBlockModelRegister // { // List<IBlockState> getBlockStates (); // // IBakedModel getModel (IBlockState state, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java // public interface IItemModelRegister // { // Item getItem (); // // List<ItemStack> getItemVariants (); // // IBakedModel getModel (ItemStack stack, IBakedModel existingModel); // } // // Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java // public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister // { // } // Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister; import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import java.util.*; registerItemMapping(item, register); } } } private void registerItemMapping (Item item) { registerItemMapping(item, null); } private void registerItemMapping (Item item, IItemModelRegister register) { if (item instanceof IItemMeshResolver) ModelLoader.setCustomMeshDefinition(item, ((IItemMeshResolver) item).getMeshResolver()); else if (register != null) { for (ItemStack stack : register.getItemVariants()) ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack)); } else if (item instanceof IItemMeshMapper) { for (Pair<ItemStack, ModelResourceLocation> pair : ((IItemMeshMapper) item).getMeshMappings()) ModelLoader.setCustomModelResourceLocation(item, pair.getKey().getMetadata(), pair.getValue()); } else { NonNullList<ItemStack> variants = NonNullList.create(); item.getSubItems(item.getCreativeTab(), variants); for (ItemStack stack : variants) ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack)); } } private void registerTextureResources (List<ResourceLocation> resources) { for (ResourceLocation resource : resources)
Chameleon.instance.iconRegistry.registerIcon(resource);
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java // public class LockableData extends TileDataShim // { // private LockCode code = LockCode.EMPTY_CODE; // // @Override // public void readFromNBT (NBTTagCompound tag) { // code = LockCode.fromNBT(tag); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (code != null) // code.toNBT(tag); // // return tag; // } // // public boolean isLocked () // { // return this.code != null && !this.code.isEmpty(); // } // // public LockCode getLockCode () // { // return this.code; // } // // public void setLockCode (LockCode code) // { // this.code = code; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // }
import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode;
package com.jaquadro.minecraft.chameleon.block; public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer {
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java // public class LockableData extends TileDataShim // { // private LockCode code = LockCode.EMPTY_CODE; // // @Override // public void readFromNBT (NBTTagCompound tag) { // code = LockCode.fromNBT(tag); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (code != null) // code.toNBT(tag); // // return tag; // } // // public boolean isLocked () // { // return this.code != null && !this.code.isEmpty(); // } // // public LockCode getLockCode () // { // return this.code; // } // // public void setLockCode (LockCode code) // { // this.code = code; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // } // Path: src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode; package com.jaquadro.minecraft.chameleon.block; public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer {
private LockableData lockableData;
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java // public class LockableData extends TileDataShim // { // private LockCode code = LockCode.EMPTY_CODE; // // @Override // public void readFromNBT (NBTTagCompound tag) { // code = LockCode.fromNBT(tag); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (code != null) // code.toNBT(tag); // // return tag; // } // // public boolean isLocked () // { // return this.code != null && !this.code.isEmpty(); // } // // public LockCode getLockCode () // { // return this.code; // } // // public void setLockCode (LockCode code) // { // this.code = code; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // }
import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode;
package com.jaquadro.minecraft.chameleon.block; public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer { private LockableData lockableData; @Override
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java // public class LockableData extends TileDataShim // { // private LockCode code = LockCode.EMPTY_CODE; // // @Override // public void readFromNBT (NBTTagCompound tag) { // code = LockCode.fromNBT(tag); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (code != null) // code.toNBT(tag); // // return tag; // } // // public boolean isLocked () // { // return this.code != null && !this.code.isEmpty(); // } // // public LockCode getLockCode () // { // return this.code; // } // // public void setLockCode (LockCode code) // { // this.code = code; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // } // Path: src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode; package com.jaquadro.minecraft.chameleon.block; public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer { private LockableData lockableData; @Override
public void injectData (TileDataShim shim) {
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/integration/IntegrationRegistry.java
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // }
import com.jaquadro.minecraft.chameleon.Chameleon; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import org.apache.logging.log4j.Level; import java.util.ArrayList; import java.util.List;
package com.jaquadro.minecraft.chameleon.integration; public class IntegrationRegistry { private String modId; private List<IntegrationModule> registry; public IntegrationRegistry (String modId) { this.modId = modId; this.registry = new ArrayList<IntegrationModule>(); } public void add (IntegrationModule module) { if (module.versionCheck()) registry.add(module); } public void init () { for (int i = 0; i < registry.size(); i++) { IntegrationModule module = registry.get(i); if (module.getModID() != null && !Loader.isModLoaded(module.getModID())) { registry.remove(i--); continue; } try { module.init(); } catch (Throwable t) { registry.remove(i--);
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // Path: src/com/jaquadro/minecraft/chameleon/integration/IntegrationRegistry.java import com.jaquadro.minecraft.chameleon.Chameleon; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import org.apache.logging.log4j.Level; import java.util.ArrayList; import java.util.List; package com.jaquadro.minecraft.chameleon.integration; public class IntegrationRegistry { private String modId; private List<IntegrationModule> registry; public IntegrationRegistry (String modId) { this.modId = modId; this.registry = new ArrayList<IntegrationModule>(); } public void add (IntegrationModule module) { if (module.versionCheck()) registry.add(module); } public void init () { for (int i = 0; i < registry.size(); i++) { IntegrationModule module = registry.get(i); if (module.getModID() != null && !Loader.isModLoaded(module.getModID())) { registry.remove(i--); continue; } try { module.init(); } catch (Throwable t) { registry.remove(i--);
Chameleon.log.info("Could not load integration module: " + module.getClass().getName());
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // }
import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.Level; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package com.jaquadro.minecraft.chameleon.block; public class ChamTileEntity extends TileEntity { private NBTTagCompound failureSnapshot;
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // } // Path: src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.Level; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package com.jaquadro.minecraft.chameleon.block; public class ChamTileEntity extends TileEntity { private NBTTagCompound failureSnapshot;
private List<TileDataShim> fixedShims;
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // }
import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.Level; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
@Override public final void readFromNBT (NBTTagCompound tag) { super.readFromNBT(tag); failureSnapshot = null; try { readFromFixedNBT(tag); readFromPortableNBT(tag); } catch (Throwable t) { trapLoadFailure(t, tag); } } @Override public final NBTTagCompound writeToNBT (NBTTagCompound tag) { super.writeToNBT(tag); if (failureSnapshot != null) { restoreLoadFailure(tag); return tag; } try { tag = writeToFixedNBT(tag); tag = writeToPortableNBT(tag); } catch (Throwable t) {
// Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java // @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)") // public class Chameleon // { // public static final String MOD_ID = "chameleon"; // public static final String MOD_NAME = "Chameleon"; // public static final String MOD_VERSION = "@VERSION@"; // public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon."; // // public static Logger log; // // @SideOnly(Side.CLIENT) // public IconRegistry iconRegistry; // // @SideOnly(Side.CLIENT) // public ModelRegistry modelRegistry; // // @Mod.Instance(MOD_ID) // public static Chameleon instance; // // @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy") // public static CommonProxy proxy; // // @Mod.EventHandler // public void preInit (FMLPreInitializationEvent event) { // log = event.getModLog(); // // MinecraftForge.EVENT_BUS.register(proxy); // proxy.preInitSidedResources(); // } // // @Mod.EventHandler // public void init (FMLInitializationEvent event) { // proxy.initSidedResources(); // // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // } // Path: src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java import com.jaquadro.minecraft.chameleon.Chameleon; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.Level; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @Override public final void readFromNBT (NBTTagCompound tag) { super.readFromNBT(tag); failureSnapshot = null; try { readFromFixedNBT(tag); readFromPortableNBT(tag); } catch (Throwable t) { trapLoadFailure(t, tag); } } @Override public final NBTTagCompound writeToNBT (NBTTagCompound tag) { super.writeToNBT(tag); if (failureSnapshot != null) { restoreLoadFailure(tag); return tag; } try { tag = writeToFixedNBT(tag); tag = writeToPortableNBT(tag); } catch (Throwable t) {
Chameleon.log.error("Tile Save Failure.", t);
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java // public class CustomNameData extends TileDataShim implements IWorldNameable // { // private String defaultName; // private String customName; // // public CustomNameData (String defaultName) { // this.defaultName = defaultName; // } // // @Override // public void readFromNBT (NBTTagCompound tag) { // customName = null; // if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING)) // customName = tag.getString("CustomName"); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (hasCustomName()) // tag.setString("CustomName", customName); // // return tag; // } // // @Override // public String getName () { // return hasCustomName() ? customName : defaultName; // } // // @Override // public boolean hasCustomName () { // return customName != null && customName.length() > 0; // } // // @Override // public ITextComponent getDisplayName () { // return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName); // } // // public void setName (String name) { // customName = name; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // }
import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.IWorldNameable; import javax.annotation.Nullable;
package com.jaquadro.minecraft.chameleon.block; public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable { private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0);
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java // public class CustomNameData extends TileDataShim implements IWorldNameable // { // private String defaultName; // private String customName; // // public CustomNameData (String defaultName) { // this.defaultName = defaultName; // } // // @Override // public void readFromNBT (NBTTagCompound tag) { // customName = null; // if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING)) // customName = tag.getString("CustomName"); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (hasCustomName()) // tag.setString("CustomName", customName); // // return tag; // } // // @Override // public String getName () { // return hasCustomName() ? customName : defaultName; // } // // @Override // public boolean hasCustomName () { // return customName != null && customName.length() > 0; // } // // @Override // public ITextComponent getDisplayName () { // return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName); // } // // public void setName (String name) { // customName = name; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // } // Path: src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.IWorldNameable; import javax.annotation.Nullable; package com.jaquadro.minecraft.chameleon.block; public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable { private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0);
private CustomNameData customNameData;
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java // public class CustomNameData extends TileDataShim implements IWorldNameable // { // private String defaultName; // private String customName; // // public CustomNameData (String defaultName) { // this.defaultName = defaultName; // } // // @Override // public void readFromNBT (NBTTagCompound tag) { // customName = null; // if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING)) // customName = tag.getString("CustomName"); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (hasCustomName()) // tag.setString("CustomName", customName); // // return tag; // } // // @Override // public String getName () { // return hasCustomName() ? customName : defaultName; // } // // @Override // public boolean hasCustomName () { // return customName != null && customName.length() > 0; // } // // @Override // public ITextComponent getDisplayName () { // return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName); // } // // public void setName (String name) { // customName = name; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // }
import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.IWorldNameable; import javax.annotation.Nullable;
package com.jaquadro.minecraft.chameleon.block; public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable { private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0); private CustomNameData customNameData; @Override
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java // public class CustomNameData extends TileDataShim implements IWorldNameable // { // private String defaultName; // private String customName; // // public CustomNameData (String defaultName) { // this.defaultName = defaultName; // } // // @Override // public void readFromNBT (NBTTagCompound tag) { // customName = null; // if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING)) // customName = tag.getString("CustomName"); // } // // @Override // public NBTTagCompound writeToNBT (NBTTagCompound tag) { // if (hasCustomName()) // tag.setString("CustomName", customName); // // return tag; // } // // @Override // public String getName () { // return hasCustomName() ? customName : defaultName; // } // // @Override // public boolean hasCustomName () { // return customName != null && customName.length() > 0; // } // // @Override // public ITextComponent getDisplayName () { // return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName); // } // // public void setName (String name) { // customName = name; // } // } // // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java // public abstract class TileDataShim implements INBTSerializable<NBTTagCompound> // { // public abstract void readFromNBT (NBTTagCompound tag); // // public abstract NBTTagCompound writeToNBT (NBTTagCompound tag); // // @Override // public NBTTagCompound serializeNBT () { // NBTTagCompound tag = new NBTTagCompound(); // return writeToNBT(tag); // } // // @Override // public void deserializeNBT (NBTTagCompound nbt) { // readFromNBT(nbt); // } // } // Path: src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData; import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.IWorldNameable; import javax.annotation.Nullable; package com.jaquadro.minecraft.chameleon.block; public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable { private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0); private CustomNameData customNameData; @Override
public void injectData (TileDataShim shim) {
jaquadro/Chameleon
src/com/jaquadro/minecraft/chameleon/resources/register/DefaultRegister.java
// Path: src/com/jaquadro/minecraft/chameleon/resources/IItemMeshMapper.java // public interface IItemMeshMapper // { // List<Pair<ItemStack, ModelResourceLocation>> getMeshMappings (); // }
import com.jaquadro.minecraft.chameleon.resources.IItemMeshMapper; import net.minecraft.block.Block; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import org.apache.commons.lang3.tuple.Pair; import java.util.ArrayList; import java.util.List;
package com.jaquadro.minecraft.chameleon.resources.register; public abstract class DefaultRegister<T extends Block> implements IUnifiedRegister { private final T block; public DefaultRegister (T block) { this.block = block; } @Override public Item getItem () { return Item.getItemFromBlock(block); } @Override public List<ItemStack> getItemVariants () { Item item = getItem(); NonNullList<ItemStack> variants = NonNullList.create();
// Path: src/com/jaquadro/minecraft/chameleon/resources/IItemMeshMapper.java // public interface IItemMeshMapper // { // List<Pair<ItemStack, ModelResourceLocation>> getMeshMappings (); // } // Path: src/com/jaquadro/minecraft/chameleon/resources/register/DefaultRegister.java import com.jaquadro.minecraft.chameleon.resources.IItemMeshMapper; import net.minecraft.block.Block; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import org.apache.commons.lang3.tuple.Pair; import java.util.ArrayList; import java.util.List; package com.jaquadro.minecraft.chameleon.resources.register; public abstract class DefaultRegister<T extends Block> implements IUnifiedRegister { private final T block; public DefaultRegister (T block) { this.block = block; } @Override public Item getItem () { return Item.getItemFromBlock(block); } @Override public List<ItemStack> getItemVariants () { Item item = getItem(); NonNullList<ItemStack> variants = NonNullList.create();
if (item instanceof IItemMeshMapper) {
qiujuer/Blink
Android/Blink/library/src/main/java/net/qiujuer/blink/box/FileSendPacket.java
// Path: Android/Blink/library/src/main/java/net/qiujuer/blink/listener/SendListener.java // public interface SendListener { // /** // * On sender send the packet call this // * On start progress == 0 // * On end progress ==1 // * // * @param progress Send progress (0~1) // */ // void onSendProgress(float progress); // }
import java.io.FileInputStream; import java.io.FileNotFoundException; import net.qiujuer.blink.listener.SendListener; import java.io.File;
/* * Copyright (C) 2014 Qiujuer <qiujuer@live.cn> * WebSite http://www.qiujuer.net * Created 04/16/2015 * Changed 04/19/2015 * Version 1.0.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.qiujuer.blink.box; /** * File send class */ public class FileSendPacket extends BaseSendPacket<File> { public FileSendPacket(File file) { this(file, null); }
// Path: Android/Blink/library/src/main/java/net/qiujuer/blink/listener/SendListener.java // public interface SendListener { // /** // * On sender send the packet call this // * On start progress == 0 // * On end progress ==1 // * // * @param progress Send progress (0~1) // */ // void onSendProgress(float progress); // } // Path: Android/Blink/library/src/main/java/net/qiujuer/blink/box/FileSendPacket.java import java.io.FileInputStream; import java.io.FileNotFoundException; import net.qiujuer.blink.listener.SendListener; import java.io.File; /* * Copyright (C) 2014 Qiujuer <qiujuer@live.cn> * WebSite http://www.qiujuer.net * Created 04/16/2015 * Changed 04/19/2015 * Version 1.0.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.qiujuer.blink.box; /** * File send class */ public class FileSendPacket extends BaseSendPacket<File> { public FileSendPacket(File file) { this(file, null); }
public FileSendPacket(File entity, SendListener listener) {