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 |
|---|---|---|---|---|---|---|
strooooke/quickfit | app/src/test/java/com/lambdasoup/quickfit/util/DateTimesTest.java | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
| import com.lambdasoup.quickfit.model.DayOfWeek;
import org.junit.Test;
import java.util.Calendar;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals; | /*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.util;
/**
* Tests for {@link DateTimes}.
*/
public class DateTimesTest {
private static final long JULY_FIRST_2016; // 2016-07-01T13:00Z+02:00, Friday
static {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
cal.set(2016, Calendar.JULY, 1, 13, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
JULY_FIRST_2016 = cal.getTimeInMillis();
}
@Test
public void testGetNextOccurrence_laterToday() throws Exception {
Calendar expected = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
expected.set(2016, Calendar.JULY, 1, 14, 0, 0);
expected.set(Calendar.MILLISECOND, 0); | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
// Path: app/src/test/java/com/lambdasoup/quickfit/util/DateTimesTest.java
import com.lambdasoup.quickfit.model.DayOfWeek;
import org.junit.Test;
import java.util.Calendar;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.util;
/**
* Tests for {@link DateTimes}.
*/
public class DateTimesTest {
private static final long JULY_FIRST_2016; // 2016-07-01T13:00Z+02:00, Friday
static {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
cal.set(2016, Calendar.JULY, 1, 13, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
JULY_FIRST_2016 = cal.getTimeInMillis();
}
@Test
public void testGetNextOccurrence_laterToday() throws Exception {
Calendar expected = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
expected.set(2016, Calendar.JULY, 1, 14, 0, 0);
expected.set(Calendar.MILLISECOND, 0); | assertEquals(expected.getTimeInMillis(), DateTimes.getNextOccurrence(JULY_FIRST_2016, DayOfWeek.FRIDAY, 14, 0)); |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/util/DateTimes.java | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
| import com.lambdasoup.quickfit.model.DayOfWeek;
import java.util.Calendar; | /*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.util;
/**
* Helper methods for manipulating datetime values expressed as posix timestamps
*/
public class DateTimes {
private DateTimes() {
// do not instantiate
}
| // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
// Path: app/src/main/java/com/lambdasoup/quickfit/util/DateTimes.java
import com.lambdasoup.quickfit.model.DayOfWeek;
import java.util.Calendar;
/*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.util;
/**
* Helper methods for manipulating datetime values expressed as posix timestamps
*/
public class DateTimes {
private DateTimes() {
// do not instantiate
}
| public static long getNextOccurrence(long now, DayOfWeek dayOfWeek, int hour, int minute) { |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/viewmodel/ScheduleList.java | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Lists.java
// public class Lists {
// private Lists() {
// // do not instantiate
// }
//
//
// @NonNull
// public static <S, T> List<T> map(@NonNull List<S> source, @NonNull Function<S, T> transformation) {
// return new AbstractList<T>() {
// @Override
// public T get(int location) {
// return transformation.apply(source.get(location));
// }
//
// @Override
// public int size() {
// return source.size();
// }
// };
// }
//
// /**
// * Assumes that list is ordered according to ordering. If not, results
// * are undefined.
// * Finds index i, such that list.get(j) for all j < i is less than item
// * according to ordering, and list.get(j) for all j>= i is at least item
// * according to ordering. In other words, the left-most possible insertion
// * point for item that keeps list ordered is found.
// */
// public static <T> int bisectLeft(@NonNull List<T> list, @NonNull Comparator<T> ordering, @NonNull T item) {
// int low = 0;
// int high = list.size();
// int mid;
//
// while (low < high) {
// mid = (low + high) / 2;
// if (ordering.compare(item, list.get(mid)) <= 0) {
// high = mid;
// } else {
// low = mid + 1;
// }
// }
// return low;
// }
// }
| import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Lists;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean; | /*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.viewmodel;
/**
* List model for {@link ScheduleItem} items. Inspired by {@link androidx.recyclerview.widget.SortedList},
* but does not depend on compare, itemsTheSame and contentsTheSame being compatible.
* <p>
* Assumes that item.id is a unique key for items; assumes that there are no duplicate ids in swapped
* in item iterables.
* <p>
* Not threadsafe; current usage is always on the main thread. Detects attempts for concurrent updates
* and warns by throwing.
*/
public class ScheduleList {
private static final int POSITION_INVALID = -1;
private final AtomicBoolean writing = new AtomicBoolean(false);
private final List<ScheduleItem> dataset = new ArrayList<>();
private final Map<Long, Integer> positionForId = new HashMap<>();
private final ItemChangeCallback callback; | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Lists.java
// public class Lists {
// private Lists() {
// // do not instantiate
// }
//
//
// @NonNull
// public static <S, T> List<T> map(@NonNull List<S> source, @NonNull Function<S, T> transformation) {
// return new AbstractList<T>() {
// @Override
// public T get(int location) {
// return transformation.apply(source.get(location));
// }
//
// @Override
// public int size() {
// return source.size();
// }
// };
// }
//
// /**
// * Assumes that list is ordered according to ordering. If not, results
// * are undefined.
// * Finds index i, such that list.get(j) for all j < i is less than item
// * according to ordering, and list.get(j) for all j>= i is at least item
// * according to ordering. In other words, the left-most possible insertion
// * point for item that keeps list ordered is found.
// */
// public static <T> int bisectLeft(@NonNull List<T> list, @NonNull Comparator<T> ordering, @NonNull T item) {
// int low = 0;
// int high = list.size();
// int mid;
//
// while (low < high) {
// mid = (low + high) / 2;
// if (ordering.compare(item, list.get(mid)) <= 0) {
// high = mid;
// } else {
// low = mid + 1;
// }
// }
// return low;
// }
// }
// Path: app/src/main/java/com/lambdasoup/quickfit/viewmodel/ScheduleList.java
import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Lists;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.viewmodel;
/**
* List model for {@link ScheduleItem} items. Inspired by {@link androidx.recyclerview.widget.SortedList},
* but does not depend on compare, itemsTheSame and contentsTheSame being compatible.
* <p>
* Assumes that item.id is a unique key for items; assumes that there are no duplicate ids in swapped
* in item iterables.
* <p>
* Not threadsafe; current usage is always on the main thread. Detects attempts for concurrent updates
* and warns by throwing.
*/
public class ScheduleList {
private static final int POSITION_INVALID = -1;
private final AtomicBoolean writing = new AtomicBoolean(false);
private final List<ScheduleItem> dataset = new ArrayList<>();
private final Map<Long, Integer> positionForId = new HashMap<>();
private final ItemChangeCallback callback; | private final ScheduleItem.ByCalendar ordering = new ScheduleItem.ByCalendar(DayOfWeek.getWeek()); |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/viewmodel/ScheduleList.java | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Lists.java
// public class Lists {
// private Lists() {
// // do not instantiate
// }
//
//
// @NonNull
// public static <S, T> List<T> map(@NonNull List<S> source, @NonNull Function<S, T> transformation) {
// return new AbstractList<T>() {
// @Override
// public T get(int location) {
// return transformation.apply(source.get(location));
// }
//
// @Override
// public int size() {
// return source.size();
// }
// };
// }
//
// /**
// * Assumes that list is ordered according to ordering. If not, results
// * are undefined.
// * Finds index i, such that list.get(j) for all j < i is less than item
// * according to ordering, and list.get(j) for all j>= i is at least item
// * according to ordering. In other words, the left-most possible insertion
// * point for item that keeps list ordered is found.
// */
// public static <T> int bisectLeft(@NonNull List<T> list, @NonNull Comparator<T> ordering, @NonNull T item) {
// int low = 0;
// int high = list.size();
// int mid;
//
// while (low < high) {
// mid = (low + high) / 2;
// if (ordering.compare(item, list.get(mid)) <= 0) {
// high = mid;
// } else {
// low = mid + 1;
// }
// }
// return low;
// }
// }
| import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Lists;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean; | refreshPositions();
callback.onMoved(oldPosition, newPosition);
}
}
}
List<Long> leavingIds = new ArrayList<>();
//noinspection Convert2streamapi
for (Long oldId : positionForId.keySet()) {
if (!newIds.contains(oldId)) {
leavingIds.add(oldId);
}
}
for (Long leavingId : leavingIds) {
dataset.remove(getPositionForId(leavingId));
int oldPosition = getPositionForId(leavingId);
callback.onRemoved(oldPosition);
refreshPositions();
}
releaseWriteLock();
}
private int getPositionForId(long id) {
Integer pos = positionForId.get(id);
return pos == null ? POSITION_INVALID : pos;
}
private int findPositionFor(ScheduleItem item) { | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Lists.java
// public class Lists {
// private Lists() {
// // do not instantiate
// }
//
//
// @NonNull
// public static <S, T> List<T> map(@NonNull List<S> source, @NonNull Function<S, T> transformation) {
// return new AbstractList<T>() {
// @Override
// public T get(int location) {
// return transformation.apply(source.get(location));
// }
//
// @Override
// public int size() {
// return source.size();
// }
// };
// }
//
// /**
// * Assumes that list is ordered according to ordering. If not, results
// * are undefined.
// * Finds index i, such that list.get(j) for all j < i is less than item
// * according to ordering, and list.get(j) for all j>= i is at least item
// * according to ordering. In other words, the left-most possible insertion
// * point for item that keeps list ordered is found.
// */
// public static <T> int bisectLeft(@NonNull List<T> list, @NonNull Comparator<T> ordering, @NonNull T item) {
// int low = 0;
// int high = list.size();
// int mid;
//
// while (low < high) {
// mid = (low + high) / 2;
// if (ordering.compare(item, list.get(mid)) <= 0) {
// high = mid;
// } else {
// low = mid + 1;
// }
// }
// return low;
// }
// }
// Path: app/src/main/java/com/lambdasoup/quickfit/viewmodel/ScheduleList.java
import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Lists;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
refreshPositions();
callback.onMoved(oldPosition, newPosition);
}
}
}
List<Long> leavingIds = new ArrayList<>();
//noinspection Convert2streamapi
for (Long oldId : positionForId.keySet()) {
if (!newIds.contains(oldId)) {
leavingIds.add(oldId);
}
}
for (Long leavingId : leavingIds) {
dataset.remove(getPositionForId(leavingId));
int oldPosition = getPositionForId(leavingId);
callback.onRemoved(oldPosition);
refreshPositions();
}
releaseWriteLock();
}
private int getPositionForId(long id) {
Integer pos = positionForId.get(id);
return pos == null ? POSITION_INVALID : pos;
}
private int findPositionFor(ScheduleItem item) { | return Lists.bisectLeft(dataset, ordering, item); |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/ui/DayOfWeekDialogFragment.java | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Arrays.java
// public class Arrays {
// public static <S, T> T[] map(S[] source, Class<T[]> targetClass, Function<S, T> transformation) {
// T[] target = targetClass.cast(Array.newInstance(targetClass.getComponentType(), source.length));
// for (int i = 0; i < source.length; i++) {
// target[i] = transformation.apply(source[i]);
// }
// return target;
// }
//
// public static <T> int firstIndexOf(@NonNull T[] array, @NonNull T item) {
// for (int i = 0; i < array.length; i++) {
// if (item.equals(array[i])) {
// return i;
// }
// }
// throw new NoSuchElementException();
// }
// }
| import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AlertDialog;
import com.lambdasoup.quickfit.R;
import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Arrays; | /*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.ui;
public class DayOfWeekDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
private static final String KEY_SCHEDULE_ID = "scheduleId";
private static final String KEY_OLD_VALUE = "oldValue";
private OnFragmentInteractionListener listener; | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Arrays.java
// public class Arrays {
// public static <S, T> T[] map(S[] source, Class<T[]> targetClass, Function<S, T> transformation) {
// T[] target = targetClass.cast(Array.newInstance(targetClass.getComponentType(), source.length));
// for (int i = 0; i < source.length; i++) {
// target[i] = transformation.apply(source[i]);
// }
// return target;
// }
//
// public static <T> int firstIndexOf(@NonNull T[] array, @NonNull T item) {
// for (int i = 0; i < array.length; i++) {
// if (item.equals(array[i])) {
// return i;
// }
// }
// throw new NoSuchElementException();
// }
// }
// Path: app/src/main/java/com/lambdasoup/quickfit/ui/DayOfWeekDialogFragment.java
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AlertDialog;
import com.lambdasoup.quickfit.R;
import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Arrays;
/*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.ui;
public class DayOfWeekDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
private static final String KEY_SCHEDULE_ID = "scheduleId";
private static final String KEY_OLD_VALUE = "oldValue";
private OnFragmentInteractionListener listener; | private DayOfWeek[] week; |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/ui/DayOfWeekDialogFragment.java | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Arrays.java
// public class Arrays {
// public static <S, T> T[] map(S[] source, Class<T[]> targetClass, Function<S, T> transformation) {
// T[] target = targetClass.cast(Array.newInstance(targetClass.getComponentType(), source.length));
// for (int i = 0; i < source.length; i++) {
// target[i] = transformation.apply(source[i]);
// }
// return target;
// }
//
// public static <T> int firstIndexOf(@NonNull T[] array, @NonNull T item) {
// for (int i = 0; i < array.length; i++) {
// if (item.equals(array[i])) {
// return i;
// }
// }
// throw new NoSuchElementException();
// }
// }
| import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AlertDialog;
import com.lambdasoup.quickfit.R;
import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Arrays; | public static DayOfWeekDialogFragment newInstance(long objectId, DayOfWeek oldValue) {
DayOfWeekDialogFragment fragment = new DayOfWeekDialogFragment();
Bundle args = new Bundle();
args.putLong(KEY_SCHEDULE_ID, objectId);
args.putParcelable(KEY_OLD_VALUE, oldValue);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnFragmentInteractionListenerProvider) {
listener = ((OnFragmentInteractionListenerProvider) activity).getOnDayOfWeekDialogFragmentInteractionListener();
} else {
throw new IllegalArgumentException(activity.toString() + " must implement OnFragmentInteractionListenerProvider");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
week = DayOfWeek.getWeek();
//noinspection ConstantConditions | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
//
// Path: app/src/main/java/com/lambdasoup/quickfit/util/Arrays.java
// public class Arrays {
// public static <S, T> T[] map(S[] source, Class<T[]> targetClass, Function<S, T> transformation) {
// T[] target = targetClass.cast(Array.newInstance(targetClass.getComponentType(), source.length));
// for (int i = 0; i < source.length; i++) {
// target[i] = transformation.apply(source[i]);
// }
// return target;
// }
//
// public static <T> int firstIndexOf(@NonNull T[] array, @NonNull T item) {
// for (int i = 0; i < array.length; i++) {
// if (item.equals(array[i])) {
// return i;
// }
// }
// throw new NoSuchElementException();
// }
// }
// Path: app/src/main/java/com/lambdasoup/quickfit/ui/DayOfWeekDialogFragment.java
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AlertDialog;
import com.lambdasoup.quickfit.R;
import com.lambdasoup.quickfit.model.DayOfWeek;
import com.lambdasoup.quickfit.util.Arrays;
public static DayOfWeekDialogFragment newInstance(long objectId, DayOfWeek oldValue) {
DayOfWeekDialogFragment fragment = new DayOfWeekDialogFragment();
Bundle args = new Bundle();
args.putLong(KEY_SCHEDULE_ID, objectId);
args.putParcelable(KEY_OLD_VALUE, oldValue);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnFragmentInteractionListenerProvider) {
listener = ((OnFragmentInteractionListenerProvider) activity).getOnDayOfWeekDialogFragmentInteractionListener();
} else {
throw new IllegalArgumentException(activity.toString() + " must implement OnFragmentInteractionListenerProvider");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
week = DayOfWeek.getWeek();
//noinspection ConstantConditions | checkedItemPosition = Arrays.firstIndexOf(week, getArguments().getParcelable(KEY_OLD_VALUE)); |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/viewmodel/ScheduleItem.java | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
| import androidx.annotation.NonNull;
import com.lambdasoup.quickfit.model.DayOfWeek;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator; | /*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.viewmodel;
/**
* ViewModel for a single schedule item.
*/
public class ScheduleItem {
final public long id; | // Path: app/src/main/java/com/lambdasoup/quickfit/model/DayOfWeek.java
// public enum DayOfWeek implements Parcelable {
// MONDAY(Calendar.MONDAY, R.string.monday),
// TUESDAY(Calendar.TUESDAY, R.string.tuesday),
// WEDNESDAY(Calendar.WEDNESDAY, R.string.wednesday),
// THURSDAY(Calendar.THURSDAY, R.string.thursday),
// FRIDAY(Calendar.FRIDAY, R.string.friday),
// SATURDAY(Calendar.SATURDAY, R.string.saturday),
// SUNDAY(Calendar.SUNDAY, R.string.sunday);
//
// public final int calendarConst;
// public final int fullNameResId;
//
// DayOfWeek(int calendarConst, @StringRes int fullNameResId) {
// this.calendarConst = calendarConst;
// this.fullNameResId = fullNameResId;
// }
//
// @NonNull
// public static DayOfWeek[] getWeek() {
// return getWeek(Calendar.getInstance());
// }
//
// @NonNull
// protected static DayOfWeek[] getWeek(Calendar calendar) {
// int firstDay = calendar.getFirstDayOfWeek();
// DayOfWeek[] week = new DayOfWeek[7];
// for (int i = 0; i < 7; i++) {
// int calendarConst = firstDay + i;
// if (calendarConst > 7) {
// calendarConst -= 7;
// }
// week[i] = getByCalendarConst(calendarConst);
// }
// return week;
// }
//
// public static DayOfWeek getByCalendarConst(int calendarConst) {
// switch (calendarConst) {
// case Calendar.MONDAY:
// return MONDAY;
// case Calendar.TUESDAY:
// return TUESDAY;
// case Calendar.WEDNESDAY:
// return WEDNESDAY;
// case Calendar.THURSDAY:
// return THURSDAY;
// case Calendar.FRIDAY:
// return FRIDAY;
// case Calendar.SATURDAY:
// return SATURDAY;
// case Calendar.SUNDAY:
// return SUNDAY;
// default:
// throw new IllegalArgumentException("Not a java.util.Calendar weekday constant: " + calendarConst);
// }
// }
//
// // GENERATED START
// // by parcelable AndroidStudio plugin
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(final Parcel dest, final int flags) {
// dest.writeString(name());
// }
//
// public static final Creator<DayOfWeek> CREATOR = new Creator<DayOfWeek>() {
// @Override
// public DayOfWeek createFromParcel(final Parcel source) {
// return DayOfWeek.valueOf(source.readString());
// }
//
// @Override
// public DayOfWeek[] newArray(final int size) {
// return new DayOfWeek[size];
// }
// };
//
// // GENERATED END
// }
// Path: app/src/main/java/com/lambdasoup/quickfit/viewmodel/ScheduleItem.java
import androidx.annotation.NonNull;
import com.lambdasoup.quickfit.model.DayOfWeek;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
/*
* Copyright 2016 Juliane Lehmann <jl@lambdasoup.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.viewmodel;
/**
* ViewModel for a single schedule item.
*/
public class ScheduleItem {
final public long id; | final public DayOfWeek dayOfWeek; |
ruigoncalo/passarola | app/src/main/java/pt/passarola/model/viewmodel/BeerViewModel.java | // Path: app/src/main/java/pt/passarola/model/Beer.java
// public class Beer implements Comparable<Beer> {
//
// private String id;
// private String brewer;
// private String name;
// @SerializedName("short_name")
// private String shortName;
// @SerializedName("bjcp_style")
// private String style;
// private String ibu;
// private String abv;
// @SerializedName("brewed_at")
// private String brewedAt;
// @SerializedName("collab_with")
// private String collabWith;
// private String barcode;
// @SerializedName("label_pic")
// private String labelPic;
// @SerializedName("label_pic_small")
// private String labelPicSmall;
// @SerializedName("untappd_id")
// private String untappdId;
// @SerializedName("untappd_url")
// private String untappdUrl;
// @SerializedName("ratebeer_id")
// private String ratebeerId;
// @SerializedName("ratebeer_url")
// private String ratebeerUrl;
// @SerializedName("start_date")
// private String startDate;
// @SerializedName("end_date")
// private String endDate;
// private String active;
// @SerializedName("series_id")
// private String seriesId;
// @SerializedName("series_name")
// private String seriesName;
// private String ingredients;
// @SerializedName("medium_description")
// private String mediumDescription;
//
// public String getId() {
// return id;
// }
//
// public String getBrewer() {
// return brewer;
// }
//
// public String getName() {
// return name;
// }
//
// public String getShortName() {
// return shortName;
// }
//
// public String getStyle() {
// return style;
// }
//
// public String getIbu() {
// return ibu;
// }
//
// public String getAbv() {
// return abv;
// }
//
// public String getBrewedAt() {
// return brewedAt;
// }
//
// public String getCollabWith() {
// return collabWith;
// }
//
// public String getBarcode() {
// return barcode;
// }
//
// public String getLabelPic() {
// return labelPic;
// }
//
// public String getLabelPicSmall() {
// return labelPicSmall;
// }
//
// public String getUntappdId() {
// return untappdId;
// }
//
// public String getUntappdUrl() {
// return untappdUrl;
// }
//
// public String getRatebeerId() {
// return ratebeerId;
// }
//
// public String getRatebeerUrl() {
// return ratebeerUrl;
// }
//
// public String getStartDate() {
// return startDate;
// }
//
// public String getEndDate() {
// return endDate;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getSeriesId() {
// return seriesId;
// }
//
// public String getSeriesName() {
// return seriesName;
// }
//
// public String getIngredients() {
// return ingredients;
// }
//
// public String getMediumDescription() {
// return mediumDescription;
// }
//
// public boolean isValid(){
// return id != null && name != null &&
// style != null && labelPicSmall != null &&
// seriesId != null && startDate != null;
// }
//
// @Override
// public int compareTo(@NonNull Beer another) {
// if (this.isValid() && another.isValid()) {
// int seriesIdL = Integer.valueOf(this.seriesId);
// int seriesIdR = Integer.valueOf(another.seriesId);
// if(seriesIdL > seriesIdR) {
// return 1;
// } else if(seriesIdL < seriesIdR){
// return -1;
// } else {
// return compareDates(this.getStartDate(), another.getStartDate());
// }
// } else {
// return 0;
// }
// }
//
// private int compareDates(String dateA, String dateB){
// Date dateFormattedA = Utils.getDateFromString(dateA);
// Date dateFormattedB = Utils.getDateFromString(dateB);
//
// if(dateFormattedA != null && dateFormattedB != null){
// if(dateFormattedA.after(dateFormattedB)){
// return 1;
// } else {
// return -1;
// }
// } else {
// return 0;
// }
// }
// }
| import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.Beer; | public Builder description(String description){
this.description = description;
return this;
}
public Builder labelPic(String labelPic){
this.labelPic = labelPic;
return this;
}
public Builder labelPicSmall(String labelPicSmall){
this.labelPicSmall = labelPicSmall;
return this;
}
public Builder rateBeerUrl(String rateBeerUrl){
this.rateBeerUrl = rateBeerUrl;
return this;
}
public Builder untappdUrl(String untappdUrl){
this.untappdUrl = untappdUrl;
return this;
}
public BeerViewModel build(){
return new BeerViewModel(this);
}
}
| // Path: app/src/main/java/pt/passarola/model/Beer.java
// public class Beer implements Comparable<Beer> {
//
// private String id;
// private String brewer;
// private String name;
// @SerializedName("short_name")
// private String shortName;
// @SerializedName("bjcp_style")
// private String style;
// private String ibu;
// private String abv;
// @SerializedName("brewed_at")
// private String brewedAt;
// @SerializedName("collab_with")
// private String collabWith;
// private String barcode;
// @SerializedName("label_pic")
// private String labelPic;
// @SerializedName("label_pic_small")
// private String labelPicSmall;
// @SerializedName("untappd_id")
// private String untappdId;
// @SerializedName("untappd_url")
// private String untappdUrl;
// @SerializedName("ratebeer_id")
// private String ratebeerId;
// @SerializedName("ratebeer_url")
// private String ratebeerUrl;
// @SerializedName("start_date")
// private String startDate;
// @SerializedName("end_date")
// private String endDate;
// private String active;
// @SerializedName("series_id")
// private String seriesId;
// @SerializedName("series_name")
// private String seriesName;
// private String ingredients;
// @SerializedName("medium_description")
// private String mediumDescription;
//
// public String getId() {
// return id;
// }
//
// public String getBrewer() {
// return brewer;
// }
//
// public String getName() {
// return name;
// }
//
// public String getShortName() {
// return shortName;
// }
//
// public String getStyle() {
// return style;
// }
//
// public String getIbu() {
// return ibu;
// }
//
// public String getAbv() {
// return abv;
// }
//
// public String getBrewedAt() {
// return brewedAt;
// }
//
// public String getCollabWith() {
// return collabWith;
// }
//
// public String getBarcode() {
// return barcode;
// }
//
// public String getLabelPic() {
// return labelPic;
// }
//
// public String getLabelPicSmall() {
// return labelPicSmall;
// }
//
// public String getUntappdId() {
// return untappdId;
// }
//
// public String getUntappdUrl() {
// return untappdUrl;
// }
//
// public String getRatebeerId() {
// return ratebeerId;
// }
//
// public String getRatebeerUrl() {
// return ratebeerUrl;
// }
//
// public String getStartDate() {
// return startDate;
// }
//
// public String getEndDate() {
// return endDate;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getSeriesId() {
// return seriesId;
// }
//
// public String getSeriesName() {
// return seriesName;
// }
//
// public String getIngredients() {
// return ingredients;
// }
//
// public String getMediumDescription() {
// return mediumDescription;
// }
//
// public boolean isValid(){
// return id != null && name != null &&
// style != null && labelPicSmall != null &&
// seriesId != null && startDate != null;
// }
//
// @Override
// public int compareTo(@NonNull Beer another) {
// if (this.isValid() && another.isValid()) {
// int seriesIdL = Integer.valueOf(this.seriesId);
// int seriesIdR = Integer.valueOf(another.seriesId);
// if(seriesIdL > seriesIdR) {
// return 1;
// } else if(seriesIdL < seriesIdR){
// return -1;
// } else {
// return compareDates(this.getStartDate(), another.getStartDate());
// }
// } else {
// return 0;
// }
// }
//
// private int compareDates(String dateA, String dateB){
// Date dateFormattedA = Utils.getDateFromString(dateA);
// Date dateFormattedB = Utils.getDateFromString(dateB);
//
// if(dateFormattedA != null && dateFormattedB != null){
// if(dateFormattedA.after(dateFormattedB)){
// return 1;
// } else {
// return -1;
// }
// } else {
// return 0;
// }
// }
// }
// Path: app/src/main/java/pt/passarola/model/viewmodel/BeerViewModel.java
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.Beer;
public Builder description(String description){
this.description = description;
return this;
}
public Builder labelPic(String labelPic){
this.labelPic = labelPic;
return this;
}
public Builder labelPicSmall(String labelPicSmall){
this.labelPicSmall = labelPicSmall;
return this;
}
public Builder rateBeerUrl(String rateBeerUrl){
this.rateBeerUrl = rateBeerUrl;
return this;
}
public Builder untappdUrl(String untappdUrl){
this.untappdUrl = untappdUrl;
return this;
}
public BeerViewModel build(){
return new BeerViewModel(this);
}
}
| public static List<BeerViewModel> createViewModelList(List<Beer> beers){ |
ruigoncalo/passarola | app/src/main/java/pt/passarola/model/Beer.java | // Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
| import pt.passarola.utils.Utils;
import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName;
import java.util.Date; | }
public String getMediumDescription() {
return mediumDescription;
}
public boolean isValid(){
return id != null && name != null &&
style != null && labelPicSmall != null &&
seriesId != null && startDate != null;
}
@Override
public int compareTo(@NonNull Beer another) {
if (this.isValid() && another.isValid()) {
int seriesIdL = Integer.valueOf(this.seriesId);
int seriesIdR = Integer.valueOf(another.seriesId);
if(seriesIdL > seriesIdR) {
return 1;
} else if(seriesIdL < seriesIdR){
return -1;
} else {
return compareDates(this.getStartDate(), another.getStartDate());
}
} else {
return 0;
}
}
private int compareDates(String dateA, String dateB){ | // Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
// Path: app/src/main/java/pt/passarola/model/Beer.java
import pt.passarola.utils.Utils;
import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
}
public String getMediumDescription() {
return mediumDescription;
}
public boolean isValid(){
return id != null && name != null &&
style != null && labelPicSmall != null &&
seriesId != null && startDate != null;
}
@Override
public int compareTo(@NonNull Beer another) {
if (this.isValid() && another.isValid()) {
int seriesIdL = Integer.valueOf(this.seriesId);
int seriesIdR = Integer.valueOf(another.seriesId);
if(seriesIdL > seriesIdR) {
return 1;
} else if(seriesIdL < seriesIdR){
return -1;
} else {
return compareDates(this.getStartDate(), another.getStartDate());
}
} else {
return 0;
}
}
private int compareDates(String dateA, String dateB){ | Date dateFormattedA = Utils.getDateFromString(dateA); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/ServicesModule.java | // Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/tracker/TrackerManager.java
// public class TrackerManager {
//
// public static final String EVENT_CLICK_TAB_BEERS = "event-click-tab-beers";
// public static final String EVENT_CLICK_TAB_PLACES = "event-click-tab-places";
// public static final String EVENT_CLICK_TAB_CLOSEST = "event-click-tab-closest";
// public static final String EVENT_CLICK_PLACE_CLOSEST = "event-click-place-close";
// public static final String EVENT_CLICK_MARKER = "event-click-marker";
// public static final String EVENT_CLICK_INFO_WINDOW = "event-click-info-window";
// public static final String EVENT_CLICK_PLACE_PHONE = "event-click-place-phone";
// public static final String EVENT_CLICK_PLACE_FACEBOOK = "event-click-place-facebook";
// public static final String EVENT_CLICK_PLACE_ZOMATO = "event-click-place-zomato";
// public static final String EVENT_CLICK_PLACE_TRIPADVISOR = "event-click-tripadvisor";
// public static final String EVENT_CLICK_ALL_PLACES_FACEBOOK = "event-click-all-places-facebook";
// public static final String EVENT_CLICK_ALL_PLACES_ZOMATO = "event-click-all-places-zomato";
// public static final String EVENT_CLICK_ALL_PLACES_TRIPADVISOR = "event-click-all-places-tripadvisor";
// public static final String EVENT_CLICK_BEER_RATEBEER = "event-click-beer-ratebeer";
// public static final String EVENT_CLICK_BEER_UNTAPPD = "event-click-beer-untappd";
// public static final String EVENT_CLICK_ABOUT_EMAIL = "event-click-about-email";
// public static final String EVENT_CLICK_ABOUT_FACEBOOK = "event-click-about-facebook";
//
// public void trackEvent(String eventName){
// Answers.getInstance().logCustom(new CustomEvent(eventName));
// }
//
// public void trackEvent(String eventName, String key, String value){
//
// //truncate value to 100 chars
// if(value.length() > 100) {
// value = value.substring(0, 99);
// }
//
// CustomEvent customEvent = new CustomEvent(eventName);
// customEvent.putCustomAttribute(key, value);
//
// Answers.getInstance().logCustom(customEvent);
// }
//
// public void trackEvent(String eventName, HashMap<String, String> attributes){
// CustomEvent customEvent = new CustomEvent(eventName);
// for(Map.Entry<String, String> entry : attributes.entrySet()){
// customEvent.putCustomAttribute(entry.getKey(), entry.getValue());
// }
//
// Answers.getInstance().logCustom(customEvent);
// }
// }
| import android.content.Context;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import pt.passarola.services.rest.RestApi;
import pt.passarola.services.tracker.TrackerManager; | package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
@Module(library = true, complete = false)
public class ServicesModule {
@Provides
@Singleton
BusProvider provideBus() {
return new BusProvider();
}
@Provides
@Singleton | // Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/tracker/TrackerManager.java
// public class TrackerManager {
//
// public static final String EVENT_CLICK_TAB_BEERS = "event-click-tab-beers";
// public static final String EVENT_CLICK_TAB_PLACES = "event-click-tab-places";
// public static final String EVENT_CLICK_TAB_CLOSEST = "event-click-tab-closest";
// public static final String EVENT_CLICK_PLACE_CLOSEST = "event-click-place-close";
// public static final String EVENT_CLICK_MARKER = "event-click-marker";
// public static final String EVENT_CLICK_INFO_WINDOW = "event-click-info-window";
// public static final String EVENT_CLICK_PLACE_PHONE = "event-click-place-phone";
// public static final String EVENT_CLICK_PLACE_FACEBOOK = "event-click-place-facebook";
// public static final String EVENT_CLICK_PLACE_ZOMATO = "event-click-place-zomato";
// public static final String EVENT_CLICK_PLACE_TRIPADVISOR = "event-click-tripadvisor";
// public static final String EVENT_CLICK_ALL_PLACES_FACEBOOK = "event-click-all-places-facebook";
// public static final String EVENT_CLICK_ALL_PLACES_ZOMATO = "event-click-all-places-zomato";
// public static final String EVENT_CLICK_ALL_PLACES_TRIPADVISOR = "event-click-all-places-tripadvisor";
// public static final String EVENT_CLICK_BEER_RATEBEER = "event-click-beer-ratebeer";
// public static final String EVENT_CLICK_BEER_UNTAPPD = "event-click-beer-untappd";
// public static final String EVENT_CLICK_ABOUT_EMAIL = "event-click-about-email";
// public static final String EVENT_CLICK_ABOUT_FACEBOOK = "event-click-about-facebook";
//
// public void trackEvent(String eventName){
// Answers.getInstance().logCustom(new CustomEvent(eventName));
// }
//
// public void trackEvent(String eventName, String key, String value){
//
// //truncate value to 100 chars
// if(value.length() > 100) {
// value = value.substring(0, 99);
// }
//
// CustomEvent customEvent = new CustomEvent(eventName);
// customEvent.putCustomAttribute(key, value);
//
// Answers.getInstance().logCustom(customEvent);
// }
//
// public void trackEvent(String eventName, HashMap<String, String> attributes){
// CustomEvent customEvent = new CustomEvent(eventName);
// for(Map.Entry<String, String> entry : attributes.entrySet()){
// customEvent.putCustomAttribute(entry.getKey(), entry.getValue());
// }
//
// Answers.getInstance().logCustom(customEvent);
// }
// }
// Path: app/src/main/java/pt/passarola/services/ServicesModule.java
import android.content.Context;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import pt.passarola.services.rest.RestApi;
import pt.passarola.services.tracker.TrackerManager;
package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
@Module(library = true, complete = false)
public class ServicesModule {
@Provides
@Singleton
BusProvider provideBus() {
return new BusProvider();
}
@Provides
@Singleton | WebApiService provideWebApiService(RestApi restApi) { |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/ServicesModule.java | // Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/tracker/TrackerManager.java
// public class TrackerManager {
//
// public static final String EVENT_CLICK_TAB_BEERS = "event-click-tab-beers";
// public static final String EVENT_CLICK_TAB_PLACES = "event-click-tab-places";
// public static final String EVENT_CLICK_TAB_CLOSEST = "event-click-tab-closest";
// public static final String EVENT_CLICK_PLACE_CLOSEST = "event-click-place-close";
// public static final String EVENT_CLICK_MARKER = "event-click-marker";
// public static final String EVENT_CLICK_INFO_WINDOW = "event-click-info-window";
// public static final String EVENT_CLICK_PLACE_PHONE = "event-click-place-phone";
// public static final String EVENT_CLICK_PLACE_FACEBOOK = "event-click-place-facebook";
// public static final String EVENT_CLICK_PLACE_ZOMATO = "event-click-place-zomato";
// public static final String EVENT_CLICK_PLACE_TRIPADVISOR = "event-click-tripadvisor";
// public static final String EVENT_CLICK_ALL_PLACES_FACEBOOK = "event-click-all-places-facebook";
// public static final String EVENT_CLICK_ALL_PLACES_ZOMATO = "event-click-all-places-zomato";
// public static final String EVENT_CLICK_ALL_PLACES_TRIPADVISOR = "event-click-all-places-tripadvisor";
// public static final String EVENT_CLICK_BEER_RATEBEER = "event-click-beer-ratebeer";
// public static final String EVENT_CLICK_BEER_UNTAPPD = "event-click-beer-untappd";
// public static final String EVENT_CLICK_ABOUT_EMAIL = "event-click-about-email";
// public static final String EVENT_CLICK_ABOUT_FACEBOOK = "event-click-about-facebook";
//
// public void trackEvent(String eventName){
// Answers.getInstance().logCustom(new CustomEvent(eventName));
// }
//
// public void trackEvent(String eventName, String key, String value){
//
// //truncate value to 100 chars
// if(value.length() > 100) {
// value = value.substring(0, 99);
// }
//
// CustomEvent customEvent = new CustomEvent(eventName);
// customEvent.putCustomAttribute(key, value);
//
// Answers.getInstance().logCustom(customEvent);
// }
//
// public void trackEvent(String eventName, HashMap<String, String> attributes){
// CustomEvent customEvent = new CustomEvent(eventName);
// for(Map.Entry<String, String> entry : attributes.entrySet()){
// customEvent.putCustomAttribute(entry.getKey(), entry.getValue());
// }
//
// Answers.getInstance().logCustom(customEvent);
// }
// }
| import android.content.Context;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import pt.passarola.services.rest.RestApi;
import pt.passarola.services.tracker.TrackerManager; | package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
@Module(library = true, complete = false)
public class ServicesModule {
@Provides
@Singleton
BusProvider provideBus() {
return new BusProvider();
}
@Provides
@Singleton
WebApiService provideWebApiService(RestApi restApi) {
return new WebApiService(restApi);
}
@Provides
@Singleton
PlaceProvider providePlaceProvider(BusProvider busProvider, WebApiService webApiService) {
return new PlaceProvider(busProvider, webApiService);
}
@Provides
@Singleton
LocationProvider providesLocationProvider(BusProvider busProvider, Context context){
return new LocationProvider(busProvider, context);
}
@Provides
@Singleton
BeerProvider providesBeerProvider(BusProvider busProvider, WebApiService webApiService){
return new BeerProvider(busProvider, webApiService);
}
@Provides
@Singleton | // Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/tracker/TrackerManager.java
// public class TrackerManager {
//
// public static final String EVENT_CLICK_TAB_BEERS = "event-click-tab-beers";
// public static final String EVENT_CLICK_TAB_PLACES = "event-click-tab-places";
// public static final String EVENT_CLICK_TAB_CLOSEST = "event-click-tab-closest";
// public static final String EVENT_CLICK_PLACE_CLOSEST = "event-click-place-close";
// public static final String EVENT_CLICK_MARKER = "event-click-marker";
// public static final String EVENT_CLICK_INFO_WINDOW = "event-click-info-window";
// public static final String EVENT_CLICK_PLACE_PHONE = "event-click-place-phone";
// public static final String EVENT_CLICK_PLACE_FACEBOOK = "event-click-place-facebook";
// public static final String EVENT_CLICK_PLACE_ZOMATO = "event-click-place-zomato";
// public static final String EVENT_CLICK_PLACE_TRIPADVISOR = "event-click-tripadvisor";
// public static final String EVENT_CLICK_ALL_PLACES_FACEBOOK = "event-click-all-places-facebook";
// public static final String EVENT_CLICK_ALL_PLACES_ZOMATO = "event-click-all-places-zomato";
// public static final String EVENT_CLICK_ALL_PLACES_TRIPADVISOR = "event-click-all-places-tripadvisor";
// public static final String EVENT_CLICK_BEER_RATEBEER = "event-click-beer-ratebeer";
// public static final String EVENT_CLICK_BEER_UNTAPPD = "event-click-beer-untappd";
// public static final String EVENT_CLICK_ABOUT_EMAIL = "event-click-about-email";
// public static final String EVENT_CLICK_ABOUT_FACEBOOK = "event-click-about-facebook";
//
// public void trackEvent(String eventName){
// Answers.getInstance().logCustom(new CustomEvent(eventName));
// }
//
// public void trackEvent(String eventName, String key, String value){
//
// //truncate value to 100 chars
// if(value.length() > 100) {
// value = value.substring(0, 99);
// }
//
// CustomEvent customEvent = new CustomEvent(eventName);
// customEvent.putCustomAttribute(key, value);
//
// Answers.getInstance().logCustom(customEvent);
// }
//
// public void trackEvent(String eventName, HashMap<String, String> attributes){
// CustomEvent customEvent = new CustomEvent(eventName);
// for(Map.Entry<String, String> entry : attributes.entrySet()){
// customEvent.putCustomAttribute(entry.getKey(), entry.getValue());
// }
//
// Answers.getInstance().logCustom(customEvent);
// }
// }
// Path: app/src/main/java/pt/passarola/services/ServicesModule.java
import android.content.Context;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import pt.passarola.services.rest.RestApi;
import pt.passarola.services.tracker.TrackerManager;
package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
@Module(library = true, complete = false)
public class ServicesModule {
@Provides
@Singleton
BusProvider provideBus() {
return new BusProvider();
}
@Provides
@Singleton
WebApiService provideWebApiService(RestApi restApi) {
return new WebApiService(restApi);
}
@Provides
@Singleton
PlaceProvider providePlaceProvider(BusProvider busProvider, WebApiService webApiService) {
return new PlaceProvider(busProvider, webApiService);
}
@Provides
@Singleton
LocationProvider providesLocationProvider(BusProvider busProvider, Context context){
return new LocationProvider(busProvider, context);
}
@Provides
@Singleton
BeerProvider providesBeerProvider(BusProvider busProvider, WebApiService webApiService){
return new BeerProvider(busProvider, webApiService);
}
@Provides
@Singleton | TrackerManager providesTrackerManager(){ |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/dagger/DaggerableAppCompatActivity.java | // Path: app/src/main/java/pt/passarola/App.java
// public class App extends Application implements Daggerable {
//
// private ObjectGraph objectGraph;
//
//
// public static App obtain(Context context) {
// return (App) context.getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// Fabric.with(this, new Crashlytics());
// buildDebugOptions();
// buildObjectGraph();
// }
//
// @Override
// public void inject(Object object) {
// objectGraph.inject(object);
// }
//
// @Override
// public void inject(Object object, Object... modules) {
// objectGraph.plus(modules).inject(object);
// }
//
// private void buildObjectGraph() {
// objectGraph = ObjectGraph.create(getModules().toArray());
// objectGraph.inject(this);
// }
//
// private List<Object> getModules() {
// return Arrays.<Object>asList(new AppModule(this));
// }
//
// private void buildDebugOptions() {
// if (BuildConfig.DEBUG) {
// RestApi.DEBUG = true;
// Timber.plant(new Timber.DebugTree());
// }
// }
//
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import pt.passarola.App; | package pt.passarola.services.dagger;
/**
* Created by ruigoncalo on 22/10/15.
*/
public abstract class DaggerableAppCompatActivity extends AppCompatActivity implements Daggerable {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inject(this);
}
@Override
public void inject(Object object) { | // Path: app/src/main/java/pt/passarola/App.java
// public class App extends Application implements Daggerable {
//
// private ObjectGraph objectGraph;
//
//
// public static App obtain(Context context) {
// return (App) context.getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// Fabric.with(this, new Crashlytics());
// buildDebugOptions();
// buildObjectGraph();
// }
//
// @Override
// public void inject(Object object) {
// objectGraph.inject(object);
// }
//
// @Override
// public void inject(Object object, Object... modules) {
// objectGraph.plus(modules).inject(object);
// }
//
// private void buildObjectGraph() {
// objectGraph = ObjectGraph.create(getModules().toArray());
// objectGraph.inject(this);
// }
//
// private List<Object> getModules() {
// return Arrays.<Object>asList(new AppModule(this));
// }
//
// private void buildDebugOptions() {
// if (BuildConfig.DEBUG) {
// RestApi.DEBUG = true;
// Timber.plant(new Timber.DebugTree());
// }
// }
//
// }
// Path: app/src/main/java/pt/passarola/services/dagger/DaggerableAppCompatActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import pt.passarola.App;
package pt.passarola.services.dagger;
/**
* Created by ruigoncalo on 22/10/15.
*/
public abstract class DaggerableAppCompatActivity extends AppCompatActivity implements Daggerable {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inject(this);
}
@Override
public void inject(Object object) { | App.obtain(this).inject(object); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/MapPresenterCallback.java | // Path: app/src/main/java/pt/passarola/model/MapItems.java
// public class MapItems {
//
// private final List<PlaceViewModel> places;
//
// public MapItems(List<PlaceViewModel> places) {
// this.places = places;
// }
//
// public List<PlaceViewModel> getPlaces() {
// return places;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/viewmodel/MixedViewModel.java
// public interface MixedViewModel {
//
// int TYPE_A = 1;
// int TYPE_B = 2;
//
// int getType();
// }
| import android.location.Location;
import java.util.List;
import pt.passarola.model.MapItems;
import pt.passarola.model.viewmodel.MixedViewModel; | package pt.passarola.ui;
/**
* Created by ruigoncalo on 19/11/15.
*/
public interface MapPresenterCallback {
void onLocationSuccessEvent(Location location);
void onLocationErrorEvent(Exception e); | // Path: app/src/main/java/pt/passarola/model/MapItems.java
// public class MapItems {
//
// private final List<PlaceViewModel> places;
//
// public MapItems(List<PlaceViewModel> places) {
// this.places = places;
// }
//
// public List<PlaceViewModel> getPlaces() {
// return places;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/viewmodel/MixedViewModel.java
// public interface MixedViewModel {
//
// int TYPE_A = 1;
// int TYPE_B = 2;
//
// int getType();
// }
// Path: app/src/main/java/pt/passarola/ui/MapPresenterCallback.java
import android.location.Location;
import java.util.List;
import pt.passarola.model.MapItems;
import pt.passarola.model.viewmodel.MixedViewModel;
package pt.passarola.ui;
/**
* Created by ruigoncalo on 19/11/15.
*/
public interface MapPresenterCallback {
void onLocationSuccessEvent(Location location);
void onLocationErrorEvent(Exception e); | void onPlacesSuccessEvent(MapItems items); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/MapPresenterCallback.java | // Path: app/src/main/java/pt/passarola/model/MapItems.java
// public class MapItems {
//
// private final List<PlaceViewModel> places;
//
// public MapItems(List<PlaceViewModel> places) {
// this.places = places;
// }
//
// public List<PlaceViewModel> getPlaces() {
// return places;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/viewmodel/MixedViewModel.java
// public interface MixedViewModel {
//
// int TYPE_A = 1;
// int TYPE_B = 2;
//
// int getType();
// }
| import android.location.Location;
import java.util.List;
import pt.passarola.model.MapItems;
import pt.passarola.model.viewmodel.MixedViewModel; | package pt.passarola.ui;
/**
* Created by ruigoncalo on 19/11/15.
*/
public interface MapPresenterCallback {
void onLocationSuccessEvent(Location location);
void onLocationErrorEvent(Exception e);
void onPlacesSuccessEvent(MapItems items);
void onPlacesErrorEvent(Exception e); | // Path: app/src/main/java/pt/passarola/model/MapItems.java
// public class MapItems {
//
// private final List<PlaceViewModel> places;
//
// public MapItems(List<PlaceViewModel> places) {
// this.places = places;
// }
//
// public List<PlaceViewModel> getPlaces() {
// return places;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/viewmodel/MixedViewModel.java
// public interface MixedViewModel {
//
// int TYPE_A = 1;
// int TYPE_B = 2;
//
// int getType();
// }
// Path: app/src/main/java/pt/passarola/ui/MapPresenterCallback.java
import android.location.Location;
import java.util.List;
import pt.passarola.model.MapItems;
import pt.passarola.model.viewmodel.MixedViewModel;
package pt.passarola.ui;
/**
* Created by ruigoncalo on 19/11/15.
*/
public interface MapPresenterCallback {
void onLocationSuccessEvent(Location location);
void onLocationErrorEvent(Exception e);
void onPlacesSuccessEvent(MapItems items);
void onPlacesErrorEvent(Exception e); | void onClosestPlacesSuccessEvent(List<MixedViewModel> list); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/rest/ApiServices.java | // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
| import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import retrofit.Callback;
import retrofit.http.GET; | package pt.passarola.services.rest;
/**
* Created by ruigoncalo on 22/10/15.
*/
public interface ApiServices {
@GET(Endpoints.places) | // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
// Path: app/src/main/java/pt/passarola/services/rest/ApiServices.java
import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import retrofit.Callback;
import retrofit.http.GET;
package pt.passarola.services.rest;
/**
* Created by ruigoncalo on 22/10/15.
*/
public interface ApiServices {
@GET(Endpoints.places) | void getPlaces(Callback<MetaPlaces> callback); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/rest/ApiServices.java | // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
| import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import retrofit.Callback;
import retrofit.http.GET; | package pt.passarola.services.rest;
/**
* Created by ruigoncalo on 22/10/15.
*/
public interface ApiServices {
@GET(Endpoints.places)
void getPlaces(Callback<MetaPlaces> callback);
@GET(Endpoints.beers) | // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
// Path: app/src/main/java/pt/passarola/services/rest/ApiServices.java
import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import retrofit.Callback;
import retrofit.http.GET;
package pt.passarola.services.rest;
/**
* Created by ruigoncalo on 22/10/15.
*/
public interface ApiServices {
@GET(Endpoints.places)
void getPlaces(Callback<MetaPlaces> callback);
@GET(Endpoints.beers) | void getBeers(Callback<MetaBeers> callback); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/LocationProvider.java | // Path: app/src/main/java/pt/passarola/model/events/LocationErrorEvent.java
// public class LocationErrorEvent extends ErrorEvent {
//
// public LocationErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/LocationSuccessEvent.java
// public class LocationSuccessEvent {
//
// private final Location location;
//
// public LocationSuccessEvent(Location location) {
// this.location = location;
// }
//
// public Location getLocation() {
// return location;
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
| import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import pt.passarola.model.events.LocationErrorEvent;
import pt.passarola.model.events.LocationSuccessEvent;
import pt.passarola.utils.Utils; | package pt.passarola.services;
/**
* Created by ruigoncalo on 19/12/15.
*/
public class LocationProvider
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Context context;
private BusProvider busProvider;
private GoogleApiClient googleApiClient;
public LocationProvider(BusProvider busProvider, Context context) {
this.busProvider = busProvider;
this.context = context;
}
public void getCurrentLocation() {
if (isGooglePlayServicesAvailable()) {
createGoogleApiClient();
googleApiClient.connect();
} else {
postError(new Exception("Google Play Services not available"));
}
}
private boolean isGooglePlayServicesAvailable() { | // Path: app/src/main/java/pt/passarola/model/events/LocationErrorEvent.java
// public class LocationErrorEvent extends ErrorEvent {
//
// public LocationErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/LocationSuccessEvent.java
// public class LocationSuccessEvent {
//
// private final Location location;
//
// public LocationSuccessEvent(Location location) {
// this.location = location;
// }
//
// public Location getLocation() {
// return location;
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
// Path: app/src/main/java/pt/passarola/services/LocationProvider.java
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import pt.passarola.model.events.LocationErrorEvent;
import pt.passarola.model.events.LocationSuccessEvent;
import pt.passarola.utils.Utils;
package pt.passarola.services;
/**
* Created by ruigoncalo on 19/12/15.
*/
public class LocationProvider
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Context context;
private BusProvider busProvider;
private GoogleApiClient googleApiClient;
public LocationProvider(BusProvider busProvider, Context context) {
this.busProvider = busProvider;
this.context = context;
}
public void getCurrentLocation() {
if (isGooglePlayServicesAvailable()) {
createGoogleApiClient();
googleApiClient.connect();
} else {
postError(new Exception("Google Play Services not available"));
}
}
private boolean isGooglePlayServicesAvailable() { | return Utils.isGooglePlayServicesAvailable(context); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/LocationProvider.java | // Path: app/src/main/java/pt/passarola/model/events/LocationErrorEvent.java
// public class LocationErrorEvent extends ErrorEvent {
//
// public LocationErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/LocationSuccessEvent.java
// public class LocationSuccessEvent {
//
// private final Location location;
//
// public LocationSuccessEvent(Location location) {
// this.location = location;
// }
//
// public Location getLocation() {
// return location;
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
| import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import pt.passarola.model.events.LocationErrorEvent;
import pt.passarola.model.events.LocationSuccessEvent;
import pt.passarola.utils.Utils; | package pt.passarola.services;
/**
* Created by ruigoncalo on 19/12/15.
*/
public class LocationProvider
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Context context;
private BusProvider busProvider;
private GoogleApiClient googleApiClient;
public LocationProvider(BusProvider busProvider, Context context) {
this.busProvider = busProvider;
this.context = context;
}
public void getCurrentLocation() {
if (isGooglePlayServicesAvailable()) {
createGoogleApiClient();
googleApiClient.connect();
} else {
postError(new Exception("Google Play Services not available"));
}
}
private boolean isGooglePlayServicesAvailable() {
return Utils.isGooglePlayServicesAvailable(context);
}
private void createGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void postError(Exception e) { | // Path: app/src/main/java/pt/passarola/model/events/LocationErrorEvent.java
// public class LocationErrorEvent extends ErrorEvent {
//
// public LocationErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/LocationSuccessEvent.java
// public class LocationSuccessEvent {
//
// private final Location location;
//
// public LocationSuccessEvent(Location location) {
// this.location = location;
// }
//
// public Location getLocation() {
// return location;
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
// Path: app/src/main/java/pt/passarola/services/LocationProvider.java
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import pt.passarola.model.events.LocationErrorEvent;
import pt.passarola.model.events.LocationSuccessEvent;
import pt.passarola.utils.Utils;
package pt.passarola.services;
/**
* Created by ruigoncalo on 19/12/15.
*/
public class LocationProvider
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Context context;
private BusProvider busProvider;
private GoogleApiClient googleApiClient;
public LocationProvider(BusProvider busProvider, Context context) {
this.busProvider = busProvider;
this.context = context;
}
public void getCurrentLocation() {
if (isGooglePlayServicesAvailable()) {
createGoogleApiClient();
googleApiClient.connect();
} else {
postError(new Exception("Google Play Services not available"));
}
}
private boolean isGooglePlayServicesAvailable() {
return Utils.isGooglePlayServicesAvailable(context);
}
private void createGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void postError(Exception e) { | busProvider.post(new LocationErrorEvent(e)); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/LocationProvider.java | // Path: app/src/main/java/pt/passarola/model/events/LocationErrorEvent.java
// public class LocationErrorEvent extends ErrorEvent {
//
// public LocationErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/LocationSuccessEvent.java
// public class LocationSuccessEvent {
//
// private final Location location;
//
// public LocationSuccessEvent(Location location) {
// this.location = location;
// }
//
// public Location getLocation() {
// return location;
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
| import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import pt.passarola.model.events.LocationErrorEvent;
import pt.passarola.model.events.LocationSuccessEvent;
import pt.passarola.utils.Utils; | if (isGooglePlayServicesAvailable()) {
createGoogleApiClient();
googleApiClient.connect();
} else {
postError(new Exception("Google Play Services not available"));
}
}
private boolean isGooglePlayServicesAvailable() {
return Utils.isGooglePlayServicesAvailable(context);
}
private void createGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void postError(Exception e) {
busProvider.post(new LocationErrorEvent(e));
}
@Override
public void onConnected(Bundle bundle) {
if(googleApiClient != null) {
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
googleApiClient.disconnect();
if (currentLocation != null) { | // Path: app/src/main/java/pt/passarola/model/events/LocationErrorEvent.java
// public class LocationErrorEvent extends ErrorEvent {
//
// public LocationErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/LocationSuccessEvent.java
// public class LocationSuccessEvent {
//
// private final Location location;
//
// public LocationSuccessEvent(Location location) {
// this.location = location;
// }
//
// public Location getLocation() {
// return location;
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/Utils.java
// public class Utils {
//
// /**
// * Validate if device has GooglePlayServices app installed
// */
// public static boolean isGooglePlayServicesAvailable(Context context) {
// return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == SUCCESS;
// }
//
// /**
// * Normalize the value of a distance expressed in meters.
// * 989 meters = 989 meters
// * 1000 meters = 1.0 km
// * 1500 meters = 1.5 km
// *
// * @param distanceInMeters distance number in meters
// * @return distance normalized with distance units
// */
// public static String getNormalizedDistance(int distanceInMeters){
// float distance = (float) distanceInMeters;
// if(distance < 1000){
// return distanceInMeters + " meters";
// } else {
// return String.format("%.02f", distance/1000) + " km";
// }
// }
//
// /**
// * Generate a date object from a string
// *
// * @param date string date
// * @return date object that follows the format "yyyy-mm-dd"
// */
// @Nullable
// public static Date getDateFromString(String date){
// Date result;
// DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.UK);
//
// try {
// result = dateFormat.parse(date);
// } catch (ParseException e){
// result = null;
// }
//
// return result;
// }
//
// /**
// * Open intent with data
// *
// * @param context used to start activity
// * @param link intent's data
// */
// public static void openLink(Context context, String link) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse(link));
// context.startActivity(intent);
// }
//
// /**
// * Open contact screen by providing a phone number
// * @param context used to start activity
// * @param phoneNumber data to show on contact screen
// */
// public static void openContact(Context context, String phoneNumber){
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("tel:" + phoneNumber));
// context.startActivity(intent);
// }
//
// }
// Path: app/src/main/java/pt/passarola/services/LocationProvider.java
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import pt.passarola.model.events.LocationErrorEvent;
import pt.passarola.model.events.LocationSuccessEvent;
import pt.passarola.utils.Utils;
if (isGooglePlayServicesAvailable()) {
createGoogleApiClient();
googleApiClient.connect();
} else {
postError(new Exception("Google Play Services not available"));
}
}
private boolean isGooglePlayServicesAvailable() {
return Utils.isGooglePlayServicesAvailable(context);
}
private void createGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void postError(Exception e) {
busProvider.post(new LocationErrorEvent(e));
}
@Override
public void onConnected(Bundle bundle) {
if(googleApiClient != null) {
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
googleApiClient.disconnect();
if (currentLocation != null) { | busProvider.post(new LocationSuccessEvent(currentLocation)); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/WebApiService.java | // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
| import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import pt.passarola.services.rest.RestApi;
import retrofit.Callback; | package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class WebApiService {
private RestApi restApi;
public WebApiService(RestApi restApi) {
this.restApi = restApi;
}
| // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
// Path: app/src/main/java/pt/passarola/services/WebApiService.java
import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import pt.passarola.services.rest.RestApi;
import retrofit.Callback;
package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class WebApiService {
private RestApi restApi;
public WebApiService(RestApi restApi) {
this.restApi = restApi;
}
| public void getPlaces(Callback<MetaPlaces> callback){ |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/WebApiService.java | // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
| import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import pt.passarola.services.rest.RestApi;
import retrofit.Callback; | package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class WebApiService {
private RestApi restApi;
public WebApiService(RestApi restApi) {
this.restApi = restApi;
}
public void getPlaces(Callback<MetaPlaces> callback){
restApi.getApiServices().getPlaces(callback);
}
| // Path: app/src/main/java/pt/passarola/model/MetaBeers.java
// public class MetaBeers {
//
// private String message;
// private int results;
// private List<Beer> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Beer> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
// Path: app/src/main/java/pt/passarola/services/WebApiService.java
import pt.passarola.model.MetaBeers;
import pt.passarola.model.MetaPlaces;
import pt.passarola.services.rest.RestApi;
import retrofit.Callback;
package pt.passarola.services;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class WebApiService {
private RestApi restApi;
public WebApiService(RestApi restApi) {
this.restApi = restApi;
}
public void getPlaces(Callback<MetaPlaces> callback){
restApi.getApiServices().getPlaces(callback);
}
| public void getBeers(Callback<MetaBeers> callback){ |
ruigoncalo/passarola | app/src/main/java/pt/passarola/model/viewmodel/PlaceViewModel.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
| import android.support.annotation.Nullable;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.Place; | public Builder latLng(LatLng latLng){
this.latLng = latLng;
return this;
}
public Builder distance(int distance){
this.distance = distance;
return this;
}
public Builder facebook(String facebook){
this.facebook = facebook;
return this;
}
public Builder zomato(String zomato){
this.zomato = zomato;
return this;
}
public Builder tripadvisor(String tripadvisor){
this.tripadvisor = tripadvisor;
return this;
}
public PlaceViewModel build(){
return new PlaceViewModel(this);
}
}
| // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
// Path: app/src/main/java/pt/passarola/model/viewmodel/PlaceViewModel.java
import android.support.annotation.Nullable;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.Place;
public Builder latLng(LatLng latLng){
this.latLng = latLng;
return this;
}
public Builder distance(int distance){
this.distance = distance;
return this;
}
public Builder facebook(String facebook){
this.facebook = facebook;
return this;
}
public Builder zomato(String zomato){
this.zomato = zomato;
return this;
}
public Builder tripadvisor(String tripadvisor){
this.tripadvisor = tripadvisor;
return this;
}
public PlaceViewModel build(){
return new PlaceViewModel(this);
}
}
| public static List<PlaceViewModel> createViewModelList(List<Place> places){ |
ruigoncalo/passarola | app/src/main/java/pt/passarola/model/viewmodel/PlaceViewModel.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
| import android.support.annotation.Nullable;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.Place; | result.add(placeViewModel);
}
}
return result;
}
@Nullable
public static PlaceViewModel createPlaceViewModel(Place place){
PlaceViewModel result = null;
if(place.isValid()){
result = new Builder()
.id(place.getId())
.name(place.getName())
.fullAddress(place.getFullAddress())
.council(place.getCouncil())
.country(place.getCountry())
.telephone(place.getTelephone())
.latLng(place.getLatLng())
.facebook(place.getFacebook())
.zomato(place.getZomato())
.tripadvisor(place.getTripadvisor())
.build();
}
return result;
}
@Nullable | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
// Path: app/src/main/java/pt/passarola/model/viewmodel/PlaceViewModel.java
import android.support.annotation.Nullable;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.Place;
result.add(placeViewModel);
}
}
return result;
}
@Nullable
public static PlaceViewModel createPlaceViewModel(Place place){
PlaceViewModel result = null;
if(place.isValid()){
result = new Builder()
.id(place.getId())
.name(place.getName())
.fullAddress(place.getFullAddress())
.council(place.getCouncil())
.country(place.getCountry())
.telephone(place.getTelephone())
.latLng(place.getLatLng())
.facebook(place.getFacebook())
.zomato(place.getZomato())
.tripadvisor(place.getTripadvisor())
.build();
}
return result;
}
@Nullable | public static PlaceViewModel createPlaceViewModel(ClosestPlace closestPlace){ |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/recyclerview/MixedBaseAdapter.java | // Path: app/src/main/java/pt/passarola/model/viewmodel/MixedViewModel.java
// public interface MixedViewModel {
//
// int TYPE_A = 1;
// int TYPE_B = 2;
//
// int getType();
// }
| import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.viewmodel.MixedViewModel; | package pt.passarola.ui.recyclerview;
/**
* Created by ruigoncalo on 20/12/15.
*/
public abstract class MixedBaseAdapter<VHA extends RecyclerView.ViewHolder, VHB extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
| // Path: app/src/main/java/pt/passarola/model/viewmodel/MixedViewModel.java
// public interface MixedViewModel {
//
// int TYPE_A = 1;
// int TYPE_B = 2;
//
// int getType();
// }
// Path: app/src/main/java/pt/passarola/ui/recyclerview/MixedBaseAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import pt.passarola.model.viewmodel.MixedViewModel;
package pt.passarola.ui.recyclerview;
/**
* Created by ruigoncalo on 20/12/15.
*/
public abstract class MixedBaseAdapter<VHA extends RecyclerView.ViewHolder, VHB extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
| private List<MixedViewModel> itemList; |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/recyclerview/BeersViewHolder.java | // Path: app/src/main/java/pt/passarola/model/viewmodel/BeerViewModel.java
// public class BeerViewModel {
//
// private final String id;
// private final String name;
// private final String style;
// private final String abv;
// private final String ingredients;
// private final String description;
// private final String labelPic;
// private final String labelPicSmall;
// private final String rateBeerUrl;
// private final String untappdUrl;
//
// private BeerViewModel(Builder builder){
// this.id = builder.id;
// this.name = builder.name;
// this.style = builder.style;
// this.abv = builder.abv;
// this.ingredients = builder.ingredients;
// this.description = builder.description;
// this.labelPic = builder.labelPic;
// this.labelPicSmall = builder.labelPicSmall;
// this.rateBeerUrl = builder.rateBeerUrl;
// this.untappdUrl = builder.untappdUrl;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getStyle() {
// return style;
// }
//
// public String getAbv() {
// return abv;
// }
//
// public String getIngredients() {
// return ingredients;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getLabelPic() {
// return labelPic;
// }
//
// public String getLabelPicSmall() {
// return labelPicSmall;
// }
//
// public String getRateBeerUrl() {
// return rateBeerUrl;
// }
//
// public String getUntappdUrl() {
// return untappdUrl;
// }
//
// public static class Builder {
// private String id;
// private String name;
// private String style;
// private String abv;
// private String ingredients;
// private String description;
// private String labelPic;
// private String labelPicSmall;
// private String rateBeerUrl;
// private String untappdUrl;
//
// public Builder id(String id){
// this.id = id;
// return this;
// }
//
// public Builder name(String name){
// this.name = name;
// return this;
// }
//
// public Builder style(String style){
// this.style = style;
// return this;
// }
//
// public Builder abv(String abv){
// this.abv = abv;
// return this;
// }
//
// public Builder ingredients(String ingredients){
// this.ingredients = ingredients;
// return this;
// }
//
// public Builder description(String description){
// this.description = description;
// return this;
// }
//
// public Builder labelPic(String labelPic){
// this.labelPic = labelPic;
// return this;
// }
//
// public Builder labelPicSmall(String labelPicSmall){
// this.labelPicSmall = labelPicSmall;
// return this;
// }
//
// public Builder rateBeerUrl(String rateBeerUrl){
// this.rateBeerUrl = rateBeerUrl;
// return this;
// }
//
// public Builder untappdUrl(String untappdUrl){
// this.untappdUrl = untappdUrl;
// return this;
// }
//
// public BeerViewModel build(){
// return new BeerViewModel(this);
// }
// }
//
// public static List<BeerViewModel> createViewModelList(List<Beer> beers){
// List<BeerViewModel> result = new ArrayList<>();
// for(Beer beer : beers){
// BeerViewModel viewModel = createBeerViewModel(beer);
// if(viewModel != null){
// result.add(viewModel);
// }
// }
//
// return result;
// }
//
// @Nullable
// public static BeerViewModel createBeerViewModel(Beer beer){
// if(beer != null) {
// return new Builder()
// .id(beer.getId())
// .name(beer.getName())
// .style(beer.getStyle())
// .abv(beer.getAbv())
// .ingredients(beer.getIngredients())
// .description(beer.getMediumDescription())
// .labelPic(beer.getLabelPic())
// .labelPicSmall(beer.getLabelPicSmall())
// .rateBeerUrl(beer.getRatebeerUrl())
// .untappdUrl(beer.getUntappdUrl())
// .build();
// } else {
// return null;
// }
// }
// }
//
// Path: app/src/main/java/pt/passarola/ui/SocialBeerListener.java
// public interface SocialBeerListener {
// void onRateBeerClick(String link);
//
// void onUntappdClick(String link);
// }
| import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import butterknife.Bind;
import butterknife.ButterKnife;
import pt.passarola.R;
import pt.passarola.model.viewmodel.BeerViewModel;
import pt.passarola.ui.SocialBeerListener; | package pt.passarola.ui.recyclerview;
/**
* Created by ruigoncalo on 19/11/15.
*/
public class BeersViewHolder extends RecyclerView.ViewHolder implements Composer<BeerViewModel> {
@Bind(R.id.image_beer) ImageView image;
@Bind(R.id.text_beer_name) TextView textName;
@Bind(R.id.text_beer_style) TextView textStyle;
@Bind(R.id.text_beer_description) TextView textDescription;
@Bind(R.id.text_beer_ingredients) TextView textIngredients;
@Bind(R.id.button_ratebeer) View rateBeerButton;
@Bind(R.id.button_untappd) View untappdButton;
| // Path: app/src/main/java/pt/passarola/model/viewmodel/BeerViewModel.java
// public class BeerViewModel {
//
// private final String id;
// private final String name;
// private final String style;
// private final String abv;
// private final String ingredients;
// private final String description;
// private final String labelPic;
// private final String labelPicSmall;
// private final String rateBeerUrl;
// private final String untappdUrl;
//
// private BeerViewModel(Builder builder){
// this.id = builder.id;
// this.name = builder.name;
// this.style = builder.style;
// this.abv = builder.abv;
// this.ingredients = builder.ingredients;
// this.description = builder.description;
// this.labelPic = builder.labelPic;
// this.labelPicSmall = builder.labelPicSmall;
// this.rateBeerUrl = builder.rateBeerUrl;
// this.untappdUrl = builder.untappdUrl;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getStyle() {
// return style;
// }
//
// public String getAbv() {
// return abv;
// }
//
// public String getIngredients() {
// return ingredients;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getLabelPic() {
// return labelPic;
// }
//
// public String getLabelPicSmall() {
// return labelPicSmall;
// }
//
// public String getRateBeerUrl() {
// return rateBeerUrl;
// }
//
// public String getUntappdUrl() {
// return untappdUrl;
// }
//
// public static class Builder {
// private String id;
// private String name;
// private String style;
// private String abv;
// private String ingredients;
// private String description;
// private String labelPic;
// private String labelPicSmall;
// private String rateBeerUrl;
// private String untappdUrl;
//
// public Builder id(String id){
// this.id = id;
// return this;
// }
//
// public Builder name(String name){
// this.name = name;
// return this;
// }
//
// public Builder style(String style){
// this.style = style;
// return this;
// }
//
// public Builder abv(String abv){
// this.abv = abv;
// return this;
// }
//
// public Builder ingredients(String ingredients){
// this.ingredients = ingredients;
// return this;
// }
//
// public Builder description(String description){
// this.description = description;
// return this;
// }
//
// public Builder labelPic(String labelPic){
// this.labelPic = labelPic;
// return this;
// }
//
// public Builder labelPicSmall(String labelPicSmall){
// this.labelPicSmall = labelPicSmall;
// return this;
// }
//
// public Builder rateBeerUrl(String rateBeerUrl){
// this.rateBeerUrl = rateBeerUrl;
// return this;
// }
//
// public Builder untappdUrl(String untappdUrl){
// this.untappdUrl = untappdUrl;
// return this;
// }
//
// public BeerViewModel build(){
// return new BeerViewModel(this);
// }
// }
//
// public static List<BeerViewModel> createViewModelList(List<Beer> beers){
// List<BeerViewModel> result = new ArrayList<>();
// for(Beer beer : beers){
// BeerViewModel viewModel = createBeerViewModel(beer);
// if(viewModel != null){
// result.add(viewModel);
// }
// }
//
// return result;
// }
//
// @Nullable
// public static BeerViewModel createBeerViewModel(Beer beer){
// if(beer != null) {
// return new Builder()
// .id(beer.getId())
// .name(beer.getName())
// .style(beer.getStyle())
// .abv(beer.getAbv())
// .ingredients(beer.getIngredients())
// .description(beer.getMediumDescription())
// .labelPic(beer.getLabelPic())
// .labelPicSmall(beer.getLabelPicSmall())
// .rateBeerUrl(beer.getRatebeerUrl())
// .untappdUrl(beer.getUntappdUrl())
// .build();
// } else {
// return null;
// }
// }
// }
//
// Path: app/src/main/java/pt/passarola/ui/SocialBeerListener.java
// public interface SocialBeerListener {
// void onRateBeerClick(String link);
//
// void onUntappdClick(String link);
// }
// Path: app/src/main/java/pt/passarola/ui/recyclerview/BeersViewHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import butterknife.Bind;
import butterknife.ButterKnife;
import pt.passarola.R;
import pt.passarola.model.viewmodel.BeerViewModel;
import pt.passarola.ui.SocialBeerListener;
package pt.passarola.ui.recyclerview;
/**
* Created by ruigoncalo on 19/11/15.
*/
public class BeersViewHolder extends RecyclerView.ViewHolder implements Composer<BeerViewModel> {
@Bind(R.id.image_beer) ImageView image;
@Bind(R.id.text_beer_name) TextView textName;
@Bind(R.id.text_beer_style) TextView textStyle;
@Bind(R.id.text_beer_description) TextView textDescription;
@Bind(R.id.text_beer_ingredients) TextView textIngredients;
@Bind(R.id.button_ratebeer) View rateBeerButton;
@Bind(R.id.button_untappd) View untappdButton;
| private SocialBeerListener listener; |
ruigoncalo/passarola | app/src/main/java/pt/passarola/App.java | // Path: app/src/main/java/pt/passarola/services/dagger/Daggerable.java
// public interface Daggerable {
// void inject(Object object);
// void inject(Object object, Object... modules);
// }
//
// Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
| import android.app.Application;
import android.content.Context;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
import java.util.Arrays;
import java.util.List;
import dagger.ObjectGraph;
import pt.passarola.services.dagger.Daggerable;
import pt.passarola.services.rest.RestApi;
import timber.log.Timber; | package pt.passarola;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class App extends Application implements Daggerable {
private ObjectGraph objectGraph;
public static App obtain(Context context) {
return (App) context.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
buildDebugOptions();
buildObjectGraph();
}
@Override
public void inject(Object object) {
objectGraph.inject(object);
}
@Override
public void inject(Object object, Object... modules) {
objectGraph.plus(modules).inject(object);
}
private void buildObjectGraph() {
objectGraph = ObjectGraph.create(getModules().toArray());
objectGraph.inject(this);
}
private List<Object> getModules() {
return Arrays.<Object>asList(new AppModule(this));
}
private void buildDebugOptions() {
if (BuildConfig.DEBUG) { | // Path: app/src/main/java/pt/passarola/services/dagger/Daggerable.java
// public interface Daggerable {
// void inject(Object object);
// void inject(Object object, Object... modules);
// }
//
// Path: app/src/main/java/pt/passarola/services/rest/RestApi.java
// @Singleton
// public class RestApi {
//
// public static boolean DEBUG = true;
// private ApiServices apiServices;
//
// @Inject
// public RestApi() {
// RestAdapter restAdapter = build(Endpoints.baseUrl);
// apiServices = restAdapter.create(ApiServices.class);
// }
//
// public RestAdapter build(String baseUrl) {
// RestAdapter adapter = new RestAdapter.Builder()
// .setEndpoint(baseUrl)
// .build();
//
// if (DEBUG) {
// adapter.setLogLevel(RestAdapter.LogLevel.FULL);
// }
//
// return adapter;
// }
//
// public ApiServices getApiServices() {
// return apiServices;
// }
// }
// Path: app/src/main/java/pt/passarola/App.java
import android.app.Application;
import android.content.Context;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
import java.util.Arrays;
import java.util.List;
import dagger.ObjectGraph;
import pt.passarola.services.dagger.Daggerable;
import pt.passarola.services.rest.RestApi;
import timber.log.Timber;
package pt.passarola;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class App extends Application implements Daggerable {
private ObjectGraph objectGraph;
public static App obtain(Context context) {
return (App) context.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
buildDebugOptions();
buildObjectGraph();
}
@Override
public void inject(Object object) {
objectGraph.inject(object);
}
@Override
public void inject(Object object, Object... modules) {
objectGraph.plus(modules).inject(object);
}
private void buildObjectGraph() {
objectGraph = ObjectGraph.create(getModules().toArray());
objectGraph.inject(this);
}
private List<Object> getModules() {
return Arrays.<Object>asList(new AppModule(this));
}
private void buildDebugOptions() {
if (BuildConfig.DEBUG) { | RestApi.DEBUG = true; |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/components/PassarolaTabLayoutManager.java | // Path: app/src/main/java/pt/passarola/utils/AnimatorManager.java
// public class AnimatorManager {
//
// private static final int SHORT_DURATION = 200; //ms
//
// public static void fadeInPartial(@NonNull final View view){
// view.setAlpha(0.5f);
// view.animate()
// .alpha(1)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeOutPartial(@NonNull final View view){
// view.animate()
// .alpha(0.5f)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeInView(@NonNull final View view){
// view.setAlpha(0f);
// view.setVisibility(View.VISIBLE);
// view.animate()
// .alpha(1)
// .setDuration(200)
// .setListener(null);
// }
//
// public static void fadeOutView(@NonNull final View view){
// view.animate()
// .alpha(0f)
// .setDuration(SHORT_DURATION)
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
//
// public static void slideInView(@NonNull final View view, int distance){
// view.setVisibility(View.VISIBLE);
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(null);
// }
//
// public static void slideOutView(@NonNull final View view, int distance){
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/ScreenInspector.java
// public class ScreenInspector {
//
// private static final int STATUS_BAR_HEIGHT_DP = 24;
// private static final int APP_BAR_HEIGHT_DP = 56;
//
// public static double getDensity(Context context){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return displayMetrics.density;
// }
//
// public static int getScreenWidthPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.x;
// }
//
// public static int getScreenHeightPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.y;
// }
//
// public static int getScreenWidthDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenWidthDp;
// }
//
// public static int getScreenHeightDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenHeightDp;
// }
//
// public static int getStatusBarHeightPx(Context context){
// return (int) dpToPx(context, STATUS_BAR_HEIGHT_DP);
// }
//
// public static int getAppBarHeightPx(Context context){
// return (int) dpToPx(context, APP_BAR_HEIGHT_DP);
// }
//
// /**
// * Get Navigation Bar (bottom) height in px
// */
// public static int getNavigationBarHeightPx(Context context){
// int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
// return (resourceId > 0) ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// public static float pxToDp(Context context, int px){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static float dpToPx(Context context, int dp){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
// }
| import android.support.design.widget.TabLayout;
import pt.passarola.R;
import pt.passarola.utils.AnimatorManager;
import pt.passarola.utils.ScreenInspector; |
TabLayout.Tab beersTab = tabLayout.newTab();
beersTab.setTag(TAB_BEERS);
beersTab.setIcon(R.drawable.ic_beers);
tabLayout.addTab(closestPlacesTab, TAB_CLOSEST_POSITION);
tabLayout.addTab(allPlacesTab, TAB_PLACES_POSITION);
tabLayout.addTab(beersTab, TAB_BEERS_POSITION);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(onTabSelectedListener != null){
onTabSelectedListener.onTabSelected(tab.getPosition());
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
onTabSelected(tab);
}
});
}
private void setupSize(){ | // Path: app/src/main/java/pt/passarola/utils/AnimatorManager.java
// public class AnimatorManager {
//
// private static final int SHORT_DURATION = 200; //ms
//
// public static void fadeInPartial(@NonNull final View view){
// view.setAlpha(0.5f);
// view.animate()
// .alpha(1)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeOutPartial(@NonNull final View view){
// view.animate()
// .alpha(0.5f)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeInView(@NonNull final View view){
// view.setAlpha(0f);
// view.setVisibility(View.VISIBLE);
// view.animate()
// .alpha(1)
// .setDuration(200)
// .setListener(null);
// }
//
// public static void fadeOutView(@NonNull final View view){
// view.animate()
// .alpha(0f)
// .setDuration(SHORT_DURATION)
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
//
// public static void slideInView(@NonNull final View view, int distance){
// view.setVisibility(View.VISIBLE);
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(null);
// }
//
// public static void slideOutView(@NonNull final View view, int distance){
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/ScreenInspector.java
// public class ScreenInspector {
//
// private static final int STATUS_BAR_HEIGHT_DP = 24;
// private static final int APP_BAR_HEIGHT_DP = 56;
//
// public static double getDensity(Context context){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return displayMetrics.density;
// }
//
// public static int getScreenWidthPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.x;
// }
//
// public static int getScreenHeightPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.y;
// }
//
// public static int getScreenWidthDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenWidthDp;
// }
//
// public static int getScreenHeightDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenHeightDp;
// }
//
// public static int getStatusBarHeightPx(Context context){
// return (int) dpToPx(context, STATUS_BAR_HEIGHT_DP);
// }
//
// public static int getAppBarHeightPx(Context context){
// return (int) dpToPx(context, APP_BAR_HEIGHT_DP);
// }
//
// /**
// * Get Navigation Bar (bottom) height in px
// */
// public static int getNavigationBarHeightPx(Context context){
// int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
// return (resourceId > 0) ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// public static float pxToDp(Context context, int px){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static float dpToPx(Context context, int dp){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
// }
// Path: app/src/main/java/pt/passarola/ui/components/PassarolaTabLayoutManager.java
import android.support.design.widget.TabLayout;
import pt.passarola.R;
import pt.passarola.utils.AnimatorManager;
import pt.passarola.utils.ScreenInspector;
TabLayout.Tab beersTab = tabLayout.newTab();
beersTab.setTag(TAB_BEERS);
beersTab.setIcon(R.drawable.ic_beers);
tabLayout.addTab(closestPlacesTab, TAB_CLOSEST_POSITION);
tabLayout.addTab(allPlacesTab, TAB_PLACES_POSITION);
tabLayout.addTab(beersTab, TAB_BEERS_POSITION);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(onTabSelectedListener != null){
onTabSelectedListener.onTabSelected(tab.getPosition());
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
onTabSelected(tab);
}
});
}
private void setupSize(){ | size = ScreenInspector.getAppBarHeightPx(tabLayout.getContext()); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/components/PassarolaTabLayoutManager.java | // Path: app/src/main/java/pt/passarola/utils/AnimatorManager.java
// public class AnimatorManager {
//
// private static final int SHORT_DURATION = 200; //ms
//
// public static void fadeInPartial(@NonNull final View view){
// view.setAlpha(0.5f);
// view.animate()
// .alpha(1)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeOutPartial(@NonNull final View view){
// view.animate()
// .alpha(0.5f)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeInView(@NonNull final View view){
// view.setAlpha(0f);
// view.setVisibility(View.VISIBLE);
// view.animate()
// .alpha(1)
// .setDuration(200)
// .setListener(null);
// }
//
// public static void fadeOutView(@NonNull final View view){
// view.animate()
// .alpha(0f)
// .setDuration(SHORT_DURATION)
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
//
// public static void slideInView(@NonNull final View view, int distance){
// view.setVisibility(View.VISIBLE);
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(null);
// }
//
// public static void slideOutView(@NonNull final View view, int distance){
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/ScreenInspector.java
// public class ScreenInspector {
//
// private static final int STATUS_BAR_HEIGHT_DP = 24;
// private static final int APP_BAR_HEIGHT_DP = 56;
//
// public static double getDensity(Context context){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return displayMetrics.density;
// }
//
// public static int getScreenWidthPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.x;
// }
//
// public static int getScreenHeightPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.y;
// }
//
// public static int getScreenWidthDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenWidthDp;
// }
//
// public static int getScreenHeightDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenHeightDp;
// }
//
// public static int getStatusBarHeightPx(Context context){
// return (int) dpToPx(context, STATUS_BAR_HEIGHT_DP);
// }
//
// public static int getAppBarHeightPx(Context context){
// return (int) dpToPx(context, APP_BAR_HEIGHT_DP);
// }
//
// /**
// * Get Navigation Bar (bottom) height in px
// */
// public static int getNavigationBarHeightPx(Context context){
// int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
// return (resourceId > 0) ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// public static float pxToDp(Context context, int px){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static float dpToPx(Context context, int dp){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
// }
| import android.support.design.widget.TabLayout;
import pt.passarola.R;
import pt.passarola.utils.AnimatorManager;
import pt.passarola.utils.ScreenInspector; | tabLayout.addTab(allPlacesTab, TAB_PLACES_POSITION);
tabLayout.addTab(beersTab, TAB_BEERS_POSITION);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(onTabSelectedListener != null){
onTabSelectedListener.onTabSelected(tab.getPosition());
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
onTabSelected(tab);
}
});
}
private void setupSize(){
size = ScreenInspector.getAppBarHeightPx(tabLayout.getContext());
}
public void show(boolean show) {
if (show) {
// sliding up | // Path: app/src/main/java/pt/passarola/utils/AnimatorManager.java
// public class AnimatorManager {
//
// private static final int SHORT_DURATION = 200; //ms
//
// public static void fadeInPartial(@NonNull final View view){
// view.setAlpha(0.5f);
// view.animate()
// .alpha(1)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeOutPartial(@NonNull final View view){
// view.animate()
// .alpha(0.5f)
// .setDuration(SHORT_DURATION);
// }
//
// public static void fadeInView(@NonNull final View view){
// view.setAlpha(0f);
// view.setVisibility(View.VISIBLE);
// view.animate()
// .alpha(1)
// .setDuration(200)
// .setListener(null);
// }
//
// public static void fadeOutView(@NonNull final View view){
// view.animate()
// .alpha(0f)
// .setDuration(SHORT_DURATION)
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
//
// public static void slideInView(@NonNull final View view, int distance){
// view.setVisibility(View.VISIBLE);
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(null);
// }
//
// public static void slideOutView(@NonNull final View view, int distance){
// view.animate()
// .translationY(distance)
// .setDuration(SHORT_DURATION)
// .setInterpolator(new AccelerateDecelerateInterpolator())
// .setListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// view.setVisibility(View.GONE);
// }
// });
// }
// }
//
// Path: app/src/main/java/pt/passarola/utils/ScreenInspector.java
// public class ScreenInspector {
//
// private static final int STATUS_BAR_HEIGHT_DP = 24;
// private static final int APP_BAR_HEIGHT_DP = 56;
//
// public static double getDensity(Context context){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return displayMetrics.density;
// }
//
// public static int getScreenWidthPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.x;
// }
//
// public static int getScreenHeightPx(Context context){
// WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display display = windowManager.getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size.y;
// }
//
// public static int getScreenWidthDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenWidthDp;
// }
//
// public static int getScreenHeightDp(Context context){
// Configuration configuration = context.getResources().getConfiguration();
// return configuration.screenHeightDp;
// }
//
// public static int getStatusBarHeightPx(Context context){
// return (int) dpToPx(context, STATUS_BAR_HEIGHT_DP);
// }
//
// public static int getAppBarHeightPx(Context context){
// return (int) dpToPx(context, APP_BAR_HEIGHT_DP);
// }
//
// /**
// * Get Navigation Bar (bottom) height in px
// */
// public static int getNavigationBarHeightPx(Context context){
// int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
// return (resourceId > 0) ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// public static float pxToDp(Context context, int px){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
//
// public static float dpToPx(Context context, int dp){
// DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
// return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
// }
// }
// Path: app/src/main/java/pt/passarola/ui/components/PassarolaTabLayoutManager.java
import android.support.design.widget.TabLayout;
import pt.passarola.R;
import pt.passarola.utils.AnimatorManager;
import pt.passarola.utils.ScreenInspector;
tabLayout.addTab(allPlacesTab, TAB_PLACES_POSITION);
tabLayout.addTab(beersTab, TAB_BEERS_POSITION);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(onTabSelectedListener != null){
onTabSelectedListener.onTabSelected(tab.getPosition());
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
onTabSelected(tab);
}
});
}
private void setupSize(){
size = ScreenInspector.getAppBarHeightPx(tabLayout.getContext());
}
public void show(boolean show) {
if (show) {
// sliding up | AnimatorManager.slideInView(tabLayout, 0); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/dagger/DaggerableFragment.java | // Path: app/src/main/java/pt/passarola/App.java
// public class App extends Application implements Daggerable {
//
// private ObjectGraph objectGraph;
//
//
// public static App obtain(Context context) {
// return (App) context.getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// Fabric.with(this, new Crashlytics());
// buildDebugOptions();
// buildObjectGraph();
// }
//
// @Override
// public void inject(Object object) {
// objectGraph.inject(object);
// }
//
// @Override
// public void inject(Object object, Object... modules) {
// objectGraph.plus(modules).inject(object);
// }
//
// private void buildObjectGraph() {
// objectGraph = ObjectGraph.create(getModules().toArray());
// objectGraph.inject(this);
// }
//
// private List<Object> getModules() {
// return Arrays.<Object>asList(new AppModule(this));
// }
//
// private void buildDebugOptions() {
// if (BuildConfig.DEBUG) {
// RestApi.DEBUG = true;
// Timber.plant(new Timber.DebugTree());
// }
// }
//
// }
| import pt.passarola.App;
import android.os.Bundle;
import android.support.v4.app.Fragment; | package pt.passarola.services.dagger;
/**
* Created by ruigoncalo on 31/10/15.
*/
public class DaggerableFragment extends Fragment implements Daggerable {
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
inject(this);
}
@Override
public void inject(Object object) { | // Path: app/src/main/java/pt/passarola/App.java
// public class App extends Application implements Daggerable {
//
// private ObjectGraph objectGraph;
//
//
// public static App obtain(Context context) {
// return (App) context.getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// Fabric.with(this, new Crashlytics());
// buildDebugOptions();
// buildObjectGraph();
// }
//
// @Override
// public void inject(Object object) {
// objectGraph.inject(object);
// }
//
// @Override
// public void inject(Object object, Object... modules) {
// objectGraph.plus(modules).inject(object);
// }
//
// private void buildObjectGraph() {
// objectGraph = ObjectGraph.create(getModules().toArray());
// objectGraph.inject(this);
// }
//
// private List<Object> getModules() {
// return Arrays.<Object>asList(new AppModule(this));
// }
//
// private void buildDebugOptions() {
// if (BuildConfig.DEBUG) {
// RestApi.DEBUG = true;
// Timber.plant(new Timber.DebugTree());
// }
// }
//
// }
// Path: app/src/main/java/pt/passarola/services/dagger/DaggerableFragment.java
import pt.passarola.App;
import android.os.Bundle;
import android.support.v4.app.Fragment;
package pt.passarola.services.dagger;
/**
* Created by ruigoncalo on 31/10/15.
*/
public class DaggerableFragment extends Fragment implements Daggerable {
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
inject(this);
}
@Override
public void inject(Object object) { | App.obtain(getActivity()).inject(object); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/recyclerview/PlacesMixedAdapter.java | // Path: app/src/main/java/pt/passarola/model/viewmodel/MixedPlaceViewModel.java
// public class MixedPlaceViewModel implements MixedViewModel {
//
// private final PlaceViewModel placeViewModel;
// private final int type;
//
// public MixedPlaceViewModel(PlaceViewModel placeViewModel, int type) {
// this.placeViewModel = placeViewModel;
// this.type = type;
// }
//
// public PlaceViewModel getPlaceViewModel() {
// return placeViewModel;
// }
//
// @Override
// public int getType() {
// return type;
// }
// }
| import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import pt.passarola.R;
import pt.passarola.model.viewmodel.MixedPlaceViewModel; | package pt.passarola.ui.recyclerview;
/**
* Created by ruigoncalo on 20/12/15.
*/
public class PlacesMixedAdapter extends MixedBaseAdapter<ClosestPlacesViewHolder, TransparentViewHolder> {
@Override
public ClosestPlacesViewHolder onCreateViewHolderA(
ViewGroup viewGroup, int viewType, OnBaseItemClickListener onBaseItemClickListener) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_item_closest_place, viewGroup, false);
return new ClosestPlacesViewHolder(view, onBaseItemClickListener);
}
@Override
public TransparentViewHolder onCreateViewHolderB(
ViewGroup viewGroup, int viewType, OnBaseItemClickListener onBaseItemClickListener) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_item_transparent, viewGroup, false);
return new TransparentViewHolder(view, onBaseItemClickListener);
}
@Override
public void onBindViewHolderA(RecyclerView.ViewHolder holder, int position) { | // Path: app/src/main/java/pt/passarola/model/viewmodel/MixedPlaceViewModel.java
// public class MixedPlaceViewModel implements MixedViewModel {
//
// private final PlaceViewModel placeViewModel;
// private final int type;
//
// public MixedPlaceViewModel(PlaceViewModel placeViewModel, int type) {
// this.placeViewModel = placeViewModel;
// this.type = type;
// }
//
// public PlaceViewModel getPlaceViewModel() {
// return placeViewModel;
// }
//
// @Override
// public int getType() {
// return type;
// }
// }
// Path: app/src/main/java/pt/passarola/ui/recyclerview/PlacesMixedAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import pt.passarola.R;
import pt.passarola.model.viewmodel.MixedPlaceViewModel;
package pt.passarola.ui.recyclerview;
/**
* Created by ruigoncalo on 20/12/15.
*/
public class PlacesMixedAdapter extends MixedBaseAdapter<ClosestPlacesViewHolder, TransparentViewHolder> {
@Override
public ClosestPlacesViewHolder onCreateViewHolderA(
ViewGroup viewGroup, int viewType, OnBaseItemClickListener onBaseItemClickListener) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_item_closest_place, viewGroup, false);
return new ClosestPlacesViewHolder(view, onBaseItemClickListener);
}
@Override
public TransparentViewHolder onCreateViewHolderB(
ViewGroup viewGroup, int viewType, OnBaseItemClickListener onBaseItemClickListener) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_item_transparent, viewGroup, false);
return new TransparentViewHolder(view, onBaseItemClickListener);
}
@Override
public void onBindViewHolderA(RecyclerView.ViewHolder holder, int position) { | MixedPlaceViewModel mixedPlaceViewModel = (MixedPlaceViewModel) getItem(position); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/PlaceProvider.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
| import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
| // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
// Path: app/src/main/java/pt/passarola/services/PlaceProvider.java
import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
| private List<Place> places; |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/PlaceProvider.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
| import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
private List<Place> places;
private WebApiService webApiService;
private BusProvider busProvider;
private AtomicInteger requestsCounter;
public PlaceProvider(BusProvider busProvider, WebApiService webApiService) {
this.busProvider = busProvider;
this.webApiService = webApiService;
places = new ArrayList<>();
requestsCounter = new AtomicInteger();
}
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) { | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
// Path: app/src/main/java/pt/passarola/services/PlaceProvider.java
import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
private List<Place> places;
private WebApiService webApiService;
private BusProvider busProvider;
private AtomicInteger requestsCounter;
public PlaceProvider(BusProvider busProvider, WebApiService webApiService) {
this.busProvider = busProvider;
this.webApiService = webApiService;
places = new ArrayList<>();
requestsCounter = new AtomicInteger();
}
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) { | busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed"))); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/PlaceProvider.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
| import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
private List<Place> places;
private WebApiService webApiService;
private BusProvider busProvider;
private AtomicInteger requestsCounter;
public PlaceProvider(BusProvider busProvider, WebApiService webApiService) {
this.busProvider = busProvider;
this.webApiService = webApiService;
places = new ArrayList<>();
requestsCounter = new AtomicInteger();
}
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) {
busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else { | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
// Path: app/src/main/java/pt/passarola/services/PlaceProvider.java
import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
private List<Place> places;
private WebApiService webApiService;
private BusProvider busProvider;
private AtomicInteger requestsCounter;
public PlaceProvider(BusProvider busProvider, WebApiService webApiService) {
this.busProvider = busProvider;
this.webApiService = webApiService;
places = new ArrayList<>();
requestsCounter = new AtomicInteger();
}
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) {
busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else { | busProvider.post(new PlacesSuccessEvent(places)); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/PlaceProvider.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
| import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
private List<Place> places;
private WebApiService webApiService;
private BusProvider busProvider;
private AtomicInteger requestsCounter;
public PlaceProvider(BusProvider busProvider, WebApiService webApiService) {
this.busProvider = busProvider;
this.webApiService = webApiService;
places = new ArrayList<>();
requestsCounter = new AtomicInteger();
}
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) {
busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else {
busProvider.post(new PlacesSuccessEvent(places));
}
}
public void getClosestPlaces(Location location){ | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
// Path: app/src/main/java/pt/passarola/services/PlaceProvider.java
import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
package pt.passarola.services;
/**
* Created by ruigoncalo on 18/12/15.
*/
public class PlaceProvider {
private final static String LOCATION_PROVIDER = "";
private List<Place> places;
private WebApiService webApiService;
private BusProvider busProvider;
private AtomicInteger requestsCounter;
public PlaceProvider(BusProvider busProvider, WebApiService webApiService) {
this.busProvider = busProvider;
this.webApiService = webApiService;
places = new ArrayList<>();
requestsCounter = new AtomicInteger();
}
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) {
busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else {
busProvider.post(new PlacesSuccessEvent(places));
}
}
public void getClosestPlaces(Location location){ | List<ClosestPlace> closestPlaces = new ArrayList<>(); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/PlaceProvider.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
| import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | }
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) {
busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else {
busProvider.post(new PlacesSuccessEvent(places));
}
}
public void getClosestPlaces(Location location){
List<ClosestPlace> closestPlaces = new ArrayList<>();
Map<Place, Integer> placesOrderedByLocation =
getLocationMapOrderedByDistance(location, places);
int count = 0, max = 20;
for(Map.Entry<Place, Integer> entry : placesOrderedByLocation.entrySet()){
if(count >= max){
break;
}
count++;
closestPlaces.add(new ClosestPlace(entry.getKey(), entry.getValue()));
}
| // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
// Path: app/src/main/java/pt/passarola/services/PlaceProvider.java
import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
}
public void getPlaces(){
if(places.isEmpty()){
if(isLoading()) {
busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else {
busProvider.post(new PlacesSuccessEvent(places));
}
}
public void getClosestPlaces(Location location){
List<ClosestPlace> closestPlaces = new ArrayList<>();
Map<Place, Integer> placesOrderedByLocation =
getLocationMapOrderedByDistance(location, places);
int count = 0, max = 20;
for(Map.Entry<Place, Integer> entry : placesOrderedByLocation.entrySet()){
if(count >= max){
break;
}
count++;
closestPlaces.add(new ClosestPlace(entry.getKey(), entry.getValue()));
}
| busProvider.post(new ClosestPlacesSuccessEvent(closestPlaces)); |
ruigoncalo/passarola | app/src/main/java/pt/passarola/services/PlaceProvider.java | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
| import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response; | busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else {
busProvider.post(new PlacesSuccessEvent(places));
}
}
public void getClosestPlaces(Location location){
List<ClosestPlace> closestPlaces = new ArrayList<>();
Map<Place, Integer> placesOrderedByLocation =
getLocationMapOrderedByDistance(location, places);
int count = 0, max = 20;
for(Map.Entry<Place, Integer> entry : placesOrderedByLocation.entrySet()){
if(count >= max){
break;
}
count++;
closestPlaces.add(new ClosestPlace(entry.getKey(), entry.getValue()));
}
busProvider.post(new ClosestPlacesSuccessEvent(closestPlaces));
}
private void fetchPlaces() {
requestsCounter.incrementAndGet(); | // Path: app/src/main/java/pt/passarola/model/ClosestPlace.java
// public class ClosestPlace {
//
// private final Place place;
// private final int distance;
//
// public ClosestPlace(Place place, int distance) {
// this.place = place;
// this.distance = distance;
// }
//
// public Place getPlace() {
// return place;
// }
//
// public int getDistance() {
// return distance;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/MetaPlaces.java
// public class MetaPlaces {
//
// private String message;
// private int results;
// private List<Place> data;
//
// public String getMessage() {
// return message;
// }
//
// public int getResults() {
// return results;
// }
//
// public List<Place> getData() {
// return data;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/Place.java
// public class Place {
//
// private String id;
// private String name;
// @SerializedName("full_address")
// private String fullAddress;
// private String location;
// private String council;
// private String country;
// private String lat;
// private String lng;
// private String type;
// private String facebook;
// private String zomato;
// private String gmaps;
// private String tripadvisor;
// private String website;
// private String email;
// private String telephone;
// private String active;
// private String updated;
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFullAddress() {
// return fullAddress;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCouncil() {
// return council;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getLat() {
// return lat;
// }
//
// public String getLng() {
// return lng;
// }
//
// public String getType() {
// return type;
// }
//
// public String getFacebook() {
// return facebook;
// }
//
// public String getGmaps() {
// return gmaps;
// }
//
// public String getTripadvisor() {
// return tripadvisor;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getTelephone() {
// return telephone;
// }
//
// public String getActive() {
// return active;
// }
//
// public String getUpdated() {
// return updated;
// }
//
// public String getZomato() {
// return zomato;
// }
//
// public LatLng getLatLng(){
// Double dLat = Double.valueOf(lat);
// Double dLng = Double.valueOf(lng);
// return new LatLng(dLat, dLng);
// }
//
// public boolean isValid(){
// return name != null && !name.isEmpty() &&
// lat != null && !lat.isEmpty() &&
// lng != null && !lng.isEmpty();
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/ClosestPlacesSuccessEvent.java
// public class ClosestPlacesSuccessEvent {
//
// private List<ClosestPlace> closestPlaces;
//
// public ClosestPlacesSuccessEvent(List<ClosestPlace> closestPlaces){
// this.closestPlaces = closestPlaces;
// }
//
// public List<ClosestPlace> getClosestPlaces() {
// return closestPlaces;
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesErrorEvent.java
// public class PlacesErrorEvent extends ErrorEvent {
//
// public PlacesErrorEvent(Exception e){
// super(e);
// }
// }
//
// Path: app/src/main/java/pt/passarola/model/events/PlacesSuccessEvent.java
// public class PlacesSuccessEvent {
//
// private final List<Place> placeList;
//
// public PlacesSuccessEvent(List<Place> placeList) {
// this.placeList = placeList;
// }
//
// public List<Place> getPlaceList() {
// return placeList;
// }
// }
// Path: app/src/main/java/pt/passarola/services/PlaceProvider.java
import android.location.Location;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import pt.passarola.model.ClosestPlace;
import pt.passarola.model.MetaPlaces;
import pt.passarola.model.Place;
import pt.passarola.model.events.ClosestPlacesSuccessEvent;
import pt.passarola.model.events.PlacesErrorEvent;
import pt.passarola.model.events.PlacesSuccessEvent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
busProvider.post(new PlacesErrorEvent(new Exception("Request is not completed")));
} else {
fetchPlaces();
}
} else {
busProvider.post(new PlacesSuccessEvent(places));
}
}
public void getClosestPlaces(Location location){
List<ClosestPlace> closestPlaces = new ArrayList<>();
Map<Place, Integer> placesOrderedByLocation =
getLocationMapOrderedByDistance(location, places);
int count = 0, max = 20;
for(Map.Entry<Place, Integer> entry : placesOrderedByLocation.entrySet()){
if(count >= max){
break;
}
count++;
closestPlaces.add(new ClosestPlace(entry.getKey(), entry.getValue()));
}
busProvider.post(new ClosestPlacesSuccessEvent(closestPlaces));
}
private void fetchPlaces() {
requestsCounter.incrementAndGet(); | webApiService.getPlaces(new Callback<MetaPlaces>() { |
ruigoncalo/passarola | app/src/main/java/pt/passarola/ui/AboutActivity.java | // Path: app/src/main/java/pt/passarola/services/dagger/DaggerableAppCompatActivity.java
// public abstract class DaggerableAppCompatActivity extends AppCompatActivity implements Daggerable {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// inject(this);
// }
//
// @Override
// public void inject(Object object) {
// App.obtain(this).inject(object);
// }
//
// @Override
// public void inject(Object object, Object... modules) {
// App.obtain(this).inject(object, modules);
// }
//
// }
//
// Path: app/src/main/java/pt/passarola/services/tracker/TrackerManager.java
// public class TrackerManager {
//
// public static final String EVENT_CLICK_TAB_BEERS = "event-click-tab-beers";
// public static final String EVENT_CLICK_TAB_PLACES = "event-click-tab-places";
// public static final String EVENT_CLICK_TAB_CLOSEST = "event-click-tab-closest";
// public static final String EVENT_CLICK_PLACE_CLOSEST = "event-click-place-close";
// public static final String EVENT_CLICK_MARKER = "event-click-marker";
// public static final String EVENT_CLICK_INFO_WINDOW = "event-click-info-window";
// public static final String EVENT_CLICK_PLACE_PHONE = "event-click-place-phone";
// public static final String EVENT_CLICK_PLACE_FACEBOOK = "event-click-place-facebook";
// public static final String EVENT_CLICK_PLACE_ZOMATO = "event-click-place-zomato";
// public static final String EVENT_CLICK_PLACE_TRIPADVISOR = "event-click-tripadvisor";
// public static final String EVENT_CLICK_ALL_PLACES_FACEBOOK = "event-click-all-places-facebook";
// public static final String EVENT_CLICK_ALL_PLACES_ZOMATO = "event-click-all-places-zomato";
// public static final String EVENT_CLICK_ALL_PLACES_TRIPADVISOR = "event-click-all-places-tripadvisor";
// public static final String EVENT_CLICK_BEER_RATEBEER = "event-click-beer-ratebeer";
// public static final String EVENT_CLICK_BEER_UNTAPPD = "event-click-beer-untappd";
// public static final String EVENT_CLICK_ABOUT_EMAIL = "event-click-about-email";
// public static final String EVENT_CLICK_ABOUT_FACEBOOK = "event-click-about-facebook";
//
// public void trackEvent(String eventName){
// Answers.getInstance().logCustom(new CustomEvent(eventName));
// }
//
// public void trackEvent(String eventName, String key, String value){
//
// //truncate value to 100 chars
// if(value.length() > 100) {
// value = value.substring(0, 99);
// }
//
// CustomEvent customEvent = new CustomEvent(eventName);
// customEvent.putCustomAttribute(key, value);
//
// Answers.getInstance().logCustom(customEvent);
// }
//
// public void trackEvent(String eventName, HashMap<String, String> attributes){
// CustomEvent customEvent = new CustomEvent(eventName);
// for(Map.Entry<String, String> entry : attributes.entrySet()){
// customEvent.putCustomAttribute(entry.getKey(), entry.getValue());
// }
//
// Answers.getInstance().logCustom(customEvent);
// }
// }
| import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pt.passarola.R;
import pt.passarola.services.dagger.DaggerableAppCompatActivity;
import pt.passarola.services.tracker.TrackerManager; | package pt.passarola.ui;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class AboutActivity extends DaggerableAppCompatActivity {
private static final String FB_PASSAROLA_ID = "713214482083435";
| // Path: app/src/main/java/pt/passarola/services/dagger/DaggerableAppCompatActivity.java
// public abstract class DaggerableAppCompatActivity extends AppCompatActivity implements Daggerable {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// inject(this);
// }
//
// @Override
// public void inject(Object object) {
// App.obtain(this).inject(object);
// }
//
// @Override
// public void inject(Object object, Object... modules) {
// App.obtain(this).inject(object, modules);
// }
//
// }
//
// Path: app/src/main/java/pt/passarola/services/tracker/TrackerManager.java
// public class TrackerManager {
//
// public static final String EVENT_CLICK_TAB_BEERS = "event-click-tab-beers";
// public static final String EVENT_CLICK_TAB_PLACES = "event-click-tab-places";
// public static final String EVENT_CLICK_TAB_CLOSEST = "event-click-tab-closest";
// public static final String EVENT_CLICK_PLACE_CLOSEST = "event-click-place-close";
// public static final String EVENT_CLICK_MARKER = "event-click-marker";
// public static final String EVENT_CLICK_INFO_WINDOW = "event-click-info-window";
// public static final String EVENT_CLICK_PLACE_PHONE = "event-click-place-phone";
// public static final String EVENT_CLICK_PLACE_FACEBOOK = "event-click-place-facebook";
// public static final String EVENT_CLICK_PLACE_ZOMATO = "event-click-place-zomato";
// public static final String EVENT_CLICK_PLACE_TRIPADVISOR = "event-click-tripadvisor";
// public static final String EVENT_CLICK_ALL_PLACES_FACEBOOK = "event-click-all-places-facebook";
// public static final String EVENT_CLICK_ALL_PLACES_ZOMATO = "event-click-all-places-zomato";
// public static final String EVENT_CLICK_ALL_PLACES_TRIPADVISOR = "event-click-all-places-tripadvisor";
// public static final String EVENT_CLICK_BEER_RATEBEER = "event-click-beer-ratebeer";
// public static final String EVENT_CLICK_BEER_UNTAPPD = "event-click-beer-untappd";
// public static final String EVENT_CLICK_ABOUT_EMAIL = "event-click-about-email";
// public static final String EVENT_CLICK_ABOUT_FACEBOOK = "event-click-about-facebook";
//
// public void trackEvent(String eventName){
// Answers.getInstance().logCustom(new CustomEvent(eventName));
// }
//
// public void trackEvent(String eventName, String key, String value){
//
// //truncate value to 100 chars
// if(value.length() > 100) {
// value = value.substring(0, 99);
// }
//
// CustomEvent customEvent = new CustomEvent(eventName);
// customEvent.putCustomAttribute(key, value);
//
// Answers.getInstance().logCustom(customEvent);
// }
//
// public void trackEvent(String eventName, HashMap<String, String> attributes){
// CustomEvent customEvent = new CustomEvent(eventName);
// for(Map.Entry<String, String> entry : attributes.entrySet()){
// customEvent.putCustomAttribute(entry.getKey(), entry.getValue());
// }
//
// Answers.getInstance().logCustom(customEvent);
// }
// }
// Path: app/src/main/java/pt/passarola/ui/AboutActivity.java
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pt.passarola.R;
import pt.passarola.services.dagger.DaggerableAppCompatActivity;
import pt.passarola.services.tracker.TrackerManager;
package pt.passarola.ui;
/**
* Created by ruigoncalo on 22/10/15.
*/
public class AboutActivity extends DaggerableAppCompatActivity {
private static final String FB_PASSAROLA_ID = "713214482083435";
| @Inject TrackerManager trackerManager; |
imagej/imagej-server | src/main/java/net/imagej/server/services/DefaultObjectInfo.java | // Path: src/main/java/net/imagej/server/Utils.java
// public class Utils {
//
// private Utils() {
// // NB: prevent instantiation of utility class.
// }
//
// public static final String alphanumeric_lower =
// "0123456789abcdefghijklmnopqrstuvwxyz";
//
// public static final String alphanumeric_both =
// "01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
//
// private static final MimetypesFileTypeMap mftm = new MimetypesFileTypeMap();
//
// /**
// * Generates a lowercase alphanumeric random String.
// *
// * @param len length of String to be generated
// * @return random generated String
// */
// public static String randomString(final int len) {
// return randomString(len, alphanumeric_lower);
// }
//
// /**
// * Generate a random string of length {@code len} from the given
// * {@code alphabet}.
// */
// public static String randomString(final int len, final String alphabet) {
// final StringBuilder sb = new StringBuilder(len);
// final Random random = ThreadLocalRandom.current();
// for (int i = 0; i < len; i++)
// sb.append(alphabet.charAt(random.nextInt(alphabet.length())));
// return sb.toString();
// }
//
// /**
// * Converts the current time in milliseconds to an 8-digit lowercase
// * alphanumeric String.
// *
// * @return 8-digit String encoding the current timestamp
// */
// public static String timestampString() {
// return Long.toUnsignedString(System.currentTimeMillis(), 36);
// }
//
// /**
// * Generates a (8+n) bit alphanumeric lowercase random ID. The first eight
// * digits encode the timestamp.
// *
// * @return a timestamped random ID
// */
// public static String timestampedId(final int n) {
// return timestampString() + randomString(n);
// }
//
// public static String getMimetype(final String filename) {
// return mftm.getContentType(filename.toLowerCase());
// }
//
// }
| import net.imagej.server.Utils;
import java.util.Date; | /*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.services;
/**
* Default implementation of {@link ObjectInfo}.
*
* @author Leon Yang
*/
public class DefaultObjectInfo implements ObjectInfo {
private final String id;
private final Object object;
private final String createdAt;
private final String createdBy;
private String lastUsed;
public DefaultObjectInfo(final Object object, final String createdBy) {
final Date now = new Date();
createdAt = now.toString(); | // Path: src/main/java/net/imagej/server/Utils.java
// public class Utils {
//
// private Utils() {
// // NB: prevent instantiation of utility class.
// }
//
// public static final String alphanumeric_lower =
// "0123456789abcdefghijklmnopqrstuvwxyz";
//
// public static final String alphanumeric_both =
// "01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
//
// private static final MimetypesFileTypeMap mftm = new MimetypesFileTypeMap();
//
// /**
// * Generates a lowercase alphanumeric random String.
// *
// * @param len length of String to be generated
// * @return random generated String
// */
// public static String randomString(final int len) {
// return randomString(len, alphanumeric_lower);
// }
//
// /**
// * Generate a random string of length {@code len} from the given
// * {@code alphabet}.
// */
// public static String randomString(final int len, final String alphabet) {
// final StringBuilder sb = new StringBuilder(len);
// final Random random = ThreadLocalRandom.current();
// for (int i = 0; i < len; i++)
// sb.append(alphabet.charAt(random.nextInt(alphabet.length())));
// return sb.toString();
// }
//
// /**
// * Converts the current time in milliseconds to an 8-digit lowercase
// * alphanumeric String.
// *
// * @return 8-digit String encoding the current timestamp
// */
// public static String timestampString() {
// return Long.toUnsignedString(System.currentTimeMillis(), 36);
// }
//
// /**
// * Generates a (8+n) bit alphanumeric lowercase random ID. The first eight
// * digits encode the timestamp.
// *
// * @return a timestamped random ID
// */
// public static String timestampedId(final int n) {
// return timestampString() + randomString(n);
// }
//
// public static String getMimetype(final String filename) {
// return mftm.getContentType(filename.toLowerCase());
// }
//
// }
// Path: src/main/java/net/imagej/server/services/DefaultObjectInfo.java
import net.imagej.server.Utils;
import java.util.Date;
/*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.services;
/**
* Default implementation of {@link ObjectInfo}.
*
* @author Leon Yang
*/
public class DefaultObjectInfo implements ObjectInfo {
private final String id;
private final Object object;
private final String createdAt;
private final String createdBy;
private String lastUsed;
public DefaultObjectInfo(final Object object, final String createdBy) {
final Date now = new Date();
createdAt = now.toString(); | this.id = "object:" + Long.toUnsignedString(now.getTime(), 36) + Utils |
imagej/imagej-server | src/main/java/net/imagej/server/commands/StartServer.java | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
| import org.scijava.ui.UIService;
import java.util.List;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.command.Command;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin; | /*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.commands;
/**
* Starts the ImageJ Server, if one is not already running.
*
* @author Curtis Rueden
*/
@Plugin(type = Command.class, menuPath = "Plugins > Utilities > Start Server")
public class StartServer implements Command {
@Parameter
private ObjectService objectService;
@Parameter | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
// Path: src/main/java/net/imagej/server/commands/StartServer.java
import org.scijava.ui.UIService;
import java.util.List;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.command.Command;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.commands;
/**
* Starts the ImageJ Server, if one is not already running.
*
* @author Curtis Rueden
*/
@Plugin(type = Command.class, menuPath = "Plugins > Utilities > Start Server")
public class StartServer implements Command {
@Parameter
private ObjectService objectService;
@Parameter | private ImageJServerService imagejServerService; |
imagej/imagej-server | src/main/java/net/imagej/server/commands/StartServer.java | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
| import org.scijava.ui.UIService;
import java.util.List;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.command.Command;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin; | /*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.commands;
/**
* Starts the ImageJ Server, if one is not already running.
*
* @author Curtis Rueden
*/
@Plugin(type = Command.class, menuPath = "Plugins > Utilities > Start Server")
public class StartServer implements Command {
@Parameter
private ObjectService objectService;
@Parameter
private ImageJServerService imagejServerService;
@Parameter(required = false)
private UIService ui;
@Override
public void run() { | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
// Path: src/main/java/net/imagej/server/commands/StartServer.java
import org.scijava.ui.UIService;
import java.util.List;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.command.Command;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.commands;
/**
* Starts the ImageJ Server, if one is not already running.
*
* @author Curtis Rueden
*/
@Plugin(type = Command.class, menuPath = "Plugins > Utilities > Start Server")
public class StartServer implements Command {
@Parameter
private ObjectService objectService;
@Parameter
private ImageJServerService imagejServerService;
@Parameter(required = false)
private UIService ui;
@Override
public void run() { | final List<ImageJServer> servers = // |
imagej/imagej-server | src/main/java/net/imagej/server/console/ServerArgument.java | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
| import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.startup.StartupService;
import org.scijava.ui.UIService;
import java.util.LinkedList;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.console.AbstractConsoleArgument;
import org.scijava.console.ConsoleArgument;
import org.scijava.log.LogService;
import org.scijava.object.ObjectService; | /*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.console;
/**
* Handles the {@code --server} argument to signal that an ImageJ Server
* should be started immediately when ImageJ launches.
*
* @author Curtis Rueden
*/
@Plugin(type = ConsoleArgument.class)
public class ServerArgument extends AbstractConsoleArgument {
@Parameter(required = false) | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
// Path: src/main/java/net/imagej/server/console/ServerArgument.java
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.startup.StartupService;
import org.scijava.ui.UIService;
import java.util.LinkedList;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.console.AbstractConsoleArgument;
import org.scijava.console.ConsoleArgument;
import org.scijava.log.LogService;
import org.scijava.object.ObjectService;
/*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.console;
/**
* Handles the {@code --server} argument to signal that an ImageJ Server
* should be started immediately when ImageJ launches.
*
* @author Curtis Rueden
*/
@Plugin(type = ConsoleArgument.class)
public class ServerArgument extends AbstractConsoleArgument {
@Parameter(required = false) | private ImageJServerService imagejServerService; |
imagej/imagej-server | src/main/java/net/imagej/server/console/ServerArgument.java | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
| import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.startup.StartupService;
import org.scijava.ui.UIService;
import java.util.LinkedList;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.console.AbstractConsoleArgument;
import org.scijava.console.ConsoleArgument;
import org.scijava.log.LogService;
import org.scijava.object.ObjectService; | /*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.console;
/**
* Handles the {@code --server} argument to signal that an ImageJ Server
* should be started immediately when ImageJ launches.
*
* @author Curtis Rueden
*/
@Plugin(type = ConsoleArgument.class)
public class ServerArgument extends AbstractConsoleArgument {
@Parameter(required = false)
private ImageJServerService imagejServerService;
@Parameter(required = false)
private ObjectService objectService;
@Parameter(required = false)
private UIService uiService;
@Parameter(required = false)
private StartupService startupService;
@Parameter(required = false)
private LogService log;
// -- Constructor --
public ServerArgument() {
super(1, "--server");
}
// -- ConsoleArgument methods --
@Override
public void handle(final LinkedList<String> args) {
if (!supports(args)) return;
args.removeFirst(); // --server
| // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
//
// Path: src/main/java/net/imagej/server/ImageJServerService.java
// public interface ImageJServerService extends ImageJService {
//
// /**
// * Launches an instance of the ImageJ Server.
// *
// * @param args Arguments to pass to the server.
// * @throws RuntimeException if something goes wrong launching the server.
// */
// ImageJServer start(String... args);
// }
// Path: src/main/java/net/imagej/server/console/ServerArgument.java
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.startup.StartupService;
import org.scijava.ui.UIService;
import java.util.LinkedList;
import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;
import org.scijava.console.AbstractConsoleArgument;
import org.scijava.console.ConsoleArgument;
import org.scijava.log.LogService;
import org.scijava.object.ObjectService;
/*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.console;
/**
* Handles the {@code --server} argument to signal that an ImageJ Server
* should be started immediately when ImageJ launches.
*
* @author Curtis Rueden
*/
@Plugin(type = ConsoleArgument.class)
public class ServerArgument extends AbstractConsoleArgument {
@Parameter(required = false)
private ImageJServerService imagejServerService;
@Parameter(required = false)
private ObjectService objectService;
@Parameter(required = false)
private UIService uiService;
@Parameter(required = false)
private StartupService startupService;
@Parameter(required = false)
private LogService log;
// -- Constructor --
public ServerArgument() {
super(1, "--server");
}
// -- ConsoleArgument methods --
@Override
public void handle(final LinkedList<String> args) {
if (!supports(args)) return;
args.removeFirst(); // --server
| final ImageJServer server = imagejServerService.start(); |
imagej/imagej-server | src/main/java/net/imagej/server/resources/ModulesResource.java | // Path: src/main/java/net/imagej/server/WebCommandInfo.java
// public class WebCommandInfo extends CommandInfo {
//
// private final Module relatedModule;
//
// public WebCommandInfo(CommandInfo commandInfo, Module module) {
// super(commandInfo);
// relatedModule = module;
// }
//
// @Override
// public Iterable<ModuleItem<?>> inputs() {
//
// final List<WebCommandModuleItem<?>> checkedInputs = new ArrayList<>();
// for (final ModuleItem<?> input : super.inputs()) {
// if (input instanceof CommandModuleItem) {
// final WebCommandModuleItem<Object> webCommandModuleItem =
// new WebCommandModuleItem<>(this, ((CommandModuleItem<?>) input)
// .getField());
// final String name = input.getName();
//
// final boolean isResolved = relatedModule.isInputResolved(name);
//
// // Include resolved status in the JSON feed.
// // This is handy for judiciously overwriting already-resolved inputs,
// // particularly the "active image" inputs, which will be reported as
// // resolved, but not necessarily match what's selected on the client
// // side.
// webCommandModuleItem.isResolved = isResolved;
//
// // If the input is not resolved, include startingValue in the JSON feed.
// // This is useful for populating the dialog.
// webCommandModuleItem.startingValue = (!isResolved) ? relatedModule
// .getInput(name) : null;
//
// checkedInputs.add(webCommandModuleItem);
// }
// }
//
// return Collections.unmodifiableList(checkedInputs);
// }
// }
//
// Path: src/main/java/net/imagej/server/services/JsonService.java
// public interface JsonService {
//
// /**
// * Adds a deserializer to a given {@link ObjectMapper} to modify the default
// * behavior.
// *
// * @param objectMapper
// */
// void addDeserializerTo(final ObjectMapper objectMapper);
//
// /**
// * Parses the given Object.
// *
// * @param obj Object to be parsed.
// * @return a JSON format String of the parsed Object
// * @throws JsonProcessingException
// */
// String parseObject(final Object obj) throws JsonProcessingException;
// }
| import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import net.imagej.ops.Initializable;
import net.imagej.server.WebCommandInfo;
import net.imagej.server.services.JsonService;
import org.scijava.Context;
import org.scijava.Identifiable;
import org.scijava.Priority;
import org.scijava.command.CommandInfo;
import org.scijava.module.Module;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleService;
import org.scijava.module.process.AbstractPreprocessorPlugin;
import org.scijava.module.process.ModulePreprocessor;
import org.scijava.module.process.PreprocessorPlugin;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginInfo;
import org.scijava.plugin.PluginService;
import org.scijava.widget.InputHarvester; | /*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.resources;
/**
* Server resource that manages module operations.
*
* @author Leon Yang
*/
@Path("/modules")
@Singleton
@Produces(MediaType.APPLICATION_JSON)
public class ModulesResource {
@Parameter
private ModuleService moduleService;
@Parameter
private PluginService pluginService;
@Inject | // Path: src/main/java/net/imagej/server/WebCommandInfo.java
// public class WebCommandInfo extends CommandInfo {
//
// private final Module relatedModule;
//
// public WebCommandInfo(CommandInfo commandInfo, Module module) {
// super(commandInfo);
// relatedModule = module;
// }
//
// @Override
// public Iterable<ModuleItem<?>> inputs() {
//
// final List<WebCommandModuleItem<?>> checkedInputs = new ArrayList<>();
// for (final ModuleItem<?> input : super.inputs()) {
// if (input instanceof CommandModuleItem) {
// final WebCommandModuleItem<Object> webCommandModuleItem =
// new WebCommandModuleItem<>(this, ((CommandModuleItem<?>) input)
// .getField());
// final String name = input.getName();
//
// final boolean isResolved = relatedModule.isInputResolved(name);
//
// // Include resolved status in the JSON feed.
// // This is handy for judiciously overwriting already-resolved inputs,
// // particularly the "active image" inputs, which will be reported as
// // resolved, but not necessarily match what's selected on the client
// // side.
// webCommandModuleItem.isResolved = isResolved;
//
// // If the input is not resolved, include startingValue in the JSON feed.
// // This is useful for populating the dialog.
// webCommandModuleItem.startingValue = (!isResolved) ? relatedModule
// .getInput(name) : null;
//
// checkedInputs.add(webCommandModuleItem);
// }
// }
//
// return Collections.unmodifiableList(checkedInputs);
// }
// }
//
// Path: src/main/java/net/imagej/server/services/JsonService.java
// public interface JsonService {
//
// /**
// * Adds a deserializer to a given {@link ObjectMapper} to modify the default
// * behavior.
// *
// * @param objectMapper
// */
// void addDeserializerTo(final ObjectMapper objectMapper);
//
// /**
// * Parses the given Object.
// *
// * @param obj Object to be parsed.
// * @return a JSON format String of the parsed Object
// * @throws JsonProcessingException
// */
// String parseObject(final Object obj) throws JsonProcessingException;
// }
// Path: src/main/java/net/imagej/server/resources/ModulesResource.java
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import net.imagej.ops.Initializable;
import net.imagej.server.WebCommandInfo;
import net.imagej.server.services.JsonService;
import org.scijava.Context;
import org.scijava.Identifiable;
import org.scijava.Priority;
import org.scijava.command.CommandInfo;
import org.scijava.module.Module;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleService;
import org.scijava.module.process.AbstractPreprocessorPlugin;
import org.scijava.module.process.ModulePreprocessor;
import org.scijava.module.process.PreprocessorPlugin;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginInfo;
import org.scijava.plugin.PluginService;
import org.scijava.widget.InputHarvester;
/*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.resources;
/**
* Server resource that manages module operations.
*
* @author Leon Yang
*/
@Path("/modules")
@Singleton
@Produces(MediaType.APPLICATION_JSON)
public class ModulesResource {
@Parameter
private ModuleService moduleService;
@Parameter
private PluginService pluginService;
@Inject | private JsonService jsonService; |
imagej/imagej-server | src/main/java/net/imagej/server/resources/ModulesResource.java | // Path: src/main/java/net/imagej/server/WebCommandInfo.java
// public class WebCommandInfo extends CommandInfo {
//
// private final Module relatedModule;
//
// public WebCommandInfo(CommandInfo commandInfo, Module module) {
// super(commandInfo);
// relatedModule = module;
// }
//
// @Override
// public Iterable<ModuleItem<?>> inputs() {
//
// final List<WebCommandModuleItem<?>> checkedInputs = new ArrayList<>();
// for (final ModuleItem<?> input : super.inputs()) {
// if (input instanceof CommandModuleItem) {
// final WebCommandModuleItem<Object> webCommandModuleItem =
// new WebCommandModuleItem<>(this, ((CommandModuleItem<?>) input)
// .getField());
// final String name = input.getName();
//
// final boolean isResolved = relatedModule.isInputResolved(name);
//
// // Include resolved status in the JSON feed.
// // This is handy for judiciously overwriting already-resolved inputs,
// // particularly the "active image" inputs, which will be reported as
// // resolved, but not necessarily match what's selected on the client
// // side.
// webCommandModuleItem.isResolved = isResolved;
//
// // If the input is not resolved, include startingValue in the JSON feed.
// // This is useful for populating the dialog.
// webCommandModuleItem.startingValue = (!isResolved) ? relatedModule
// .getInput(name) : null;
//
// checkedInputs.add(webCommandModuleItem);
// }
// }
//
// return Collections.unmodifiableList(checkedInputs);
// }
// }
//
// Path: src/main/java/net/imagej/server/services/JsonService.java
// public interface JsonService {
//
// /**
// * Adds a deserializer to a given {@link ObjectMapper} to modify the default
// * behavior.
// *
// * @param objectMapper
// */
// void addDeserializerTo(final ObjectMapper objectMapper);
//
// /**
// * Parses the given Object.
// *
// * @param obj Object to be parsed.
// * @return a JSON format String of the parsed Object
// * @throws JsonProcessingException
// */
// String parseObject(final Object obj) throws JsonProcessingException;
// }
| import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import net.imagej.ops.Initializable;
import net.imagej.server.WebCommandInfo;
import net.imagej.server.services.JsonService;
import org.scijava.Context;
import org.scijava.Identifiable;
import org.scijava.Priority;
import org.scijava.command.CommandInfo;
import org.scijava.module.Module;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleService;
import org.scijava.module.process.AbstractPreprocessorPlugin;
import org.scijava.module.process.ModulePreprocessor;
import org.scijava.module.process.PreprocessorPlugin;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginInfo;
import org.scijava.plugin.PluginService;
import org.scijava.widget.InputHarvester; | // Check if we're dealing with Command information
if (!(info instanceof CommandInfo)) {
// TODO - decide what to do if this happens.
throw new IllegalArgumentException("Object is not an instance of " + CommandInfo.class.getName());
}
// Create a transient instance of the module, so we can do some
// selective preprocessing. This is necessary to determine which
// inputs are still unresolved at the time of user input harvesting,
// as well as what their current starting values are.
final Module module = moduleService.createModule(info);
// Get the complete list of preprocessors.
final List<PluginInfo<PreprocessorPlugin>> allPPs =
pluginService.getPluginsOfType(PreprocessorPlugin.class);
// Filter the list to only those which run _before_ input harvesting.
final List<PluginInfo<PreprocessorPlugin>> goodPPs = allPPs.stream() //
.filter(ppInfo -> ppInfo.getPriority() > InputHarvester.PRIORITY) //
.collect(Collectors.toList());
// Execute all of these "good" preprocessors to prep the module correctly.
for (final ModulePreprocessor p : pluginService.createInstances(goodPPs)) {
p.process(module);
if (p.isCanceled()) {
// TODO - decide what to do if this happens.
}
}
// Create a WebCommandInfo instance and parse it (resolved inputs will be identified during the process) | // Path: src/main/java/net/imagej/server/WebCommandInfo.java
// public class WebCommandInfo extends CommandInfo {
//
// private final Module relatedModule;
//
// public WebCommandInfo(CommandInfo commandInfo, Module module) {
// super(commandInfo);
// relatedModule = module;
// }
//
// @Override
// public Iterable<ModuleItem<?>> inputs() {
//
// final List<WebCommandModuleItem<?>> checkedInputs = new ArrayList<>();
// for (final ModuleItem<?> input : super.inputs()) {
// if (input instanceof CommandModuleItem) {
// final WebCommandModuleItem<Object> webCommandModuleItem =
// new WebCommandModuleItem<>(this, ((CommandModuleItem<?>) input)
// .getField());
// final String name = input.getName();
//
// final boolean isResolved = relatedModule.isInputResolved(name);
//
// // Include resolved status in the JSON feed.
// // This is handy for judiciously overwriting already-resolved inputs,
// // particularly the "active image" inputs, which will be reported as
// // resolved, but not necessarily match what's selected on the client
// // side.
// webCommandModuleItem.isResolved = isResolved;
//
// // If the input is not resolved, include startingValue in the JSON feed.
// // This is useful for populating the dialog.
// webCommandModuleItem.startingValue = (!isResolved) ? relatedModule
// .getInput(name) : null;
//
// checkedInputs.add(webCommandModuleItem);
// }
// }
//
// return Collections.unmodifiableList(checkedInputs);
// }
// }
//
// Path: src/main/java/net/imagej/server/services/JsonService.java
// public interface JsonService {
//
// /**
// * Adds a deserializer to a given {@link ObjectMapper} to modify the default
// * behavior.
// *
// * @param objectMapper
// */
// void addDeserializerTo(final ObjectMapper objectMapper);
//
// /**
// * Parses the given Object.
// *
// * @param obj Object to be parsed.
// * @return a JSON format String of the parsed Object
// * @throws JsonProcessingException
// */
// String parseObject(final Object obj) throws JsonProcessingException;
// }
// Path: src/main/java/net/imagej/server/resources/ModulesResource.java
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import net.imagej.ops.Initializable;
import net.imagej.server.WebCommandInfo;
import net.imagej.server.services.JsonService;
import org.scijava.Context;
import org.scijava.Identifiable;
import org.scijava.Priority;
import org.scijava.command.CommandInfo;
import org.scijava.module.Module;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleService;
import org.scijava.module.process.AbstractPreprocessorPlugin;
import org.scijava.module.process.ModulePreprocessor;
import org.scijava.module.process.PreprocessorPlugin;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginInfo;
import org.scijava.plugin.PluginService;
import org.scijava.widget.InputHarvester;
// Check if we're dealing with Command information
if (!(info instanceof CommandInfo)) {
// TODO - decide what to do if this happens.
throw new IllegalArgumentException("Object is not an instance of " + CommandInfo.class.getName());
}
// Create a transient instance of the module, so we can do some
// selective preprocessing. This is necessary to determine which
// inputs are still unresolved at the time of user input harvesting,
// as well as what their current starting values are.
final Module module = moduleService.createModule(info);
// Get the complete list of preprocessors.
final List<PluginInfo<PreprocessorPlugin>> allPPs =
pluginService.getPluginsOfType(PreprocessorPlugin.class);
// Filter the list to only those which run _before_ input harvesting.
final List<PluginInfo<PreprocessorPlugin>> goodPPs = allPPs.stream() //
.filter(ppInfo -> ppInfo.getPriority() > InputHarvester.PRIORITY) //
.collect(Collectors.toList());
// Execute all of these "good" preprocessors to prep the module correctly.
for (final ModulePreprocessor p : pluginService.createInstances(goodPPs)) {
p.process(module);
if (p.isCanceled()) {
// TODO - decide what to do if this happens.
}
}
// Create a WebCommandInfo instance and parse it (resolved inputs will be identified during the process) | return jsonService.parseObject(new WebCommandInfo((CommandInfo)info, module)); |
imagej/imagej-server | src/main/java/net/imagej/server/commands/StopServer.java | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
| import org.scijava.ui.UIService;
import java.util.List;
import net.imagej.server.ImageJServer;
import org.scijava.command.Command;
import org.scijava.log.LogService;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin; | /*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.commands;
/**
* Stops the ImageJ Server, if one is running.
*
* @author Curtis Rueden
*/
@Plugin(type = Command.class, menuPath = "Plugins > Utilities > Stop Server")
public class StopServer implements Command {
@Parameter
private ObjectService objectService;
@Parameter(required = false)
private UIService ui;
@Parameter
private LogService log;
@Override
public void run() { | // Path: src/main/java/net/imagej/server/ImageJServer.java
// public class ImageJServer extends Application<ImageJServerConfiguration> {
//
// private final Context ctx;
//
// private final ObjectService objectService;
//
// private final JsonService jsonService;
//
// private Environment env;
//
// public ImageJServer(final Context ctx) {
// this.ctx = ctx;
// objectService = new DefaultObjectService();
// jsonService = new DefaultJsonService(ctx, objectService);
// }
//
// @Override
// public String getName() {
// return "ImageJ";
// }
//
// @Override
// public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
// jsonService.addDeserializerTo(bootstrap.getObjectMapper());
// }
//
// @Override
// public void run(final ImageJServerConfiguration configuration,
// final Environment environment)
// {
// // Enable CORS headers
// final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
// "CORS", CrossOriginFilter.class);
//
// // Configure CORS parameters
// cors.setInitParameter("allowedOrigins", "*");
// cors.setInitParameter("allowedHeaders",
// "X-Requested-With,Content-Type,Accept,Origin");
// cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
//
// // Add URL mapping
// cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
// "/*");
//
// env = environment;
//
// // NB: not implemented yet
// final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
// environment.healthChecks().register("imagej-server", healthCheck);
//
// environment.jersey().register(MultiPartFeature.class);
//
// // -- resources --
//
// environment.jersey().register(AdminResource.class);
//
// environment.jersey().register(ModulesResource.class);
//
// environment.jersey().register(ObjectsResource.class);
//
// // -- context dependencies injection --
//
// environment.jersey().register(new AbstractBinder() {
//
// @Override
// protected void configure() {
// bind(ctx).to(Context.class);
// bind(env).to(Environment.class);
// bind(objectService).to(ObjectService.class);
// bind(jsonService).to(JsonService.class);
// }
//
// });
// }
//
// public void stop() throws Exception {
// if (env == null) return;
// env.getApplicationContext().getServer().stop();
// }
//
// public void join() throws InterruptedException {
// if (env == null) return;
// env.getApplicationContext().getServer().join();
// }
// }
// Path: src/main/java/net/imagej/server/commands/StopServer.java
import org.scijava.ui.UIService;
import java.util.List;
import net.imagej.server.ImageJServer;
import org.scijava.command.Command;
import org.scijava.log.LogService;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/*
* #%L
* ImageJ server for RESTful access to ImageJ.
* %%
* Copyright (C) 2013 - 2016 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.imagej.server.commands;
/**
* Stops the ImageJ Server, if one is running.
*
* @author Curtis Rueden
*/
@Plugin(type = Command.class, menuPath = "Plugins > Utilities > Stop Server")
public class StopServer implements Command {
@Parameter
private ObjectService objectService;
@Parameter(required = false)
private UIService ui;
@Parameter
private LogService log;
@Override
public void run() { | final List<ImageJServer> servers = // |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/events/EventNutritionKey.java | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
| import ca.wescook.nutrition.Nutrition;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.proxy.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard; | package ca.wescook.nutrition.events;
public class EventNutritionKey {
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void keyInput(InputEvent.KeyInputEvent event) {
// Exit on key de-press
if (!Keyboard.getEventKeyState()) {
return;
}
// If Nutrition key is pressed, and F3 key is not being held (F3+N toggles Spectator mode) | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
// Path: src/main/java/ca/wescook/nutrition/events/EventNutritionKey.java
import ca.wescook.nutrition.Nutrition;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.proxy.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
package ca.wescook.nutrition.events;
public class EventNutritionKey {
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void keyInput(InputEvent.KeyInputEvent event) {
// Exit on key de-press
if (!Keyboard.getEventKeyState()) {
return;
}
// If Nutrition key is pressed, and F3 key is not being held (F3+N toggles Spectator mode) | if (ClientProxy.keyNutritionGui.isKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_F3)) { |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/events/EventNutritionKey.java | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
| import ca.wescook.nutrition.Nutrition;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.proxy.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard; | package ca.wescook.nutrition.events;
public class EventNutritionKey {
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void keyInput(InputEvent.KeyInputEvent event) {
// Exit on key de-press
if (!Keyboard.getEventKeyState()) {
return;
}
// If Nutrition key is pressed, and F3 key is not being held (F3+N toggles Spectator mode)
if (ClientProxy.keyNutritionGui.isKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_F3)) {
openNutritionGui();
}
}
// Opens GUI to show nutrition menu
@SideOnly(Side.CLIENT)
private void openNutritionGui() {
// Get data
EntityPlayer player = Minecraft.getMinecraft().player;
World world = Minecraft.getMinecraft().world;
// Open GUI | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
// Path: src/main/java/ca/wescook/nutrition/events/EventNutritionKey.java
import ca.wescook.nutrition.Nutrition;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.proxy.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
package ca.wescook.nutrition.events;
public class EventNutritionKey {
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void keyInput(InputEvent.KeyInputEvent event) {
// Exit on key de-press
if (!Keyboard.getEventKeyState()) {
return;
}
// If Nutrition key is pressed, and F3 key is not being held (F3+N toggles Spectator mode)
if (ClientProxy.keyNutritionGui.isKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_F3)) {
openNutritionGui();
}
}
// Opens GUI to show nutrition menu
@SideOnly(Side.CLIENT)
private void openNutritionGui() {
// Get data
EntityPlayer player = Minecraft.getMinecraft().player;
World world = Minecraft.getMinecraft().world;
// Open GUI | player.openGui(Nutrition.instance, ModGuiHandler.NUTRITION_GUI_ID, world, (int) player.posX, (int) player.posY, (int) player.posZ); |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/events/EventNutritionKey.java | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
| import ca.wescook.nutrition.Nutrition;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.proxy.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard; | package ca.wescook.nutrition.events;
public class EventNutritionKey {
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void keyInput(InputEvent.KeyInputEvent event) {
// Exit on key de-press
if (!Keyboard.getEventKeyState()) {
return;
}
// If Nutrition key is pressed, and F3 key is not being held (F3+N toggles Spectator mode)
if (ClientProxy.keyNutritionGui.isKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_F3)) {
openNutritionGui();
}
}
// Opens GUI to show nutrition menu
@SideOnly(Side.CLIENT)
private void openNutritionGui() {
// Get data
EntityPlayer player = Minecraft.getMinecraft().player;
World world = Minecraft.getMinecraft().world;
// Open GUI | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
// Path: src/main/java/ca/wescook/nutrition/events/EventNutritionKey.java
import ca.wescook.nutrition.Nutrition;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.proxy.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
package ca.wescook.nutrition.events;
public class EventNutritionKey {
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void keyInput(InputEvent.KeyInputEvent event) {
// Exit on key de-press
if (!Keyboard.getEventKeyState()) {
return;
}
// If Nutrition key is pressed, and F3 key is not being held (F3+N toggles Spectator mode)
if (ClientProxy.keyNutritionGui.isKeyDown() && !Keyboard.isKeyDown(Keyboard.KEY_F3)) {
openNutritionGui();
}
}
// Opens GUI to show nutrition menu
@SideOnly(Side.CLIENT)
private void openNutritionGui() {
// Get data
EntityPlayer player = Minecraft.getMinecraft().player;
World world = Minecraft.getMinecraft().world;
// Open GUI | player.openGui(Nutrition.instance, ModGuiHandler.NUTRITION_GUI_ID, world, (int) player.posX, (int) player.posY, (int) player.posZ); |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/utility/ChatCommand.java | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/network/Sync.java
// public class Sync {
// // Server sends a nutrition update to client
// // Only call from server
// public static void serverRequest(EntityPlayer player) {
// if (!player.world.isRemote) // Server-only
// ModPacketHandler.NETWORK_CHANNEL.sendTo(new PacketNutritionResponse.Message(player), (EntityPlayerMP) player);
// }
//
// // Client requests a nutrition update from server
// // Only call from client
// public static void clientRequest() {
// ModPacketHandler.NETWORK_CHANNEL.sendToServer(new PacketNutritionRequest.Message());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
| import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.network.Sync;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.apache.commons.lang3.math.NumberUtils;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; | private final String helpString = "/nutrition <get/set/add/subtract/reset/reload> <player> <nutrient> <value>";
private enum actions {SET, ADD, SUBTRACT}
@Override
public String getName() {
return "nutrition";
}
@Override
public String getUsage(ICommandSender sender) {
return helpString;
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length == 1) { // Sub-commands list
return getListOfStringsMatchingLastWord(args, Arrays.asList("get", "set", "add", "subtract", "reset", "reload"));
}
else if (args.length == 2 && playerSubCommands.contains(args[0])) { // Player list/reload command
return getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames());
}
else if (args.length == 3) { // Nutrients list
List<String> nutrientList = new ArrayList<>(); | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/network/Sync.java
// public class Sync {
// // Server sends a nutrition update to client
// // Only call from server
// public static void serverRequest(EntityPlayer player) {
// if (!player.world.isRemote) // Server-only
// ModPacketHandler.NETWORK_CHANNEL.sendTo(new PacketNutritionResponse.Message(player), (EntityPlayerMP) player);
// }
//
// // Client requests a nutrition update from server
// // Only call from client
// public static void clientRequest() {
// ModPacketHandler.NETWORK_CHANNEL.sendToServer(new PacketNutritionRequest.Message());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
// Path: src/main/java/ca/wescook/nutrition/utility/ChatCommand.java
import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.network.Sync;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.apache.commons.lang3.math.NumberUtils;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
private final String helpString = "/nutrition <get/set/add/subtract/reset/reload> <player> <nutrient> <value>";
private enum actions {SET, ADD, SUBTRACT}
@Override
public String getName() {
return "nutrition";
}
@Override
public String getUsage(ICommandSender sender) {
return helpString;
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length == 1) { // Sub-commands list
return getListOfStringsMatchingLastWord(args, Arrays.asList("get", "set", "add", "subtract", "reset", "reload"));
}
else if (args.length == 2 && playerSubCommands.contains(args[0])) { // Player list/reload command
return getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames());
}
else if (args.length == 3) { // Nutrients list
List<String> nutrientList = new ArrayList<>(); | for (Nutrient nutrient : NutrientList.get()) |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/utility/ChatCommand.java | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/network/Sync.java
// public class Sync {
// // Server sends a nutrition update to client
// // Only call from server
// public static void serverRequest(EntityPlayer player) {
// if (!player.world.isRemote) // Server-only
// ModPacketHandler.NETWORK_CHANNEL.sendTo(new PacketNutritionResponse.Message(player), (EntityPlayerMP) player);
// }
//
// // Client requests a nutrition update from server
// // Only call from client
// public static void clientRequest() {
// ModPacketHandler.NETWORK_CHANNEL.sendToServer(new PacketNutritionRequest.Message());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
| import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.network.Sync;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.apache.commons.lang3.math.NumberUtils;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; | private final String helpString = "/nutrition <get/set/add/subtract/reset/reload> <player> <nutrient> <value>";
private enum actions {SET, ADD, SUBTRACT}
@Override
public String getName() {
return "nutrition";
}
@Override
public String getUsage(ICommandSender sender) {
return helpString;
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length == 1) { // Sub-commands list
return getListOfStringsMatchingLastWord(args, Arrays.asList("get", "set", "add", "subtract", "reset", "reload"));
}
else if (args.length == 2 && playerSubCommands.contains(args[0])) { // Player list/reload command
return getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames());
}
else if (args.length == 3) { // Nutrients list
List<String> nutrientList = new ArrayList<>(); | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/network/Sync.java
// public class Sync {
// // Server sends a nutrition update to client
// // Only call from server
// public static void serverRequest(EntityPlayer player) {
// if (!player.world.isRemote) // Server-only
// ModPacketHandler.NETWORK_CHANNEL.sendTo(new PacketNutritionResponse.Message(player), (EntityPlayerMP) player);
// }
//
// // Client requests a nutrition update from server
// // Only call from client
// public static void clientRequest() {
// ModPacketHandler.NETWORK_CHANNEL.sendToServer(new PacketNutritionRequest.Message());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
// Path: src/main/java/ca/wescook/nutrition/utility/ChatCommand.java
import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.network.Sync;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.apache.commons.lang3.math.NumberUtils;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
private final String helpString = "/nutrition <get/set/add/subtract/reset/reload> <player> <nutrient> <value>";
private enum actions {SET, ADD, SUBTRACT}
@Override
public String getName() {
return "nutrition";
}
@Override
public String getUsage(ICommandSender sender) {
return helpString;
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length == 1) { // Sub-commands list
return getListOfStringsMatchingLastWord(args, Arrays.asList("get", "set", "add", "subtract", "reset", "reload"));
}
else if (args.length == 2 && playerSubCommands.contains(args[0])) { // Player list/reload command
return getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames());
}
else if (args.length == 3) { // Nutrients list
List<String> nutrientList = new ArrayList<>(); | for (Nutrient nutrient : NutrientList.get()) |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/utility/ChatCommand.java | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/network/Sync.java
// public class Sync {
// // Server sends a nutrition update to client
// // Only call from server
// public static void serverRequest(EntityPlayer player) {
// if (!player.world.isRemote) // Server-only
// ModPacketHandler.NETWORK_CHANNEL.sendTo(new PacketNutritionResponse.Message(player), (EntityPlayerMP) player);
// }
//
// // Client requests a nutrition update from server
// // Only call from client
// public static void clientRequest() {
// ModPacketHandler.NETWORK_CHANNEL.sendToServer(new PacketNutritionRequest.Message());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
| import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.network.Sync;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.apache.commons.lang3.math.NumberUtils;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; |
private void commandGetNutrition(EntityPlayer player, ICommandSender sender, String[] args) {
// Write nutrient name and percentage to chat
Nutrient nutrient = NutrientList.getByName(args[2]);
if (nutrient != null) {
Float nutrientValue = player.getCapability(NUTRITION_CAPABILITY, null).get(nutrient);
sender.sendMessage(new TextComponentString(nutrient.name + ": " + String.format("%.2f", nutrientValue) + "%"));
}
else // Write error message
sender.sendMessage(new TextComponentString("'" + args[2] + "' is not a valid nutrient."));
}
// Used to set, add, and subtract nutrients (defined under actions)
private void commandSetNutrition(EntityPlayer player, ICommandSender sender, String[] args, actions action) {
// Sanity checking
if (!validNumber(sender, args[3]))
return;
// Set nutrient value and output
Nutrient nutrient = NutrientList.getByName(args[2]);
if (nutrient != null) {
// Update nutrition based on action type
if (action == actions.SET)
player.getCapability(NUTRITION_CAPABILITY, null).set(nutrient, Float.parseFloat(args[3]));
else if (action == actions.ADD)
player.getCapability(NUTRITION_CAPABILITY, null).add(nutrient, Float.parseFloat(args[3]));
else if (action == actions.SUBTRACT)
player.getCapability(NUTRITION_CAPABILITY, null).subtract(nutrient, Float.parseFloat(args[3]));
// Sync nutrition | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/network/Sync.java
// public class Sync {
// // Server sends a nutrition update to client
// // Only call from server
// public static void serverRequest(EntityPlayer player) {
// if (!player.world.isRemote) // Server-only
// ModPacketHandler.NETWORK_CHANNEL.sendTo(new PacketNutritionResponse.Message(player), (EntityPlayerMP) player);
// }
//
// // Client requests a nutrition update from server
// // Only call from client
// public static void clientRequest() {
// ModPacketHandler.NETWORK_CHANNEL.sendToServer(new PacketNutritionRequest.Message());
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
// Path: src/main/java/ca/wescook/nutrition/utility/ChatCommand.java
import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.network.Sync;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.apache.commons.lang3.math.NumberUtils;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
private void commandGetNutrition(EntityPlayer player, ICommandSender sender, String[] args) {
// Write nutrient name and percentage to chat
Nutrient nutrient = NutrientList.getByName(args[2]);
if (nutrient != null) {
Float nutrientValue = player.getCapability(NUTRITION_CAPABILITY, null).get(nutrient);
sender.sendMessage(new TextComponentString(nutrient.name + ": " + String.format("%.2f", nutrientValue) + "%"));
}
else // Write error message
sender.sendMessage(new TextComponentString("'" + args[2] + "' is not a valid nutrient."));
}
// Used to set, add, and subtract nutrients (defined under actions)
private void commandSetNutrition(EntityPlayer player, ICommandSender sender, String[] args, actions action) {
// Sanity checking
if (!validNumber(sender, args[3]))
return;
// Set nutrient value and output
Nutrient nutrient = NutrientList.getByName(args[2]);
if (nutrient != null) {
// Update nutrition based on action type
if (action == actions.SET)
player.getCapability(NUTRITION_CAPABILITY, null).set(nutrient, Float.parseFloat(args[3]));
else if (action == actions.ADD)
player.getCapability(NUTRITION_CAPABILITY, null).add(nutrient, Float.parseFloat(args[3]));
else if (action == actions.SUBTRACT)
player.getCapability(NUTRITION_CAPABILITY, null).subtract(nutrient, Float.parseFloat(args[3]));
// Sync nutrition | Sync.serverRequest(player); |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/effects/Effect.java | // Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
| import ca.wescook.nutrition.nutrients.Nutrient;
import net.minecraft.potion.Potion;
import java.util.ArrayList;
import java.util.List; | package ca.wescook.nutrition.effects;
// This class represents cleaned up and parsed potion effects
public class Effect {
public String name;
public Potion potion;
public int amplifier;
public int minimum;
public int maximum;
public String detect; | // Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
// Path: src/main/java/ca/wescook/nutrition/effects/Effect.java
import ca.wescook.nutrition.nutrients.Nutrient;
import net.minecraft.potion.Potion;
import java.util.ArrayList;
import java.util.List;
package ca.wescook.nutrition.effects;
// This class represents cleaned up and parsed potion effects
public class Effect {
public String name;
public Potion potion;
public int amplifier;
public int minimum;
public int maximum;
public String detect; | public List<Nutrient> nutrients = new ArrayList<>(); |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/gui/GuiScreenDynamic.java | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
| import ca.wescook.nutrition.Nutrition;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiLabel;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation; | package ca.wescook.nutrition.gui;
// Similar to GuiScreen, but draws a dynamic Minecraft border around any size
public abstract class GuiScreenDynamic extends GuiScreen {
// Container size
private int guiWidth = 0;
private int guiHeight = 0;
// Offsets
public int top = 0;
public int left = 0;
public int right = 0;
public int bottom = 0;
// Container info | // Path: src/main/java/ca/wescook/nutrition/Nutrition.java
// @Mod(
// modid = MODID,
// name = MODNAME,
// version = "@VERSION@",
// acceptedMinecraftVersions = FORGE_VERSIONS,
// acceptableRemoteVersions = "*"
// )
//
// public class Nutrition {
// public static final String MODID = "nutrition";
// public static final String MODNAME = "Nutrition";
// public static final String FORGE_VERSIONS = "[1.12,1.13)";
//
// // Create instance of mod
// @Mod.Instance
// public static Nutrition instance;
//
// // Create instance of proxy
// // This will vary depending on if the client or server is running
// @SidedProxy(
// clientSide="ca.wescook.nutrition.proxy.ClientProxy",
// serverSide="ca.wescook.nutrition.proxy.ServerProxy"
// )
// public static IProxy proxy;
//
// // Events
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file
// ModPacketHandler.registerMessages(); // Register network messages
// CapabilityManager.register(); // Register capability
//
// ModPotions.createPotions(); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions
// MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player
// MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping
// MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event
// MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects
//
// Nutrition.proxy.preInit(event);
// }
//
// @EventHandler
// public void init(FMLInitializationEvent event) {
// NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler
//
// Nutrition.proxy.init(event);
// }
//
// @EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// DataImporter.reload(); // Load nutrients and effects
//
// Nutrition.proxy.postInit(event);
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new ChatCommand());
// }
// }
// Path: src/main/java/ca/wescook/nutrition/gui/GuiScreenDynamic.java
import ca.wescook.nutrition.Nutrition;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiLabel;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
package ca.wescook.nutrition.gui;
// Similar to GuiScreen, but draws a dynamic Minecraft border around any size
public abstract class GuiScreenDynamic extends GuiScreen {
// Container size
private int guiWidth = 0;
private int guiHeight = 0;
// Offsets
public int top = 0;
public int left = 0;
public int right = 0;
public int bottom = 0;
// Container info | private final ResourceLocation GUI_BORDERS = new ResourceLocation(Nutrition.MODID, "textures/gui/gui.png"); |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/network/PacketNutritionResponse.java | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
| import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import ca.wescook.nutrition.proxy.ClientProxy;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import java.util.HashMap;
import java.util.Map; | package ca.wescook.nutrition.network;
public class PacketNutritionResponse {
// Message Subclass
public static class Message implements IMessage { | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
// Path: src/main/java/ca/wescook/nutrition/network/PacketNutritionResponse.java
import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import ca.wescook.nutrition.proxy.ClientProxy;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import java.util.HashMap;
import java.util.Map;
package ca.wescook.nutrition.network;
public class PacketNutritionResponse {
// Message Subclass
public static class Message implements IMessage { | @CapabilityInject(INutrientManager.class) |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/network/PacketNutritionResponse.java | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
| import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import ca.wescook.nutrition.proxy.ClientProxy;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import java.util.HashMap;
import java.util.Map; | package ca.wescook.nutrition.network;
public class PacketNutritionResponse {
// Message Subclass
public static class Message implements IMessage {
@CapabilityInject(INutrientManager.class)
private static final Capability<INutrientManager> NUTRITION_CAPABILITY = null;
// Server vars only
EntityPlayer serverPlayer;
// Client vars only | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/gui/ModGuiHandler.java
// public class ModGuiHandler implements IGuiHandler {
// // GUI IDs
// public static final int NUTRITION_GUI_ID = 0;
// public static NutritionGui nutritionGui;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// return null;
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// if (ID == NUTRITION_GUI_ID)
// return nutritionGui = new NutritionGui();
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/NutrientList.java
// public class NutrientList {
// private static List<Nutrient> nutrients = new ArrayList<>();
//
// // Register list of JSON objects
// public static void register(List<Nutrient> nutrientsIn) {
// nutrients.clear();
// nutrients.addAll(nutrientsIn);
// }
//
// // Return all nutrients
// public static List<Nutrient> get() {
// return nutrients;
// }
//
// // Return all visible nutrients
// public static List<Nutrient> getVisible() {
// List<Nutrient> visibleNutrients = new ArrayList<>();
// for (Nutrient nutrient : nutrients)
// if (nutrient.visible)
// visibleNutrients.add(nutrient);
// return visibleNutrients;
// }
//
// // Return nutrient by name (null if not found)
// public static Nutrient getByName(String name) {
// for (Nutrient nutrient : nutrients) {
// if (nutrient.name.equals(name))
// return nutrient;
// }
// return null;
// }
// }
//
// Path: src/main/java/ca/wescook/nutrition/proxy/ClientProxy.java
// public class ClientProxy implements IProxy {
// public static INutrientManager localNutrition; // Holds local copy of data/methods for client-side prediction
// public static KeyBinding keyNutritionGui;
//
// @Override
// public void preInit(FMLPreInitializationEvent event) {
// }
//
// @Override
// public void init(FMLInitializationEvent event) {
//
// if (Config.enableGui) { // If GUI is enabled
// ClientRegistry.registerKeyBinding(keyNutritionGui = new KeyBinding("key.nutrition", 49, "Nutrition")); // Register Nutrition keybind, default to "N"
// MinecraftForge.EVENT_BUS.register(new EventNutritionKey()); // Register key input event to respond to keybind
// if (Config.enableGuiButton)
// MinecraftForge.EVENT_BUS.register(new EventNutritionButton()); // Register GUI button event
// }
//
// if (Config.enableTooltips)
// MinecraftForge.EVENT_BUS.register(new EventTooltip()); // Register tooltip event
// }
//
// @Override
// public void postInit(FMLPostInitializationEvent event) {
// }
// }
// Path: src/main/java/ca/wescook/nutrition/network/PacketNutritionResponse.java
import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.gui.ModGuiHandler;
import ca.wescook.nutrition.nutrients.Nutrient;
import ca.wescook.nutrition.nutrients.NutrientList;
import ca.wescook.nutrition.proxy.ClientProxy;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import java.util.HashMap;
import java.util.Map;
package ca.wescook.nutrition.network;
public class PacketNutritionResponse {
// Message Subclass
public static class Message implements IMessage {
@CapabilityInject(INutrientManager.class)
private static final Capability<INutrientManager> NUTRITION_CAPABILITY = null;
// Server vars only
EntityPlayer serverPlayer;
// Client vars only | Map<Nutrient, Float> clientNutrients; |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/effects/EffectsManager.java | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
| import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.nutrients.Nutrient;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | package ca.wescook.nutrition.effects;
public class EffectsManager {
@CapabilityInject(INutrientManager.class)
private static final Capability<INutrientManager> NUTRITION_CAPABILITY = null;
// Called from EventWorldTick#PlayerTickEvent and EventEatFood#reapplyEffectsFromMilk
public static void reapplyEffects(EntityPlayer player) {
List<Effect> effects = removeDuplicates(getEffectsInThreshold(player));
for (Effect effect : effects) {
boolean ambient = (effect.particles == Effect.ParticleVisibility.TRANSLUCENT); // Determine if particles should be shown, and what strength
boolean showParticles = (effect.particles == Effect.ParticleVisibility.TRANSLUCENT || effect.particles == Effect.ParticleVisibility.OPAQUE);
player.addPotionEffect(new PotionEffect(effect.potion, 619, effect.amplifier, ambient, showParticles));
}
}
// Returns which effects match threshold conditions
private static List<Effect> getEffectsInThreshold(EntityPlayer player) {
// List of effects being turned on
List<Effect> effectsInThreshold = new ArrayList<>();
// Get player nutrition | // Path: src/main/java/ca/wescook/nutrition/capabilities/INutrientManager.java
// public interface INutrientManager {
// // Return all nutrients and values
// Map<Nutrient, Float> get();
//
// // Return value of specific nutrient
// Float get(Nutrient nutrient);
//
// // Set value of specific nutrient
// void set(Nutrient nutrient, Float value);
//
// // Update all nutrients
// void set(Map<Nutrient, Float> nutrientData);
//
// // Increase specific nutrient by amount
// void add(Nutrient nutrient, float amount);
//
// // Increase list of nutrients by amount
// void add(List<Nutrient> nutrientData, float amount);
//
// // Decrease specific nutrient by amount
// void subtract(Nutrient nutrient, float amount);
//
// // Decrease list of nutrients by amount
// void subtract(List<Nutrient> nutrientData, float amount);
//
// // Reset specific nutrient to default nutrition
// void reset(Nutrient nutrient);
//
// // Reset all nutrients to default nutrition
// void reset();
//
// // Internal: Called to update Nutrient object references in player's capability
// void updateCapability();
// }
//
// Path: src/main/java/ca/wescook/nutrition/nutrients/Nutrient.java
// public class Nutrient {
// public String name;
// public ItemStack icon;
// public int color;
// public float decay;
// public boolean visible;
// public List<String> foodOreDict = new ArrayList<>();
// public List<ItemStack> foodItems = new ArrayList<>();
// }
// Path: src/main/java/ca/wescook/nutrition/effects/EffectsManager.java
import ca.wescook.nutrition.capabilities.INutrientManager;
import ca.wescook.nutrition.nutrients.Nutrient;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
package ca.wescook.nutrition.effects;
public class EffectsManager {
@CapabilityInject(INutrientManager.class)
private static final Capability<INutrientManager> NUTRITION_CAPABILITY = null;
// Called from EventWorldTick#PlayerTickEvent and EventEatFood#reapplyEffectsFromMilk
public static void reapplyEffects(EntityPlayer player) {
List<Effect> effects = removeDuplicates(getEffectsInThreshold(player));
for (Effect effect : effects) {
boolean ambient = (effect.particles == Effect.ParticleVisibility.TRANSLUCENT); // Determine if particles should be shown, and what strength
boolean showParticles = (effect.particles == Effect.ParticleVisibility.TRANSLUCENT || effect.particles == Effect.ParticleVisibility.OPAQUE);
player.addPotionEffect(new PotionEffect(effect.potion, 619, effect.amplifier, ambient, showParticles));
}
}
// Returns which effects match threshold conditions
private static List<Effect> getEffectsInThreshold(EntityPlayer player) {
// List of effects being turned on
List<Effect> effectsInThreshold = new ArrayList<>();
// Get player nutrition | Map<Nutrient, Float> playerNutrition = player.getCapability(NUTRITION_CAPABILITY, null).get(); |
WesCook/Nutrition | src/main/java/ca/wescook/nutrition/events/EventRegistry.java | // Path: src/main/java/ca/wescook/nutrition/potions/ModPotions.java
// public class ModPotions {
// public static PotionToughness toughness;
// public static PotionMalnourished malnourished;
// public static PotionNourished nourished;
//
// static final UUID TOUGHNESS_HEALTH = UUID.fromString("d80b5ec3-8cf9-4b74-bc0d-6f3ef7b48b2e");
// static final UUID TOUGHNESS_ARMOR = UUID.fromString("f42431e4-8efc-44d2-8249-fea2a2cb418e");
// static final UUID TOUGHNESS_ATTACK_SPEED = UUID.fromString("10d42c27-f160-4909-a523-9b2553e14eac");
// static final UUID NOURISHMENT_HEALTH = UUID.fromString("bdafe0c7-5881-4505-802e-e18f6c419554");
// static final UUID MALNOURISHMENT_HEALTH = UUID.fromString("ea9cebf7-7c7a-4a89-a04f-221dab8ffdf7");
//
// public static void createPotions() {
// // Toughness
// toughness = new PotionToughness(true, new ResourceLocation("nutrition", "textures/potions/toughness.png"));
// toughness.setRegistryName("toughness");
// toughness.setPotionName("potion." + toughness.getRegistryName());
// toughness.setBeneficial();
// toughness.registerPotionAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, TOUGHNESS_HEALTH.toString(), 0D, 0);
// toughness.registerPotionAttributeModifier(SharedMonsterAttributes.ARMOR_TOUGHNESS, TOUGHNESS_ARMOR.toString(), 0D, 0);
// toughness.registerPotionAttributeModifier(SharedMonsterAttributes.ATTACK_SPEED, TOUGHNESS_ATTACK_SPEED.toString(), 0D, 0);
//
// // Nourished
// nourished = new PotionNourished(true, new ResourceLocation("nutrition", "textures/potions/nourished.png"));
// nourished.setRegistryName("nourished");
// nourished.setPotionName("potion." + nourished.getRegistryName());
// toughness.setBeneficial();
// nourished.registerPotionAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, NOURISHMENT_HEALTH.toString(), 0D, 0);
//
// // Malnourished
// malnourished = new PotionMalnourished(true, new ResourceLocation("nutrition", "textures/potions/malnourished.png"));
// malnourished.setRegistryName("malnourished");
// malnourished.setPotionName("potion." + malnourished.getRegistryName());
// malnourished.registerPotionAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, MALNOURISHMENT_HEALTH.toString(), 0D, 0);
// }
// }
| import ca.wescook.nutrition.potions.ModPotions;
import net.minecraft.potion.Potion;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; | package ca.wescook.nutrition.events;
public class EventRegistry {
@SubscribeEvent
public void registerPotions(RegistryEvent.Register<Potion> event) { | // Path: src/main/java/ca/wescook/nutrition/potions/ModPotions.java
// public class ModPotions {
// public static PotionToughness toughness;
// public static PotionMalnourished malnourished;
// public static PotionNourished nourished;
//
// static final UUID TOUGHNESS_HEALTH = UUID.fromString("d80b5ec3-8cf9-4b74-bc0d-6f3ef7b48b2e");
// static final UUID TOUGHNESS_ARMOR = UUID.fromString("f42431e4-8efc-44d2-8249-fea2a2cb418e");
// static final UUID TOUGHNESS_ATTACK_SPEED = UUID.fromString("10d42c27-f160-4909-a523-9b2553e14eac");
// static final UUID NOURISHMENT_HEALTH = UUID.fromString("bdafe0c7-5881-4505-802e-e18f6c419554");
// static final UUID MALNOURISHMENT_HEALTH = UUID.fromString("ea9cebf7-7c7a-4a89-a04f-221dab8ffdf7");
//
// public static void createPotions() {
// // Toughness
// toughness = new PotionToughness(true, new ResourceLocation("nutrition", "textures/potions/toughness.png"));
// toughness.setRegistryName("toughness");
// toughness.setPotionName("potion." + toughness.getRegistryName());
// toughness.setBeneficial();
// toughness.registerPotionAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, TOUGHNESS_HEALTH.toString(), 0D, 0);
// toughness.registerPotionAttributeModifier(SharedMonsterAttributes.ARMOR_TOUGHNESS, TOUGHNESS_ARMOR.toString(), 0D, 0);
// toughness.registerPotionAttributeModifier(SharedMonsterAttributes.ATTACK_SPEED, TOUGHNESS_ATTACK_SPEED.toString(), 0D, 0);
//
// // Nourished
// nourished = new PotionNourished(true, new ResourceLocation("nutrition", "textures/potions/nourished.png"));
// nourished.setRegistryName("nourished");
// nourished.setPotionName("potion." + nourished.getRegistryName());
// toughness.setBeneficial();
// nourished.registerPotionAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, NOURISHMENT_HEALTH.toString(), 0D, 0);
//
// // Malnourished
// malnourished = new PotionMalnourished(true, new ResourceLocation("nutrition", "textures/potions/malnourished.png"));
// malnourished.setRegistryName("malnourished");
// malnourished.setPotionName("potion." + malnourished.getRegistryName());
// malnourished.registerPotionAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, MALNOURISHMENT_HEALTH.toString(), 0D, 0);
// }
// }
// Path: src/main/java/ca/wescook/nutrition/events/EventRegistry.java
import ca.wescook.nutrition.potions.ModPotions;
import net.minecraft.potion.Potion;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
package ca.wescook.nutrition.events;
public class EventRegistry {
@SubscribeEvent
public void registerPotions(RegistryEvent.Register<Potion> event) { | event.getRegistry().register(ModPotions.toughness); |
CBSkarmory/AWGW | src/main/java/cbskarmory/units/land/HeavyTank.java | // Path: src/main/java/cbskarmory/Player.java
// public class Player {
//
// public static int numberOfPlayers;
// public final CO CO;
// public final int id;
// private ArrayList<Unit> unitsControlled;
// private int money;
// private ArrayList<Property> propertiesOwned;
// private int commTowers;
// private Color teamColor;
//
// /**
// * Constructs a Player
// *
// * @param startingMoney starting amount of money
// * @param teamColor team color to be assigned to this Player
// */
// public Player(CO commandingOfficer, int startingMoney, Color teamColor) {
// //if error when setting starting funds, set to 0
// if (setMoney(startingMoney) == -1) {
// setMoney(0);
// } else {
// setMoney(startingMoney);
// }
// this.id = ++Player.numberOfPlayers;
// this.CO = commandingOfficer;
// this.teamColor = teamColor;
// this.unitsControlled = new ArrayList<>();
// this.propertiesOwned = new ArrayList<>();
// }
//
// /**
// * @return the player's team color
// */
// public Color getTeamColor() {
// return this.teamColor;
// }
//
// /**
// * @return the amount of money this player has
// */
// public int getMoney() {
// return this.money;
// }
//
// /**
// * @param money a positive integer to set money to
// * @return the amount of money that this player has after execution
// * or -1 if the amount was invalid
// */
// public int setMoney(int money) {
// if (money >= 0) {
// this.money = money;
// return this.money;
// } else {
// return -1;
// }
// }
//
// /**
// * @return a list of all of the units that this player controls
// */
// public ArrayList<Unit> getUnitsControlled() {
// return unitsControlled;
// }
//
// /**
// * @return the number of Units that this player controls
// */
// public int getNumUnitControlled() {
// return getUnitsControlled().size();
// }
//
// /**
// * @return a list of all of the Properties that this player owns
// */
// public ArrayList<Property> getPropertiesOwned() {
// return this.propertiesOwned;
// }
//
// /**
// * @return the number of Properties that this player controls
// */
// public int getNumPropertiesOwned() {
// return getPropertiesOwned().size();
// }
//
// public int getCommTowers() {
// return commTowers;
// }
//
// public void setCommTowers(int commTowers) {
// this.commTowers = commTowers;
// }
//
// public boolean hasHQ() {
// for (Property prop : getPropertiesOwned()) {
// if (prop instanceof HQ) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/cbskarmory/weapons/WeaponType.java
// public final class WeaponType {
//
// //direct fire
// public static final String NONE = "NONE";
// public static final String RIFLE = "RIFLE";
// public static final String ROCKET_LAUNCHER = "ROCKET_LAUNCHER";
// public static final String MG = "MG";
// public static final String HMG = "HMG";
// public static final String AP = "AP";
// public static final String HE = "HE";
// public static final String HEAT = "HEAT";
// public static final String ROCKET_POD = "ROCKET_POD";
// public static final String MISSILE = "MISSILE";
// public static final String FLAK = "FLAK";
// public static final String TORPEDO = "TORPEDO";
// public static final String DEPTH_CHARGE = "DEPTH_CHARGE";
//
// //indirect fire
// public static final String SHELL = "SHELL";
// public static final String MISSILES = "MISSILES";
// public static final String ROCKET = "ROCKET";
// public static final String ROTARY = "ROTARY";
//
// //special
// public static final String ICBM = "ICBM";
// }
| import cbskarmory.Player;
import cbskarmory.weapons.WeaponType; | /*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.units.land;
/**
* A HeavyTank is a Tank
* Gets AP, HMG
* Costs 2200
* Armor Piercing rounds are strong against armor and trucks
*/
public class HeavyTank extends Tank {
/**
* Constructs a Heavy Tank
* sets primary weapon to AP,
* secondary to HMG
*
* @param owner owner of the Unit
*/
public HeavyTank(Player owner) {
super(owner); | // Path: src/main/java/cbskarmory/Player.java
// public class Player {
//
// public static int numberOfPlayers;
// public final CO CO;
// public final int id;
// private ArrayList<Unit> unitsControlled;
// private int money;
// private ArrayList<Property> propertiesOwned;
// private int commTowers;
// private Color teamColor;
//
// /**
// * Constructs a Player
// *
// * @param startingMoney starting amount of money
// * @param teamColor team color to be assigned to this Player
// */
// public Player(CO commandingOfficer, int startingMoney, Color teamColor) {
// //if error when setting starting funds, set to 0
// if (setMoney(startingMoney) == -1) {
// setMoney(0);
// } else {
// setMoney(startingMoney);
// }
// this.id = ++Player.numberOfPlayers;
// this.CO = commandingOfficer;
// this.teamColor = teamColor;
// this.unitsControlled = new ArrayList<>();
// this.propertiesOwned = new ArrayList<>();
// }
//
// /**
// * @return the player's team color
// */
// public Color getTeamColor() {
// return this.teamColor;
// }
//
// /**
// * @return the amount of money this player has
// */
// public int getMoney() {
// return this.money;
// }
//
// /**
// * @param money a positive integer to set money to
// * @return the amount of money that this player has after execution
// * or -1 if the amount was invalid
// */
// public int setMoney(int money) {
// if (money >= 0) {
// this.money = money;
// return this.money;
// } else {
// return -1;
// }
// }
//
// /**
// * @return a list of all of the units that this player controls
// */
// public ArrayList<Unit> getUnitsControlled() {
// return unitsControlled;
// }
//
// /**
// * @return the number of Units that this player controls
// */
// public int getNumUnitControlled() {
// return getUnitsControlled().size();
// }
//
// /**
// * @return a list of all of the Properties that this player owns
// */
// public ArrayList<Property> getPropertiesOwned() {
// return this.propertiesOwned;
// }
//
// /**
// * @return the number of Properties that this player controls
// */
// public int getNumPropertiesOwned() {
// return getPropertiesOwned().size();
// }
//
// public int getCommTowers() {
// return commTowers;
// }
//
// public void setCommTowers(int commTowers) {
// this.commTowers = commTowers;
// }
//
// public boolean hasHQ() {
// for (Property prop : getPropertiesOwned()) {
// if (prop instanceof HQ) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/cbskarmory/weapons/WeaponType.java
// public final class WeaponType {
//
// //direct fire
// public static final String NONE = "NONE";
// public static final String RIFLE = "RIFLE";
// public static final String ROCKET_LAUNCHER = "ROCKET_LAUNCHER";
// public static final String MG = "MG";
// public static final String HMG = "HMG";
// public static final String AP = "AP";
// public static final String HE = "HE";
// public static final String HEAT = "HEAT";
// public static final String ROCKET_POD = "ROCKET_POD";
// public static final String MISSILE = "MISSILE";
// public static final String FLAK = "FLAK";
// public static final String TORPEDO = "TORPEDO";
// public static final String DEPTH_CHARGE = "DEPTH_CHARGE";
//
// //indirect fire
// public static final String SHELL = "SHELL";
// public static final String MISSILES = "MISSILES";
// public static final String ROCKET = "ROCKET";
// public static final String ROTARY = "ROTARY";
//
// //special
// public static final String ICBM = "ICBM";
// }
// Path: src/main/java/cbskarmory/units/land/HeavyTank.java
import cbskarmory.Player;
import cbskarmory.weapons.WeaponType;
/*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.units.land;
/**
* A HeavyTank is a Tank
* Gets AP, HMG
* Costs 2200
* Armor Piercing rounds are strong against armor and trucks
*/
public class HeavyTank extends Tank {
/**
* Constructs a Heavy Tank
* sets primary weapon to AP,
* secondary to HMG
*
* @param owner owner of the Unit
*/
public HeavyTank(Player owner) {
super(owner); | setWeapon(0, WeaponType.AP); |
CBSkarmory/AWGW | src/main/java/cbskarmory/units/Sea.java | // Path: src/main/java/cbskarmory/Player.java
// public class Player {
//
// public static int numberOfPlayers;
// public final CO CO;
// public final int id;
// private ArrayList<Unit> unitsControlled;
// private int money;
// private ArrayList<Property> propertiesOwned;
// private int commTowers;
// private Color teamColor;
//
// /**
// * Constructs a Player
// *
// * @param startingMoney starting amount of money
// * @param teamColor team color to be assigned to this Player
// */
// public Player(CO commandingOfficer, int startingMoney, Color teamColor) {
// //if error when setting starting funds, set to 0
// if (setMoney(startingMoney) == -1) {
// setMoney(0);
// } else {
// setMoney(startingMoney);
// }
// this.id = ++Player.numberOfPlayers;
// this.CO = commandingOfficer;
// this.teamColor = teamColor;
// this.unitsControlled = new ArrayList<>();
// this.propertiesOwned = new ArrayList<>();
// }
//
// /**
// * @return the player's team color
// */
// public Color getTeamColor() {
// return this.teamColor;
// }
//
// /**
// * @return the amount of money this player has
// */
// public int getMoney() {
// return this.money;
// }
//
// /**
// * @param money a positive integer to set money to
// * @return the amount of money that this player has after execution
// * or -1 if the amount was invalid
// */
// public int setMoney(int money) {
// if (money >= 0) {
// this.money = money;
// return this.money;
// } else {
// return -1;
// }
// }
//
// /**
// * @return a list of all of the units that this player controls
// */
// public ArrayList<Unit> getUnitsControlled() {
// return unitsControlled;
// }
//
// /**
// * @return the number of Units that this player controls
// */
// public int getNumUnitControlled() {
// return getUnitsControlled().size();
// }
//
// /**
// * @return a list of all of the Properties that this player owns
// */
// public ArrayList<Property> getPropertiesOwned() {
// return this.propertiesOwned;
// }
//
// /**
// * @return the number of Properties that this player controls
// */
// public int getNumPropertiesOwned() {
// return getPropertiesOwned().size();
// }
//
// public int getCommTowers() {
// return commTowers;
// }
//
// public void setCommTowers(int commTowers) {
// this.commTowers = commTowers;
// }
//
// public boolean hasHQ() {
// for (Property prop : getPropertiesOwned()) {
// if (prop instanceof HQ) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum MoveType {
// FOOT,
// TIRES,
// TREADS,
// SEA,
// AIR,
// LANDER
// }
| import cbskarmory.Player;
import cbskarmory.PassiveFlag.MoveType; | /*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.units;
/**
* abstract Sea represents all sea units
* Sea units use some fuel every day to stay afloat and
* will sink without fuel.
* These get MoveType.SEA
*/
public abstract class Sea extends Unit {
/**
* calls super(Player) from child classes
* don't invoke this
*
* @param owner owner of unit
*/
public Sea(Player owner) {
super(owner);
}
@Override | // Path: src/main/java/cbskarmory/Player.java
// public class Player {
//
// public static int numberOfPlayers;
// public final CO CO;
// public final int id;
// private ArrayList<Unit> unitsControlled;
// private int money;
// private ArrayList<Property> propertiesOwned;
// private int commTowers;
// private Color teamColor;
//
// /**
// * Constructs a Player
// *
// * @param startingMoney starting amount of money
// * @param teamColor team color to be assigned to this Player
// */
// public Player(CO commandingOfficer, int startingMoney, Color teamColor) {
// //if error when setting starting funds, set to 0
// if (setMoney(startingMoney) == -1) {
// setMoney(0);
// } else {
// setMoney(startingMoney);
// }
// this.id = ++Player.numberOfPlayers;
// this.CO = commandingOfficer;
// this.teamColor = teamColor;
// this.unitsControlled = new ArrayList<>();
// this.propertiesOwned = new ArrayList<>();
// }
//
// /**
// * @return the player's team color
// */
// public Color getTeamColor() {
// return this.teamColor;
// }
//
// /**
// * @return the amount of money this player has
// */
// public int getMoney() {
// return this.money;
// }
//
// /**
// * @param money a positive integer to set money to
// * @return the amount of money that this player has after execution
// * or -1 if the amount was invalid
// */
// public int setMoney(int money) {
// if (money >= 0) {
// this.money = money;
// return this.money;
// } else {
// return -1;
// }
// }
//
// /**
// * @return a list of all of the units that this player controls
// */
// public ArrayList<Unit> getUnitsControlled() {
// return unitsControlled;
// }
//
// /**
// * @return the number of Units that this player controls
// */
// public int getNumUnitControlled() {
// return getUnitsControlled().size();
// }
//
// /**
// * @return a list of all of the Properties that this player owns
// */
// public ArrayList<Property> getPropertiesOwned() {
// return this.propertiesOwned;
// }
//
// /**
// * @return the number of Properties that this player controls
// */
// public int getNumPropertiesOwned() {
// return getPropertiesOwned().size();
// }
//
// public int getCommTowers() {
// return commTowers;
// }
//
// public void setCommTowers(int commTowers) {
// this.commTowers = commTowers;
// }
//
// public boolean hasHQ() {
// for (Property prop : getPropertiesOwned()) {
// if (prop instanceof HQ) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum MoveType {
// FOOT,
// TIRES,
// TREADS,
// SEA,
// AIR,
// LANDER
// }
// Path: src/main/java/cbskarmory/units/Sea.java
import cbskarmory.Player;
import cbskarmory.PassiveFlag.MoveType;
/*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.units;
/**
* abstract Sea represents all sea units
* Sea units use some fuel every day to stay afloat and
* will sink without fuel.
* These get MoveType.SEA
*/
public abstract class Sea extends Unit {
/**
* calls super(Player) from child classes
* don't invoke this
*
* @param owner owner of unit
*/
public Sea(Player owner) {
super(owner);
}
@Override | public MoveType getMovementType() { |
CBSkarmory/AWGW | src/main/java/cbskarmory/CO/TestCO.java | // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
| import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType; | /*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
public class TestCO extends CO {
@Override
public void power() {
//Nothing
}
@Override
public void superPower() {
//nothing
}
@Override
public int getPowerCost() {
return 99;
}
@Override
public int getSuperPowerCost() {
return 99;
}
@Override | // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
// Path: src/main/java/cbskarmory/CO/TestCO.java
import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType;
/*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
public class TestCO extends CO {
@Override
public void power() {
//Nothing
}
@Override
public void superPower() {
//nothing
}
@Override
public int getPowerCost() {
return 99;
}
@Override
public int getSuperPowerCost() {
return 99;
}
@Override | public double passive(double number, COFlag tag, UnitType unitType) { |
CBSkarmory/AWGW | src/main/java/cbskarmory/CO/TestCO.java | // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
| import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType; | /*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
public class TestCO extends CO {
@Override
public void power() {
//Nothing
}
@Override
public void superPower() {
//nothing
}
@Override
public int getPowerCost() {
return 99;
}
@Override
public int getSuperPowerCost() {
return 99;
}
@Override | // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
// Path: src/main/java/cbskarmory/CO/TestCO.java
import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType;
/*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
public class TestCO extends CO {
@Override
public void power() {
//Nothing
}
@Override
public void superPower() {
//nothing
}
@Override
public int getPowerCost() {
return 99;
}
@Override
public int getSuperPowerCost() {
return 99;
}
@Override | public double passive(double number, COFlag tag, UnitType unitType) { |
CBSkarmory/AWGW | src/main/java/cbskarmory/units/Air.java | // Path: src/main/java/cbskarmory/Player.java
// public class Player {
//
// public static int numberOfPlayers;
// public final CO CO;
// public final int id;
// private ArrayList<Unit> unitsControlled;
// private int money;
// private ArrayList<Property> propertiesOwned;
// private int commTowers;
// private Color teamColor;
//
// /**
// * Constructs a Player
// *
// * @param startingMoney starting amount of money
// * @param teamColor team color to be assigned to this Player
// */
// public Player(CO commandingOfficer, int startingMoney, Color teamColor) {
// //if error when setting starting funds, set to 0
// if (setMoney(startingMoney) == -1) {
// setMoney(0);
// } else {
// setMoney(startingMoney);
// }
// this.id = ++Player.numberOfPlayers;
// this.CO = commandingOfficer;
// this.teamColor = teamColor;
// this.unitsControlled = new ArrayList<>();
// this.propertiesOwned = new ArrayList<>();
// }
//
// /**
// * @return the player's team color
// */
// public Color getTeamColor() {
// return this.teamColor;
// }
//
// /**
// * @return the amount of money this player has
// */
// public int getMoney() {
// return this.money;
// }
//
// /**
// * @param money a positive integer to set money to
// * @return the amount of money that this player has after execution
// * or -1 if the amount was invalid
// */
// public int setMoney(int money) {
// if (money >= 0) {
// this.money = money;
// return this.money;
// } else {
// return -1;
// }
// }
//
// /**
// * @return a list of all of the units that this player controls
// */
// public ArrayList<Unit> getUnitsControlled() {
// return unitsControlled;
// }
//
// /**
// * @return the number of Units that this player controls
// */
// public int getNumUnitControlled() {
// return getUnitsControlled().size();
// }
//
// /**
// * @return a list of all of the Properties that this player owns
// */
// public ArrayList<Property> getPropertiesOwned() {
// return this.propertiesOwned;
// }
//
// /**
// * @return the number of Properties that this player controls
// */
// public int getNumPropertiesOwned() {
// return getPropertiesOwned().size();
// }
//
// public int getCommTowers() {
// return commTowers;
// }
//
// public void setCommTowers(int commTowers) {
// this.commTowers = commTowers;
// }
//
// public boolean hasHQ() {
// for (Property prop : getPropertiesOwned()) {
// if (prop instanceof HQ) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum MoveType {
// FOOT,
// TIRES,
// TREADS,
// SEA,
// AIR,
// LANDER
// }
| import cbskarmory.Player;
import cbskarmory.PassiveFlag.MoveType; | /*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.units;
/**
* abstract Air represents all air units
* Air units use some fuel every day to stay in flight and will crash without fuel.
* These get MoveType.AIR
* Air units traverse all Terrains for 1 mobility
*/
public abstract class Air extends Unit {
/**
* calls super(Player) from child classes
* don't invoke this
*
* @param owner owner of unit
*/
public Air(Player owner) {
super(owner);
}
@Override
public void outOfFuel() {
//TODO crash animation
this.selfDestruct(true);
}
@Override | // Path: src/main/java/cbskarmory/Player.java
// public class Player {
//
// public static int numberOfPlayers;
// public final CO CO;
// public final int id;
// private ArrayList<Unit> unitsControlled;
// private int money;
// private ArrayList<Property> propertiesOwned;
// private int commTowers;
// private Color teamColor;
//
// /**
// * Constructs a Player
// *
// * @param startingMoney starting amount of money
// * @param teamColor team color to be assigned to this Player
// */
// public Player(CO commandingOfficer, int startingMoney, Color teamColor) {
// //if error when setting starting funds, set to 0
// if (setMoney(startingMoney) == -1) {
// setMoney(0);
// } else {
// setMoney(startingMoney);
// }
// this.id = ++Player.numberOfPlayers;
// this.CO = commandingOfficer;
// this.teamColor = teamColor;
// this.unitsControlled = new ArrayList<>();
// this.propertiesOwned = new ArrayList<>();
// }
//
// /**
// * @return the player's team color
// */
// public Color getTeamColor() {
// return this.teamColor;
// }
//
// /**
// * @return the amount of money this player has
// */
// public int getMoney() {
// return this.money;
// }
//
// /**
// * @param money a positive integer to set money to
// * @return the amount of money that this player has after execution
// * or -1 if the amount was invalid
// */
// public int setMoney(int money) {
// if (money >= 0) {
// this.money = money;
// return this.money;
// } else {
// return -1;
// }
// }
//
// /**
// * @return a list of all of the units that this player controls
// */
// public ArrayList<Unit> getUnitsControlled() {
// return unitsControlled;
// }
//
// /**
// * @return the number of Units that this player controls
// */
// public int getNumUnitControlled() {
// return getUnitsControlled().size();
// }
//
// /**
// * @return a list of all of the Properties that this player owns
// */
// public ArrayList<Property> getPropertiesOwned() {
// return this.propertiesOwned;
// }
//
// /**
// * @return the number of Properties that this player controls
// */
// public int getNumPropertiesOwned() {
// return getPropertiesOwned().size();
// }
//
// public int getCommTowers() {
// return commTowers;
// }
//
// public void setCommTowers(int commTowers) {
// this.commTowers = commTowers;
// }
//
// public boolean hasHQ() {
// for (Property prop : getPropertiesOwned()) {
// if (prop instanceof HQ) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum MoveType {
// FOOT,
// TIRES,
// TREADS,
// SEA,
// AIR,
// LANDER
// }
// Path: src/main/java/cbskarmory/units/Air.java
import cbskarmory.Player;
import cbskarmory.PassiveFlag.MoveType;
/*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.units;
/**
* abstract Air represents all air units
* Air units use some fuel every day to stay in flight and will crash without fuel.
* These get MoveType.AIR
* Air units traverse all Terrains for 1 mobility
*/
public abstract class Air extends Unit {
/**
* calls super(Player) from child classes
* don't invoke this
*
* @param owner owner of unit
*/
public Air(Player owner) {
super(owner);
}
@Override
public void outOfFuel() {
//TODO crash animation
this.selfDestruct(true);
}
@Override | public MoveType getMovementType() { |
CBSkarmory/AWGW | src/main/java/cbskarmory/CO/CO.java | // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
| import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType; | /*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
/**
* Commanding Officer: other classes are COs and implement methods. CO itself cannot be instantiated.
*/
public abstract class CO {
//mandatory
public abstract void power();
public abstract void superPower();
public abstract int getPowerCost();
public abstract int getSuperPowerCost();
| // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
// Path: src/main/java/cbskarmory/CO/CO.java
import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType;
/*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
/**
* Commanding Officer: other classes are COs and implement methods. CO itself cannot be instantiated.
*/
public abstract class CO {
//mandatory
public abstract void power();
public abstract void superPower();
public abstract int getPowerCost();
public abstract int getSuperPowerCost();
| public abstract double passive(double number, COFlag tag, UnitType unitType); |
CBSkarmory/AWGW | src/main/java/cbskarmory/CO/CO.java | // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
| import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType; | /*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
/**
* Commanding Officer: other classes are COs and implement methods. CO itself cannot be instantiated.
*/
public abstract class CO {
//mandatory
public abstract void power();
public abstract void superPower();
public abstract int getPowerCost();
public abstract int getSuperPowerCost();
| // Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum COFlag {
// COST,
// ATTACK,
// DEFENSE,
// COUNTER,
// MOVE,
// DAILY_COST,
// STEALTH_COST,
// LUCK,
// CAPTURE
// }
//
// Path: src/main/java/cbskarmory/PassiveFlag.java
// public enum UnitType {
// //land
// INFANTRY,
// MECH,
// RECON,
// APC,
// TANK,
// ARTILLERY,
// MEDIUM_TANK,
// ANTI_AIR,
// ROCKETS,
// MISSILES,
// HEAVY_TANK,
// HOVER_TANK,
//
// //air
// T_COPTER,
// B_COPTER,
// FIGHTER,
// BOMBER,
// CAS,
// S_COPTER,
// STEALTH_BOMBER,
// DROPSHIP,
// ADVANCED_FIGHTER,
// JSF,
//
// //sea
// LANDER,
// CRUISER,
// SUB,
// BATTLESHIP,
// CARRIER,
// ICBM_SUB
// }
// Path: src/main/java/cbskarmory/CO/CO.java
import cbskarmory.PassiveFlag.COFlag;
import cbskarmory.PassiveFlag.UnitType;
/*
* Copyright(c) 2017 CBSkarmory (https://github.com/CBSkarmory)
*
* This code 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.
*
* This code 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.
*
* @author CBSkarmory
*/
package cbskarmory.CO;
/**
* Commanding Officer: other classes are COs and implement methods. CO itself cannot be instantiated.
*/
public abstract class CO {
//mandatory
public abstract void power();
public abstract void superPower();
public abstract int getPowerCost();
public abstract int getSuperPowerCost();
| public abstract double passive(double number, COFlag tag, UnitType unitType); |
sudheerj/primefaces-blueprints | chapter05/src/main/java/com/packt/pfblueprints/dao/AccountSummaryDAO.java | // Path: chapter05/src/main/java/com/packt/pfblueprints/model/AccountSummary.java
// public class AccountSummary implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int id;
// private String investorName;
// private String registeredAccholderName;
// private String accountNumber;
// private String accountType;
// private String status;
// private String registrationDate;
// private String openDate;
// private String closeDate;
// private Boolean jointAccount;
// private String balanceUS;
// private String balanceUK;
//
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getInvestorName() {
// return investorName;
// }
// public void setInvestorName(String investorName) {
// this.investorName = investorName;
// }
// public String getRegisteredAccholderName() {
// return registeredAccholderName;
// }
// public void setRegisteredAccholderName(String registeredAccholderName) {
// this.registeredAccholderName = registeredAccholderName;
// }
// public String getAccountNumber() {
// return accountNumber;
// }
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
// public String getAccountType() {
// return accountType;
// }
// public void setAccountType(String accountType) {
// this.accountType = accountType;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
// public String getRegistrationDate() {
// return registrationDate;
// }
// public void setRegistrationDate(String registrationDate) {
// this.registrationDate = registrationDate;
// }
// public String getOpenDate() {
// return openDate;
// }
// public void setOpenDate(String openDate) {
// this.openDate = openDate;
// }
// public Boolean getJointAccount() {
// return jointAccount;
// }
// public void setJointAccount(Boolean jointAccount) {
// this.jointAccount = jointAccount;
// }
// public String getCloseDate() {
// return closeDate;
// }
// public void setCloseDate(String closeDate) {
// this.closeDate = closeDate;
// }
// public String getBalanceUS() {
// return balanceUS;
// }
// public void setBalanceUS(String balanceUS) {
// this.balanceUS = balanceUS;
// }
// public String getBalanceUK() {
// return balanceUK;
// }
// public void setBalanceUK(String balanceUK) {
// this.balanceUK = balanceUK;
// }
//
//
// }
| import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.AccountSummary;
| package com.packt.pfblueprints.dao;
public class AccountSummaryDAO {
private SessionFactory sessionFactory;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public AccountSummaryDAO() {
super();
// TODO Auto-generated constructor stub
}
| // Path: chapter05/src/main/java/com/packt/pfblueprints/model/AccountSummary.java
// public class AccountSummary implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int id;
// private String investorName;
// private String registeredAccholderName;
// private String accountNumber;
// private String accountType;
// private String status;
// private String registrationDate;
// private String openDate;
// private String closeDate;
// private Boolean jointAccount;
// private String balanceUS;
// private String balanceUK;
//
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getInvestorName() {
// return investorName;
// }
// public void setInvestorName(String investorName) {
// this.investorName = investorName;
// }
// public String getRegisteredAccholderName() {
// return registeredAccholderName;
// }
// public void setRegisteredAccholderName(String registeredAccholderName) {
// this.registeredAccholderName = registeredAccholderName;
// }
// public String getAccountNumber() {
// return accountNumber;
// }
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
// public String getAccountType() {
// return accountType;
// }
// public void setAccountType(String accountType) {
// this.accountType = accountType;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
// public String getRegistrationDate() {
// return registrationDate;
// }
// public void setRegistrationDate(String registrationDate) {
// this.registrationDate = registrationDate;
// }
// public String getOpenDate() {
// return openDate;
// }
// public void setOpenDate(String openDate) {
// this.openDate = openDate;
// }
// public Boolean getJointAccount() {
// return jointAccount;
// }
// public void setJointAccount(Boolean jointAccount) {
// this.jointAccount = jointAccount;
// }
// public String getCloseDate() {
// return closeDate;
// }
// public void setCloseDate(String closeDate) {
// this.closeDate = closeDate;
// }
// public String getBalanceUS() {
// return balanceUS;
// }
// public void setBalanceUS(String balanceUS) {
// this.balanceUS = balanceUS;
// }
// public String getBalanceUK() {
// return balanceUK;
// }
// public void setBalanceUK(String balanceUK) {
// this.balanceUK = balanceUK;
// }
//
//
// }
// Path: chapter05/src/main/java/com/packt/pfblueprints/dao/AccountSummaryDAO.java
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.AccountSummary;
package com.packt.pfblueprints.dao;
public class AccountSummaryDAO {
private SessionFactory sessionFactory;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public AccountSummaryDAO() {
super();
// TODO Auto-generated constructor stub
}
| public List<AccountSummary> getAllAccounts() {
|
sudheerj/primefaces-blueprints | chapter09/src/main/java/com/packtpub/pf/blueprint/controller/ChatResource.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/Message.java
// public class Message {
//
// private String text;
// private String user;
// private boolean updateList;
//
// public Message() {
// }
//
// public Message(String text) {
// this.text = text;
// }
//
// public Message(String text, boolean updateList) {
// this.text = text;
// this.updateList = updateList;
// }
//
// public Message(String user, String text, boolean updateList) {
// this.text = text;
// this.user = user;
// this.updateList = updateList;
// }
//
// public String getText() {
// return text;
// }
//
// public Message setText(String text) {
// this.text = text;
// return this;
// }
//
// public String getUser() {
// return user;
// }
//
// public Message setUser(String user) {
// this.user = user;
// return this;
// }
//
// public boolean isUpdateList() {
// return updateList;
// }
//
// public void setUpdateList(boolean updateList) {
// this.updateList = updateList;
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageDecoder.java
// public class MessageDecoder implements Decoder<String,Message> {
//
// @Override
// public Message decode(String s) {
// String[] userAndMessage = s.split(":");
// if (userAndMessage.length >= 2) {
// return new Message().setUser(userAndMessage[0]).setText(userAndMessage[1]);
// }
// else {
// return new Message(s);
// }
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageEncoder.java
// public final class MessageEncoder implements Encoder<Message, String> {
//
// @Override
// public String encode(Message message) {
// return new JSONObject(message).toString();
// }
//
// }
| import com.packtpub.pf.blueprint.chat.Message;
import com.packtpub.pf.blueprint.chat.MessageDecoder;
import com.packtpub.pf.blueprint.chat.MessageEncoder;
import org.primefaces.push.EventBus;
import org.primefaces.push.RemoteEndpoint;
import org.primefaces.push.annotation.OnClose;
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.OnOpen;
import org.primefaces.push.annotation.PathParam;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.annotation.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.ServletContext; |
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 1/8/14
* Time: 9:00 AM
* To change this template use File | Settings | File Templates.
*/
@PushEndpoint("/{room}/{user}")
@Singleton
public class ChatResource {
private final Logger logger = LoggerFactory.getLogger(ChatResource.class);
@PathParam("room")
private String room;
@PathParam("user")
private String username;
@Inject
private ServletContext ctx;
@OnOpen
public void onOpen(RemoteEndpoint r, EventBus eventBus) {
logger.info("OnOpen {}", r);
eventBus.publish(room + "/*", | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/Message.java
// public class Message {
//
// private String text;
// private String user;
// private boolean updateList;
//
// public Message() {
// }
//
// public Message(String text) {
// this.text = text;
// }
//
// public Message(String text, boolean updateList) {
// this.text = text;
// this.updateList = updateList;
// }
//
// public Message(String user, String text, boolean updateList) {
// this.text = text;
// this.user = user;
// this.updateList = updateList;
// }
//
// public String getText() {
// return text;
// }
//
// public Message setText(String text) {
// this.text = text;
// return this;
// }
//
// public String getUser() {
// return user;
// }
//
// public Message setUser(String user) {
// this.user = user;
// return this;
// }
//
// public boolean isUpdateList() {
// return updateList;
// }
//
// public void setUpdateList(boolean updateList) {
// this.updateList = updateList;
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageDecoder.java
// public class MessageDecoder implements Decoder<String,Message> {
//
// @Override
// public Message decode(String s) {
// String[] userAndMessage = s.split(":");
// if (userAndMessage.length >= 2) {
// return new Message().setUser(userAndMessage[0]).setText(userAndMessage[1]);
// }
// else {
// return new Message(s);
// }
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageEncoder.java
// public final class MessageEncoder implements Encoder<Message, String> {
//
// @Override
// public String encode(Message message) {
// return new JSONObject(message).toString();
// }
//
// }
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/controller/ChatResource.java
import com.packtpub.pf.blueprint.chat.Message;
import com.packtpub.pf.blueprint.chat.MessageDecoder;
import com.packtpub.pf.blueprint.chat.MessageEncoder;
import org.primefaces.push.EventBus;
import org.primefaces.push.RemoteEndpoint;
import org.primefaces.push.annotation.OnClose;
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.OnOpen;
import org.primefaces.push.annotation.PathParam;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.annotation.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.ServletContext;
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 1/8/14
* Time: 9:00 AM
* To change this template use File | Settings | File Templates.
*/
@PushEndpoint("/{room}/{user}")
@Singleton
public class ChatResource {
private final Logger logger = LoggerFactory.getLogger(ChatResource.class);
@PathParam("room")
private String room;
@PathParam("user")
private String username;
@Inject
private ServletContext ctx;
@OnOpen
public void onOpen(RemoteEndpoint r, EventBus eventBus) {
logger.info("OnOpen {}", r);
eventBus.publish(room + "/*", | new Message(String.format("%s has entered the room '%s'", |
sudheerj/primefaces-blueprints | chapter09/src/main/java/com/packtpub/pf/blueprint/controller/ChatResource.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/Message.java
// public class Message {
//
// private String text;
// private String user;
// private boolean updateList;
//
// public Message() {
// }
//
// public Message(String text) {
// this.text = text;
// }
//
// public Message(String text, boolean updateList) {
// this.text = text;
// this.updateList = updateList;
// }
//
// public Message(String user, String text, boolean updateList) {
// this.text = text;
// this.user = user;
// this.updateList = updateList;
// }
//
// public String getText() {
// return text;
// }
//
// public Message setText(String text) {
// this.text = text;
// return this;
// }
//
// public String getUser() {
// return user;
// }
//
// public Message setUser(String user) {
// this.user = user;
// return this;
// }
//
// public boolean isUpdateList() {
// return updateList;
// }
//
// public void setUpdateList(boolean updateList) {
// this.updateList = updateList;
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageDecoder.java
// public class MessageDecoder implements Decoder<String,Message> {
//
// @Override
// public Message decode(String s) {
// String[] userAndMessage = s.split(":");
// if (userAndMessage.length >= 2) {
// return new Message().setUser(userAndMessage[0]).setText(userAndMessage[1]);
// }
// else {
// return new Message(s);
// }
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageEncoder.java
// public final class MessageEncoder implements Encoder<Message, String> {
//
// @Override
// public String encode(Message message) {
// return new JSONObject(message).toString();
// }
//
// }
| import com.packtpub.pf.blueprint.chat.Message;
import com.packtpub.pf.blueprint.chat.MessageDecoder;
import com.packtpub.pf.blueprint.chat.MessageEncoder;
import org.primefaces.push.EventBus;
import org.primefaces.push.RemoteEndpoint;
import org.primefaces.push.annotation.OnClose;
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.OnOpen;
import org.primefaces.push.annotation.PathParam;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.annotation.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.ServletContext; |
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 1/8/14
* Time: 9:00 AM
* To change this template use File | Settings | File Templates.
*/
@PushEndpoint("/{room}/{user}")
@Singleton
public class ChatResource {
private final Logger logger = LoggerFactory.getLogger(ChatResource.class);
@PathParam("room")
private String room;
@PathParam("user")
private String username;
@Inject
private ServletContext ctx;
@OnOpen
public void onOpen(RemoteEndpoint r, EventBus eventBus) {
logger.info("OnOpen {}", r);
eventBus.publish(room + "/*",
new Message(String.format("%s has entered the room '%s'",
username, room), true));
}
@OnClose
public void onClose(RemoteEndpoint r, EventBus eventBus) {
ChatUsers users= (ChatUsers) ctx.getAttribute("chatUsers");
users.remove(username);
eventBus.publish(room + "/*", new Message(String.format("%s has left the room", username), true));
}
| // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/Message.java
// public class Message {
//
// private String text;
// private String user;
// private boolean updateList;
//
// public Message() {
// }
//
// public Message(String text) {
// this.text = text;
// }
//
// public Message(String text, boolean updateList) {
// this.text = text;
// this.updateList = updateList;
// }
//
// public Message(String user, String text, boolean updateList) {
// this.text = text;
// this.user = user;
// this.updateList = updateList;
// }
//
// public String getText() {
// return text;
// }
//
// public Message setText(String text) {
// this.text = text;
// return this;
// }
//
// public String getUser() {
// return user;
// }
//
// public Message setUser(String user) {
// this.user = user;
// return this;
// }
//
// public boolean isUpdateList() {
// return updateList;
// }
//
// public void setUpdateList(boolean updateList) {
// this.updateList = updateList;
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageDecoder.java
// public class MessageDecoder implements Decoder<String,Message> {
//
// @Override
// public Message decode(String s) {
// String[] userAndMessage = s.split(":");
// if (userAndMessage.length >= 2) {
// return new Message().setUser(userAndMessage[0]).setText(userAndMessage[1]);
// }
// else {
// return new Message(s);
// }
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageEncoder.java
// public final class MessageEncoder implements Encoder<Message, String> {
//
// @Override
// public String encode(Message message) {
// return new JSONObject(message).toString();
// }
//
// }
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/controller/ChatResource.java
import com.packtpub.pf.blueprint.chat.Message;
import com.packtpub.pf.blueprint.chat.MessageDecoder;
import com.packtpub.pf.blueprint.chat.MessageEncoder;
import org.primefaces.push.EventBus;
import org.primefaces.push.RemoteEndpoint;
import org.primefaces.push.annotation.OnClose;
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.OnOpen;
import org.primefaces.push.annotation.PathParam;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.annotation.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.ServletContext;
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 1/8/14
* Time: 9:00 AM
* To change this template use File | Settings | File Templates.
*/
@PushEndpoint("/{room}/{user}")
@Singleton
public class ChatResource {
private final Logger logger = LoggerFactory.getLogger(ChatResource.class);
@PathParam("room")
private String room;
@PathParam("user")
private String username;
@Inject
private ServletContext ctx;
@OnOpen
public void onOpen(RemoteEndpoint r, EventBus eventBus) {
logger.info("OnOpen {}", r);
eventBus.publish(room + "/*",
new Message(String.format("%s has entered the room '%s'",
username, room), true));
}
@OnClose
public void onClose(RemoteEndpoint r, EventBus eventBus) {
ChatUsers users= (ChatUsers) ctx.getAttribute("chatUsers");
users.remove(username);
eventBus.publish(room + "/*", new Message(String.format("%s has left the room", username), true));
}
| @OnMessage(decoders = {MessageDecoder.class}, encoders = {MessageEncoder.class}) |
sudheerj/primefaces-blueprints | chapter09/src/main/java/com/packtpub/pf/blueprint/controller/ChatResource.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/Message.java
// public class Message {
//
// private String text;
// private String user;
// private boolean updateList;
//
// public Message() {
// }
//
// public Message(String text) {
// this.text = text;
// }
//
// public Message(String text, boolean updateList) {
// this.text = text;
// this.updateList = updateList;
// }
//
// public Message(String user, String text, boolean updateList) {
// this.text = text;
// this.user = user;
// this.updateList = updateList;
// }
//
// public String getText() {
// return text;
// }
//
// public Message setText(String text) {
// this.text = text;
// return this;
// }
//
// public String getUser() {
// return user;
// }
//
// public Message setUser(String user) {
// this.user = user;
// return this;
// }
//
// public boolean isUpdateList() {
// return updateList;
// }
//
// public void setUpdateList(boolean updateList) {
// this.updateList = updateList;
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageDecoder.java
// public class MessageDecoder implements Decoder<String,Message> {
//
// @Override
// public Message decode(String s) {
// String[] userAndMessage = s.split(":");
// if (userAndMessage.length >= 2) {
// return new Message().setUser(userAndMessage[0]).setText(userAndMessage[1]);
// }
// else {
// return new Message(s);
// }
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageEncoder.java
// public final class MessageEncoder implements Encoder<Message, String> {
//
// @Override
// public String encode(Message message) {
// return new JSONObject(message).toString();
// }
//
// }
| import com.packtpub.pf.blueprint.chat.Message;
import com.packtpub.pf.blueprint.chat.MessageDecoder;
import com.packtpub.pf.blueprint.chat.MessageEncoder;
import org.primefaces.push.EventBus;
import org.primefaces.push.RemoteEndpoint;
import org.primefaces.push.annotation.OnClose;
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.OnOpen;
import org.primefaces.push.annotation.PathParam;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.annotation.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.ServletContext; |
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 1/8/14
* Time: 9:00 AM
* To change this template use File | Settings | File Templates.
*/
@PushEndpoint("/{room}/{user}")
@Singleton
public class ChatResource {
private final Logger logger = LoggerFactory.getLogger(ChatResource.class);
@PathParam("room")
private String room;
@PathParam("user")
private String username;
@Inject
private ServletContext ctx;
@OnOpen
public void onOpen(RemoteEndpoint r, EventBus eventBus) {
logger.info("OnOpen {}", r);
eventBus.publish(room + "/*",
new Message(String.format("%s has entered the room '%s'",
username, room), true));
}
@OnClose
public void onClose(RemoteEndpoint r, EventBus eventBus) {
ChatUsers users= (ChatUsers) ctx.getAttribute("chatUsers");
users.remove(username);
eventBus.publish(room + "/*", new Message(String.format("%s has left the room", username), true));
}
| // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/Message.java
// public class Message {
//
// private String text;
// private String user;
// private boolean updateList;
//
// public Message() {
// }
//
// public Message(String text) {
// this.text = text;
// }
//
// public Message(String text, boolean updateList) {
// this.text = text;
// this.updateList = updateList;
// }
//
// public Message(String user, String text, boolean updateList) {
// this.text = text;
// this.user = user;
// this.updateList = updateList;
// }
//
// public String getText() {
// return text;
// }
//
// public Message setText(String text) {
// this.text = text;
// return this;
// }
//
// public String getUser() {
// return user;
// }
//
// public Message setUser(String user) {
// this.user = user;
// return this;
// }
//
// public boolean isUpdateList() {
// return updateList;
// }
//
// public void setUpdateList(boolean updateList) {
// this.updateList = updateList;
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageDecoder.java
// public class MessageDecoder implements Decoder<String,Message> {
//
// @Override
// public Message decode(String s) {
// String[] userAndMessage = s.split(":");
// if (userAndMessage.length >= 2) {
// return new Message().setUser(userAndMessage[0]).setText(userAndMessage[1]);
// }
// else {
// return new Message(s);
// }
// }
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/chat/MessageEncoder.java
// public final class MessageEncoder implements Encoder<Message, String> {
//
// @Override
// public String encode(Message message) {
// return new JSONObject(message).toString();
// }
//
// }
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/controller/ChatResource.java
import com.packtpub.pf.blueprint.chat.Message;
import com.packtpub.pf.blueprint.chat.MessageDecoder;
import com.packtpub.pf.blueprint.chat.MessageEncoder;
import org.primefaces.push.EventBus;
import org.primefaces.push.RemoteEndpoint;
import org.primefaces.push.annotation.OnClose;
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.OnOpen;
import org.primefaces.push.annotation.PathParam;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.annotation.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.ServletContext;
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 1/8/14
* Time: 9:00 AM
* To change this template use File | Settings | File Templates.
*/
@PushEndpoint("/{room}/{user}")
@Singleton
public class ChatResource {
private final Logger logger = LoggerFactory.getLogger(ChatResource.class);
@PathParam("room")
private String room;
@PathParam("user")
private String username;
@Inject
private ServletContext ctx;
@OnOpen
public void onOpen(RemoteEndpoint r, EventBus eventBus) {
logger.info("OnOpen {}", r);
eventBus.publish(room + "/*",
new Message(String.format("%s has entered the room '%s'",
username, room), true));
}
@OnClose
public void onClose(RemoteEndpoint r, EventBus eventBus) {
ChatUsers users= (ChatUsers) ctx.getAttribute("chatUsers");
users.remove(username);
eventBus.publish(room + "/*", new Message(String.format("%s has left the room", username), true));
}
| @OnMessage(decoders = {MessageDecoder.class}, encoders = {MessageEncoder.class}) |
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java | // Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/ProgressStatus.java
// public class ProgressStatus{
// private String year;
// private String percentage;
//
// public ProgressStatus(String year, String percentage) {
// super();
// this.year = year;
// this.percentage = percentage;
// }
//
// public ProgressStatus() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public String getYear() {
// return year;
// }
// public void setYear(String year) {
// this.year = year;
// }
// public String getPercentage() {
// return percentage;
// }
// public void setPercentage(String percentage) {
// this.percentage = percentage;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.Advisor;
import com.packt.pfblueprints.model.ProgressStatus;
| package com.packt.pfblueprints.dao;
public class DealerDAO {
private SessionFactory sessionFactory;
private String dealerNumber;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public DealerDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
dealerNumber=(String) sessionMap.get("dealertinnumber");
// TODO Auto-generated constructor stub
}
| // Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/ProgressStatus.java
// public class ProgressStatus{
// private String year;
// private String percentage;
//
// public ProgressStatus(String year, String percentage) {
// super();
// this.year = year;
// this.percentage = percentage;
// }
//
// public ProgressStatus() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public String getYear() {
// return year;
// }
// public void setYear(String year) {
// this.year = year;
// }
// public String getPercentage() {
// return percentage;
// }
// public void setPercentage(String percentage) {
// this.percentage = percentage;
// }
//
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.Advisor;
import com.packt.pfblueprints.model.ProgressStatus;
package com.packt.pfblueprints.dao;
public class DealerDAO {
private SessionFactory sessionFactory;
private String dealerNumber;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public DealerDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
dealerNumber=(String) sessionMap.get("dealertinnumber");
// TODO Auto-generated constructor stub
}
| public List<Advisor> getAllAdvisors() {
|
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java | // Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/ProgressStatus.java
// public class ProgressStatus{
// private String year;
// private String percentage;
//
// public ProgressStatus(String year, String percentage) {
// super();
// this.year = year;
// this.percentage = percentage;
// }
//
// public ProgressStatus() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public String getYear() {
// return year;
// }
// public void setYear(String year) {
// this.year = year;
// }
// public String getPercentage() {
// return percentage;
// }
// public void setPercentage(String percentage) {
// this.percentage = percentage;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.Advisor;
import com.packt.pfblueprints.model.ProgressStatus;
| configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public DealerDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
dealerNumber=(String) sessionMap.get("dealertinnumber");
// TODO Auto-generated constructor stub
}
public List<Advisor> getAllAdvisors() {
sessionFactory = configureSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query queryResult=null;
if(dealerNumber!=""){
queryResult = session.createQuery("from Advisor where dealernumber = :dealerNum");
queryResult.setParameter("dealerNum", dealerNumber);
}else{
queryResult = session.createQuery("from Advisor");
}
List<Advisor> allDealers = queryResult.list();
for(Advisor dealerobj:allDealers){
| // Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/ProgressStatus.java
// public class ProgressStatus{
// private String year;
// private String percentage;
//
// public ProgressStatus(String year, String percentage) {
// super();
// this.year = year;
// this.percentage = percentage;
// }
//
// public ProgressStatus() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public String getYear() {
// return year;
// }
// public void setYear(String year) {
// this.year = year;
// }
// public String getPercentage() {
// return percentage;
// }
// public void setPercentage(String percentage) {
// this.percentage = percentage;
// }
//
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.Advisor;
import com.packt.pfblueprints.model.ProgressStatus;
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public DealerDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
dealerNumber=(String) sessionMap.get("dealertinnumber");
// TODO Auto-generated constructor stub
}
public List<Advisor> getAllAdvisors() {
sessionFactory = configureSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query queryResult=null;
if(dealerNumber!=""){
queryResult = session.createQuery("from Advisor where dealernumber = :dealerNum");
queryResult.setParameter("dealerNum", dealerNumber);
}else{
queryResult = session.createQuery("from Advisor");
}
List<Advisor> allDealers = queryResult.list();
for(Advisor dealerobj:allDealers){
| List<ProgressStatus> progressStatus=generateProgressStatus();
|
sudheerj/primefaces-blueprints | chapter08/src/main/java/com/packtpub/pf/blueprint/persistence/entity/PrintJobs.java | // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/JobStatus.java
// public enum JobStatus {
// SUBMITTED("SUBMITTED"), REJECTED("REJECTED"), CANCELED("CANCELED"), PROCESS("PROCESS"), COMPLETED("COMPLETED");
//
//
// private final String name;
//
// JobStatus(final String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import com.packtpub.pf.blueprint.JobStatus;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Date; | package com.packtpub.pf.blueprint.persistence.entity;
/**
* Created by psramkumar on 4/29/14.
*/
@Entity
@Table
public class PrintJobs implements java.io.Serializable {
@Id
@GeneratedValue
@Getter @Setter private Long id;
@Getter @Setter private String jobRefId;
@Getter @Setter private String jobName;
@Getter @Setter private String jobDescription;
@Getter @Setter private String fileName;
@Getter @Setter private int noOfPrints;
@Getter @Setter private int pageStart = 1;
@Getter @Setter private int pageEnd;
@Getter @Setter private boolean pageRange;
| // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/JobStatus.java
// public enum JobStatus {
// SUBMITTED("SUBMITTED"), REJECTED("REJECTED"), CANCELED("CANCELED"), PROCESS("PROCESS"), COMPLETED("COMPLETED");
//
//
// private final String name;
//
// JobStatus(final String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/persistence/entity/PrintJobs.java
import com.packtpub.pf.blueprint.JobStatus;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Date;
package com.packtpub.pf.blueprint.persistence.entity;
/**
* Created by psramkumar on 4/29/14.
*/
@Entity
@Table
public class PrintJobs implements java.io.Serializable {
@Id
@GeneratedValue
@Getter @Setter private Long id;
@Getter @Setter private String jobRefId;
@Getter @Setter private String jobName;
@Getter @Setter private String jobDescription;
@Getter @Setter private String fileName;
@Getter @Setter private int noOfPrints;
@Getter @Setter private int pageStart = 1;
@Getter @Setter private int pageEnd;
@Getter @Setter private boolean pageRange;
| @Getter @Setter private JobStatus status; |
sudheerj/primefaces-blueprints | chapter08/src/main/java/com/packtpub/pf/blueprint/controller/CustomerController.java | // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Customer.java
// @Data
// @Entity
// @Table
// public class Customer implements Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
// private String lastName;
// private String email;
// private String password;
// private String phoneNumber;
//
// @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER)
// private List<PrintJobs> jobs = new ArrayList<>();
//
//
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
| import com.packtpub.pf.blueprint.persistence.entity.Customer;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable; | package com.packtpub.pf.blueprint.controller;
/**
* Created by psramkumar on 4/21/14.
*/
@ManagedBean
@SessionScoped
public class CustomerController implements Serializable {
private static final long serialVersionUID = -1890125026548028469L;
private Logger _log = Logger.getLogger(CustomerController.class);
@Getter
@Setter | // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Customer.java
// @Data
// @Entity
// @Table
// public class Customer implements Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
// private String lastName;
// private String email;
// private String password;
// private String phoneNumber;
//
// @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER)
// private List<PrintJobs> jobs = new ArrayList<>();
//
//
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/controller/CustomerController.java
import com.packtpub.pf.blueprint.persistence.entity.Customer;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
package com.packtpub.pf.blueprint.controller;
/**
* Created by psramkumar on 4/21/14.
*/
@ManagedBean
@SessionScoped
public class CustomerController implements Serializable {
private static final long serialVersionUID = -1890125026548028469L;
private Logger _log = Logger.getLogger(CustomerController.class);
@Getter
@Setter | private Customer customer; |
sudheerj/primefaces-blueprints | chapter08/src/main/java/com/packtpub/pf/blueprint/controller/CustomerController.java | // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Customer.java
// @Data
// @Entity
// @Table
// public class Customer implements Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
// private String lastName;
// private String email;
// private String password;
// private String phoneNumber;
//
// @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER)
// private List<PrintJobs> jobs = new ArrayList<>();
//
//
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
| import com.packtpub.pf.blueprint.persistence.entity.Customer;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable; | package com.packtpub.pf.blueprint.controller;
/**
* Created by psramkumar on 4/21/14.
*/
@ManagedBean
@SessionScoped
public class CustomerController implements Serializable {
private static final long serialVersionUID = -1890125026548028469L;
private Logger _log = Logger.getLogger(CustomerController.class);
@Getter
@Setter
private Customer customer;
@Getter
@Setter
private Customer newCustomer = new Customer();
@Getter
@Setter
private String useremail;
@Getter
@Setter
private String password;
@Getter
@Setter
private boolean loggedIn = false;
| // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Customer.java
// @Data
// @Entity
// @Table
// public class Customer implements Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
// private String lastName;
// private String email;
// private String password;
// private String phoneNumber;
//
// @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER)
// private List<PrintJobs> jobs = new ArrayList<>();
//
//
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/controller/CustomerController.java
import com.packtpub.pf.blueprint.persistence.entity.Customer;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
package com.packtpub.pf.blueprint.controller;
/**
* Created by psramkumar on 4/21/14.
*/
@ManagedBean
@SessionScoped
public class CustomerController implements Serializable {
private static final long serialVersionUID = -1890125026548028469L;
private Logger _log = Logger.getLogger(CustomerController.class);
@Getter
@Setter
private Customer customer;
@Getter
@Setter
private Customer newCustomer = new Customer();
@Getter
@Setter
private String useremail;
@Getter
@Setter
private String password;
@Getter
@Setter
private boolean loggedIn = false;
| DAOService ds = new DAOService(); |
sudheerj/primefaces-blueprints | chapter08/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java | // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
| import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger; | package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class.getName());
@PostConstruct
public void init() {
log.info ("Current Lati & longi : $currentLati & $currentLong" );
populateLocationCoordinates();
}
| // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java
import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class.getName());
@PostConstruct
public void init() {
log.info ("Current Lati & longi : $currentLati & $currentLong" );
populateLocationCoordinates();
}
| DAOService ds = new DAOService(); |
sudheerj/primefaces-blueprints | chapter08/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java | // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
| import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger; | package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class.getName());
@PostConstruct
public void init() {
log.info ("Current Lati & longi : $currentLati & $currentLong" );
populateLocationCoordinates();
}
DAOService ds = new DAOService();
public void onMarkerSelect(OverlaySelectEvent event) {
marker = (Marker) event.getOverlay();
location = ds.getLocationByFranchiseeNo((Long) marker.getData());
}
private void populateLocationCoordinates(){ | // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java
import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class.getName());
@PostConstruct
public void init() {
log.info ("Current Lati & longi : $currentLati & $currentLong" );
populateLocationCoordinates();
}
DAOService ds = new DAOService();
public void onMarkerSelect(OverlaySelectEvent event) {
marker = (Marker) event.getOverlay();
location = ds.getLocationByFranchiseeNo((Long) marker.getData());
}
private void populateLocationCoordinates(){ | List<Location> locations = ds.getAllLocations(); |
sudheerj/primefaces-blueprints | chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java | // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/JobStatus.java
// public enum JobStatus {
// SUBMITTED("SUBMITTED"), REJECTED("REJECTED"), CANCELED("CANCELED"), PROCESS("PROCESS"), COMPLETED("COMPLETED");
//
//
// private final String name;
//
// JobStatus(final String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import com.packtpub.pf.blueprint.JobStatus;
import com.packtpub.pf.blueprint.persistence.entity.*;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.List; | _log.info("Added Successfully....");
}
}
public Object loadEntityById(Class<?> cl, Long id) {
Object o = null;
if (id != null) {
org.hibernate.Transaction tx = getSession().beginTransaction();
o = getSession().load(cl, id);
tx.commit();
getSession().close();
_log.info(" Successfully Loaded Object....");
}
return o;
}
public List<PrintJobs> getJobsByCustomerId(Customer c) {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(PrintJobs.class)
.add(Restrictions.eq("customer", c))
.addOrder(Order.desc("createDate")).list();
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return list;
}
public List<PrintJobs> getJobsBySubmittedStatus() {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(PrintJobs.class) | // Path: chapter08/src/main/java/com/packtpub/pf/blueprint/JobStatus.java
// public enum JobStatus {
// SUBMITTED("SUBMITTED"), REJECTED("REJECTED"), CANCELED("CANCELED"), PROCESS("PROCESS"), COMPLETED("COMPLETED");
//
//
// private final String name;
//
// JobStatus(final String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
import com.packtpub.pf.blueprint.JobStatus;
import com.packtpub.pf.blueprint.persistence.entity.*;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.List;
_log.info("Added Successfully....");
}
}
public Object loadEntityById(Class<?> cl, Long id) {
Object o = null;
if (id != null) {
org.hibernate.Transaction tx = getSession().beginTransaction();
o = getSession().load(cl, id);
tx.commit();
getSession().close();
_log.info(" Successfully Loaded Object....");
}
return o;
}
public List<PrintJobs> getJobsByCustomerId(Customer c) {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(PrintJobs.class)
.add(Restrictions.eq("customer", c))
.addOrder(Order.desc("createDate")).list();
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return list;
}
public List<PrintJobs> getJobsBySubmittedStatus() {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(PrintJobs.class) | .add(Restrictions.eq("status", JobStatus.SUBMITTED)) |
sudheerj/primefaces-blueprints | chapter07/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java | // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
| import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import java.io.Serializable;
import java.util.List; | package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class);
| // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java
import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import java.io.Serializable;
import java.util.List;
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class);
| DAOService ds = new DAOService(); |
sudheerj/primefaces-blueprints | chapter07/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java | // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
| import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import java.io.Serializable;
import java.util.List; | package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class);
DAOService ds = new DAOService();
@PostConstruct
public void init() {
log.info ("Current Lati & longi : $currentLati & $currentLong" );
populateLocationCoordinates();
}
public void onMarkerSelect(OverlaySelectEvent event) {
marker = (Marker) event.getOverlay();
}
private void populateLocationCoordinates(){ | // Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
//
// Path: chapter08/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
// public class DAOService {
// private static final Logger _log = Logger.getLogger(DAOService.class);
// public final String OPEN_STATUS = "OPEN";
//
// public Customer validateUser(String username, String password) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Customer.class);
// criteria.add(Restrictions.eq("email", username));
// criteria.add(Restrictions.eq("password", password));
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// Customer user = (Customer) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return user;
// }
//
// public List<Location> getAllLocations(){
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(Location.class).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public void addOrUpdateEntity(Object o) {
// if (o != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// getSession().saveOrUpdate(o);
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// }
//
// public Object loadEntityById(Class<?> cl, Long id) {
// Object o = null;
// if (id != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// o = getSession().load(cl, id);
// tx.commit();
// getSession().close();
// _log.info(" Successfully Loaded Object....");
// }
// return o;
// }
//
// public List<PrintJobs> getJobsByCustomerId(Customer c) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("customer", c))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
// public List<PrintJobs> getJobsBySubmittedStatus() {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// List list = getSession().createCriteria(PrintJobs.class)
// .add(Restrictions.eq("status", JobStatus.SUBMITTED))
// .addOrder(Order.desc("createDate")).list();
// tx.commit();
// getSession().close();
// _log.info("Listed Successfully....");
// return list;
// }
//
//
// public Location getLocationByFranchiseeNo(Long franchiseeNo){
// Location loc = null;
// if (franchiseeNo != null) {
// org.hibernate.Transaction tx = getSession().beginTransaction();
// Criteria criteria = getSession().createCriteria(Location.class);
// criteria.add(Restrictions.eq("franchiseeNo", franchiseeNo));
// loc = (Location) criteria.uniqueResult();
// tx.commit();
// getSession().close();
// _log.info("Added Successfully....");
// }
// return loc;
//
// }
//
// private Session getSession() {
// SessionFactory sf = com.packtpub.pf.blueprint.persistence.HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
//
// }
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/controller/LocationController.java
import com.packtpub.pf.blueprint.persistence.entity.Location;
import com.packtpub.pf.blueprint.service.DAOService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import java.io.Serializable;
import java.util.List;
package com.packtpub.pf.blueprint.controller;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai
* Date: 3/30/14
* Time: 7:50 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@SessionScoped
public class LocationController implements Serializable {
private static final Logger log = Logger.getLogger(LocationController.class);
DAOService ds = new DAOService();
@PostConstruct
public void init() {
log.info ("Current Lati & longi : $currentLati & $currentLong" );
populateLocationCoordinates();
}
public void onMarkerSelect(OverlaySelectEvent event) {
marker = (Marker) event.getOverlay();
}
private void populateLocationCoordinates(){ | List<Location> locations = ds.getAllLocations(); |
sudheerj/primefaces-blueprints | chapter08/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Location;
import org.hibernate.Session;
import java.util.List; | package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class"); | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
// Path: chapter08/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Location;
import org.hibernate.Session;
import java.util.List;
package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class"); | Session session = HibernateUtil.getSessionFactory().openSession(); |
sudheerj/primefaces-blueprints | chapter08/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Location;
import org.hibernate.Session;
import java.util.List; | package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Location.java
// @Data
// @Entity
// @Table
// public class Location implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private int id;
// @NaturalId
// @Basic(optional = false)
// @Column(name = "franchisee_no")
// Long franchiseeNo;
// @Basic(optional = false)
// double longitude;
// @Basic(optional = false)
// double latitude;
// @Basic(optional = false)
// String street1;
// @Basic(optional = false)
// String city;
// String state;
// @Basic(optional = false)
// String zipcode;
// String country;
// }
// Path: chapter08/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Location;
import org.hibernate.Session;
import java.util.List;
package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); | Location loc = new Location(); |
sudheerj/primefaces-blueprints | chapter02/src/main/java/com/packt/pfblueprints/controller/LoginController.java | // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/LoginDAO.java
// public class LoginDAO {
//
// private DataSource ds;
// Connection con;
//
// public LoginDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null) {
// throw new SQLException("Can't get data source");
// }
// // get database connection
// con = ds.getConnection();
// if (con == null) {
// throw new SQLException("Can't get database connection");
// }
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
//
// public boolean changepassword(String userid, String oldpassword,
// String newpassword) {
// try {
// // Persist employee
// PreparedStatement ps = con
// .prepareStatement("UPDATE blueprintsdb.employee SET password='"
// + newpassword
// + "' WHERE userid='"
// + userid + "' and password='" + oldpassword + "'");
// int count = ps.executeUpdate();
// return (count > 0);
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
//
// }
//
// public boolean validateUser(String userid, String password) {
// try {
// // Check the logged jobseeker is valid user or not
// PreparedStatement ps = con
// .prepareStatement("select * FROM blueprintsdb.employee WHERE userid='"
// + userid + "' and password='" + password + "'");
// ResultSet resultSet = ps.executeQuery();
// if (resultSet.next()) {
// return true;
// } else {
// return false;
// }
//
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
// }
// }
| import java.io.Serializable;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.bean.ViewScoped;
import javax.faces.bean.ManagedBean;
import com.packt.pfblueprints.dao.LoginDAO; | package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class LoginController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String newpassword;
public LoginController() {
super();
}
public String validateUser() throws SQLException {
FacesMessage msg = null;
boolean isValidUser = false;
if (username.equalsIgnoreCase("admin")
&& password.equalsIgnoreCase("admin")) {
return "/views/admin?faces-redirect=true";
}
| // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/LoginDAO.java
// public class LoginDAO {
//
// private DataSource ds;
// Connection con;
//
// public LoginDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null) {
// throw new SQLException("Can't get data source");
// }
// // get database connection
// con = ds.getConnection();
// if (con == null) {
// throw new SQLException("Can't get database connection");
// }
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
//
// public boolean changepassword(String userid, String oldpassword,
// String newpassword) {
// try {
// // Persist employee
// PreparedStatement ps = con
// .prepareStatement("UPDATE blueprintsdb.employee SET password='"
// + newpassword
// + "' WHERE userid='"
// + userid + "' and password='" + oldpassword + "'");
// int count = ps.executeUpdate();
// return (count > 0);
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
//
// }
//
// public boolean validateUser(String userid, String password) {
// try {
// // Check the logged jobseeker is valid user or not
// PreparedStatement ps = con
// .prepareStatement("select * FROM blueprintsdb.employee WHERE userid='"
// + userid + "' and password='" + password + "'");
// ResultSet resultSet = ps.executeQuery();
// if (resultSet.next()) {
// return true;
// } else {
// return false;
// }
//
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
// }
// }
// Path: chapter02/src/main/java/com/packt/pfblueprints/controller/LoginController.java
import java.io.Serializable;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.bean.ViewScoped;
import javax.faces.bean.ManagedBean;
import com.packt.pfblueprints.dao.LoginDAO;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class LoginController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String newpassword;
public LoginController() {
super();
}
public String validateUser() throws SQLException {
FacesMessage msg = null;
boolean isValidUser = false;
if (username.equalsIgnoreCase("admin")
&& password.equalsIgnoreCase("admin")) {
return "/views/admin?faces-redirect=true";
}
| LoginDAO dao = new LoginDAO(); |
sudheerj/primefaces-blueprints | chapter10/src/main/java/com/packt/pfblueprints/controller/HealthkartController.java | // Path: chapter10/src/main/java/com/packt/pfblueprints/model/Product.java
// @Entity
// @Table
// public class Product implements Serializable{
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue
// private Long id;
//
// private String prodname;
// private String prodimage;
// private String prodcat;
// private int rating;
// private String discount;
// private String price;
//
//
// public Product() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public Product(String prodname,String prodimage,String prodcat,int rating, String discount,String price) {
// super();
// this.prodname = prodname;
// this.prodimage = prodimage;
// this.prodcat = prodcat;
// this.rating = rating;
// this.discount = discount;
// this.price = price;
// }
//
// public String getProdname() {
// return prodname;
// }
//
// public void setProdname(String prodname) {
// this.prodname = prodname;
// }
//
// public String getProdimage() {
// return prodimage;
// }
//
// public void setProdimage(String prodimage) {
// this.prodimage = prodimage;
// }
//
// public String getProdcat() {
// return prodcat;
// }
//
// public void setProdcat(String prodcat) {
// this.prodcat = prodcat;
// }
//
// public String getPrice() {
// return price;
// }
//
// public void setPrice(String price) {
// this.price = price;
// }
//
// public String getDiscount() {
// return discount;
// }
//
// public void setDiscount(String discount) {
// this.discount = discount;
// }
//
// public void setRating(int rating) {
// this.rating = rating;
// }
//
// public int getRating() {
// return rating;
// }
// }
//
// Path: chapter10/src/main/java/com/packt/pfblueprints/dao/ProductsDAO.java
// public class ProductsDAO {
//
// private String productCategory;
//
// public ProductsDAO() {
// super();
// }
//
// public List<Product> getAllProducts(int first, int pageSize,
// String sortField, String sortOrderValue, Map<String, Object> filters) {
// Session session = getSession();// sessionFactory.openSession();
// session.beginTransaction();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance()
// .getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// productCategory = (String) sessionMap.get("productCategory");
// String query = null;
//
// Query queryResult=null;
// if (productCategory != "") {
// query = "from Product where prodcat = :productCategory ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// queryResult.setParameter("productCategory", productCategory);
// } else {
// query = "from Product ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// }
// List<Product> allProducts = queryResult.list();
// session.getTransaction().commit();
// return allProducts;
//
// }
//
// private Session getSession() {
// SessionFactory sf = HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
// }
| import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.TreeNode;
import com.packt.pfblueprints.model.Product;
import com.packt.pfblueprints.dao.ProductsDAO;
| package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class HealthkartController implements Serializable {
private static final long serialVersionUID = 1L;
| // Path: chapter10/src/main/java/com/packt/pfblueprints/model/Product.java
// @Entity
// @Table
// public class Product implements Serializable{
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue
// private Long id;
//
// private String prodname;
// private String prodimage;
// private String prodcat;
// private int rating;
// private String discount;
// private String price;
//
//
// public Product() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public Product(String prodname,String prodimage,String prodcat,int rating, String discount,String price) {
// super();
// this.prodname = prodname;
// this.prodimage = prodimage;
// this.prodcat = prodcat;
// this.rating = rating;
// this.discount = discount;
// this.price = price;
// }
//
// public String getProdname() {
// return prodname;
// }
//
// public void setProdname(String prodname) {
// this.prodname = prodname;
// }
//
// public String getProdimage() {
// return prodimage;
// }
//
// public void setProdimage(String prodimage) {
// this.prodimage = prodimage;
// }
//
// public String getProdcat() {
// return prodcat;
// }
//
// public void setProdcat(String prodcat) {
// this.prodcat = prodcat;
// }
//
// public String getPrice() {
// return price;
// }
//
// public void setPrice(String price) {
// this.price = price;
// }
//
// public String getDiscount() {
// return discount;
// }
//
// public void setDiscount(String discount) {
// this.discount = discount;
// }
//
// public void setRating(int rating) {
// this.rating = rating;
// }
//
// public int getRating() {
// return rating;
// }
// }
//
// Path: chapter10/src/main/java/com/packt/pfblueprints/dao/ProductsDAO.java
// public class ProductsDAO {
//
// private String productCategory;
//
// public ProductsDAO() {
// super();
// }
//
// public List<Product> getAllProducts(int first, int pageSize,
// String sortField, String sortOrderValue, Map<String, Object> filters) {
// Session session = getSession();// sessionFactory.openSession();
// session.beginTransaction();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance()
// .getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// productCategory = (String) sessionMap.get("productCategory");
// String query = null;
//
// Query queryResult=null;
// if (productCategory != "") {
// query = "from Product where prodcat = :productCategory ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// queryResult.setParameter("productCategory", productCategory);
// } else {
// query = "from Product ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// }
// List<Product> allProducts = queryResult.list();
// session.getTransaction().commit();
// return allProducts;
//
// }
//
// private Session getSession() {
// SessionFactory sf = HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
// }
// Path: chapter10/src/main/java/com/packt/pfblueprints/controller/HealthkartController.java
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.TreeNode;
import com.packt.pfblueprints.model.Product;
import com.packt.pfblueprints.dao.ProductsDAO;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class HealthkartController implements Serializable {
private static final long serialVersionUID = 1L;
| private LazyDataModel<Product> lazyModel;
|
sudheerj/primefaces-blueprints | chapter10/src/main/java/com/packt/pfblueprints/controller/HealthkartController.java | // Path: chapter10/src/main/java/com/packt/pfblueprints/model/Product.java
// @Entity
// @Table
// public class Product implements Serializable{
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue
// private Long id;
//
// private String prodname;
// private String prodimage;
// private String prodcat;
// private int rating;
// private String discount;
// private String price;
//
//
// public Product() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public Product(String prodname,String prodimage,String prodcat,int rating, String discount,String price) {
// super();
// this.prodname = prodname;
// this.prodimage = prodimage;
// this.prodcat = prodcat;
// this.rating = rating;
// this.discount = discount;
// this.price = price;
// }
//
// public String getProdname() {
// return prodname;
// }
//
// public void setProdname(String prodname) {
// this.prodname = prodname;
// }
//
// public String getProdimage() {
// return prodimage;
// }
//
// public void setProdimage(String prodimage) {
// this.prodimage = prodimage;
// }
//
// public String getProdcat() {
// return prodcat;
// }
//
// public void setProdcat(String prodcat) {
// this.prodcat = prodcat;
// }
//
// public String getPrice() {
// return price;
// }
//
// public void setPrice(String price) {
// this.price = price;
// }
//
// public String getDiscount() {
// return discount;
// }
//
// public void setDiscount(String discount) {
// this.discount = discount;
// }
//
// public void setRating(int rating) {
// this.rating = rating;
// }
//
// public int getRating() {
// return rating;
// }
// }
//
// Path: chapter10/src/main/java/com/packt/pfblueprints/dao/ProductsDAO.java
// public class ProductsDAO {
//
// private String productCategory;
//
// public ProductsDAO() {
// super();
// }
//
// public List<Product> getAllProducts(int first, int pageSize,
// String sortField, String sortOrderValue, Map<String, Object> filters) {
// Session session = getSession();// sessionFactory.openSession();
// session.beginTransaction();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance()
// .getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// productCategory = (String) sessionMap.get("productCategory");
// String query = null;
//
// Query queryResult=null;
// if (productCategory != "") {
// query = "from Product where prodcat = :productCategory ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// queryResult.setParameter("productCategory", productCategory);
// } else {
// query = "from Product ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// }
// List<Product> allProducts = queryResult.list();
// session.getTransaction().commit();
// return allProducts;
//
// }
//
// private Session getSession() {
// SessionFactory sf = HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
// }
| import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.TreeNode;
import com.packt.pfblueprints.model.Product;
import com.packt.pfblueprints.dao.ProductsDAO;
| package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class HealthkartController implements Serializable {
private static final long serialVersionUID = 1L;
private LazyDataModel<Product> lazyModel;
private List<Product> productsInfo = new ArrayList<Product>();
private int chunkSize = 5;
| // Path: chapter10/src/main/java/com/packt/pfblueprints/model/Product.java
// @Entity
// @Table
// public class Product implements Serializable{
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue
// private Long id;
//
// private String prodname;
// private String prodimage;
// private String prodcat;
// private int rating;
// private String discount;
// private String price;
//
//
// public Product() {
// super();
// // TODO Auto-generated constructor stub
// }
//
// public Product(String prodname,String prodimage,String prodcat,int rating, String discount,String price) {
// super();
// this.prodname = prodname;
// this.prodimage = prodimage;
// this.prodcat = prodcat;
// this.rating = rating;
// this.discount = discount;
// this.price = price;
// }
//
// public String getProdname() {
// return prodname;
// }
//
// public void setProdname(String prodname) {
// this.prodname = prodname;
// }
//
// public String getProdimage() {
// return prodimage;
// }
//
// public void setProdimage(String prodimage) {
// this.prodimage = prodimage;
// }
//
// public String getProdcat() {
// return prodcat;
// }
//
// public void setProdcat(String prodcat) {
// this.prodcat = prodcat;
// }
//
// public String getPrice() {
// return price;
// }
//
// public void setPrice(String price) {
// this.price = price;
// }
//
// public String getDiscount() {
// return discount;
// }
//
// public void setDiscount(String discount) {
// this.discount = discount;
// }
//
// public void setRating(int rating) {
// this.rating = rating;
// }
//
// public int getRating() {
// return rating;
// }
// }
//
// Path: chapter10/src/main/java/com/packt/pfblueprints/dao/ProductsDAO.java
// public class ProductsDAO {
//
// private String productCategory;
//
// public ProductsDAO() {
// super();
// }
//
// public List<Product> getAllProducts(int first, int pageSize,
// String sortField, String sortOrderValue, Map<String, Object> filters) {
// Session session = getSession();// sessionFactory.openSession();
// session.beginTransaction();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance()
// .getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// productCategory = (String) sessionMap.get("productCategory");
// String query = null;
//
// Query queryResult=null;
// if (productCategory != "") {
// query = "from Product where prodcat = :productCategory ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// queryResult.setParameter("productCategory", productCategory);
// } else {
// query = "from Product ORDER BY "+sortField+" "+sortOrderValue;
// queryResult = session.createQuery(query);
// }
// List<Product> allProducts = queryResult.list();
// session.getTransaction().commit();
// return allProducts;
//
// }
//
// private Session getSession() {
// SessionFactory sf = HibernateUtil.getSessionFactory();
// return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
// }
//
// }
// Path: chapter10/src/main/java/com/packt/pfblueprints/controller/HealthkartController.java
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.TreeNode;
import com.packt.pfblueprints.model.Product;
import com.packt.pfblueprints.dao.ProductsDAO;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class HealthkartController implements Serializable {
private static final long serialVersionUID = 1L;
private LazyDataModel<Product> lazyModel;
private List<Product> productsInfo = new ArrayList<Product>();
private int chunkSize = 5;
| ProductsDAO dao = new ProductsDAO();
|
sudheerj/primefaces-blueprints | chapter02/src/main/java/com/packt/pfblueprints/dao/JobPostsDAO.java | // Path: chapter02/src/main/java/com/packt/pfblueprints/model/JobPosts.java
// public class JobPosts {
//
// private String company;
// private String domain;
// private String experience;
// private String position;
// private String location;
//
//
//
// public String getCompany() {
// return company;
// }
// public void setCompany(String company) {
// this.company = company;
// }
// public String getDomain() {
// return domain;
// }
// public void setDomain(String domain) {
// this.domain = domain;
// }
// public String getExperience() {
// return experience;
// }
// public void setExperience(String experience) {
// this.experience = experience;
// }
// public String getPosition() {
// return position;
// }
// public void setPosition(String position) {
// this.position = position;
// }
// public String getLocation() {
// return location;
// }
// public void setLocation(String location) {
// this.location = location;
// }
//
//
//
// }
| import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.packt.pfblueprints.model.JobPosts; | package com.packt.pfblueprints.dao;
public class JobPostsDAO {
private DataSource ds;
Connection con;
public JobPostsDAO() throws SQLException {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
if (ds == null)
throw new SQLException("Can't get data source");
// get database connection
con = ds.getConnection();
if (con == null)
throw new SQLException("Can't get database connection");
} catch (NamingException e) {
e.printStackTrace();
}
} | // Path: chapter02/src/main/java/com/packt/pfblueprints/model/JobPosts.java
// public class JobPosts {
//
// private String company;
// private String domain;
// private String experience;
// private String position;
// private String location;
//
//
//
// public String getCompany() {
// return company;
// }
// public void setCompany(String company) {
// this.company = company;
// }
// public String getDomain() {
// return domain;
// }
// public void setDomain(String domain) {
// this.domain = domain;
// }
// public String getExperience() {
// return experience;
// }
// public void setExperience(String experience) {
// this.experience = experience;
// }
// public String getPosition() {
// return position;
// }
// public void setPosition(String position) {
// this.position = position;
// }
// public String getLocation() {
// return location;
// }
// public void setLocation(String location) {
// this.location = location;
// }
//
//
//
// }
// Path: chapter02/src/main/java/com/packt/pfblueprints/dao/JobPostsDAO.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.packt.pfblueprints.model.JobPosts;
package com.packt.pfblueprints.dao;
public class JobPostsDAO {
private DataSource ds;
Connection con;
public JobPostsDAO() throws SQLException {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
if (ds == null)
throw new SQLException("Can't get data source");
// get database connection
con = ds.getConnection();
if (con == null)
throw new SQLException("Can't get database connection");
} catch (NamingException e) {
e.printStackTrace();
}
} | public List<JobPosts> getAllJobs() throws SQLException{ |
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/dao/AdvisorDAO.java | // Path: chapter04/src/main/java/com/packt/pfblueprints/model/Representative.java
// public class Representative implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String repnumber;
// private String repname;
// private String advisornumber;
// private String dor;
// private String branch;
// private String status;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRepnumber() {
// return repnumber;
// }
// public void setRepnumber(String repnumber) {
// this.repnumber = repnumber;
// }
// public String getRepname() {
// return repname;
// }
// public void setRepname(String repname) {
// this.repname = repname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
// public String getDor() {
// return dor;
// }
// public void setDor(String dor) {
// this.dor = dor;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.Representative;
| package com.packt.pfblueprints.dao;
public class AdvisorDAO {
private SessionFactory sessionFactory;
private String advisorNumber;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public AdvisorDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
advisorNumber=(String) sessionMap.get("advisornumber");
}
| // Path: chapter04/src/main/java/com/packt/pfblueprints/model/Representative.java
// public class Representative implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String repnumber;
// private String repname;
// private String advisornumber;
// private String dor;
// private String branch;
// private String status;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRepnumber() {
// return repnumber;
// }
// public void setRepnumber(String repnumber) {
// this.repnumber = repnumber;
// }
// public String getRepname() {
// return repname;
// }
// public void setRepname(String repname) {
// this.repname = repname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
// public String getDor() {
// return dor;
// }
// public void setDor(String dor) {
// this.dor = dor;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/dao/AdvisorDAO.java
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.Representative;
package com.packt.pfblueprints.dao;
public class AdvisorDAO {
private SessionFactory sessionFactory;
private String advisorNumber;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public AdvisorDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
advisorNumber=(String) sessionMap.get("advisornumber");
}
| public List<Representative> getAllRepresentatives() {
|
sudheerj/primefaces-blueprints | chapter02/src/main/java/com/packt/pfblueprints/controller/JobPostsController.java | // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/JobPostsDAO.java
// public class JobPostsDAO {
// private DataSource ds;
// Connection con;
//
//
// public JobPostsDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null)
// throw new SQLException("Can't get data source");
//
// // get database connection
// con = ds.getConnection();
//
// if (con == null)
// throw new SQLException("Can't get database connection");
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
// public List<JobPosts> getAllJobs() throws SQLException{
// PreparedStatement ps
// = con.prepareStatement(
// "select company,domain,experience,position,location from blueprintsdb.jobposts");
//
// //get jobposts data from database
// ResultSet result = ps.executeQuery();
//
// List<JobPosts> list = new ArrayList<JobPosts>();
//
// while(result.next()){
// JobPosts post = new JobPosts();
//
// post.setCompany(result.getString("company"));
// post.setDomain(result.getString("domain"));
// post.setExperience(result.getString("experience"));
// post.setPosition(result.getString("position"));
// post.setLocation(result.getString("location"));
//
// list.add(post);
// }
//
// return list;
//
// }
//
// }
//
// Path: chapter02/src/main/java/com/packt/pfblueprints/model/JobPosts.java
// public class JobPosts {
//
// private String company;
// private String domain;
// private String experience;
// private String position;
// private String location;
//
//
//
// public String getCompany() {
// return company;
// }
// public void setCompany(String company) {
// this.company = company;
// }
// public String getDomain() {
// return domain;
// }
// public void setDomain(String domain) {
// this.domain = domain;
// }
// public String getExperience() {
// return experience;
// }
// public void setExperience(String experience) {
// this.experience = experience;
// }
// public String getPosition() {
// return position;
// }
// public void setPosition(String position) {
// this.position = position;
// }
// public String getLocation() {
// return location;
// }
// public void setLocation(String location) {
// this.location = location;
// }
//
//
//
// }
| import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.JobPostsDAO;
import com.packt.pfblueprints.model.JobPosts; | package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class JobPostsController implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L; | // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/JobPostsDAO.java
// public class JobPostsDAO {
// private DataSource ds;
// Connection con;
//
//
// public JobPostsDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null)
// throw new SQLException("Can't get data source");
//
// // get database connection
// con = ds.getConnection();
//
// if (con == null)
// throw new SQLException("Can't get database connection");
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
// public List<JobPosts> getAllJobs() throws SQLException{
// PreparedStatement ps
// = con.prepareStatement(
// "select company,domain,experience,position,location from blueprintsdb.jobposts");
//
// //get jobposts data from database
// ResultSet result = ps.executeQuery();
//
// List<JobPosts> list = new ArrayList<JobPosts>();
//
// while(result.next()){
// JobPosts post = new JobPosts();
//
// post.setCompany(result.getString("company"));
// post.setDomain(result.getString("domain"));
// post.setExperience(result.getString("experience"));
// post.setPosition(result.getString("position"));
// post.setLocation(result.getString("location"));
//
// list.add(post);
// }
//
// return list;
//
// }
//
// }
//
// Path: chapter02/src/main/java/com/packt/pfblueprints/model/JobPosts.java
// public class JobPosts {
//
// private String company;
// private String domain;
// private String experience;
// private String position;
// private String location;
//
//
//
// public String getCompany() {
// return company;
// }
// public void setCompany(String company) {
// this.company = company;
// }
// public String getDomain() {
// return domain;
// }
// public void setDomain(String domain) {
// this.domain = domain;
// }
// public String getExperience() {
// return experience;
// }
// public void setExperience(String experience) {
// this.experience = experience;
// }
// public String getPosition() {
// return position;
// }
// public void setPosition(String position) {
// this.position = position;
// }
// public String getLocation() {
// return location;
// }
// public void setLocation(String location) {
// this.location = location;
// }
//
//
//
// }
// Path: chapter02/src/main/java/com/packt/pfblueprints/controller/JobPostsController.java
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.JobPostsDAO;
import com.packt.pfblueprints.model.JobPosts;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class JobPostsController implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L; | List<JobPosts> jobslist=new ArrayList<JobPosts>(); |
sudheerj/primefaces-blueprints | chapter02/src/main/java/com/packt/pfblueprints/controller/JobPostsController.java | // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/JobPostsDAO.java
// public class JobPostsDAO {
// private DataSource ds;
// Connection con;
//
//
// public JobPostsDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null)
// throw new SQLException("Can't get data source");
//
// // get database connection
// con = ds.getConnection();
//
// if (con == null)
// throw new SQLException("Can't get database connection");
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
// public List<JobPosts> getAllJobs() throws SQLException{
// PreparedStatement ps
// = con.prepareStatement(
// "select company,domain,experience,position,location from blueprintsdb.jobposts");
//
// //get jobposts data from database
// ResultSet result = ps.executeQuery();
//
// List<JobPosts> list = new ArrayList<JobPosts>();
//
// while(result.next()){
// JobPosts post = new JobPosts();
//
// post.setCompany(result.getString("company"));
// post.setDomain(result.getString("domain"));
// post.setExperience(result.getString("experience"));
// post.setPosition(result.getString("position"));
// post.setLocation(result.getString("location"));
//
// list.add(post);
// }
//
// return list;
//
// }
//
// }
//
// Path: chapter02/src/main/java/com/packt/pfblueprints/model/JobPosts.java
// public class JobPosts {
//
// private String company;
// private String domain;
// private String experience;
// private String position;
// private String location;
//
//
//
// public String getCompany() {
// return company;
// }
// public void setCompany(String company) {
// this.company = company;
// }
// public String getDomain() {
// return domain;
// }
// public void setDomain(String domain) {
// this.domain = domain;
// }
// public String getExperience() {
// return experience;
// }
// public void setExperience(String experience) {
// this.experience = experience;
// }
// public String getPosition() {
// return position;
// }
// public void setPosition(String position) {
// this.position = position;
// }
// public String getLocation() {
// return location;
// }
// public void setLocation(String location) {
// this.location = location;
// }
//
//
//
// }
| import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.JobPostsDAO;
import com.packt.pfblueprints.model.JobPosts; | package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class JobPostsController implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
List<JobPosts> jobslist=new ArrayList<JobPosts>();
@SuppressWarnings("restriction")
@PostConstruct
public void init() { | // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/JobPostsDAO.java
// public class JobPostsDAO {
// private DataSource ds;
// Connection con;
//
//
// public JobPostsDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null)
// throw new SQLException("Can't get data source");
//
// // get database connection
// con = ds.getConnection();
//
// if (con == null)
// throw new SQLException("Can't get database connection");
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
// public List<JobPosts> getAllJobs() throws SQLException{
// PreparedStatement ps
// = con.prepareStatement(
// "select company,domain,experience,position,location from blueprintsdb.jobposts");
//
// //get jobposts data from database
// ResultSet result = ps.executeQuery();
//
// List<JobPosts> list = new ArrayList<JobPosts>();
//
// while(result.next()){
// JobPosts post = new JobPosts();
//
// post.setCompany(result.getString("company"));
// post.setDomain(result.getString("domain"));
// post.setExperience(result.getString("experience"));
// post.setPosition(result.getString("position"));
// post.setLocation(result.getString("location"));
//
// list.add(post);
// }
//
// return list;
//
// }
//
// }
//
// Path: chapter02/src/main/java/com/packt/pfblueprints/model/JobPosts.java
// public class JobPosts {
//
// private String company;
// private String domain;
// private String experience;
// private String position;
// private String location;
//
//
//
// public String getCompany() {
// return company;
// }
// public void setCompany(String company) {
// this.company = company;
// }
// public String getDomain() {
// return domain;
// }
// public void setDomain(String domain) {
// this.domain = domain;
// }
// public String getExperience() {
// return experience;
// }
// public void setExperience(String experience) {
// this.experience = experience;
// }
// public String getPosition() {
// return position;
// }
// public void setPosition(String position) {
// this.position = position;
// }
// public String getLocation() {
// return location;
// }
// public void setLocation(String location) {
// this.location = location;
// }
//
//
//
// }
// Path: chapter02/src/main/java/com/packt/pfblueprints/controller/JobPostsController.java
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.JobPostsDAO;
import com.packt.pfblueprints.model.JobPosts;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class JobPostsController implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
List<JobPosts> jobslist=new ArrayList<JobPosts>();
@SuppressWarnings("restriction")
@PostConstruct
public void init() { | JobPostsDAO dao; |
sudheerj/primefaces-blueprints | chapter09/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.hibernate.Session;
import java.util.Date;
import java.util.List; | package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class"); | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
// Path: chapter09/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.hibernate.Session;
import java.util.Date;
import java.util.List;
package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class"); | Session session = HibernateUtil.getSessionFactory().openSession(); |
sudheerj/primefaces-blueprints | chapter09/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.hibernate.Session;
import java.util.Date;
import java.util.List; | package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
// Path: chapter09/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.hibernate.Session;
import java.util.Date;
import java.util.List;
package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); | Profile u = new Profile(); |
sudheerj/primefaces-blueprints | chapter05/src/main/java/com/packt/pfblueprints/dao/InvestmentSummaryDAO.java | // Path: chapter05/src/main/java/com/packt/pfblueprints/model/InvestmentSummary.java
// public class InvestmentSummary implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int id;
// private String accountNumber;
// private String fundname;
// private String investmentNumber;
// private String investmentManager;
// private String marketingCompany;
// private String avgUnitPrice;
// private Double marketValue1;
// private Double marketValue2;
// private Double marketValue3;
// private Double marketValue4;
// private Double marketValue5;
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
// public String getFundname() {
// return fundname;
// }
// public void setFundname(String fundname) {
// this.fundname = fundname;
// }
//
// public String getInvestmentNumber() {
// return investmentNumber;
// }
// public void setInvestmentNumber(String investmentNumber) {
// this.investmentNumber = investmentNumber;
// }
// public String getInvestmentManager() {
// return investmentManager;
// }
// public void setInvestmentManager(String investmentManager) {
// this.investmentManager = investmentManager;
// }
// public String getMarketingCompany() {
// return marketingCompany;
// }
// public void setMarketingCompany(String marketingCompany) {
// this.marketingCompany = marketingCompany;
// }
// public String getAvgUnitPrice() {
// return avgUnitPrice;
// }
// public void setAvgUnitPrice(String avgUnitPrice) {
// this.avgUnitPrice = avgUnitPrice;
// }
// public Double getMarketValue1() {
// return marketValue1;
// }
// public void setMarketValue1(Double marketValue1) {
// this.marketValue1 = marketValue1;
// }
// public Double getMarketValue2() {
// return marketValue2;
// }
// public void setMarketValue2(Double marketValue2) {
// this.marketValue2 = marketValue2;
// }
// public Double getMarketValue3() {
// return marketValue3;
// }
// public void setMarketValue3(Double marketValue3) {
// this.marketValue3 = marketValue3;
// }
// public Double getMarketValue4() {
// return marketValue4;
// }
// public void setMarketValue4(Double marketValue4) {
// this.marketValue4 = marketValue4;
// }
// public Double getMarketValue5() {
// return marketValue5;
// }
// public void setMarketValue5(Double marketValue5) {
// this.marketValue5 = marketValue5;
// }
//
// }
| import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.InvestmentSummary;
| package com.packt.pfblueprints.dao;
public class InvestmentSummaryDAO {
private SessionFactory sessionFactory;
private String accountNumber;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public InvestmentSummaryDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
accountNumber=(String) sessionMap.get("accountNumber");
// TODO Auto-generated constructor stub
}
| // Path: chapter05/src/main/java/com/packt/pfblueprints/model/InvestmentSummary.java
// public class InvestmentSummary implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int id;
// private String accountNumber;
// private String fundname;
// private String investmentNumber;
// private String investmentManager;
// private String marketingCompany;
// private String avgUnitPrice;
// private Double marketValue1;
// private Double marketValue2;
// private Double marketValue3;
// private Double marketValue4;
// private Double marketValue5;
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
// public String getFundname() {
// return fundname;
// }
// public void setFundname(String fundname) {
// this.fundname = fundname;
// }
//
// public String getInvestmentNumber() {
// return investmentNumber;
// }
// public void setInvestmentNumber(String investmentNumber) {
// this.investmentNumber = investmentNumber;
// }
// public String getInvestmentManager() {
// return investmentManager;
// }
// public void setInvestmentManager(String investmentManager) {
// this.investmentManager = investmentManager;
// }
// public String getMarketingCompany() {
// return marketingCompany;
// }
// public void setMarketingCompany(String marketingCompany) {
// this.marketingCompany = marketingCompany;
// }
// public String getAvgUnitPrice() {
// return avgUnitPrice;
// }
// public void setAvgUnitPrice(String avgUnitPrice) {
// this.avgUnitPrice = avgUnitPrice;
// }
// public Double getMarketValue1() {
// return marketValue1;
// }
// public void setMarketValue1(Double marketValue1) {
// this.marketValue1 = marketValue1;
// }
// public Double getMarketValue2() {
// return marketValue2;
// }
// public void setMarketValue2(Double marketValue2) {
// this.marketValue2 = marketValue2;
// }
// public Double getMarketValue3() {
// return marketValue3;
// }
// public void setMarketValue3(Double marketValue3) {
// this.marketValue3 = marketValue3;
// }
// public Double getMarketValue4() {
// return marketValue4;
// }
// public void setMarketValue4(Double marketValue4) {
// this.marketValue4 = marketValue4;
// }
// public Double getMarketValue5() {
// return marketValue5;
// }
// public void setMarketValue5(Double marketValue5) {
// this.marketValue5 = marketValue5;
// }
//
// }
// Path: chapter05/src/main/java/com/packt/pfblueprints/dao/InvestmentSummaryDAO.java
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.InvestmentSummary;
package com.packt.pfblueprints.dao;
public class InvestmentSummaryDAO {
private SessionFactory sessionFactory;
private String accountNumber;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public InvestmentSummaryDAO() {
super();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
accountNumber=(String) sessionMap.get("accountNumber");
// TODO Auto-generated constructor stub
}
| public List<InvestmentSummary> getAllInvestments() {
|
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/controller/DealerController.java | // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java
// public class DealerDAO {
//
// private SessionFactory sessionFactory;
// private String dealerNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public DealerDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// dealerNumber=(String) sessionMap.get("dealertinnumber");
// // TODO Auto-generated constructor stub
// }
//
// public List<Advisor> getAllAdvisors() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(dealerNumber!=""){
// queryResult = session.createQuery("from Advisor where dealernumber = :dealerNum");
// queryResult.setParameter("dealerNum", dealerNumber);
// }else{
// queryResult = session.createQuery("from Advisor");
// }
// List<Advisor> allDealers = queryResult.list();
// for(Advisor dealerobj:allDealers){
// List<ProgressStatus> progressStatus=generateProgressStatus();
// dealerobj.setProgressStatus(progressStatus);
// }
// session.getTransaction().commit();
// return allDealers;
// }
//
// public List<ProgressStatus> generateProgressStatus(){
// List<ProgressStatus> progressStatus=new ArrayList<ProgressStatus>();
// progressStatus.add(new ProgressStatus("2000",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2002",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2004",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2006",((int)(Math.random()*10))+""));
// return progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import com.packt.pfblueprints.dao.DealerDAO;
import com.packt.pfblueprints.model.Advisor;
| package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class DealerController implements Serializable{
private static final long serialVersionUID = 1L;
| // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java
// public class DealerDAO {
//
// private SessionFactory sessionFactory;
// private String dealerNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public DealerDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// dealerNumber=(String) sessionMap.get("dealertinnumber");
// // TODO Auto-generated constructor stub
// }
//
// public List<Advisor> getAllAdvisors() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(dealerNumber!=""){
// queryResult = session.createQuery("from Advisor where dealernumber = :dealerNum");
// queryResult.setParameter("dealerNum", dealerNumber);
// }else{
// queryResult = session.createQuery("from Advisor");
// }
// List<Advisor> allDealers = queryResult.list();
// for(Advisor dealerobj:allDealers){
// List<ProgressStatus> progressStatus=generateProgressStatus();
// dealerobj.setProgressStatus(progressStatus);
// }
// session.getTransaction().commit();
// return allDealers;
// }
//
// public List<ProgressStatus> generateProgressStatus(){
// List<ProgressStatus> progressStatus=new ArrayList<ProgressStatus>();
// progressStatus.add(new ProgressStatus("2000",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2002",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2004",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2006",((int)(Math.random()*10))+""));
// return progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/controller/DealerController.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import com.packt.pfblueprints.dao.DealerDAO;
import com.packt.pfblueprints.model.Advisor;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class DealerController implements Serializable{
private static final long serialVersionUID = 1L;
| private List<Advisor> dealerInfo=new ArrayList<Advisor>();
|
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/controller/DealerController.java | // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java
// public class DealerDAO {
//
// private SessionFactory sessionFactory;
// private String dealerNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public DealerDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// dealerNumber=(String) sessionMap.get("dealertinnumber");
// // TODO Auto-generated constructor stub
// }
//
// public List<Advisor> getAllAdvisors() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(dealerNumber!=""){
// queryResult = session.createQuery("from Advisor where dealernumber = :dealerNum");
// queryResult.setParameter("dealerNum", dealerNumber);
// }else{
// queryResult = session.createQuery("from Advisor");
// }
// List<Advisor> allDealers = queryResult.list();
// for(Advisor dealerobj:allDealers){
// List<ProgressStatus> progressStatus=generateProgressStatus();
// dealerobj.setProgressStatus(progressStatus);
// }
// session.getTransaction().commit();
// return allDealers;
// }
//
// public List<ProgressStatus> generateProgressStatus(){
// List<ProgressStatus> progressStatus=new ArrayList<ProgressStatus>();
// progressStatus.add(new ProgressStatus("2000",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2002",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2004",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2006",((int)(Math.random()*10))+""));
// return progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import com.packt.pfblueprints.dao.DealerDAO;
import com.packt.pfblueprints.model.Advisor;
| package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class DealerController implements Serializable{
private static final long serialVersionUID = 1L;
private List<Advisor> dealerInfo=new ArrayList<Advisor>();
private SelectItem[] managementcompanies;
private String[] branches;
private Advisor advisorobj=new Advisor();
| // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/DealerDAO.java
// public class DealerDAO {
//
// private SessionFactory sessionFactory;
// private String dealerNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public DealerDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// dealerNumber=(String) sessionMap.get("dealertinnumber");
// // TODO Auto-generated constructor stub
// }
//
// public List<Advisor> getAllAdvisors() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(dealerNumber!=""){
// queryResult = session.createQuery("from Advisor where dealernumber = :dealerNum");
// queryResult.setParameter("dealerNum", dealerNumber);
// }else{
// queryResult = session.createQuery("from Advisor");
// }
// List<Advisor> allDealers = queryResult.list();
// for(Advisor dealerobj:allDealers){
// List<ProgressStatus> progressStatus=generateProgressStatus();
// dealerobj.setProgressStatus(progressStatus);
// }
// session.getTransaction().commit();
// return allDealers;
// }
//
// public List<ProgressStatus> generateProgressStatus(){
// List<ProgressStatus> progressStatus=new ArrayList<ProgressStatus>();
// progressStatus.add(new ProgressStatus("2000",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2002",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2004",((int)(Math.random()*10))+""));
// progressStatus.add(new ProgressStatus("2006",((int)(Math.random()*10))+""));
// return progressStatus;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Advisor.java
// public class Advisor implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String dealernumber;
// private String advisorname;
// private String advisornumber;
// private String managementcompany;
// private String branch;
// private int year;
// private boolean status;
// private int revenue;
// private List<ProgressStatus> progressStatus;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getDealernumber() {
// return dealernumber;
// }
// public void setDealernumber(String dealernumber) {
// this.dealernumber = dealernumber;
// }
// public String getAdvisorname() {
// return advisorname;
// }
// public void setAdvisorname(String advisorname) {
// this.advisorname = advisorname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
//
// public String getManagementcompany() {
// return managementcompany;
// }
// public void setManagementcompany(String managementcompany) {
// this.managementcompany = managementcompany;
// }
// public int getYear() {
// return year;
// }
// public void setYear(int year) {
// this.year = year;
// }
// public int getRevenue() {
// return revenue;
// }
// public void setRevenue(int revenue) {
// this.revenue = revenue;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
//
// public boolean isStatus() {
// return status;
// }
// public void setStatus(boolean status) {
// this.status = status;
// }
// public List<ProgressStatus> getProgressStatus() {
// return progressStatus;
// }
// public void setProgressStatus(List<ProgressStatus> progressStatus) {
// this.progressStatus = progressStatus;
// }
//
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/controller/DealerController.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import com.packt.pfblueprints.dao.DealerDAO;
import com.packt.pfblueprints.model.Advisor;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class DealerController implements Serializable{
private static final long serialVersionUID = 1L;
private List<Advisor> dealerInfo=new ArrayList<Advisor>();
private SelectItem[] managementcompanies;
private String[] branches;
private Advisor advisorobj=new Advisor();
| DealerDAO dao = new DealerDAO();
|
sudheerj/primefaces-blueprints | chapter07/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.*;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.ArrayList;
import java.util.List; |
public List<String> getTagsStartWith(String chars){
List<String> list = new ArrayList<>();
org.hibernate.Transaction tx = getSession().beginTransaction();
List tags = getSession().createCriteria(Tags.class)
.add(Restrictions.ilike("name", chars))
.addOrder(Order.asc("name")).list();
tx.commit();
getSession().close();
if(tags != null){
for (Tags t: (List<Tags>) tags){
list.add(t.getName());
}
}
_log.info("Listed Successfully....");
return list;
}
public Tags getTagByName(String name){
org.hibernate.Transaction tx = getSession().beginTransaction();
Tags tag = (Tags) getSession().createCriteria(Tags.class)
.add(Restrictions.eq("name", name).ignoreCase())
.uniqueResult();
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return tag;
}
private Session getSession() { | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.*;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.ArrayList;
import java.util.List;
public List<String> getTagsStartWith(String chars){
List<String> list = new ArrayList<>();
org.hibernate.Transaction tx = getSession().beginTransaction();
List tags = getSession().createCriteria(Tags.class)
.add(Restrictions.ilike("name", chars))
.addOrder(Order.asc("name")).list();
tx.commit();
getSession().close();
if(tags != null){
for (Tags t: (List<Tags>) tags){
list.add(t.getName());
}
}
_log.info("Listed Successfully....");
return list;
}
public Tags getTagByName(String name){
org.hibernate.Transaction tx = getSession().beginTransaction();
Tags tag = (Tags) getSession().createCriteria(Tags.class)
.add(Restrictions.eq("name", name).ignoreCase())
.uniqueResult();
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return tag;
}
private Session getSession() { | SessionFactory sf = HibernateUtil.getSessionFactory(); |
sudheerj/primefaces-blueprints | chapter09/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.*;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.Date;
import java.util.List; | package com.packtpub.pf.blueprint.service;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai <psramkumar@gmail.com>
* Date: 2/6/14
* Time: 8:18 PM
* To change this template use File | Settings | File Templates.
*/
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class DAOService {
private static final Logger _log = Logger.getLogger(DAOService.class);
public final String OPEN_STATUS = "OPEN";
| // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.*;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.Date;
import java.util.List;
package com.packtpub.pf.blueprint.service;
/**
* Created with IntelliJ IDEA.
* User: Ramkumar Pillai <psramkumar@gmail.com>
* Date: 2/6/14
* Time: 8:18 PM
* To change this template use File | Settings | File Templates.
*/
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class DAOService {
private static final Logger _log = Logger.getLogger(DAOService.class);
public final String OPEN_STATUS = "OPEN";
| public Profile validateUser(String username, String password) { |
sudheerj/primefaces-blueprints | chapter09/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.*;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.Date;
import java.util.List; | }
public List<UserPost> getUserPostForUser(Profile u) {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(UserPost.class)
.add(Restrictions.eq("user", u))
.addOrder(Order.desc("createDate")).list();
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return list;
}
public List<Comment> getAllCommentsForUserPost(UserPost p) {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(Comment.class)
.add(Restrictions.eq("post", p))
.addOrder(Order.desc("createDate")).list();
Comment c = new Comment();
c.setComment("Testing Comments");
c.setCreateDate(new Date());
list.add(c);
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return list;
}
private Session getSession() { | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Profile.java
// @Entity
// @Table
// @Data
// public class Profile implements java.io.Serializable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String firstName;
//
// private String lastName;
//
// @Column(unique = true)
// private String email;
// private String password;
//
// @Temporal(TemporalType.DATE)
// private Date dateOfBirth;
//
// private String gender;
//
// private String aboutme;
//
// private String avatar = "no_image_available";
//
// private String currentLocation;
//
// private boolean verified;
//
// @Temporal(TemporalType.DATE)
// private Date createDate;
//
// @OneToMany(mappedBy = "user")
// private Set<Comment> comments = new HashSet<>();
//
// @OneToMany(mappedBy = "user")
// private Set<UserPost> posts = new HashSet<>();
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="personId"),
// inverseJoinColumns=@JoinColumn(name="friendId")
// )
// private List<Profile> friends;
//
// @ManyToMany
// @JoinTable(name="tbl_friends",
// joinColumns=@JoinColumn(name="friendId"),
// inverseJoinColumns=@JoinColumn(name="personId")
// )
// private List<Profile> friendOf;
//
// }
// Path: chapter09/src/main/java/com/packtpub/pf/blueprint/service/DAOService.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.*;
import com.packtpub.pf.blueprint.persistence.entity.Profile;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import java.util.Date;
import java.util.List;
}
public List<UserPost> getUserPostForUser(Profile u) {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(UserPost.class)
.add(Restrictions.eq("user", u))
.addOrder(Order.desc("createDate")).list();
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return list;
}
public List<Comment> getAllCommentsForUserPost(UserPost p) {
org.hibernate.Transaction tx = getSession().beginTransaction();
List list = getSession().createCriteria(Comment.class)
.add(Restrictions.eq("post", p))
.addOrder(Order.desc("createDate")).list();
Comment c = new Comment();
c.setComment("Testing Comments");
c.setCreateDate(new Date());
list.add(c);
tx.commit();
getSession().close();
_log.info("Listed Successfully....");
return list;
}
private Session getSession() { | SessionFactory sf = HibernateUtil.getSessionFactory(); |
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/controller/LoginController.java | // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/LoginDAO.java
// public class LoginDAO {
//
// private DataSource ds;
// Connection con;
//
// public LoginDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null) {
// throw new SQLException("Can't get data source");
// }
// // get database connection
// con = ds.getConnection();
// if (con == null) {
// throw new SQLException("Can't get database connection");
// }
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
//
// public boolean changepassword(String userid, String oldpassword,
// String newpassword) {
// try {
// // Persist employee
// PreparedStatement ps = con
// .prepareStatement("UPDATE blueprintsdb.employee SET password='"
// + newpassword
// + "' WHERE userid='"
// + userid + "' and password='" + oldpassword + "'");
// int count = ps.executeUpdate();
// return (count > 0);
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
//
// }
//
// public boolean validateUser(String userid, String password) {
// try {
// // Check the logged jobseeker is valid user or not
// PreparedStatement ps = con
// .prepareStatement("select * FROM blueprintsdb.employee WHERE userid='"
// + userid + "' and password='" + password + "'");
// ResultSet resultSet = ps.executeQuery();
// if (resultSet.next()) {
// return true;
// } else {
// return false;
// }
//
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
// }
// }
| import java.io.Serializable;
import java.sql.SQLException;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import com.packt.pfblueprints.dao.LoginDAO;
| package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class LoginController implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String userrole="S";
public LoginController() {
super();
}
public String validateUser() throws SQLException {
FacesMessage msg = null;
boolean isValidUser = false;
| // Path: chapter02/src/main/java/com/packt/pfblueprints/dao/LoginDAO.java
// public class LoginDAO {
//
// private DataSource ds;
// Connection con;
//
// public LoginDAO() throws SQLException {
// try {
// Context ctx = new InitialContext();
// ds = (DataSource) ctx.lookup("java:comp/env/jdbc/blueprintsdb");
// if (ds == null) {
// throw new SQLException("Can't get data source");
// }
// // get database connection
// con = ds.getConnection();
// if (con == null) {
// throw new SQLException("Can't get database connection");
// }
//
// } catch (NamingException e) {
// e.printStackTrace();
// }
//
// }
//
// public boolean changepassword(String userid, String oldpassword,
// String newpassword) {
// try {
// // Persist employee
// PreparedStatement ps = con
// .prepareStatement("UPDATE blueprintsdb.employee SET password='"
// + newpassword
// + "' WHERE userid='"
// + userid + "' and password='" + oldpassword + "'");
// int count = ps.executeUpdate();
// return (count > 0);
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
//
// }
//
// public boolean validateUser(String userid, String password) {
// try {
// // Check the logged jobseeker is valid user or not
// PreparedStatement ps = con
// .prepareStatement("select * FROM blueprintsdb.employee WHERE userid='"
// + userid + "' and password='" + password + "'");
// ResultSet resultSet = ps.executeQuery();
// if (resultSet.next()) {
// return true;
// } else {
// return false;
// }
//
// } catch (SQLException e) {
// e.printStackTrace();
//
// } catch (Exception e) {
// e.printStackTrace();
//
// }
// return false;
// }
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/controller/LoginController.java
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import com.packt.pfblueprints.dao.LoginDAO;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class LoginController implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String userrole="S";
public LoginController() {
super();
}
public String validateUser() throws SQLException {
FacesMessage msg = null;
boolean isValidUser = false;
| LoginDAO dao = new LoginDAO();
|
sudheerj/primefaces-blueprints | chapter05/src/main/java/com/packt/pfblueprints/dao/LoginDAO.java | // Path: chapter05/src/main/java/com/packt/pfblueprints/model/InvestorsList.java
// public class InvestorsList implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int id;
// private String username;
// private String password;
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
| import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.InvestorsList;
| package com.packt.pfblueprints.dao;
public class LoginDAO {
private SessionFactory sessionFactory;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public LoginDAO() throws SQLException {
super();
}
public boolean validateUser(String userid, String password) {
try {
sessionFactory = configureSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
String query = "from InvestorsList where username='" + userid + "' and password='" + password + "'";
Query queryobj = session.createQuery(query);
| // Path: chapter05/src/main/java/com/packt/pfblueprints/model/InvestorsList.java
// public class InvestorsList implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int id;
// private String username;
// private String password;
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
//
// }
// Path: chapter05/src/main/java/com/packt/pfblueprints/dao/LoginDAO.java
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.packt.pfblueprints.model.InvestorsList;
package com.packt.pfblueprints.dao;
public class LoginDAO {
private SessionFactory sessionFactory;
private SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionfactory = configuration
.buildSessionFactory(builder.build());
return sessionfactory;
}
public LoginDAO() throws SQLException {
super();
}
public boolean validateUser(String userid, String password) {
try {
sessionFactory = configureSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
String query = "from InvestorsList where username='" + userid + "' and password='" + password + "'";
Query queryobj = session.createQuery(query);
| List<InvestorsList> list=queryobj.list();
|
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/controller/AdvisorController.java | // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/AdvisorDAO.java
// public class AdvisorDAO {
//
// private SessionFactory sessionFactory;
// private String advisorNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public AdvisorDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// advisorNumber=(String) sessionMap.get("advisornumber");
// }
//
// public List<Representative> getAllRepresentatives() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(advisorNumber!=""){
// queryResult = session.createQuery("from Representative where advisornumber = :advisorNum");
// queryResult.setParameter("advisorNum", advisorNumber);
// }else{
// queryResult = session.createQuery("from Representative");
// }
// List<Representative> allAdvisors = queryResult.list();
// session.getTransaction().commit();
// return allAdvisors;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Representative.java
// public class Representative implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String repnumber;
// private String repname;
// private String advisornumber;
// private String dor;
// private String branch;
// private String status;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRepnumber() {
// return repnumber;
// }
// public void setRepnumber(String repnumber) {
// this.repnumber = repnumber;
// }
// public String getRepname() {
// return repname;
// }
// public void setRepname(String repname) {
// this.repname = repname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
// public String getDor() {
// return dor;
// }
// public void setDor(String dor) {
// this.dor = dor;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.AdvisorDAO;
import com.packt.pfblueprints.model.Representative;
| package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class AdvisorController implements Serializable{
private static final long serialVersionUID = 1L;
| // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/AdvisorDAO.java
// public class AdvisorDAO {
//
// private SessionFactory sessionFactory;
// private String advisorNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public AdvisorDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// advisorNumber=(String) sessionMap.get("advisornumber");
// }
//
// public List<Representative> getAllRepresentatives() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(advisorNumber!=""){
// queryResult = session.createQuery("from Representative where advisornumber = :advisorNum");
// queryResult.setParameter("advisorNum", advisorNumber);
// }else{
// queryResult = session.createQuery("from Representative");
// }
// List<Representative> allAdvisors = queryResult.list();
// session.getTransaction().commit();
// return allAdvisors;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Representative.java
// public class Representative implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String repnumber;
// private String repname;
// private String advisornumber;
// private String dor;
// private String branch;
// private String status;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRepnumber() {
// return repnumber;
// }
// public void setRepnumber(String repnumber) {
// this.repnumber = repnumber;
// }
// public String getRepname() {
// return repname;
// }
// public void setRepname(String repname) {
// this.repname = repname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
// public String getDor() {
// return dor;
// }
// public void setDor(String dor) {
// this.dor = dor;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/controller/AdvisorController.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.AdvisorDAO;
import com.packt.pfblueprints.model.Representative;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class AdvisorController implements Serializable{
private static final long serialVersionUID = 1L;
| private List<Representative> advisorInfo=new ArrayList<Representative>();
|
sudheerj/primefaces-blueprints | chapter04/src/main/java/com/packt/pfblueprints/controller/AdvisorController.java | // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/AdvisorDAO.java
// public class AdvisorDAO {
//
// private SessionFactory sessionFactory;
// private String advisorNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public AdvisorDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// advisorNumber=(String) sessionMap.get("advisornumber");
// }
//
// public List<Representative> getAllRepresentatives() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(advisorNumber!=""){
// queryResult = session.createQuery("from Representative where advisornumber = :advisorNum");
// queryResult.setParameter("advisorNum", advisorNumber);
// }else{
// queryResult = session.createQuery("from Representative");
// }
// List<Representative> allAdvisors = queryResult.list();
// session.getTransaction().commit();
// return allAdvisors;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Representative.java
// public class Representative implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String repnumber;
// private String repname;
// private String advisornumber;
// private String dor;
// private String branch;
// private String status;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRepnumber() {
// return repnumber;
// }
// public void setRepnumber(String repnumber) {
// this.repnumber = repnumber;
// }
// public String getRepname() {
// return repname;
// }
// public void setRepname(String repname) {
// this.repname = repname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
// public String getDor() {
// return dor;
// }
// public void setDor(String dor) {
// this.dor = dor;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.AdvisorDAO;
import com.packt.pfblueprints.model.Representative;
| package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class AdvisorController implements Serializable{
private static final long serialVersionUID = 1L;
private List<Representative> advisorInfo=new ArrayList<Representative>();
Representative repobj=new Representative();
| // Path: chapter04/src/main/java/com/packt/pfblueprints/dao/AdvisorDAO.java
// public class AdvisorDAO {
//
// private SessionFactory sessionFactory;
// private String advisorNumber;
//
// private SessionFactory configureSessionFactory()
// throws HibernateException {
// Configuration configuration = new Configuration();
// configuration.configure();
// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
// SessionFactory sessionfactory = configuration
// .buildSessionFactory(builder.build());
// return sessionfactory;
// }
//
// public AdvisorDAO() {
// super();
//
// ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Map<String, Object> sessionMap = externalContext.getSessionMap();
// advisorNumber=(String) sessionMap.get("advisornumber");
// }
//
// public List<Representative> getAllRepresentatives() {
// sessionFactory = configureSessionFactory();
// Session session = sessionFactory.openSession();
// session.beginTransaction();
// Query queryResult=null;
// if(advisorNumber!=""){
// queryResult = session.createQuery("from Representative where advisornumber = :advisorNum");
// queryResult.setParameter("advisorNum", advisorNumber);
// }else{
// queryResult = session.createQuery("from Representative");
// }
// List<Representative> allAdvisors = queryResult.list();
// session.getTransaction().commit();
// return allAdvisors;
// }
//
// }
//
// Path: chapter04/src/main/java/com/packt/pfblueprints/model/Representative.java
// public class Representative implements Serializable{
//
// private static final long serialVersionUID = 1L;
// private int id;
// private String repnumber;
// private String repname;
// private String advisornumber;
// private String dor;
// private String branch;
// private String status;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRepnumber() {
// return repnumber;
// }
// public void setRepnumber(String repnumber) {
// this.repnumber = repnumber;
// }
// public String getRepname() {
// return repname;
// }
// public void setRepname(String repname) {
// this.repname = repname;
// }
// public String getAdvisornumber() {
// return advisornumber;
// }
// public void setAdvisornumber(String advisornumber) {
// this.advisornumber = advisornumber;
// }
// public String getDor() {
// return dor;
// }
// public void setDor(String dor) {
// this.dor = dor;
// }
// public String getBranch() {
// return branch;
// }
// public void setBranch(String branch) {
// this.branch = branch;
// }
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: chapter04/src/main/java/com/packt/pfblueprints/controller/AdvisorController.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.packt.pfblueprints.dao.AdvisorDAO;
import com.packt.pfblueprints.model.Representative;
package com.packt.pfblueprints.controller;
@ManagedBean
@ViewScoped
public class AdvisorController implements Serializable{
private static final long serialVersionUID = 1L;
private List<Representative> advisorInfo=new ArrayList<Representative>();
Representative repobj=new Representative();
| AdvisorDAO dao = new AdvisorDAO();
|
sudheerj/primefaces-blueprints | chapter07/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Movie.java
// @Entity
// @Table
// @Data
// public class Movie {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String title;
//
// private String description;
//
// @Temporal(TemporalType.DATE)
// private Date releaseDate;
//
// private int rating;
//
// private boolean favorite;
//
// private String image;
//
// private boolean isImageUrl;
//
// private String movieUrl;
//
// private MovieType movieType;
//
// private boolean isPublic;
//
// @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// @JoinTable(name = "MOVIE_TAGS",
// joinColumns = {@JoinColumn(name = "MOVIE_ID")},
// inverseJoinColumns = {@JoinColumn(name = "TAG_ID")})
// private Set<Tags> tags = new HashSet<>();
//
// @OneToMany(mappedBy = "movie", fetch = FetchType.LAZY)
// private Set<Comment> comments = new HashSet<>();
//
// @ManyToOne
// private User user;
//
//
// public void addToTags(Tags t){
// this.tags.add(t);
// }
//
//
// }
| import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Movie;
import org.hibernate.Session;
import java.util.List; | package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class"); | // Path: chapter09/src/main/java/com/packtpub/pf/blueprint/persistence/HibernateUtil.java
// public class HibernateUtil {
//
// private static final SessionFactory sessionFactory = buildSessionFactory();
//
// private static SessionFactory buildSessionFactory() throws HibernateException {
// Configuration configuration = new Configuration().configure();
// // configures settings from hibernate.cfg.xml
//
// StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
//
// // If you miss the below line then it will complain about a missing dialect setting
// serviceRegistryBuilder.applySettings(configuration.getProperties());
//
// ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
// return configuration.buildSessionFactory(serviceRegistry);
// }
//
// public static SessionFactory getSessionFactory() {
// return sessionFactory;
// }
//
// public static void shutdown() {
// // Close caches and connection pools
// getSessionFactory().close();
// }
//
// }
//
// Path: chapter07/src/main/java/com/packtpub/pf/blueprint/persistence/entity/Movie.java
// @Entity
// @Table
// @Data
// public class Movie {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String title;
//
// private String description;
//
// @Temporal(TemporalType.DATE)
// private Date releaseDate;
//
// private int rating;
//
// private boolean favorite;
//
// private String image;
//
// private boolean isImageUrl;
//
// private String movieUrl;
//
// private MovieType movieType;
//
// private boolean isPublic;
//
// @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// @JoinTable(name = "MOVIE_TAGS",
// joinColumns = {@JoinColumn(name = "MOVIE_ID")},
// inverseJoinColumns = {@JoinColumn(name = "TAG_ID")})
// private Set<Tags> tags = new HashSet<>();
//
// @OneToMany(mappedBy = "movie", fetch = FetchType.LAZY)
// private Set<Comment> comments = new HashSet<>();
//
// @ManyToOne
// private User user;
//
//
// public void addToTags(Tags t){
// this.tags.add(t);
// }
//
//
// }
// Path: chapter07/src/test/java/com/pocketpub/pfbp/test/HibernateUtilTest.java
import com.packtpub.pf.blueprint.persistence.HibernateUtil;
import com.packtpub.pf.blueprint.persistence.entity.Movie;
import org.hibernate.Session;
import java.util.List;
package com.pocketpub.pfbp.test;
/**
* Created with IntelliJ IDEA.
* User: psramkumar
* Date: 2/6/14
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class HibernateUtilTest {
public static void main(String[] args) {
System.out.println("Testing Hibernate Utility Class"); | Session session = HibernateUtil.getSessionFactory().openSession(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.