file_id stringlengths 3 9 | content stringlengths 360 36.5k | repo stringlengths 9 109 | path stringlengths 9 163 | token_length int64 144 8.11k | original_comment stringlengths 6 3.46k | comment_type stringclasses 2
values | detected_lang stringclasses 1
value | prompt stringlengths 273 36.4k |
|---|---|---|---|---|---|---|---|---|
193_19 | package com.unipi.vnikolis.unipismartalert;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection;
import com.unipi.vnikolis.unipismartalert.model.Values;
import com.unipi.vnikolis.unipismartalert.adapter.ItemsAdapter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
/**
* The backend code for Statistics Activity
*/
public class ShowStatistics extends AppCompatActivity implements AdapterView.OnItemClickListener {
FirebaseDatabase firebaseDatabase;
DatabaseReference possiblyDanger, bigDanger, lightDanger, speedDanger, dropDanger;
Spinner mDangerSpinner, mSortDateSpinner;
String dangerSelect, dateSelect, twoDigitMonth, twoDigitDay, dateToCompare, dateToView;
TextView dateView;
DatePickerDialog.OnDateSetListener mDateSetListener;
ArrayList<Values> dangerList = new ArrayList<>();
boolean dateIsSelected, sortDatesIsSelected, dangerIsSelected;
static boolean isItemsButtonClicked;
ArrayAdapter<String> myAdapter2, myAdapter;
ItemsAdapter adapter;
ListView mUserList;
Values v;
int firstTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_statistics);
firebaseDatabase = FirebaseDatabase.getInstance();
possiblyDanger = firebaseDatabase.getReference("PossiblyDanger");
bigDanger = firebaseDatabase.getReference("BigDanger");
lightDanger = possiblyDanger.child("LightDanger");
speedDanger = possiblyDanger.child("SpeedDanger");
dropDanger = possiblyDanger.child("DropDanger");
mUserList = findViewById(R.id.listView);
try {
if (CheckInternetConnection.isConnected(ShowStatistics.this) && CheckInternetConnection.isConnectedFast(ShowStatistics.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
calendarPicker();
dangerPicker();
datePicker();
dangerSelect();
}else{
Toast.makeText(ShowStatistics.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
/**
* Κατασκεύη ημερολογίου και
* Επιλογή ημερομηνίας
*/
public void calendarPicker(){
try {
//create the calendar date picker
dateView = findViewById(R.id.dateView);
dateView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dateIsSelected = true;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(ShowStatistics.this, mDateSetListener, year, month, day);
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@SuppressLint("SetTextI18n")
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
firstTime++;
if (firstTime > 1) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια
mDangerSpinner.setAdapter(myAdapter);
adapter.clear();
}
if (firstTime == 1 && dangerIsSelected) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια
mDangerSpinner.setAdapter(myAdapter);
adapter.clear();
}
month++; // οι μήνες ξεκινάνε από το 0 οπότε προσθέτουμε 1
// Τωρα θα τα μετατρέψω σε 2 digit format γιατί έτσι είναι αποθηκευμένα στη βάση
// ώστε να κάνω σύγκριση
if (month < 10) {
twoDigitMonth = "0" + month;
} else {
twoDigitMonth = String.valueOf(month);
}
if (dayOfMonth < 10) {
twoDigitDay = "0" + dayOfMonth;
} else {
twoDigitDay = String.valueOf(dayOfMonth);
}
dateToCompare = year + "/" + twoDigitMonth + "/" + twoDigitDay;
dateToView = twoDigitDay + "/" + twoDigitMonth + "/" + year;
dateView.setText(dateToView);
}
};
}catch (Exception e){
Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
/**
* Επιλογή κινδύνου από το dropDown Menu
*/
public void dangerPicker(){
try {
//τραβάει τα δεδομένα από το dropdown menu ανα κατηγορια συμβαντος
mDangerSpinner = findViewById(R.id.spinner);
myAdapter = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems)) {
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
tv.setVisibility(View.GONE);
} else { //τοποθετηση χρώματος
tv.setVisibility(View.VISIBLE);
if (position % 2 == 1) {
tv.setBackgroundColor(Color.parseColor("#FFF9A600"));
} else {
tv.setBackgroundColor(Color.parseColor("#FFE49200"));
}
}
return view;
}
};
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDangerSpinner.setPrompt("Choose Danger Category");
mDangerSpinner.setAdapter(myAdapter);
}catch (Exception e){
Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
/**
* Επιλογή ταξινόμισης από το dropDown Menu
*/
public void datePicker(){
mSortDateSpinner = findViewById(R.id.spinner2);
myAdapter2 = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems2)){
@SuppressLint("SetTextI18n")
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent){
sortDatesIsSelected = true;
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position == 0)
{
tv.setVisibility(View.GONE);
}
else{ //τοποθετηση χρώματος
tv.setVisibility(View.VISIBLE);
if(position%2==1)
{
tv.setBackgroundColor(Color.parseColor("#FFF9A600"));
}
else{
tv.setBackgroundColor(Color.parseColor("#FFE49200"));
}
}
return view;
}
};
myAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSortDateSpinner.setPrompt("Choose to Sort by Date");
mSortDateSpinner.setAdapter(myAdapter2);
}
/**
* Ανάλογα με την επιλογή κινδύνου που θα γίνει
* θα τραβήξει και τα αντίστοιχα αποτελέσματα
*/
public void dangerSelect()
{
try {
mDangerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dangerSelect = mDangerSpinner.getSelectedItem().toString();
switch (dangerSelect) {
case "Drop Danger":
dangerIsSelected = true;
//επιλογή κινδύνου
dangerSelector(dropDanger);
//επιλογή ταξινόμισης
sortDateSelector(dropDanger, mSortDateSpinner);
break;
case "Speed Danger":
dangerIsSelected = true;
dangerSelector(speedDanger);
sortDateSelector(speedDanger, mSortDateSpinner);
break;
case "Light Danger":
dangerIsSelected = true;
dangerSelector(lightDanger);
sortDateSelector(lightDanger, mSortDateSpinner);
break;
case "Possibly Danger":
dangerIsSelected = true;
dangerSelector(possiblyDanger);
sortDateSelector(possiblyDanger, mSortDateSpinner);
break;
case "Big Danger":
dangerIsSelected = true;
dangerSelector(bigDanger);
sortDateSelector(bigDanger, mSortDateSpinner);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
/**
* Συλλογή δεδομένων από την FireBase
* ταξινόμηση εαν χρειάζεται και τοποθέτηση
* των δεομένων στο ListView για την εμφάνιση των αποτελεσμάτων
* @param keys Μεταβλητή Iterable τύπου DataSnapshot για την καταλληλότερη
* αναζήτηση αποτελεσμάτων
*/
@SuppressLint("SetTextI18n")
private void collectDangers(Iterable<DataSnapshot> keys) {
try {
dangerList.clear();
adapter = new ItemsAdapter(this, dangerList);
mUserList.setAdapter(adapter);
mUserList.setOnItemClickListener(this);
String compareDate;
if (dangerSelect.equals("Possibly Danger")) {
for (DataSnapshot i : keys) {
for (DataSnapshot j : i.getChildren()) {
v = j.getValue(Values.class);
//εαν υπάρχει διαθέσιμη ημερομηνία από το ημερολόγιο για σύγκριση... κάνε την σύγκριση
if (dateToCompare != null) {
assert v != null;
compareDate = v.getDate().substring(0, 10); //πάρε μονο ένα κομάτι από την συμβολοσειρά της ημερομηνίας που είναι αποθηκευμένη στη βάση
if (compareDate.equals(dateToCompare)) { //και συγκρινέ αυτήν με την ημερομηνία που έχει επιλεγεί από το ημερολόγιο
adapter.add(v); //γέμισε την λίστα
}
} else {
adapter.add(v); //εδω γεμίζει η list
}
}
}
} else if (dangerSelect.equals("Big Danger") || dangerSelect.equals("Light Danger") || dangerSelect.equals("Speed Danger") || dangerSelect.equals("Drop Danger")) {
for (DataSnapshot i : keys) {
v = i.getValue(Values.class);
if (dateToCompare != null) {
assert v != null;
compareDate = v.getDate().substring(0, 10);
if (compareDate.equals(dateToCompare)) {
adapter.add(v);
}
} else {
adapter.add(v); //εδω γεμίζει η list
}
}
}
//εαν εχει επιλεγει η ταξινομιση κάνε την κατα άυξουσα η φθίνουσα σειρά
if (dateSelect != null) {
if (dateSelect.equals("Ascending")) {
//ταξινόμιση βαση ημερομηνιας κατα αυξουσα
Collections.sort(dangerList, new Comparator<Values>() {
@Override
public int compare(Values o1, Values o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
} else if (dateSelect.equals("Descending")) {
//ταξινόμηση βαση ημερομηνιας κατα φθινουσα
Collections.sort(dangerList, Collections.reverseOrder(new Comparator<Values>() {
@Override
public int compare(Values o1, Values o2) {
return o1.getDate().compareTo(o2.getDate());
}
}));
}
}
dateView.setText("Pick Date");
dateToCompare = null;
mSortDateSpinner.setAdapter(myAdapter2);
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
/**
* Σε κάθε αλλάγη της FireBase καλεί την μέδοδο collectDangers
* @param kindOfDanger To Reference της FireBase
*/
private void dangerSelector(DatabaseReference kindOfDanger){
kindOfDanger.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα
{
collectDangers(dataSnapshot.getChildren());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(ShowStatistics.this, "Αποτυχία Ανάγνωσης από τη Βάση", Toast.LENGTH_LONG).show();
}
});
}
/**
* Επιλογή ταξινόμησης κατα άυξουσα η φθίνουσα σειρά
* @param kindOfDanger To Reference της FireBase
* @param selectorToSort Ο Spinner που θέλουμε
*/
//
private void sortDateSelector(final DatabaseReference kindOfDanger, Spinner selectorToSort){
selectorToSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dateSelect = mSortDateSpinner.getSelectedItem().toString();
switch (dateSelect){
case "Ascending":
//ταξινόμιση κατα άυξουσα
dangerSelector(kindOfDanger);
break;
//ταξινόμιση κατα φθίνουσα
case "Descending":
dangerSelector(kindOfDanger);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/**
* Μετάβαση στους χάρτες για έυρεση της συγκεκριμένης
* τοποθεσίας από το ListView
* @param parent ..
* @param view ..
* @param position ..
* @param id ..
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
isItemsButtonClicked = true;
MainActivity.isMapsButtonPressed = false;
Values o =(Values) mUserList.getItemAtPosition(position);
Intent maps = new Intent(ShowStatistics.this, MapsActivity.class);
maps.putExtra("latitude", o.getLatitude());
maps.putExtra("longitude", o.getLongitude());
maps.putExtra("date", o.CorrectDate());
startActivity(maps);
}
}
| 3ngk1sha/DangerDetect | app/src/main/java/com/unipi/vnikolis/unipismartalert/ShowStatistics.java | 4,658 | //πάρε μονο ένα κομάτι από την συμβολοσειρά της ημερομηνίας που είναι αποθηκευμένη στη βάση | line_comment | el | package com.unipi.vnikolis.unipismartalert;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection;
import com.unipi.vnikolis.unipismartalert.model.Values;
import com.unipi.vnikolis.unipismartalert.adapter.ItemsAdapter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
/**
* The backend code for Statistics Activity
*/
public class ShowStatistics extends AppCompatActivity implements AdapterView.OnItemClickListener {
FirebaseDatabase firebaseDatabase;
DatabaseReference possiblyDanger, bigDanger, lightDanger, speedDanger, dropDanger;
Spinner mDangerSpinner, mSortDateSpinner;
String dangerSelect, dateSelect, twoDigitMonth, twoDigitDay, dateToCompare, dateToView;
TextView dateView;
DatePickerDialog.OnDateSetListener mDateSetListener;
ArrayList<Values> dangerList = new ArrayList<>();
boolean dateIsSelected, sortDatesIsSelected, dangerIsSelected;
static boolean isItemsButtonClicked;
ArrayAdapter<String> myAdapter2, myAdapter;
ItemsAdapter adapter;
ListView mUserList;
Values v;
int firstTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_statistics);
firebaseDatabase = FirebaseDatabase.getInstance();
possiblyDanger = firebaseDatabase.getReference("PossiblyDanger");
bigDanger = firebaseDatabase.getReference("BigDanger");
lightDanger = possiblyDanger.child("LightDanger");
speedDanger = possiblyDanger.child("SpeedDanger");
dropDanger = possiblyDanger.child("DropDanger");
mUserList = findViewById(R.id.listView);
try {
if (CheckInternetConnection.isConnected(ShowStatistics.this) && CheckInternetConnection.isConnectedFast(ShowStatistics.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
calendarPicker();
dangerPicker();
datePicker();
dangerSelect();
}else{
Toast.makeText(ShowStatistics.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
/**
* Κατασκεύη ημερολογίου και
* Επιλογή ημερομηνίας
*/
public void calendarPicker(){
try {
//create the calendar date picker
dateView = findViewById(R.id.dateView);
dateView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dateIsSelected = true;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(ShowStatistics.this, mDateSetListener, year, month, day);
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@SuppressLint("SetTextI18n")
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
firstTime++;
if (firstTime > 1) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια
mDangerSpinner.setAdapter(myAdapter);
adapter.clear();
}
if (firstTime == 1 && dangerIsSelected) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια
mDangerSpinner.setAdapter(myAdapter);
adapter.clear();
}
month++; // οι μήνες ξεκινάνε από το 0 οπότε προσθέτουμε 1
// Τωρα θα τα μετατρέψω σε 2 digit format γιατί έτσι είναι αποθηκευμένα στη βάση
// ώστε να κάνω σύγκριση
if (month < 10) {
twoDigitMonth = "0" + month;
} else {
twoDigitMonth = String.valueOf(month);
}
if (dayOfMonth < 10) {
twoDigitDay = "0" + dayOfMonth;
} else {
twoDigitDay = String.valueOf(dayOfMonth);
}
dateToCompare = year + "/" + twoDigitMonth + "/" + twoDigitDay;
dateToView = twoDigitDay + "/" + twoDigitMonth + "/" + year;
dateView.setText(dateToView);
}
};
}catch (Exception e){
Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
/**
* Επιλογή κινδύνου από το dropDown Menu
*/
public void dangerPicker(){
try {
//τραβάει τα δεδομένα από το dropdown menu ανα κατηγορια συμβαντος
mDangerSpinner = findViewById(R.id.spinner);
myAdapter = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems)) {
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
tv.setVisibility(View.GONE);
} else { //τοποθετηση χρώματος
tv.setVisibility(View.VISIBLE);
if (position % 2 == 1) {
tv.setBackgroundColor(Color.parseColor("#FFF9A600"));
} else {
tv.setBackgroundColor(Color.parseColor("#FFE49200"));
}
}
return view;
}
};
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDangerSpinner.setPrompt("Choose Danger Category");
mDangerSpinner.setAdapter(myAdapter);
}catch (Exception e){
Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
/**
* Επιλογή ταξινόμισης από το dropDown Menu
*/
public void datePicker(){
mSortDateSpinner = findViewById(R.id.spinner2);
myAdapter2 = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems2)){
@SuppressLint("SetTextI18n")
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent){
sortDatesIsSelected = true;
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position == 0)
{
tv.setVisibility(View.GONE);
}
else{ //τοποθετηση χρώματος
tv.setVisibility(View.VISIBLE);
if(position%2==1)
{
tv.setBackgroundColor(Color.parseColor("#FFF9A600"));
}
else{
tv.setBackgroundColor(Color.parseColor("#FFE49200"));
}
}
return view;
}
};
myAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSortDateSpinner.setPrompt("Choose to Sort by Date");
mSortDateSpinner.setAdapter(myAdapter2);
}
/**
* Ανάλογα με την επιλογή κινδύνου που θα γίνει
* θα τραβήξει και τα αντίστοιχα αποτελέσματα
*/
public void dangerSelect()
{
try {
mDangerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dangerSelect = mDangerSpinner.getSelectedItem().toString();
switch (dangerSelect) {
case "Drop Danger":
dangerIsSelected = true;
//επιλογή κινδύνου
dangerSelector(dropDanger);
//επιλογή ταξινόμισης
sortDateSelector(dropDanger, mSortDateSpinner);
break;
case "Speed Danger":
dangerIsSelected = true;
dangerSelector(speedDanger);
sortDateSelector(speedDanger, mSortDateSpinner);
break;
case "Light Danger":
dangerIsSelected = true;
dangerSelector(lightDanger);
sortDateSelector(lightDanger, mSortDateSpinner);
break;
case "Possibly Danger":
dangerIsSelected = true;
dangerSelector(possiblyDanger);
sortDateSelector(possiblyDanger, mSortDateSpinner);
break;
case "Big Danger":
dangerIsSelected = true;
dangerSelector(bigDanger);
sortDateSelector(bigDanger, mSortDateSpinner);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
/**
* Συλλογή δεδομένων από την FireBase
* ταξινόμηση εαν χρειάζεται και τοποθέτηση
* των δεομένων στο ListView για την εμφάνιση των αποτελεσμάτων
* @param keys Μεταβλητή Iterable τύπου DataSnapshot για την καταλληλότερη
* αναζήτηση αποτελεσμάτων
*/
@SuppressLint("SetTextI18n")
private void collectDangers(Iterable<DataSnapshot> keys) {
try {
dangerList.clear();
adapter = new ItemsAdapter(this, dangerList);
mUserList.setAdapter(adapter);
mUserList.setOnItemClickListener(this);
String compareDate;
if (dangerSelect.equals("Possibly Danger")) {
for (DataSnapshot i : keys) {
for (DataSnapshot j : i.getChildren()) {
v = j.getValue(Values.class);
//εαν υπάρχει διαθέσιμη ημερομηνία από το ημερολόγιο για σύγκριση... κάνε την σύγκριση
if (dateToCompare != null) {
assert v != null;
compareDate = v.getDate().substring(0, 10); //πάρ<SUF>
if (compareDate.equals(dateToCompare)) { //και συγκρινέ αυτήν με την ημερομηνία που έχει επιλεγεί από το ημερολόγιο
adapter.add(v); //γέμισε την λίστα
}
} else {
adapter.add(v); //εδω γεμίζει η list
}
}
}
} else if (dangerSelect.equals("Big Danger") || dangerSelect.equals("Light Danger") || dangerSelect.equals("Speed Danger") || dangerSelect.equals("Drop Danger")) {
for (DataSnapshot i : keys) {
v = i.getValue(Values.class);
if (dateToCompare != null) {
assert v != null;
compareDate = v.getDate().substring(0, 10);
if (compareDate.equals(dateToCompare)) {
adapter.add(v);
}
} else {
adapter.add(v); //εδω γεμίζει η list
}
}
}
//εαν εχει επιλεγει η ταξινομιση κάνε την κατα άυξουσα η φθίνουσα σειρά
if (dateSelect != null) {
if (dateSelect.equals("Ascending")) {
//ταξινόμιση βαση ημερομηνιας κατα αυξουσα
Collections.sort(dangerList, new Comparator<Values>() {
@Override
public int compare(Values o1, Values o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
} else if (dateSelect.equals("Descending")) {
//ταξινόμηση βαση ημερομηνιας κατα φθινουσα
Collections.sort(dangerList, Collections.reverseOrder(new Comparator<Values>() {
@Override
public int compare(Values o1, Values o2) {
return o1.getDate().compareTo(o2.getDate());
}
}));
}
}
dateView.setText("Pick Date");
dateToCompare = null;
mSortDateSpinner.setAdapter(myAdapter2);
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
/**
* Σε κάθε αλλάγη της FireBase καλεί την μέδοδο collectDangers
* @param kindOfDanger To Reference της FireBase
*/
private void dangerSelector(DatabaseReference kindOfDanger){
kindOfDanger.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα
{
collectDangers(dataSnapshot.getChildren());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(ShowStatistics.this, "Αποτυχία Ανάγνωσης από τη Βάση", Toast.LENGTH_LONG).show();
}
});
}
/**
* Επιλογή ταξινόμησης κατα άυξουσα η φθίνουσα σειρά
* @param kindOfDanger To Reference της FireBase
* @param selectorToSort Ο Spinner που θέλουμε
*/
//
private void sortDateSelector(final DatabaseReference kindOfDanger, Spinner selectorToSort){
selectorToSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dateSelect = mSortDateSpinner.getSelectedItem().toString();
switch (dateSelect){
case "Ascending":
//ταξινόμιση κατα άυξουσα
dangerSelector(kindOfDanger);
break;
//ταξινόμιση κατα φθίνουσα
case "Descending":
dangerSelector(kindOfDanger);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/**
* Μετάβαση στους χάρτες για έυρεση της συγκεκριμένης
* τοποθεσίας από το ListView
* @param parent ..
* @param view ..
* @param position ..
* @param id ..
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
isItemsButtonClicked = true;
MainActivity.isMapsButtonPressed = false;
Values o =(Values) mUserList.getItemAtPosition(position);
Intent maps = new Intent(ShowStatistics.this, MapsActivity.class);
maps.putExtra("latitude", o.getLatitude());
maps.putExtra("longitude", o.getLongitude());
maps.putExtra("date", o.CorrectDate());
startActivity(maps);
}
}
|
6201_17 | package info.android_angel.navigationdrawer.activity_movies;
/**
* Created by ANGELOS on 2017.
*/
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import info.android_angel.navigationdrawer.R;
import info.android_angel.navigationdrawer.adapter_id_movies.credits_id_adapter.CreditsAdapter_cast;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_genres;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_production_companies;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_production_countries;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_spoken_languages;
import info.android_angel.navigationdrawer.adapter_id_movies.reviews_id_adapter.ReviewsAdapter;
import info.android_angel.navigationdrawer.model_movie_id_get_credits.MovieGetCredits;
import info.android_angel.navigationdrawer.model_movie_id_get_credits.MovieGetCredits_cast;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_genres;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_production_companies;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_production_countries;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_spoken_languages;
import info.android_angel.navigationdrawer.model_movie_id_get_reviews.MovieGetReviews;
import info.android_angel.navigationdrawer.model_movie_id_get_reviews.MovieGetReviews_results;
import info.android_angel.navigationdrawer.rest.ApiClient;
import info.android_angel.navigationdrawer.rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Show_Movie_Details_ID extends AppCompatActivity {
TextView java_original_title, java_release_date, java_overview, java_vote_average;
TextView java_budge, java_homepage, java_popularity;
TextView java_revenue, java_tagline, java_runtime;
TextView java_imdb_id,java_tmdb_id;
Button button;
// private ImageView backdrop_path;
private ImageView java_backdrop_path;
private static final String TAG = Show_Movie_Details_ID.class.getSimpleName();
// Album id KEY_MOVIE_ID
String movie_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_movies_get_details_id_and_more);
//TextView java_original_title, java_release_date, java_overview, java_vote_average;
java_original_title = (TextView) findViewById(R.id.original_title);
java_release_date = (TextView) findViewById(R.id.release_date);
java_overview = (TextView) findViewById(R.id.overview);
java_vote_average = (TextView) findViewById(R.id.vote_average);
//TextView java_budge, java_homepage, java_popularity;
java_budge = (TextView) findViewById(R.id.budget);
java_homepage = (TextView) findViewById(R.id.homepage);
java_popularity = (TextView) findViewById(R.id.popularity);
//TextView java_revenue, java_tagline, java_runtime;
java_revenue = (TextView) findViewById(R.id.revenue);
//java_tagline = (TextView) findViewById(R.id.subtitle);
//java_runtime = (TextView) findViewById(R.id.runtime);
java_backdrop_path = (ImageView) findViewById(R.id.backdrop_path_view);
/** Προσοχή εδώ η αλλάγή............. **/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (getResources().getString(R.string.API_KEY).isEmpty()) {
//Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show();
return;
}
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
/** GET
/movie/latest
Call<MovieGetLatest> call = apiService.getLatestMovies(API_KEY);
call.enqueue(new Callback<MovieGetLatest>() {
**/
//intent.getStringExtra(Now_playing_ID.KEY_MOVIE_Overview);
// Get album id
Intent i = getIntent();
movie_id = i.getStringExtra("movie_id");
//key_movie_id = "278";
//Toast.makeText(getApplicationContext(), movie_id, Toast.LENGTH_SHORT).show();
//production_companies
final RecyclerView recyclerView_production_companies = (RecyclerView) findViewById(R.id.production_companies_recycler_view);
recyclerView_production_companies.setLayoutManager(new LinearLayoutManager(this));
//production_countries
final RecyclerView recyclerView_production_countries = (RecyclerView) findViewById(R.id.production_countries_recycler_view);
recyclerView_production_countries.setLayoutManager(new LinearLayoutManager(this));
//genres είδη.
final RecyclerView recyclerView_genres = (RecyclerView) findViewById(R.id.genres_recycler_view);
recyclerView_genres.setLayoutManager(new LinearLayoutManager(this));
//spoken_languages
final RecyclerView recyclerView_spoken_languages = (RecyclerView) findViewById(R.id.spoken_languages_recycler_view);
recyclerView_spoken_languages.setLayoutManager(new LinearLayoutManager(this));
//belongs_to_collection
//final RecyclerView recyclerView_belongs_to_collection = (RecyclerView) findViewById(R.id.belongs_to_collection_recycler_view);
//recyclerView_belongs_to_collection.setLayoutManager(new LinearLayoutManager(this));
/** GET
/movie/{movie_id} ok ok ok
java_tagline
java_runtime**/
Call<MovieGetDetails> call = apiService.getDetailstMoviesId(movie_id, getResources().getString(R.string.API_KEY));
call.enqueue(new Callback<MovieGetDetails>() {
@Override
public void onResponse(Call<MovieGetDetails> call, Response<MovieGetDetails> response) {
try {
if(response.isSuccessful()) {
Picasso.with(getApplicationContext()).load("https://image.tmdb.org/t/p/w1280" + response.body().getBackdropPath()).into(java_backdrop_path);
java_original_title.setText(response.body().getOriginalTitle());
java_release_date.setText(response.body().getReleaseDate());
java_overview.setText(response.body().getOverview());
java_vote_average.setText(response.body().getVoteAverage().toString());
java_budge.setText(response.body().getBudget().toString());
java_homepage.setText(response.body().getHomepage());
java_popularity.setText(response.body().getPopularity().toString());
/** recyclerView_production_companies **/
List<MovieGetDetails_production_companies> movies_Details_production_companies = response.body().getProductionCompanies();
recyclerView_production_companies.setAdapter(new DetailsAdapter_production_companies(movies_Details_production_companies, R.layout.movies_horizontal_id_details, getApplicationContext()));
/** recyclerView_production_countries **/
List<MovieGetDetails_production_countries> movies_Details_production_countries = response.body().getProductionCountries();
recyclerView_production_countries.setAdapter(new DetailsAdapter_production_countries(movies_Details_production_countries, R.layout.movies_horizontal_id_details, getApplicationContext()));
/** recyclerView_genres **/
List<MovieGetDetails_genres> movies_Details_genres = response.body().getGenres();
recyclerView_genres.setAdapter(new DetailsAdapter_genres(movies_Details_genres, R.layout.movies_horizontal_id_details, getApplicationContext()));
/** recyclerView_spoken_languages **/
List<MovieGetDetails_spoken_languages> movies_Details_spoken_languages = response.body().getSpokenLanguages();
recyclerView_spoken_languages.setAdapter(new DetailsAdapter_spoken_languages(movies_Details_spoken_languages, R.layout.movies_horizontal_id_details, getApplicationContext()));
java_revenue.setText(response.body().getRevenue().toString());
//java_tagline.setText(response.body().getTagline());
//java_runtime.setText(response.body().getRuntime().toString());
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
//Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
// Log.d("onResponse", "There is an error");
//e.printStackTrace();
}
}
@Override
public void onFailure(Call<MovieGetDetails> call, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetDetails", Toast.LENGTH_SHORT).show();
}
});
//getMovieSimilar Για να έχουμε LinearLayoutManager.HORIZONTAL
/**
final RecyclerView recyclerView_Similar = (RecyclerView) findViewById(R.id.similar_recycler_view);
recyclerView_Similar.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetSimilarMovies> call_Similar = apiService.getSimilarMoviesId(movie_id, API_KEY);
call_Similar.enqueue(new Callback<MovieGetSimilarMovies>() {
@Override
public void onResponse(Call<MovieGetSimilarMovies> call_Similar, Response<MovieGetSimilarMovies> response) {
if (!response.isSuccessful()) {
//System.out.println("Error");
Toast.makeText(getApplicationContext(),"MovieGetSimilarMovies", Toast.LENGTH_SHORT).show();
}
if(response.isSuccessful()) {
List<MovieGetSimilarMovies_results> movies_similar = response.body().getResults();
recyclerView_Similar.setAdapter(new SimilarAdapter(movies_similar, R.layout.movies_horizontal_id_similar, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
//Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetSimilarMovies> call_Similar, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetSimilarMovies onFailure", Toast.LENGTH_SHORT).show();
}
});
* **/
/**getMovieCredits Για να έχουμε LinearLayoutManager.HORIZONTAL
**/
final RecyclerView recyclerView_Credits_cast = (RecyclerView) findViewById(R.id.credits_cast_recycler_view);
recyclerView_Credits_cast.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetCredits> call_Credits_cast = apiService.getCreditsMoviesId(movie_id, getResources().getString(R.string.API_KEY));
call_Credits_cast.enqueue(new Callback<MovieGetCredits>() {
@Override
public void onResponse(Call<MovieGetCredits> call_Credits_cast, Response<MovieGetCredits> response) {
if (!response.isSuccessful()) {
//System.out.println("Error");
}
if (response.isSuccessful()) {
List<MovieGetCredits_cast> movies_cast = response.body().getCast();
recyclerView_Credits_cast.setAdapter(new CreditsAdapter_cast(movies_cast, R.layout.movies_horizontal_id_credits_cast, getApplicationContext()));
} else {
int statusCode = response.code();
switch (statusCode) {
case 401:
//Toast.makeText(getApplicationContext(), "Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(), "The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
/** 2017 11.04
recyclerView_Credits_cast.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_Credits_cast, new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i_people = new Intent(getApplicationContext(), Show_People_Details_ID.class);
String people_id = ((TextView) view.findViewById(R.id.people_id)).getText().toString();
i_people.putExtra("people_id", people_id);
//i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId());
//Toast.makeText(getApplicationContext(),people_id, Toast.LENGTH_SHORT).show();
startActivity(i_people);
}
@Override
public void onLongClick(View view, int position) {
//on selecting a single album
//TrackListActivity will be launched to show tracks inside the album
//Intent i = new Intent(getApplicationContext(), Popular_Movie.class);
// send album id to tracklist activity to get list of songs under that album
//String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString();
//i.putExtra("movie_id", movie_id);
//startActivity(i);
}
}));
**/
}
@Override
public void onFailure(Call<MovieGetCredits> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
//RecommendationsAdapter
/**getMovieRecommendations Για να έχουμε LinearLayoutManager.HORIZONTAL
final RecyclerView recyclerView_Recommendations = (RecyclerView) findViewById(R.id.recommendations_recycler_view);
recyclerView_Recommendations.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetRecommendations> call_recommendations = apiService.getRecommendationsMoviesId(movie_id, API_KEY);
call_recommendations.enqueue(new Callback<MovieGetRecommendations>() {
@Override
public void onResponse(Call<MovieGetRecommendations> call_Credits, Response<MovieGetRecommendations> response) {
if (!response.isSuccessful()) {
System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetRecommendations_results> movies_recommendations = response.body().getResults();
recyclerView_Recommendations.setAdapter(new RecommendationsAdapter(movies_recommendations, R.layout.movies_horizontal_id_recommendations, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetRecommendations> call_Credits, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetRecommendations", Toast.LENGTH_SHORT).show();
}
});
**/
//ImagesAdapter
/**getMovieImages Για να έχουμε LinearLayoutManager.HORIZONTAL
final RecyclerView recyclerView_Images = (RecyclerView) findViewById(R.id.images_recycler_view);
recyclerView_Images.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetImages> call_Images = apiService.getLatestImagesId(movie_id, API_KEY);
call_Images.enqueue(new Callback<MovieGetImages>() {
@Override
public void onResponse(Call<MovieGetImages> call_Images, Response<MovieGetImages> response) {
if (!response.isSuccessful()) {
System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetImages_backdrops> movies_images = response.body().getBackdrops();
recyclerView_Images.setAdapter(new ImagesAdapter(movies_images, R.layout.movies_horizontal_id_images, getApplicationContext()));
//https://www.themoviedb.org/documentation/api/status-codes
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetImages> call_Credits, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetImages", Toast.LENGTH_SHORT).show();
}
});
**/
//ReviewsAdapter OK OK OK
/**getMovieReviews Για να έχουμε LinearLayoutManager.HORIZONTAL
**/
final RecyclerView recyclerView_Reviews = (RecyclerView) findViewById(R.id.reviews_recycler_view);
recyclerView_Reviews.setLayoutManager(new LinearLayoutManager(this));
Call<MovieGetReviews> call_Reviews = apiService.getReviewsMoviesId(movie_id, getResources().getString(R.string.API_KEY));
call_Reviews.enqueue(new Callback<MovieGetReviews>() {
@Override
public void onResponse(Call<MovieGetReviews> call_Reviews, Response<MovieGetReviews> response) {
if (!response.isSuccessful()) {
//System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetReviews_results> movies_reviews = response.body().getResults();
recyclerView_Reviews.setAdapter(new ReviewsAdapter(movies_reviews, R.layout.movies_horizontal_id_reviews, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
//case 401:
//Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
//case 404:
//Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
case 401:
//Toast.makeText(getApplicationContext(), "Authentication failed: You do not have permissions to access the service.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(), "The resource you requested could not be found. Invalid id: The pre-requisite id is invalid or not found.", Toast.LENGTH_SHORT).show();
case 503:
//Toast.makeText(getApplicationContext(), "Service offline: This service is temporarily offline, try again later.", Toast.LENGTH_SHORT).show();
case 429:
//Toast.makeText(getApplicationContext(), "Your request count (#) is over the allowed limit of (40).", Toast.LENGTH_SHORT).show();
case 400:
//Toast.makeText(getApplicationContext(), "Too many append to response objects: The maximum number of remote calls is 20.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetReviews> call_Credits, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetReviews", Toast.LENGTH_SHORT).show();
}
});
//Credits_crew OK OK OK
/**getCredits_crew Για να έχουμε LinearLayoutManager.HORIZONTAL
*/
/**
final RecyclerView recyclerView_Credits_crew = (RecyclerView) findViewById(R.id.credits_crew_recycler_view);
recyclerView_Credits_crew.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetCredits> call_Credits_crew = apiService.getCreditsMoviesId(movie_id, API_KEY);
call_Credits_crew.enqueue(new Callback<MovieGetCredits>() {
@Override
public void onResponse(Call<MovieGetCredits> call_Similar_crew, Response<MovieGetCredits> response) {
if (!response.isSuccessful()) {
System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetCredits_crew> movies_credits_crew = response.body().getCrew();
recyclerView_Credits_crew.setAdapter(new CreditsAdapter_crew(movies_credits_crew, R.layout.movies_horizontal_id_credits_crew, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetCredits> call_Credits_crew, Throwable t) {
// Toast.makeText(getApplicationContext(), "MovieGetSimilarMovies", Toast.LENGTH_SHORT).show();
}
});
**/
}
/** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
// finish the activity
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| ANGELOS-TSILAFAKIS/NavigationDrawerPublic | app/src/main/java/info/android_angel/navigationdrawer/activity_movies/Show_Movie_Details_ID.java | 5,430 | //genres είδη. | line_comment | el | package info.android_angel.navigationdrawer.activity_movies;
/**
* Created by ANGELOS on 2017.
*/
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import info.android_angel.navigationdrawer.R;
import info.android_angel.navigationdrawer.adapter_id_movies.credits_id_adapter.CreditsAdapter_cast;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_genres;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_production_companies;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_production_countries;
import info.android_angel.navigationdrawer.adapter_id_movies.details_id_adapter.DetailsAdapter_spoken_languages;
import info.android_angel.navigationdrawer.adapter_id_movies.reviews_id_adapter.ReviewsAdapter;
import info.android_angel.navigationdrawer.model_movie_id_get_credits.MovieGetCredits;
import info.android_angel.navigationdrawer.model_movie_id_get_credits.MovieGetCredits_cast;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_genres;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_production_companies;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_production_countries;
import info.android_angel.navigationdrawer.model_movie_id_get_details.MovieGetDetails_spoken_languages;
import info.android_angel.navigationdrawer.model_movie_id_get_reviews.MovieGetReviews;
import info.android_angel.navigationdrawer.model_movie_id_get_reviews.MovieGetReviews_results;
import info.android_angel.navigationdrawer.rest.ApiClient;
import info.android_angel.navigationdrawer.rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Show_Movie_Details_ID extends AppCompatActivity {
TextView java_original_title, java_release_date, java_overview, java_vote_average;
TextView java_budge, java_homepage, java_popularity;
TextView java_revenue, java_tagline, java_runtime;
TextView java_imdb_id,java_tmdb_id;
Button button;
// private ImageView backdrop_path;
private ImageView java_backdrop_path;
private static final String TAG = Show_Movie_Details_ID.class.getSimpleName();
// Album id KEY_MOVIE_ID
String movie_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_movies_get_details_id_and_more);
//TextView java_original_title, java_release_date, java_overview, java_vote_average;
java_original_title = (TextView) findViewById(R.id.original_title);
java_release_date = (TextView) findViewById(R.id.release_date);
java_overview = (TextView) findViewById(R.id.overview);
java_vote_average = (TextView) findViewById(R.id.vote_average);
//TextView java_budge, java_homepage, java_popularity;
java_budge = (TextView) findViewById(R.id.budget);
java_homepage = (TextView) findViewById(R.id.homepage);
java_popularity = (TextView) findViewById(R.id.popularity);
//TextView java_revenue, java_tagline, java_runtime;
java_revenue = (TextView) findViewById(R.id.revenue);
//java_tagline = (TextView) findViewById(R.id.subtitle);
//java_runtime = (TextView) findViewById(R.id.runtime);
java_backdrop_path = (ImageView) findViewById(R.id.backdrop_path_view);
/** Προσοχή εδώ η αλλάγή............. **/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (getResources().getString(R.string.API_KEY).isEmpty()) {
//Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show();
return;
}
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
/** GET
/movie/latest
Call<MovieGetLatest> call = apiService.getLatestMovies(API_KEY);
call.enqueue(new Callback<MovieGetLatest>() {
**/
//intent.getStringExtra(Now_playing_ID.KEY_MOVIE_Overview);
// Get album id
Intent i = getIntent();
movie_id = i.getStringExtra("movie_id");
//key_movie_id = "278";
//Toast.makeText(getApplicationContext(), movie_id, Toast.LENGTH_SHORT).show();
//production_companies
final RecyclerView recyclerView_production_companies = (RecyclerView) findViewById(R.id.production_companies_recycler_view);
recyclerView_production_companies.setLayoutManager(new LinearLayoutManager(this));
//production_countries
final RecyclerView recyclerView_production_countries = (RecyclerView) findViewById(R.id.production_countries_recycler_view);
recyclerView_production_countries.setLayoutManager(new LinearLayoutManager(this));
//gen<SUF>
final RecyclerView recyclerView_genres = (RecyclerView) findViewById(R.id.genres_recycler_view);
recyclerView_genres.setLayoutManager(new LinearLayoutManager(this));
//spoken_languages
final RecyclerView recyclerView_spoken_languages = (RecyclerView) findViewById(R.id.spoken_languages_recycler_view);
recyclerView_spoken_languages.setLayoutManager(new LinearLayoutManager(this));
//belongs_to_collection
//final RecyclerView recyclerView_belongs_to_collection = (RecyclerView) findViewById(R.id.belongs_to_collection_recycler_view);
//recyclerView_belongs_to_collection.setLayoutManager(new LinearLayoutManager(this));
/** GET
/movie/{movie_id} ok ok ok
java_tagline
java_runtime**/
Call<MovieGetDetails> call = apiService.getDetailstMoviesId(movie_id, getResources().getString(R.string.API_KEY));
call.enqueue(new Callback<MovieGetDetails>() {
@Override
public void onResponse(Call<MovieGetDetails> call, Response<MovieGetDetails> response) {
try {
if(response.isSuccessful()) {
Picasso.with(getApplicationContext()).load("https://image.tmdb.org/t/p/w1280" + response.body().getBackdropPath()).into(java_backdrop_path);
java_original_title.setText(response.body().getOriginalTitle());
java_release_date.setText(response.body().getReleaseDate());
java_overview.setText(response.body().getOverview());
java_vote_average.setText(response.body().getVoteAverage().toString());
java_budge.setText(response.body().getBudget().toString());
java_homepage.setText(response.body().getHomepage());
java_popularity.setText(response.body().getPopularity().toString());
/** recyclerView_production_companies **/
List<MovieGetDetails_production_companies> movies_Details_production_companies = response.body().getProductionCompanies();
recyclerView_production_companies.setAdapter(new DetailsAdapter_production_companies(movies_Details_production_companies, R.layout.movies_horizontal_id_details, getApplicationContext()));
/** recyclerView_production_countries **/
List<MovieGetDetails_production_countries> movies_Details_production_countries = response.body().getProductionCountries();
recyclerView_production_countries.setAdapter(new DetailsAdapter_production_countries(movies_Details_production_countries, R.layout.movies_horizontal_id_details, getApplicationContext()));
/** recyclerView_genres **/
List<MovieGetDetails_genres> movies_Details_genres = response.body().getGenres();
recyclerView_genres.setAdapter(new DetailsAdapter_genres(movies_Details_genres, R.layout.movies_horizontal_id_details, getApplicationContext()));
/** recyclerView_spoken_languages **/
List<MovieGetDetails_spoken_languages> movies_Details_spoken_languages = response.body().getSpokenLanguages();
recyclerView_spoken_languages.setAdapter(new DetailsAdapter_spoken_languages(movies_Details_spoken_languages, R.layout.movies_horizontal_id_details, getApplicationContext()));
java_revenue.setText(response.body().getRevenue().toString());
//java_tagline.setText(response.body().getTagline());
//java_runtime.setText(response.body().getRuntime().toString());
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
//Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
// Log.d("onResponse", "There is an error");
//e.printStackTrace();
}
}
@Override
public void onFailure(Call<MovieGetDetails> call, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetDetails", Toast.LENGTH_SHORT).show();
}
});
//getMovieSimilar Για να έχουμε LinearLayoutManager.HORIZONTAL
/**
final RecyclerView recyclerView_Similar = (RecyclerView) findViewById(R.id.similar_recycler_view);
recyclerView_Similar.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetSimilarMovies> call_Similar = apiService.getSimilarMoviesId(movie_id, API_KEY);
call_Similar.enqueue(new Callback<MovieGetSimilarMovies>() {
@Override
public void onResponse(Call<MovieGetSimilarMovies> call_Similar, Response<MovieGetSimilarMovies> response) {
if (!response.isSuccessful()) {
//System.out.println("Error");
Toast.makeText(getApplicationContext(),"MovieGetSimilarMovies", Toast.LENGTH_SHORT).show();
}
if(response.isSuccessful()) {
List<MovieGetSimilarMovies_results> movies_similar = response.body().getResults();
recyclerView_Similar.setAdapter(new SimilarAdapter(movies_similar, R.layout.movies_horizontal_id_similar, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
//Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetSimilarMovies> call_Similar, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetSimilarMovies onFailure", Toast.LENGTH_SHORT).show();
}
});
* **/
/**getMovieCredits Για να έχουμε LinearLayoutManager.HORIZONTAL
**/
final RecyclerView recyclerView_Credits_cast = (RecyclerView) findViewById(R.id.credits_cast_recycler_view);
recyclerView_Credits_cast.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetCredits> call_Credits_cast = apiService.getCreditsMoviesId(movie_id, getResources().getString(R.string.API_KEY));
call_Credits_cast.enqueue(new Callback<MovieGetCredits>() {
@Override
public void onResponse(Call<MovieGetCredits> call_Credits_cast, Response<MovieGetCredits> response) {
if (!response.isSuccessful()) {
//System.out.println("Error");
}
if (response.isSuccessful()) {
List<MovieGetCredits_cast> movies_cast = response.body().getCast();
recyclerView_Credits_cast.setAdapter(new CreditsAdapter_cast(movies_cast, R.layout.movies_horizontal_id_credits_cast, getApplicationContext()));
} else {
int statusCode = response.code();
switch (statusCode) {
case 401:
//Toast.makeText(getApplicationContext(), "Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(), "The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
/** 2017 11.04
recyclerView_Credits_cast.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_Credits_cast, new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, int position) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i_people = new Intent(getApplicationContext(), Show_People_Details_ID.class);
String people_id = ((TextView) view.findViewById(R.id.people_id)).getText().toString();
i_people.putExtra("people_id", people_id);
//i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId());
//Toast.makeText(getApplicationContext(),people_id, Toast.LENGTH_SHORT).show();
startActivity(i_people);
}
@Override
public void onLongClick(View view, int position) {
//on selecting a single album
//TrackListActivity will be launched to show tracks inside the album
//Intent i = new Intent(getApplicationContext(), Popular_Movie.class);
// send album id to tracklist activity to get list of songs under that album
//String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString();
//i.putExtra("movie_id", movie_id);
//startActivity(i);
}
}));
**/
}
@Override
public void onFailure(Call<MovieGetCredits> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
//RecommendationsAdapter
/**getMovieRecommendations Για να έχουμε LinearLayoutManager.HORIZONTAL
final RecyclerView recyclerView_Recommendations = (RecyclerView) findViewById(R.id.recommendations_recycler_view);
recyclerView_Recommendations.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetRecommendations> call_recommendations = apiService.getRecommendationsMoviesId(movie_id, API_KEY);
call_recommendations.enqueue(new Callback<MovieGetRecommendations>() {
@Override
public void onResponse(Call<MovieGetRecommendations> call_Credits, Response<MovieGetRecommendations> response) {
if (!response.isSuccessful()) {
System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetRecommendations_results> movies_recommendations = response.body().getResults();
recyclerView_Recommendations.setAdapter(new RecommendationsAdapter(movies_recommendations, R.layout.movies_horizontal_id_recommendations, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetRecommendations> call_Credits, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetRecommendations", Toast.LENGTH_SHORT).show();
}
});
**/
//ImagesAdapter
/**getMovieImages Για να έχουμε LinearLayoutManager.HORIZONTAL
final RecyclerView recyclerView_Images = (RecyclerView) findViewById(R.id.images_recycler_view);
recyclerView_Images.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetImages> call_Images = apiService.getLatestImagesId(movie_id, API_KEY);
call_Images.enqueue(new Callback<MovieGetImages>() {
@Override
public void onResponse(Call<MovieGetImages> call_Images, Response<MovieGetImages> response) {
if (!response.isSuccessful()) {
System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetImages_backdrops> movies_images = response.body().getBackdrops();
recyclerView_Images.setAdapter(new ImagesAdapter(movies_images, R.layout.movies_horizontal_id_images, getApplicationContext()));
//https://www.themoviedb.org/documentation/api/status-codes
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetImages> call_Credits, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetImages", Toast.LENGTH_SHORT).show();
}
});
**/
//ReviewsAdapter OK OK OK
/**getMovieReviews Για να έχουμε LinearLayoutManager.HORIZONTAL
**/
final RecyclerView recyclerView_Reviews = (RecyclerView) findViewById(R.id.reviews_recycler_view);
recyclerView_Reviews.setLayoutManager(new LinearLayoutManager(this));
Call<MovieGetReviews> call_Reviews = apiService.getReviewsMoviesId(movie_id, getResources().getString(R.string.API_KEY));
call_Reviews.enqueue(new Callback<MovieGetReviews>() {
@Override
public void onResponse(Call<MovieGetReviews> call_Reviews, Response<MovieGetReviews> response) {
if (!response.isSuccessful()) {
//System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetReviews_results> movies_reviews = response.body().getResults();
recyclerView_Reviews.setAdapter(new ReviewsAdapter(movies_reviews, R.layout.movies_horizontal_id_reviews, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
//case 401:
//Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
//case 404:
//Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
case 401:
//Toast.makeText(getApplicationContext(), "Authentication failed: You do not have permissions to access the service.", Toast.LENGTH_SHORT).show();
case 404:
//Toast.makeText(getApplicationContext(), "The resource you requested could not be found. Invalid id: The pre-requisite id is invalid or not found.", Toast.LENGTH_SHORT).show();
case 503:
//Toast.makeText(getApplicationContext(), "Service offline: This service is temporarily offline, try again later.", Toast.LENGTH_SHORT).show();
case 429:
//Toast.makeText(getApplicationContext(), "Your request count (#) is over the allowed limit of (40).", Toast.LENGTH_SHORT).show();
case 400:
//Toast.makeText(getApplicationContext(), "Too many append to response objects: The maximum number of remote calls is 20.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetReviews> call_Credits, Throwable t) {
//Toast.makeText(getApplicationContext(), "MovieGetReviews", Toast.LENGTH_SHORT).show();
}
});
//Credits_crew OK OK OK
/**getCredits_crew Για να έχουμε LinearLayoutManager.HORIZONTAL
*/
/**
final RecyclerView recyclerView_Credits_crew = (RecyclerView) findViewById(R.id.credits_crew_recycler_view);
recyclerView_Credits_crew.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Call<MovieGetCredits> call_Credits_crew = apiService.getCreditsMoviesId(movie_id, API_KEY);
call_Credits_crew.enqueue(new Callback<MovieGetCredits>() {
@Override
public void onResponse(Call<MovieGetCredits> call_Similar_crew, Response<MovieGetCredits> response) {
if (!response.isSuccessful()) {
System.out.println("Error");
}
if(response.isSuccessful()) {
List<MovieGetCredits_crew> movies_credits_crew = response.body().getCrew();
recyclerView_Credits_crew.setAdapter(new CreditsAdapter_crew(movies_credits_crew, R.layout.movies_horizontal_id_credits_crew, getApplicationContext()));
}else{
int statusCode = response.code();
switch(statusCode){
case 401:
Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show();
case 404:
Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MovieGetCredits> call_Credits_crew, Throwable t) {
// Toast.makeText(getApplicationContext(), "MovieGetSimilarMovies", Toast.LENGTH_SHORT).show();
}
});
**/
}
/** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
// finish the activity
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
17272_21 | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"});
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"});
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} | Abbe98/corelib | corelib-schemaorg/src/test/java/eu/europeana/corelib/edm/utils/MockFullBean.java | 6,557 | //el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"}); | line_comment | el | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"});
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el.<SUF>
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} |
11039_5 | package gr.rambou.myicarus;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
public class Icarus implements Serializable {
private final String Username, Password;
public Map<String, String> Cookies;
private String StudentFullName, ID, StudentName, Surname;
//private Document Page;
private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons;
public Icarus(String username, String password) {
this.Username = username;
this.Password = password;
this.StudentFullName = null;
this.Cookies = null;
}
public boolean login() {
try {
//ενεργοποιούμε το SSL
enableSSLSocket();
//Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε
Connection.Response res = Jsoup
.connect("https://icarus-icsd.aegean.gr/authentication.php")
.timeout(10 * 1000)
.data("username", Username, "pwd", Password)
.method(Connection.Method.POST)
.execute();
//Παίρνουμε τα cookies
Cookies = res.cookies();
//Αποθηκεύουμε το περιεχόμενο της σελίδας
Document Page = res.parse();
//Ελέγχουμε αν συνδεθήκαμε
Elements name = Page.select("div#header_login").select("u");
if (name.hasText()) {
//Παίρνουμε το ονοματεπώνυμο του φοιτητή
StudentFullName = name.html();
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
Pattern r = Pattern.compile("[0-9-/-]{5,16}");
String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim();
Matcher m = r.matcher(line);
if (m.find()) {
ID = m.group(0);
}
//Παίρνουμε τους βαθμούς του φοιτητή
LoadMarks(Page);
return true;
}
} catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) {
Log.v("Icarus Class", ex.toString());
}
return false;
}
public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) {
if (papers.length != 11) {
return false;
}
String sendmethod;
if (sendtype.equals(SendType.FAX)) {
sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:";
} else if (sendtype.equals(SendType.COURIER)) {
sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:";
} else {
sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης";
}
//We create the Data to be Send
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addTextBody("aitisi_student_id", getID());
mpEntity.addTextBody("aitisi_surname", getSurname());
mpEntity.addTextBody("aitisi_name", getStudentName());
mpEntity.addTextBody("aitisi_father", fatherName);
mpEntity.addTextBody("aitisi_semester", cemester.toString());
mpEntity.addTextBody("aitisi_address", address);
mpEntity.addTextBody("aitisi_phone", phone);
mpEntity.addTextBody("aitisi_send_method", sendmethod);
mpEntity.addTextBody("aitisi_send_address", send_address);
mpEntity.addTextBody("prints_no[]", papers[0]);
mpEntity.addTextBody("prints_no[]", papers[1]);
mpEntity.addTextBody("prints_no[]", papers[2]);
mpEntity.addTextBody("prints_no[]", papers[3]);
mpEntity.addTextBody("prints_no[]", papers[4]);
mpEntity.addTextBody("prints_no[]", papers[5]);
mpEntity.addTextBody("prints_no[]", papers[6]);
mpEntity.addTextBody("prints_no[]", papers[7]);
mpEntity.addTextBody("prints_no[]", papers[8]);
mpEntity.addTextBody("prints_no[]", papers[9]);
mpEntity.addTextBody("aitisi_allo", papers[10]);
mpEntity.addTextBody("send", "");
HttpEntity entity = mpEntity.build();
//We send the request
HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php");
post.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
//Gets new/old cookies and set them in store and store to CTX
CookieStore Store = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID"));
cookie.setPath("//");
cookie.setDomain("icarus-icsd.aegean.gr");
Store.addCookie(cookie);
HttpContext CTX = new BasicHttpContext();
CTX.setAttribute(ClientContext.COOKIE_STORE, Store);
HttpResponse response = null;
try {
response = client.execute(post, CTX);
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
}
//Check if user credentials are ok
if (response == null) {
return false;
}
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 200) {
return false;
}
try {
String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7");
Document res = Jsoup.parse(html);
if (res.getElementsByClass("success").isEmpty()) {
return false;
}
} catch (IOException | org.apache.http.ParseException ex) {
return false;
}
return true;
}
public void LoadMarks(Document response) {
All_Lessons = new ArrayList<>();
Succeed_Lessons = new ArrayList<>();
Exams_Lessons = new ArrayList<>();
if (response == null) {
try {
//We send the request
response = Jsoup
.connect("https://icarus-icsd.aegean.gr/student_main.php")
.cookies(Cookies)
.get();
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
return;
}
}
//Start Catching Lessons
Elements sGrades = response.getElementById("succeeded_grades").select("tr");
Elements aGrades = response.getElementById("analytic_grades").select("tr");
Elements eGrades = response.getElementById("exetastiki_grades").select("tr");
for (Element a : sGrades) {
if (!a.select("td").isEmpty()) {
Succeed_Lessons.add(getLesson(a));
}
}
for (Element a : eGrades) {
if (!a.select("td").isEmpty()) {
Exams_Lessons.add(getLesson(a));
if (a.select("td").get(6).text().trim().compareTo("") != 0)
All_Lessons.add(getLesson(a));
}
}
for (Element a : aGrades) {
if (!a.select("td").isEmpty()) {
All_Lessons.add(getLesson(a));
}
}
}
private Lesson getLesson(Element a) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String ID = a.select("td").get(1).text();
String Title = a.select("td").get(2).text();
Double Mark = 0.0;
try {
Mark = Double.valueOf(a.select("td").get(3).text());
} catch (Exception ex) {
}
String Cemester = a.select("td").get(4).text();
Date Statement = null, Exam = null;
try {
Statement = formatter.parse(a.select("td").get(5).text().trim());
Exam = formatter.parse(a.select("td").get(6).text().trim());
} catch (ParseException ex) {
}
Lesson.LessonStatus Status;
switch (a.select("td").get(7).text().trim()) {
case "Επιτυχία":
Status = Lesson.LessonStatus.PASSED;
break;
case "Αποτυχία":
Status = Lesson.LessonStatus.FAILED;
break;
case "Ακύρωση":
Status = Lesson.LessonStatus.CANCELLED;
break;
default:
Status = Lesson.LessonStatus.NOT_GIVEN;
break;
}
return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status);
}
public ArrayList<Lesson> getSucceed_Lessons() {
return Succeed_Lessons;
}
public ArrayList<Lesson> getAll_Lessons() {
return All_Lessons;
}
public Object[] getAll_Lessons_array() {
return All_Lessons.toArray();
}
public ArrayList<Lesson> getExams_Lessons() {
return Exams_Lessons;
}
public String getStudentFullName() {
return StudentFullName;
}
public String getID() {
return ID;
}
public String getStudentName() {
return StudentFullName.split(" ")[0];
}
public String getSurname() {
return StudentFullName.split(" ")[1];
}
private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
//HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true);
SSLContext context;
context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
public enum SendType {
OFFICE, COURIER, FAX
}
public enum PaperType {
bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo,
stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma,
allo
}
}
| AegeanHawks/MobileIcarus | app/src/main/java/gr/rambou/myicarus/Icarus.java | 3,246 | //Αποθηκεύουμε το περιεχόμενο της σελίδας | line_comment | el | package gr.rambou.myicarus;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
public class Icarus implements Serializable {
private final String Username, Password;
public Map<String, String> Cookies;
private String StudentFullName, ID, StudentName, Surname;
//private Document Page;
private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons;
public Icarus(String username, String password) {
this.Username = username;
this.Password = password;
this.StudentFullName = null;
this.Cookies = null;
}
public boolean login() {
try {
//ενεργοποιούμε το SSL
enableSSLSocket();
//Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε
Connection.Response res = Jsoup
.connect("https://icarus-icsd.aegean.gr/authentication.php")
.timeout(10 * 1000)
.data("username", Username, "pwd", Password)
.method(Connection.Method.POST)
.execute();
//Παίρνουμε τα cookies
Cookies = res.cookies();
//Απο<SUF>
Document Page = res.parse();
//Ελέγχουμε αν συνδεθήκαμε
Elements name = Page.select("div#header_login").select("u");
if (name.hasText()) {
//Παίρνουμε το ονοματεπώνυμο του φοιτητή
StudentFullName = name.html();
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
Pattern r = Pattern.compile("[0-9-/-]{5,16}");
String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim();
Matcher m = r.matcher(line);
if (m.find()) {
ID = m.group(0);
}
//Παίρνουμε τους βαθμούς του φοιτητή
LoadMarks(Page);
return true;
}
} catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) {
Log.v("Icarus Class", ex.toString());
}
return false;
}
public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) {
if (papers.length != 11) {
return false;
}
String sendmethod;
if (sendtype.equals(SendType.FAX)) {
sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:";
} else if (sendtype.equals(SendType.COURIER)) {
sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:";
} else {
sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης";
}
//We create the Data to be Send
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addTextBody("aitisi_student_id", getID());
mpEntity.addTextBody("aitisi_surname", getSurname());
mpEntity.addTextBody("aitisi_name", getStudentName());
mpEntity.addTextBody("aitisi_father", fatherName);
mpEntity.addTextBody("aitisi_semester", cemester.toString());
mpEntity.addTextBody("aitisi_address", address);
mpEntity.addTextBody("aitisi_phone", phone);
mpEntity.addTextBody("aitisi_send_method", sendmethod);
mpEntity.addTextBody("aitisi_send_address", send_address);
mpEntity.addTextBody("prints_no[]", papers[0]);
mpEntity.addTextBody("prints_no[]", papers[1]);
mpEntity.addTextBody("prints_no[]", papers[2]);
mpEntity.addTextBody("prints_no[]", papers[3]);
mpEntity.addTextBody("prints_no[]", papers[4]);
mpEntity.addTextBody("prints_no[]", papers[5]);
mpEntity.addTextBody("prints_no[]", papers[6]);
mpEntity.addTextBody("prints_no[]", papers[7]);
mpEntity.addTextBody("prints_no[]", papers[8]);
mpEntity.addTextBody("prints_no[]", papers[9]);
mpEntity.addTextBody("aitisi_allo", papers[10]);
mpEntity.addTextBody("send", "");
HttpEntity entity = mpEntity.build();
//We send the request
HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php");
post.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
//Gets new/old cookies and set them in store and store to CTX
CookieStore Store = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID"));
cookie.setPath("//");
cookie.setDomain("icarus-icsd.aegean.gr");
Store.addCookie(cookie);
HttpContext CTX = new BasicHttpContext();
CTX.setAttribute(ClientContext.COOKIE_STORE, Store);
HttpResponse response = null;
try {
response = client.execute(post, CTX);
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
}
//Check if user credentials are ok
if (response == null) {
return false;
}
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 200) {
return false;
}
try {
String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7");
Document res = Jsoup.parse(html);
if (res.getElementsByClass("success").isEmpty()) {
return false;
}
} catch (IOException | org.apache.http.ParseException ex) {
return false;
}
return true;
}
public void LoadMarks(Document response) {
All_Lessons = new ArrayList<>();
Succeed_Lessons = new ArrayList<>();
Exams_Lessons = new ArrayList<>();
if (response == null) {
try {
//We send the request
response = Jsoup
.connect("https://icarus-icsd.aegean.gr/student_main.php")
.cookies(Cookies)
.get();
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
return;
}
}
//Start Catching Lessons
Elements sGrades = response.getElementById("succeeded_grades").select("tr");
Elements aGrades = response.getElementById("analytic_grades").select("tr");
Elements eGrades = response.getElementById("exetastiki_grades").select("tr");
for (Element a : sGrades) {
if (!a.select("td").isEmpty()) {
Succeed_Lessons.add(getLesson(a));
}
}
for (Element a : eGrades) {
if (!a.select("td").isEmpty()) {
Exams_Lessons.add(getLesson(a));
if (a.select("td").get(6).text().trim().compareTo("") != 0)
All_Lessons.add(getLesson(a));
}
}
for (Element a : aGrades) {
if (!a.select("td").isEmpty()) {
All_Lessons.add(getLesson(a));
}
}
}
private Lesson getLesson(Element a) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String ID = a.select("td").get(1).text();
String Title = a.select("td").get(2).text();
Double Mark = 0.0;
try {
Mark = Double.valueOf(a.select("td").get(3).text());
} catch (Exception ex) {
}
String Cemester = a.select("td").get(4).text();
Date Statement = null, Exam = null;
try {
Statement = formatter.parse(a.select("td").get(5).text().trim());
Exam = formatter.parse(a.select("td").get(6).text().trim());
} catch (ParseException ex) {
}
Lesson.LessonStatus Status;
switch (a.select("td").get(7).text().trim()) {
case "Επιτυχία":
Status = Lesson.LessonStatus.PASSED;
break;
case "Αποτυχία":
Status = Lesson.LessonStatus.FAILED;
break;
case "Ακύρωση":
Status = Lesson.LessonStatus.CANCELLED;
break;
default:
Status = Lesson.LessonStatus.NOT_GIVEN;
break;
}
return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status);
}
public ArrayList<Lesson> getSucceed_Lessons() {
return Succeed_Lessons;
}
public ArrayList<Lesson> getAll_Lessons() {
return All_Lessons;
}
public Object[] getAll_Lessons_array() {
return All_Lessons.toArray();
}
public ArrayList<Lesson> getExams_Lessons() {
return Exams_Lessons;
}
public String getStudentFullName() {
return StudentFullName;
}
public String getID() {
return ID;
}
public String getStudentName() {
return StudentFullName.split(" ")[0];
}
public String getSurname() {
return StudentFullName.split(" ")[1];
}
private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
//HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true);
SSLContext context;
context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
public enum SendType {
OFFICE, COURIER, FAX
}
public enum PaperType {
bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo,
stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma,
allo
}
}
|
16421_2 | package com.kospeac.smartgreecealert;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
/*
* H LocationService επιστρεφει τις συντεταγμενες της συσκευης του χρηστη με την χρηση του gps
* */
public class LocationService implements LocationListener {
static double latitude;
static double longitude;
@Override
public void onLocationChanged(Location location) {
if(location==null){
}else {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
/*
* getDistance
* Υπολογιζει με βαση τις συντεταγμενες εισοδου αμα η αποσταση σε μετρα ειναι
* μικροτερη η ιση με 5000 μετρα (5χμλ)
* */
public static boolean getDistance(Double lat1, Double lon1, Double lat2, Double lon2){
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
System.out.println(distanceInMeters);
if(distanceInMeters <= 5000){ // Αν η αποσταση ειναι μικροτερη απο 5χλ
return true;
}else {
return false;
}
}
}
| Afrodith/SmartAlertGreece | app/src/main/java/com/kospeac/smartgreecealert/LocationService.java | 625 | // Αν η αποσταση ειναι μικροτερη απο 5χλ | line_comment | el | package com.kospeac.smartgreecealert;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
/*
* H LocationService επιστρεφει τις συντεταγμενες της συσκευης του χρηστη με την χρηση του gps
* */
public class LocationService implements LocationListener {
static double latitude;
static double longitude;
@Override
public void onLocationChanged(Location location) {
if(location==null){
}else {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
/*
* getDistance
* Υπολογιζει με βαση τις συντεταγμενες εισοδου αμα η αποσταση σε μετρα ειναι
* μικροτερη η ιση με 5000 μετρα (5χμλ)
* */
public static boolean getDistance(Double lat1, Double lon1, Double lat2, Double lon2){
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
System.out.println(distanceInMeters);
if(distanceInMeters <= 5000){ // Αν <SUF>
return true;
}else {
return false;
}
}
}
|
18080_9 | package gr.aueb;
import org.apiguardian.api.API;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
/*The BonusContentTest class is a test class that contains test methods for testing the functionality of the BonusContent class.
It tests various scenarios such as null or empty inputs, list size, and output validation. */
public class BonusContentTest {
private static String youtubeApiKey;
/*
* testSearchAndPrintVideo_NullSearchQuery: Tests the searchAndPrintVideo method
* with a null search query.
* Expects an IllegalArgumentException to be thrown with the message
* "Search Query cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullSearchQuery() throws URISyntaxException {
String searchQuery = null;
String category = "Fun facts";
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("Search Query cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_EmptyCategory: Tests the searchAndPrintVideo method
* with an empty category.
* Expects an IllegalArgumentException to be thrown with the message
* "category cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_EmptyCategory() throws URISyntaxException {
String searchQuery = "Pulp Fiction";
String category = null;
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("category cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_NullApiKey: Tests the searchAndPrintVideo method with
* a null API key.
* Expects an IllegalArgumentException to be thrown with the message
* "ApiKey cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullApiKey() throws URISyntaxException {
String searchQuery = "Barbie";
String category = "Behind the Scenes";
String apiKey = null;
try {
BonusContent.searchAndPrintVideo(searchQuery, category, apiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("ApiKey cannot be null or empty.", e.getMessage());
}
}
/*
* testCheckItemsSize_NotEmptyList: Tests the checkItemsSize method with a
* non-empty list.
* Expects the list size to be greater than 0.
*/
@Test
public void testCheckItemsSize_NotEmptyList() {
List<Object> items = new ArrayList<>();
items.add(new Object()); // Προσθέτουμε ένα στοιχείο στη λίστα
assertTrue(items.size() > 0);
}
/*
* testCheckItemsSize_EmptyList: Tests the checkItemsSize method with an empty
* list.
* Expects the list size to be 0.
*/
@Test
public void testCheckItemsSize_EmptyList() {
List<Object> items = new ArrayList<>();
assertFalse(items.size() > 0);
}
/*
* testIterateAndPrint_NonEmptyList: Tests the iterateAndPrintWrapper method
* with a non-empty list.
* Verifies that the expected output is printed to the console.
*/
@Test
public void testIterateAndPrint_NonEmptyList() {
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος περιέχει τα αναμενόμενα κείμενα
String expectedOutput = String.format("Item 1%sItem 2%sItem 3%s", System.lineSeparator(),
System.lineSeparator(), System.lineSeparator());
assertEquals(expectedOutput, outContent.toString());
}
/*
* testIterateAndPrint_EmptyList: Tests the iterateAndPrintWrapper method with
* an empty list.
* Verifies that no output is printed to the console.
*/
@Test
public void testIterateAndPrint_EmptyList() {
List<String> items = new ArrayList<>();
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος είναι κενή
assertEquals("", outContent.toString());
}
// Wrapper γύρω από την iterateAndPrint για την κλάση δοκιμών
private static void iterateAndPrintWrapper(List<String> items) {
for (String item : items) {
System.out.println(item);
}
}
} | Aglag257/Java2_AIApp | app/src/test/java/gr/aueb/BonusContentTest.java | 1,653 | // Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών | line_comment | el | package gr.aueb;
import org.apiguardian.api.API;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
/*The BonusContentTest class is a test class that contains test methods for testing the functionality of the BonusContent class.
It tests various scenarios such as null or empty inputs, list size, and output validation. */
public class BonusContentTest {
private static String youtubeApiKey;
/*
* testSearchAndPrintVideo_NullSearchQuery: Tests the searchAndPrintVideo method
* with a null search query.
* Expects an IllegalArgumentException to be thrown with the message
* "Search Query cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullSearchQuery() throws URISyntaxException {
String searchQuery = null;
String category = "Fun facts";
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("Search Query cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_EmptyCategory: Tests the searchAndPrintVideo method
* with an empty category.
* Expects an IllegalArgumentException to be thrown with the message
* "category cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_EmptyCategory() throws URISyntaxException {
String searchQuery = "Pulp Fiction";
String category = null;
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("category cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_NullApiKey: Tests the searchAndPrintVideo method with
* a null API key.
* Expects an IllegalArgumentException to be thrown with the message
* "ApiKey cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullApiKey() throws URISyntaxException {
String searchQuery = "Barbie";
String category = "Behind the Scenes";
String apiKey = null;
try {
BonusContent.searchAndPrintVideo(searchQuery, category, apiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("ApiKey cannot be null or empty.", e.getMessage());
}
}
/*
* testCheckItemsSize_NotEmptyList: Tests the checkItemsSize method with a
* non-empty list.
* Expects the list size to be greater than 0.
*/
@Test
public void testCheckItemsSize_NotEmptyList() {
List<Object> items = new ArrayList<>();
items.add(new Object()); // Προσθέτουμε ένα στοιχείο στη λίστα
assertTrue(items.size() > 0);
}
/*
* testCheckItemsSize_EmptyList: Tests the checkItemsSize method with an empty
* list.
* Expects the list size to be 0.
*/
@Test
public void testCheckItemsSize_EmptyList() {
List<Object> items = new ArrayList<>();
assertFalse(items.size() > 0);
}
/*
* testIterateAndPrint_NonEmptyList: Tests the iterateAndPrintWrapper method
* with a non-empty list.
* Verifies that the expected output is printed to the console.
*/
@Test
public void testIterateAndPrint_NonEmptyList() {
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλ<SUF>
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος περιέχει τα αναμενόμενα κείμενα
String expectedOutput = String.format("Item 1%sItem 2%sItem 3%s", System.lineSeparator(),
System.lineSeparator(), System.lineSeparator());
assertEquals(expectedOutput, outContent.toString());
}
/*
* testIterateAndPrint_EmptyList: Tests the iterateAndPrintWrapper method with
* an empty list.
* Verifies that no output is printed to the console.
*/
@Test
public void testIterateAndPrint_EmptyList() {
List<String> items = new ArrayList<>();
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος είναι κενή
assertEquals("", outContent.toString());
}
// Wrapper γύρω από την iterateAndPrint για την κλάση δοκιμών
private static void iterateAndPrintWrapper(List<String> items) {
for (String item : items) {
System.out.println(item);
}
}
} |
10206_35 | "package com.example.hangmangame;\n\nimport javafx.application.Platform;\nimport javafx.event.Action(...TRUNCATED) | Aglogallos/Hangman-Game-JavaFx | Hangman_Game/Hangman-Game/src/main/java/com/example/hangmangame/Controller.java | 3,768 | "/*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5\n (...TRUNCATED) | block_comment | el | "package com.example.hangmangame;\n\nimport javafx.application.Platform;\nimport javafx.event.Action(...TRUNCATED) |
6074_0 | "package booking;\n\nimport java.nio.file.Path;\nimport java.util.HashMap;\nimport java.util.Map;\n\(...TRUNCATED) | AikVant/distributed_booking_2024 | src/main/java/booking/AvailabilityOfAccommodations.java | 1,206 | "// Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα(...TRUNCATED) | line_comment | el | "package booking;\n\nimport java.nio.file.Path;\nimport java.util.HashMap;\nimport java.util.Map;\n\(...TRUNCATED) |
7912_8 | "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change t(...TRUNCATED) | Alan-III/GroupBuy | groupBuyNetbeans/src/main/java/com/sphy141/probase/utils/CryptoUtils.java | 989 | "/*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφ(...TRUNCATED) | block_comment | el | "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change t(...TRUNCATED) |
5142_0 | "import java.time.LocalDate;\r\nimport java.util.ArrayList;\r\nimport java.util.TimerTask;\r\n\r\n/*(...TRUNCATED) | AlexMitsis/LibSoft | src/SystemNotification.java | 1,124 | "/*Κλάση <SystemNοtifications>\r\nΗ κλάση αυτή αφορά τις ενέργειες (...TRUNCATED) | block_comment | el | "import java.time.LocalDate;\r\nimport java.util.ArrayList;\r\nimport java.util.TimerTask;\r\n\r\n/*(...TRUNCATED) |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 3