Dataset Viewer
Auto-converted to Parquet Duplicate
file_id
stringlengths
3
8
content
stringlengths
299
36k
repo
stringlengths
9
109
path
stringlengths
9
163
token_length
int64
89
8.11k
original_comment
stringlengths
8
3.46k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
245
36k
9334_5
package com.unipi.vnikolis.unipismartalert.model; import android.annotation.SuppressLint; import android.support.annotation.NonNull; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Μοντέλο απόδοσης και αποθήκευσης τιμών στις μεταβλητές */ public class Values implements Comparable<Values> { private String stateEmergency, latitude, longitude, date; /** * Constructor used for writing values to FireBase * @param stateEmergency Κατάσταση ανάγκης * @param latitude Γεωγραφικό μήκος * @param longitude Γεωγραφικό πλάτος */ public Values(String stateEmergency, String latitude, String longitude) { @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); this.stateEmergency = stateEmergency; this.latitude = latitude; this.longitude = longitude; this.date = dateFormat.format(date); } /** * Empty Constructor we need it */ public Values(){ } public void setStateEmergency(String stateEmergency) { this.stateEmergency = stateEmergency; } public void setLatitude(String latitude) { this.latitude = latitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public void setDate(String date) { this.date = date; } public String getStateEmergency() { return stateEmergency; } public String getLatitude() { return latitude; } public String getLongitude() { return longitude; } public String getDate() { return date; } /** * Μέθοδος μτατροπής ημερομηνίας. Παίρνει την τρέχουσα ημερομηνία η οποία είναι ανάποδα και * @return Επιστρέφει την ημερομηνία στην κανονική της μορφή */ public String CorrectDate(){ @SuppressLint("SimpleDateFormat") DateFormat dateFromString = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); @SuppressLint("SimpleDateFormat") DateFormat dateToString = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); Date dates = null; try { dates = dateFromString.parse(this.date); } catch (ParseException e) { e.printStackTrace(); } return dateToString.format(dates); } /** * Πάρε την τρέχουσα ημερομηνία * και μετατροπή στο κατάλληλο φορμάτ * @return Ημερομηνία σε Συμβολοσειρά */ private String CurrentDate() { @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return this.date = dateFormat.format(date); } /** * Συγκρίνει την τρεχουσα ημ/νια με αυτη που εχουμε στη βαση * @param o Κλάσση τύπου Values * @return Έναν ακέραιο που δηλώνει ότι έγινε η σύγκριση */ // @Override public int compareTo(@NonNull Values o) { return CurrentDate().compareTo(this.date); } }
3ngk1sha/DangerDetect
app/src/main/java/com/unipi/vnikolis/unipismartalert/model/Values.java
1,013
/** * Συγκρίνει την τρεχουσα ημ/νια με αυτη που εχουμε στη βαση * @param o Κλάσση τύπου Values * @return Έναν ακέραιο που δηλώνει ότι έγινε η σύγκριση */
block_comment
el
package com.unipi.vnikolis.unipismartalert.model; import android.annotation.SuppressLint; import android.support.annotation.NonNull; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Μοντέλο απόδοσης και αποθήκευσης τιμών στις μεταβλητές */ public class Values implements Comparable<Values> { private String stateEmergency, latitude, longitude, date; /** * Constructor used for writing values to FireBase * @param stateEmergency Κατάσταση ανάγκης * @param latitude Γεωγραφικό μήκος * @param longitude Γεωγραφικό πλάτος */ public Values(String stateEmergency, String latitude, String longitude) { @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); this.stateEmergency = stateEmergency; this.latitude = latitude; this.longitude = longitude; this.date = dateFormat.format(date); } /** * Empty Constructor we need it */ public Values(){ } public void setStateEmergency(String stateEmergency) { this.stateEmergency = stateEmergency; } public void setLatitude(String latitude) { this.latitude = latitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public void setDate(String date) { this.date = date; } public String getStateEmergency() { return stateEmergency; } public String getLatitude() { return latitude; } public String getLongitude() { return longitude; } public String getDate() { return date; } /** * Μέθοδος μτατροπής ημερομηνίας. Παίρνει την τρέχουσα ημερομηνία η οποία είναι ανάποδα και * @return Επιστρέφει την ημερομηνία στην κανονική της μορφή */ public String CorrectDate(){ @SuppressLint("SimpleDateFormat") DateFormat dateFromString = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); @SuppressLint("SimpleDateFormat") DateFormat dateToString = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); Date dates = null; try { dates = dateFromString.parse(this.date); } catch (ParseException e) { e.printStackTrace(); } return dateToString.format(dates); } /** * Πάρε την τρέχουσα ημερομηνία * και μετατροπή στο κατάλληλο φορμάτ * @return Ημερομηνία σε Συμβολοσειρά */ private String CurrentDate() { @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return this.date = dateFormat.format(date); } /** * Συγκρί<SUF>*/ // @Override public int compareTo(@NonNull Values o) { return CurrentDate().compareTo(this.date); } }
6191_51
package info.android_angel.navigationdrawer.activity_tv; /** * Created by ANGELOS on 2017. */ import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.List; import info.android_angel.navigationdrawer.R; import info.android_angel.navigationdrawer.activity_movies.SearchActivity; import info.android_angel.navigationdrawer.activity_movies.Show_Movie_Details_ID; import info.android_angel.navigationdrawer.adapter.TVAdapter; import info.android_angel.navigationdrawer.model.TV; import info.android_angel.navigationdrawer.model.TVResponse; import info.android_angel.navigationdrawer.package_recycler_touch_listener.RecyclerTouchListener; 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 TV_Airing_Today_TV extends AppCompatActivity { private final static String page_2 = "2"; private final static String page_3 = "3"; /** 2017 ads private AdView mAdView;**/ private static final String TAG = TV_Airing_Today_TV.class.getSimpleName(); //http://api.themoviedb.org/3/movie/top_rated?api_key=624a7c9c17b10259855a9d9306cab848 // TODO - insert your themoviedb.org API KEY here private final static String API_KEY = "e7991f88e164bb3314b85fb4d25ac9e4"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nav_tv_get_airing_today); /** Προσοχή εδώ η αλλάγή............. **/ getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (API_KEY.isEmpty()) { Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show(); return; } final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.tvs_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); /** 2017 AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // Check the LogCat to get your test device ID .addTestDevice("C04B1BFFB0774708339BC273F8A43708") .build(); mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { } @Override public void onAdClosed() { Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { super.onAdOpened(); } }); mAdView.loadAd(adRequest);**/ /**END 2017 AdView **/ /** Προσοχή εδώ η αλλάγή............. **/ Call<TVResponse> call = apiService.getAiringTodayTv(API_KEY); call.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call, Response<TVResponse> response) { if (!response.isSuccessful()) { System.out.println("Error"); } if(response.isSuccessful()) { List<TV> tvs = response.body().getResults(); /** Προσοχή εδώ η αλλάγή............. **/ recyclerView.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, 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(); } } /** // μάλλον το βρήκα από το stackoverflow androidhive recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, 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 = new Intent(getApplicationContext(), Show_TV_Details_ID.class); String tv_id = ((TextView) view.findViewById(R.id.tv_id)).getText().toString(); i.putExtra("tv_id", tv_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),tv_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { } })); **/ } @Override public void onFailure(Call<TVResponse> call, Throwable t) { // Log error here since request failed Log.e(TAG, t.toString()); } }); /** PAGE = 2 **/ final RecyclerView recyclerView_2 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_2); recyclerView_2.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_2 = apiService.getAiringTodayTv_2(API_KEY, page_2); call_2.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_2, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_2.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, 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(); } } // μάλλον το βρήκα από το stackoverflow androidhive recyclerView_2.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_2, 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 = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @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(), Show_Movie_Details_ID.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<TVResponse> call_2, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); /** PAGE = 3 **/ final RecyclerView recyclerView_3 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_3); recyclerView_3.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_3 = apiService.getAiringTodayTv_2(API_KEY, page_3); call_3.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_3, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_3.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, 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(); } } // μάλλον το βρήκα από το stackoverflow androidhive recyclerView_3.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_3, 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 = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @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(), Show_Movie_Details_ID.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<TVResponse> call_3, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); // END protected void onCreate(Bundle savedInstanceState) { } /** SEARCH 2017 10.5 **/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem search = menu.findItem(R.id.search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); search(searchView); return true; } /** SEARCH 2017 10.5 **/ private void search(SearchView searchView) { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //Toast.makeText(Popular_Movie.this, "Search is Selected", Toast.LENGTH_SHORT).show(); Intent i = new Intent(TV_Airing_Today_TV.this,SearchActivity.class); /** Μάλλον αυτό **/ String api_key_search = query.toString(); i.putExtra("api_key_search", api_key_search); /**switch_key_activity for SearchActivity switch (switch_key_activity) **/ String switch_key_activity = "TV_Airing_Today_TV"; i.putExtra("switch_key_activity", switch_key_activity); //Toast.makeText(MainActivity.this, api_key_search, Toast.LENGTH_SHORT).show(); //String api_key_search = ((TextView) menu.findItem(R.id.search)).getText().toString(); //i.putExtra("api_key_search", api_key_search); startActivity(i); return true; } @Override public boolean onQueryTextChange(final String newText) { return false; } }); } /** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/ @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); } /** 2017 ads @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } **/ }
ANGELOS-TSILAFAKIS/NavigationDrawerPublic
app/src/main/java/info/android_angel/navigationdrawer/activity_tv/TV_Airing_Today_TV.java
3,614
/** Μάλλον αυτό **/
block_comment
el
package info.android_angel.navigationdrawer.activity_tv; /** * Created by ANGELOS on 2017. */ import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.List; import info.android_angel.navigationdrawer.R; import info.android_angel.navigationdrawer.activity_movies.SearchActivity; import info.android_angel.navigationdrawer.activity_movies.Show_Movie_Details_ID; import info.android_angel.navigationdrawer.adapter.TVAdapter; import info.android_angel.navigationdrawer.model.TV; import info.android_angel.navigationdrawer.model.TVResponse; import info.android_angel.navigationdrawer.package_recycler_touch_listener.RecyclerTouchListener; 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 TV_Airing_Today_TV extends AppCompatActivity { private final static String page_2 = "2"; private final static String page_3 = "3"; /** 2017 ads private AdView mAdView;**/ private static final String TAG = TV_Airing_Today_TV.class.getSimpleName(); //http://api.themoviedb.org/3/movie/top_rated?api_key=624a7c9c17b10259855a9d9306cab848 // TODO - insert your themoviedb.org API KEY here private final static String API_KEY = "e7991f88e164bb3314b85fb4d25ac9e4"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nav_tv_get_airing_today); /** Προσοχή εδώ η αλλάγή............. **/ getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (API_KEY.isEmpty()) { Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show(); return; } final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.tvs_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); /** 2017 AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // Check the LogCat to get your test device ID .addTestDevice("C04B1BFFB0774708339BC273F8A43708") .build(); mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { } @Override public void onAdClosed() { Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { super.onAdOpened(); } }); mAdView.loadAd(adRequest);**/ /**END 2017 AdView **/ /** Προσοχή εδώ η αλλάγή............. **/ Call<TVResponse> call = apiService.getAiringTodayTv(API_KEY); call.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call, Response<TVResponse> response) { if (!response.isSuccessful()) { System.out.println("Error"); } if(response.isSuccessful()) { List<TV> tvs = response.body().getResults(); /** Προσοχή εδώ η αλλάγή............. **/ recyclerView.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, 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(); } } /** // μάλλον το βρήκα από το stackoverflow androidhive recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, 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 = new Intent(getApplicationContext(), Show_TV_Details_ID.class); String tv_id = ((TextView) view.findViewById(R.id.tv_id)).getText().toString(); i.putExtra("tv_id", tv_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),tv_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { } })); **/ } @Override public void onFailure(Call<TVResponse> call, Throwable t) { // Log error here since request failed Log.e(TAG, t.toString()); } }); /** PAGE = 2 **/ final RecyclerView recyclerView_2 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_2); recyclerView_2.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_2 = apiService.getAiringTodayTv_2(API_KEY, page_2); call_2.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_2, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_2.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, 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(); } } // μάλλον το βρήκα από το stackoverflow androidhive recyclerView_2.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_2, 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 = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @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(), Show_Movie_Details_ID.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<TVResponse> call_2, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); /** PAGE = 3 **/ final RecyclerView recyclerView_3 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_3); recyclerView_3.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_3 = apiService.getAiringTodayTv_2(API_KEY, page_3); call_3.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_3, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_3.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, 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(); } } // μάλλον το βρήκα από το stackoverflow androidhive recyclerView_3.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_3, 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 = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @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(), Show_Movie_Details_ID.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<TVResponse> call_3, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); // END protected void onCreate(Bundle savedInstanceState) { } /** SEARCH 2017 10.5 **/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem search = menu.findItem(R.id.search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); search(searchView); return true; } /** SEARCH 2017 10.5 **/ private void search(SearchView searchView) { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //Toast.makeText(Popular_Movie.this, "Search is Selected", Toast.LENGTH_SHORT).show(); Intent i = new Intent(TV_Airing_Today_TV.this,SearchActivity.class); /** Μάλλον<SUF>*/ String api_key_search = query.toString(); i.putExtra("api_key_search", api_key_search); /**switch_key_activity for SearchActivity switch (switch_key_activity) **/ String switch_key_activity = "TV_Airing_Today_TV"; i.putExtra("switch_key_activity", switch_key_activity); //Toast.makeText(MainActivity.this, api_key_search, Toast.LENGTH_SHORT).show(); //String api_key_search = ((TextView) menu.findItem(R.id.search)).getText().toString(); //i.putExtra("api_key_search", api_key_search); startActivity(i); return true; } @Override public boolean onQueryTextChange(final String newText) { return false; } }); } /** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/ @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); } /** 2017 ads @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } **/ }
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.db<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_8
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(); //Αποθηκεύουμε το περιεχόμενο της σελίδας Document Page = res.parse(); //Ελέγχουμε αν συνδεθήκαμε Elements name = Page.select("div#header_login").select("u"); if (name.hasText()) { //Παίρνουμε το ονοματεπώνυμο του φοιτητή StudentFullName = name.html(); //Παίρν<SUF> 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 } }
16443_0
package com.kospeac.smartgreecealert; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; import android.widget.Toast; import java.util.List; import java.util.concurrent.TimeUnit; /* * Interface SeismicDetectionListener * με μεθοδο onStatusChanged * Γινεται override η μεθοδος στην main Activity και χρησιμοποιειται σαν listener οταν υπαρχει εντοπισμος δονησης * */ interface SeismicDetectionListener { public void onStatusChanged(boolean newStatus); } /* * H Κλαση SeismicDetectionHandler διαχειριζεται τις καταστασεις του επιταχυνσιομετρου * και επιστρεφει στην MainActivity status = true μεσω της μεθοδου onStatusChanged οταν * υπαρχει εντοπισμος δονησης του κινητου (seismicDetection) * * */ public class SeismicDetectionHandler implements SensorEventListener { private String TAG = "SEISMIC DETECTION HANDLER"; private SeismicDetectionListener listener; public SensorManager mSensorManager; private Sensor mSensor; private boolean moIsMin = false; private boolean moIsMax = false; private Context mContext; private int i; public static Boolean status; public SeismicDetectionHandler(Context context) { mContext = context; mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // o sensor που θα χρησιμοποιηθει (TYPE_ACCELEROMETER) registerListener(); } /* Εγγραφη του listener SensorEventListener (this) που κανει implement η κλαση */ public void registerListener(){ status = true; mSensorManager.registerListener(this,mSensor,SensorManager.SENSOR_DELAY_NORMAL); } public void unregisterListener(){ status = false; mSensorManager.unregisterListener(this); } public static Boolean getListenerStatus(){ return status; } /* * Για καθε event απο το επιταχυνσιομετρο * */ @Override public void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { double loX = sensorEvent.values[0]; double loY = sensorEvent.values[1]; double loZ = sensorEvent.values[2]; double loAccelerationReader = Math.sqrt(Math.pow(loX, 2) + Math.pow(loY, 2) + Math.pow(loZ, 2)); if (loAccelerationReader >= 11) { Toast.makeText(mContext, "An earthquake has been detected, input from other users is pending!!!!!", Toast.LENGTH_LONG).show(); setSeismicDetection(true); } } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } /* setSeismicDetection * καλει την μεθοδο onStatusChanged που εχει υλοποιηθει στην MainActivity */ public void setSeismicDetection(boolean seismicDetectionstatus){ if(listener !=null){ listener.onStatusChanged(seismicDetectionstatus); } } /* setSeismicDetectionListener * Αποθηκευση του SeismicDetectionListener instance (MainActivity) στα properties του αντικειμενου * για να γινει χρηστη του απο την setSeismicDetection */ public void setSeismicDetectionListener(SeismicDetectionListener listener ){ this.listener = listener; } /* seismicStatus * Ελεγχει αμα τα events ειναι σε κοντινη χρονικη περιοδο ( 6 δευτερολεπτα ) και * αμα η αποσταση ειναι κοντινη (5χμλ) * Επιστρεφει true / false */ public boolean seismicStatus(List<EventModel> events, long eventTimestamp, double latd,double lond){ long cureventTs = TimeUnit.MILLISECONDS.toSeconds(eventTimestamp); long eventTs; long diff; int times = 0; for(EventModel event: events){ eventTs = TimeUnit.MILLISECONDS.toSeconds(event.timestamp); diff = eventTs - cureventTs; if(diff>= -3 && diff<= 3 && LocationService.getDistance(latd,lond, event.lat,event.lon)){ times++; } } if(times> 1){ return true; }else{ return false; } } }
Afrodith/SmartAlertGreece
app/src/main/java/com/kospeac/smartgreecealert/SeismicDetectionHandler.java
1,374
/* * Interface SeismicDetectionListener * με μεθοδο onStatusChanged * Γινεται override η μεθοδος στην main Activity και χρησιμοποιειται σαν listener οταν υπαρχει εντοπισμος δονησης * */
block_comment
el
package com.kospeac.smartgreecealert; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; import android.widget.Toast; import java.util.List; import java.util.concurrent.TimeUnit; /* * Interf<SUF>*/ interface SeismicDetectionListener { public void onStatusChanged(boolean newStatus); } /* * H Κλαση SeismicDetectionHandler διαχειριζεται τις καταστασεις του επιταχυνσιομετρου * και επιστρεφει στην MainActivity status = true μεσω της μεθοδου onStatusChanged οταν * υπαρχει εντοπισμος δονησης του κινητου (seismicDetection) * * */ public class SeismicDetectionHandler implements SensorEventListener { private String TAG = "SEISMIC DETECTION HANDLER"; private SeismicDetectionListener listener; public SensorManager mSensorManager; private Sensor mSensor; private boolean moIsMin = false; private boolean moIsMax = false; private Context mContext; private int i; public static Boolean status; public SeismicDetectionHandler(Context context) { mContext = context; mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // o sensor που θα χρησιμοποιηθει (TYPE_ACCELEROMETER) registerListener(); } /* Εγγραφη του listener SensorEventListener (this) που κανει implement η κλαση */ public void registerListener(){ status = true; mSensorManager.registerListener(this,mSensor,SensorManager.SENSOR_DELAY_NORMAL); } public void unregisterListener(){ status = false; mSensorManager.unregisterListener(this); } public static Boolean getListenerStatus(){ return status; } /* * Για καθε event απο το επιταχυνσιομετρο * */ @Override public void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { double loX = sensorEvent.values[0]; double loY = sensorEvent.values[1]; double loZ = sensorEvent.values[2]; double loAccelerationReader = Math.sqrt(Math.pow(loX, 2) + Math.pow(loY, 2) + Math.pow(loZ, 2)); if (loAccelerationReader >= 11) { Toast.makeText(mContext, "An earthquake has been detected, input from other users is pending!!!!!", Toast.LENGTH_LONG).show(); setSeismicDetection(true); } } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } /* setSeismicDetection * καλει την μεθοδο onStatusChanged που εχει υλοποιηθει στην MainActivity */ public void setSeismicDetection(boolean seismicDetectionstatus){ if(listener !=null){ listener.onStatusChanged(seismicDetectionstatus); } } /* setSeismicDetectionListener * Αποθηκευση του SeismicDetectionListener instance (MainActivity) στα properties του αντικειμενου * για να γινει χρηστη του απο την setSeismicDetection */ public void setSeismicDetectionListener(SeismicDetectionListener listener ){ this.listener = listener; } /* seismicStatus * Ελεγχει αμα τα events ειναι σε κοντινη χρονικη περιοδο ( 6 δευτερολεπτα ) και * αμα η αποσταση ειναι κοντινη (5χμλ) * Επιστρεφει true / false */ public boolean seismicStatus(List<EventModel> events, long eventTimestamp, double latd,double lond){ long cureventTs = TimeUnit.MILLISECONDS.toSeconds(eventTimestamp); long eventTs; long diff; int times = 0; for(EventModel event: events){ eventTs = TimeUnit.MILLISECONDS.toSeconds(event.timestamp); diff = eventTs - cureventTs; if(diff>= -3 && diff<= 3 && LocationService.getDistance(latd,lond, event.lat,event.lon)){ times++; } } if(times> 1){ return true; }else{ return false; } } }
18080_15
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 γύρω από την iterateAndPrint για την κλάση δοκιμών
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)); // Καλείστε τη στατική μέθοδο 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()); } // Wrapp<SUF> private static void iterateAndPrintWrapper(List<String> items) { for (String item : items) { System.out.println(item); } } }
10206_34
package com.example.hangmangame; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.*; import java.util.*; import static com.example.hangmangame.LoadDictionary.*; public class Controller { public static boolean Playing; @FXML private Label AvailableWordsLabel; @FXML private Label Dictionary; @FXML private ImageView ImageView; @FXML private Label Possible_Letters_Label; @FXML private HBox word_hbox; @FXML private Label TotalPoints; @FXML private Label Success_Rate; @FXML private void open_up_add_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Settings"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening add_dictionary Scene"); } } @FXML private void open_up_load_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Load Dictionary"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Load Dictionary Scene"); } } @FXML private void solution_dialog(){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Solution"); alert.setHeaderText(null); if(Playing) alert.setContentText("Solution is " + game_word); else alert.setContentText("You are not playing !"); alert.showAndWait(); } public List<Button> word_buttons = new ArrayList<>(); public static String game_word; public int Number_of_Letters_left; public int lives; public List<Button> Invisible_Key_Buttons = new ArrayList<>(); public boolean initialise = false; @FXML public void start() { if(!initialise){ initialise_rounds(); } lives = 6; SetImage(lives); game_word = get_random_word(); Number_of_Letters_left = game_word.length(); Playing = true; Successful_Attempts = 0.0F; Total_Attempts = 0.0F; Success_Rate.setText("0%"); Available_Words(); if (game_word.equals("empty")) { Dictionary.setText("Load Dictionary!"); return; } //Reset Possible_letters.clear(); //Set invisible keys to visible if (!Invisible_Key_Buttons.isEmpty()) { for (Button invisible_key_button : Invisible_Key_Buttons) { invisible_key_button.setVisible(true); } } Dictionary.setText(title); System.out.println(title); //create a list of buttons word_hbox.getChildren().removeAll(word_buttons); word_buttons.clear(); for (int i = 0; i < game_word.length(); i++) { word_buttons.add(new Button("_")); //word_buttons.add(new Button(String.valueOf(game_word.charAt(i)))); word_hbox.getChildren().add(word_buttons.get(i)); word_buttons.get(i).setStyle("-fx-font-size: 2em; "); /* when clicked it should display the most common letters in the position of the letter in the Dictionary */ word_buttons.get(i).setOnAction(actionEvent -> { //... do something in here. }); } Same_length_stats(); } public List<String> Possible_letters = new ArrayList<>(); public List<Integer> Quantity_of_Letter = new ArrayList<>(); public Vector<String> same_length_words = new Vector<>(); public List<Element> elements = new ArrayList<Element>(); public void Same_length_stats() { /* Find words with equal length with game_word */ same_length_words.clear(); elements.clear(); for (String word : words) { if (word.length() == game_word.length() && !word.equals(game_word)) { same_length_words.add(word); } } // counter to keep track of how many int[][] CharCounter = new int[game_word.length()][26]; /* set all counters to zero */ // we have 26 counters for every letter of the game word for (int i = 0; i < game_word.length(); i++) { for (int z = 0; z < 26; z++) { CharCounter[i][z] = 0; } } // Now we count for (int i = 0; i < game_word.length(); i++) { for (String word : same_length_words) { int temp = (int) word.charAt(i) - 65; //Capital Letters CharCounter[i][temp]++; } } // add every counter to a List in order to keep track of them when we sort them for (int i = 0; i < game_word.length(); i++) { //i = position for (int z = 0; z < 26; z++) { //z = letter elements.add(new Element(i, z, CharCounter[i][z])); //System.out.println(CharCounter[i][z]); } } Collections.sort(elements); // reverse so we get the big numbers at front Collections.reverse(elements); for (int i = 0; i < game_word.length(); i++) { Possible_letters.add(""); System.out.println("---------LOOP " + String.valueOf(i) + "----------" ); System.out.println(i); for (Element element : elements) { if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0 char letter = (char) (element.letter + 65); System.out.println(letter + " quantity :" + String.valueOf(element.quantity)); Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " "); } } int java_is_dumb = i; //lamda expressions need final expressions word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));}); System.out.println(Possible_letters.get(i)); } } public void Available_Words() { AvailableWordsLabel.setText(String.valueOf(words.size())); } public float Successful_Attempts; public float Total_Attempts; public void Success_Rate(){ if (Successful_Attempts == 0){ Success_Rate.setText("0%"); return; } else if (Successful_Attempts==Total_Attempts) { Success_Rate.setText("100%"); return; } float Success_rate = 100*Successful_Attempts/Total_Attempts;; String Success_Rate_Text = String.valueOf(Success_rate); String Label = ""; for (int i = 0; i < 4; i++) { Label += String.valueOf(Success_Rate_Text.charAt(i)); } Success_Rate.setText(Label+" %"); } public int Score = 0; public void Update_Score(int position){ int total_same_length_words = same_length_words.size(); int Element_letter = ((int) game_word.charAt(position)) - 65; //we have to convert it to the way we added it 26*i + z //int quantity_of_letter = elements.get(26*position + Element_letter).quantity; int quantity_of_letter = 0; for(Element element:elements){ if(element.letter == Element_letter && element.position==position){ quantity_of_letter = element.quantity; } } float percentage = (float)quantity_of_letter / (float) total_same_length_words; System.out.println("Total words, quantity of letter , percentage"); System.out.println(total_same_length_words); System.out.println(quantity_of_letter); System.out.println(percentage); //System.out.println(Element_letter+65); if(percentage >= 0.6) { Score += 5; } else if(percentage >= 0.4){ Score += 10; } else if(percentage >= 0.25){ Score += 15; } else Score += 30; } @FXML public void Try_this_Letter(Event event) { if (!Playing) { return; //If we ain't playing do nothing } System.out.println(event.getTarget()); Button btn = (Button) event.getSource(); //temp value String button_char = btn.getId(); System.out.println(btn.getId()); //get id btn.setVisible(false); Invisible_Key_Buttons.add(btn); /* ChecK if the character exist in the game word */ boolean success = false; Total_Attempts++; for (int i = 0; i < game_word.length(); i++) { if (button_char.equals(String.valueOf(game_word.charAt(i)))) { //reveal the letters that exist in the words success = true; Number_of_Letters_left--; word_buttons.get(i).setText(button_char); Update_Score(i); //we scored at position i TotalPoints.setText(String.valueOf(Score)); if (Number_of_Letters_left < 1) { System.out.println("Congratulations"); //win = true Update_Rounds(true); win_game(true); } } } if(!success){ lives--; SetImage(lives); //game_over(); if (lives < 1) { //win = false Playing = false; Update_Rounds(false); System.out.println("You lost :("); win_game(false); } } else Successful_Attempts++; Success_Rate(); } public void win_game(boolean win){ Alert alert = new Alert(Alert.AlertType.INFORMATION); if(win) { alert.setTitle("Congratulations"); alert.setHeaderText("You Won !"); alert.setContentText("Ready for the next one ?"); File myObj = new File("./images/win.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } else { alert.setTitle("Tough luck"); alert.setHeaderText("You Lost ..."); alert.setContentText("Want to try again ?"); File myObj = new File("./images/lost.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeNextWord); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeNextWord){ start(); } } public void SetImage(int lives) { File myObj = new File("./images/" + String.valueOf(lives) + ".jpg"); Image image = new Image(myObj.getAbsolutePath()); ImageView.setImage(image); } @FXML public void exit_app(){ Platform.exit(); } @FXML public void open_Dictionary_Details(ActionEvent event){ /*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9 γράμματα και 10 ή περισσότερα γράμματα */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Dictionary Details Scene"); } } public static Vector<String> gamewords_5 = new Vector<>(); public static Vector<String> results_5 = new Vector<>(); public static Vector<String> Attempts_per_gameword = new Vector<>(); public void initialise_rounds() { for (int i = 0; i < 5; i++) { gamewords_5.add("---"); results_5.add("---"); Attempts_per_gameword.add("---"); } initialise = true; } public void Update_Rounds(Boolean win) { //gamewords gamewords_5.remove(0); gamewords_5.add(game_word); //results results_5.remove(0); if(win){ results_5.add("Victory"); } else { results_5.add("Defeat"); } //attempts Attempts_per_gameword.remove(0); Attempts_per_gameword.add(String.valueOf((int) Total_Attempts)); } @FXML public void Instructions(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("instructions.fxml")); Scene scene = new Scene(fxmlLoader.load()); Stage stage = new Stage(); stage.setTitle("Instructions"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Instructions Scene"); } } @FXML public void Rounds(){ /*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5 τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες: επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή υπολογιστής). */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("rounds.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Rounds Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Rounds Scene"); } } }
Aglogallos/Hangman-Game-JavaFx
Hangman_Game/Hangman-Game/src/main/java/com/example/hangmangame/Controller.java
3,768
/*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5 τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες: επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή υπολογιστής). */
block_comment
el
package com.example.hangmangame; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.*; import java.util.*; import static com.example.hangmangame.LoadDictionary.*; public class Controller { public static boolean Playing; @FXML private Label AvailableWordsLabel; @FXML private Label Dictionary; @FXML private ImageView ImageView; @FXML private Label Possible_Letters_Label; @FXML private HBox word_hbox; @FXML private Label TotalPoints; @FXML private Label Success_Rate; @FXML private void open_up_add_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Settings"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening add_dictionary Scene"); } } @FXML private void open_up_load_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Load Dictionary"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Load Dictionary Scene"); } } @FXML private void solution_dialog(){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Solution"); alert.setHeaderText(null); if(Playing) alert.setContentText("Solution is " + game_word); else alert.setContentText("You are not playing !"); alert.showAndWait(); } public List<Button> word_buttons = new ArrayList<>(); public static String game_word; public int Number_of_Letters_left; public int lives; public List<Button> Invisible_Key_Buttons = new ArrayList<>(); public boolean initialise = false; @FXML public void start() { if(!initialise){ initialise_rounds(); } lives = 6; SetImage(lives); game_word = get_random_word(); Number_of_Letters_left = game_word.length(); Playing = true; Successful_Attempts = 0.0F; Total_Attempts = 0.0F; Success_Rate.setText("0%"); Available_Words(); if (game_word.equals("empty")) { Dictionary.setText("Load Dictionary!"); return; } //Reset Possible_letters.clear(); //Set invisible keys to visible if (!Invisible_Key_Buttons.isEmpty()) { for (Button invisible_key_button : Invisible_Key_Buttons) { invisible_key_button.setVisible(true); } } Dictionary.setText(title); System.out.println(title); //create a list of buttons word_hbox.getChildren().removeAll(word_buttons); word_buttons.clear(); for (int i = 0; i < game_word.length(); i++) { word_buttons.add(new Button("_")); //word_buttons.add(new Button(String.valueOf(game_word.charAt(i)))); word_hbox.getChildren().add(word_buttons.get(i)); word_buttons.get(i).setStyle("-fx-font-size: 2em; "); /* when clicked it should display the most common letters in the position of the letter in the Dictionary */ word_buttons.get(i).setOnAction(actionEvent -> { //... do something in here. }); } Same_length_stats(); } public List<String> Possible_letters = new ArrayList<>(); public List<Integer> Quantity_of_Letter = new ArrayList<>(); public Vector<String> same_length_words = new Vector<>(); public List<Element> elements = new ArrayList<Element>(); public void Same_length_stats() { /* Find words with equal length with game_word */ same_length_words.clear(); elements.clear(); for (String word : words) { if (word.length() == game_word.length() && !word.equals(game_word)) { same_length_words.add(word); } } // counter to keep track of how many int[][] CharCounter = new int[game_word.length()][26]; /* set all counters to zero */ // we have 26 counters for every letter of the game word for (int i = 0; i < game_word.length(); i++) { for (int z = 0; z < 26; z++) { CharCounter[i][z] = 0; } } // Now we count for (int i = 0; i < game_word.length(); i++) { for (String word : same_length_words) { int temp = (int) word.charAt(i) - 65; //Capital Letters CharCounter[i][temp]++; } } // add every counter to a List in order to keep track of them when we sort them for (int i = 0; i < game_word.length(); i++) { //i = position for (int z = 0; z < 26; z++) { //z = letter elements.add(new Element(i, z, CharCounter[i][z])); //System.out.println(CharCounter[i][z]); } } Collections.sort(elements); // reverse so we get the big numbers at front Collections.reverse(elements); for (int i = 0; i < game_word.length(); i++) { Possible_letters.add(""); System.out.println("---------LOOP " + String.valueOf(i) + "----------" ); System.out.println(i); for (Element element : elements) { if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0 char letter = (char) (element.letter + 65); System.out.println(letter + " quantity :" + String.valueOf(element.quantity)); Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " "); } } int java_is_dumb = i; //lamda expressions need final expressions word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));}); System.out.println(Possible_letters.get(i)); } } public void Available_Words() { AvailableWordsLabel.setText(String.valueOf(words.size())); } public float Successful_Attempts; public float Total_Attempts; public void Success_Rate(){ if (Successful_Attempts == 0){ Success_Rate.setText("0%"); return; } else if (Successful_Attempts==Total_Attempts) { Success_Rate.setText("100%"); return; } float Success_rate = 100*Successful_Attempts/Total_Attempts;; String Success_Rate_Text = String.valueOf(Success_rate); String Label = ""; for (int i = 0; i < 4; i++) { Label += String.valueOf(Success_Rate_Text.charAt(i)); } Success_Rate.setText(Label+" %"); } public int Score = 0; public void Update_Score(int position){ int total_same_length_words = same_length_words.size(); int Element_letter = ((int) game_word.charAt(position)) - 65; //we have to convert it to the way we added it 26*i + z //int quantity_of_letter = elements.get(26*position + Element_letter).quantity; int quantity_of_letter = 0; for(Element element:elements){ if(element.letter == Element_letter && element.position==position){ quantity_of_letter = element.quantity; } } float percentage = (float)quantity_of_letter / (float) total_same_length_words; System.out.println("Total words, quantity of letter , percentage"); System.out.println(total_same_length_words); System.out.println(quantity_of_letter); System.out.println(percentage); //System.out.println(Element_letter+65); if(percentage >= 0.6) { Score += 5; } else if(percentage >= 0.4){ Score += 10; } else if(percentage >= 0.25){ Score += 15; } else Score += 30; } @FXML public void Try_this_Letter(Event event) { if (!Playing) { return; //If we ain't playing do nothing } System.out.println(event.getTarget()); Button btn = (Button) event.getSource(); //temp value String button_char = btn.getId(); System.out.println(btn.getId()); //get id btn.setVisible(false); Invisible_Key_Buttons.add(btn); /* ChecK if the character exist in the game word */ boolean success = false; Total_Attempts++; for (int i = 0; i < game_word.length(); i++) { if (button_char.equals(String.valueOf(game_word.charAt(i)))) { //reveal the letters that exist in the words success = true; Number_of_Letters_left--; word_buttons.get(i).setText(button_char); Update_Score(i); //we scored at position i TotalPoints.setText(String.valueOf(Score)); if (Number_of_Letters_left < 1) { System.out.println("Congratulations"); //win = true Update_Rounds(true); win_game(true); } } } if(!success){ lives--; SetImage(lives); //game_over(); if (lives < 1) { //win = false Playing = false; Update_Rounds(false); System.out.println("You lost :("); win_game(false); } } else Successful_Attempts++; Success_Rate(); } public void win_game(boolean win){ Alert alert = new Alert(Alert.AlertType.INFORMATION); if(win) { alert.setTitle("Congratulations"); alert.setHeaderText("You Won !"); alert.setContentText("Ready for the next one ?"); File myObj = new File("./images/win.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } else { alert.setTitle("Tough luck"); alert.setHeaderText("You Lost ..."); alert.setContentText("Want to try again ?"); File myObj = new File("./images/lost.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeNextWord); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeNextWord){ start(); } } public void SetImage(int lives) { File myObj = new File("./images/" + String.valueOf(lives) + ".jpg"); Image image = new Image(myObj.getAbsolutePath()); ImageView.setImage(image); } @FXML public void exit_app(){ Platform.exit(); } @FXML public void open_Dictionary_Details(ActionEvent event){ /*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9 γράμματα και 10 ή περισσότερα γράμματα */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Dictionary Details Scene"); } } public static Vector<String> gamewords_5 = new Vector<>(); public static Vector<String> results_5 = new Vector<>(); public static Vector<String> Attempts_per_gameword = new Vector<>(); public void initialise_rounds() { for (int i = 0; i < 5; i++) { gamewords_5.add("---"); results_5.add("---"); Attempts_per_gameword.add("---"); } initialise = true; } public void Update_Rounds(Boolean win) { //gamewords gamewords_5.remove(0); gamewords_5.add(game_word); //results results_5.remove(0); if(win){ results_5.add("Victory"); } else { results_5.add("Defeat"); } //attempts Attempts_per_gameword.remove(0); Attempts_per_gameword.add(String.valueOf((int) Total_Attempts)); } @FXML public void Instructions(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("instructions.fxml")); Scene scene = new Scene(fxmlLoader.load()); Stage stage = new Stage(); stage.setTitle("Instructions"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Instructions Scene"); } } @FXML public void Rounds(){ /*Rounds<SUF>*/ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("rounds.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Rounds Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Rounds Scene"); } } }
6074_2
package booking; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class AvailabilityOfAccommodations implements Runnable{ private Map<String, ReservationDateRange> roomAvailability; @Override public void run() { // Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα while (true) { // Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα try { Thread.sleep(1000); // Περιμένει 1 δευτερόλεπτο πριν συνεχίσει } catch (InterruptedException e) { e.printStackTrace(); } } } public AvailabilityOfAccommodations() { this.roomAvailability = new HashMap<>(); } public Map<String, ReservationDateRange> getRoomAvailability() { return roomAvailability; } /** * Initial input to map from JSONfile * * @param path */ public void addRoomAsAvailableFromJSON(Path path) { AccommodationList accommodationList = new AccommodationList(path); for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) { roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange()); } } /** * From Manager input to map * * @param roomName * @param from * @param to */ public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) { System.out.println("..................function: addRoomAsAvailableFromManager..............................."); boolean exist = false; for (String key : roomAvailability.keySet()) { if (key.equals(roomName)) { roomAvailability.put(roomName, new ReservationDateRange(from, to)); exist = true; } } if (exist) { System.out.println("The room " + roomName + " successfully inserted as available"); } else { System.out.println("The specific room " + roomName + " does not exist."); } } /** * booking of a room - client function * * @param roomName */ public synchronized void bookingOfRoom(String roomName) { System.out.println("..................function: bookingOfRoom..............................."); boolean booking = false; for (String key : roomAvailability.keySet()) { ReservationDateRange range = roomAvailability.get(key); if (key.equals(roomName)) if (range.isAvailable()) { range.setAvailable(false); booking = true; } } if (booking) { System.out.println("The " + roomName + " is successfully booked."); } else { System.out.println("The " + roomName + " is not available."); } } @Override public String toString() { return "Manager{" + "roomAvailability=" + roomAvailability + '}'; } public static void main(String[] args) { // Default gemisma tou list apo JSON file AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object // Default gemisma tou map apo JSON file AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object ReservationDate from = new ReservationDate(20, 4, 2024); ReservationDate to = new ReservationDate(30, 4, 2024); availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to); // ta typwnei opws akrivws ta exei parei apo to JSON for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to); for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // booking of a room availabilityOfAccommodations.bookingOfRoom("235"); availabilityOfAccommodations.bookingOfRoom("500"); } }
AikVant/distributed_booking_2024
src/main/java/booking/AvailabilityOfAccommodations.java
1,206
// Περιμένει 1 δευτερόλεπτο πριν συνεχίσει
line_comment
el
package booking; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class AvailabilityOfAccommodations implements Runnable{ private Map<String, ReservationDateRange> roomAvailability; @Override public void run() { // Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα while (true) { // Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα try { Thread.sleep(1000); // Περιμ<SUF> } catch (InterruptedException e) { e.printStackTrace(); } } } public AvailabilityOfAccommodations() { this.roomAvailability = new HashMap<>(); } public Map<String, ReservationDateRange> getRoomAvailability() { return roomAvailability; } /** * Initial input to map from JSONfile * * @param path */ public void addRoomAsAvailableFromJSON(Path path) { AccommodationList accommodationList = new AccommodationList(path); for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) { roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange()); } } /** * From Manager input to map * * @param roomName * @param from * @param to */ public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) { System.out.println("..................function: addRoomAsAvailableFromManager..............................."); boolean exist = false; for (String key : roomAvailability.keySet()) { if (key.equals(roomName)) { roomAvailability.put(roomName, new ReservationDateRange(from, to)); exist = true; } } if (exist) { System.out.println("The room " + roomName + " successfully inserted as available"); } else { System.out.println("The specific room " + roomName + " does not exist."); } } /** * booking of a room - client function * * @param roomName */ public synchronized void bookingOfRoom(String roomName) { System.out.println("..................function: bookingOfRoom..............................."); boolean booking = false; for (String key : roomAvailability.keySet()) { ReservationDateRange range = roomAvailability.get(key); if (key.equals(roomName)) if (range.isAvailable()) { range.setAvailable(false); booking = true; } } if (booking) { System.out.println("The " + roomName + " is successfully booked."); } else { System.out.println("The " + roomName + " is not available."); } } @Override public String toString() { return "Manager{" + "roomAvailability=" + roomAvailability + '}'; } public static void main(String[] args) { // Default gemisma tou list apo JSON file AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object // Default gemisma tou map apo JSON file AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object ReservationDate from = new ReservationDate(20, 4, 2024); ReservationDate to = new ReservationDate(30, 4, 2024); availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to); // ta typwnei opws akrivws ta exei parei apo to JSON for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to); for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // booking of a room availabilityOfAccommodations.bookingOfRoom("235"); availabilityOfAccommodations.bookingOfRoom("500"); } }
7912_8
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sphy141.probase.utils; /** * * @author Alan */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class CryptoUtils { private static final String key = "sphy141groupbuy!"; public static String hashString(String password) { try { // Create an instance of the SHA-256 algorithm MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Convert the password string to bytes byte[] passwordBytes = password.getBytes(); // Calculate the hash value of the password bytes byte[] hashBytes = digest.digest(passwordBytes); // Convert the hash bytes to a hexadecimal string StringBuilder sb = new StringBuilder(); for (byte hashByte : hashBytes) { sb.append(String.format("%02x", hashByte)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // Handle the exception e.printStackTrace(); } return null; }//hashString /*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/ public static String encrypt(String plainText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String decrypt(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String encryptDouble(double number) { try { String plainText = Double.toString(number); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } public static double decryptDouble(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes); return Double.parseDouble(decryptedText); } catch (Exception e) { e.printStackTrace(); } return 0.0; } }//class
Alan-III/GroupBuy
groupBuyNetbeans/src/main/java/com/sphy141/probase/utils/CryptoUtils.java
989
/*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/
block_comment
el
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sphy141.probase.utils; /** * * @author Alan */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class CryptoUtils { private static final String key = "sphy141groupbuy!"; public static String hashString(String password) { try { // Create an instance of the SHA-256 algorithm MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Convert the password string to bytes byte[] passwordBytes = password.getBytes(); // Calculate the hash value of the password bytes byte[] hashBytes = digest.digest(passwordBytes); // Convert the hash bytes to a hexadecimal string StringBuilder sb = new StringBuilder(); for (byte hashByte : hashBytes) { sb.append(String.format("%02x", hashByte)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // Handle the exception e.printStackTrace(); } return null; }//hashString /*επειδή<SUF>*/ public static String encrypt(String plainText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String decrypt(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String encryptDouble(double number) { try { String plainText = Double.toString(number); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } public static double decryptDouble(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes); return Double.parseDouble(decryptedText); } catch (Exception e) { e.printStackTrace(); } return 0.0; } }//class
5142_0
import java.time.LocalDate; import java.util.ArrayList; import java.util.TimerTask; /*Κλάση <SystemNοtifications> Η κλάση αυτή αφορά τις ενέργειες του συστήματος οι οποίες εξαρτώνται άμεσα απο τον χρόνο. Συγκεκριμένα εξυπηρετεί τις περιπτώσεις χρήσης: Penalty - Use Case Code: 26 (X02),Warning - Use Case Code: 25 (X03)*/ public class SystemNotification extends TimerTask { //synarthsh-thread gia ton taktiko elegxo twn kyrwsewn.kaleitai sthn main public static void checkforActions() { Warning.checkforWarning(); Penalty.checkforPenalty(); Penalty.undoPenalties(); } @Override public void run() { // TODO Auto-generated method stub SystemNotification.checkforActions(); } //------------------------------------------------------// private static class Warning{ public static void checkforWarning() { int timeleft=3; ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); //gia kathe daneizomeno for(BookLending booklending:borrowed) {if(booklending.getTimeLeft(LocalDate.now().plusDays(3))==timeleft){ String text="To vivlio"+booklending.getBook().getTitle()+"prepei na epistrafei se 3 meres"; Borrower recipient=booklending.getBorrower(); Message warning=new Message(text,Main.librarian); Message.messageToBorrower(recipient, warning); } } } } private static class Penalty{ public static void checkforPenalty() { ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); ArrayList<BookLending> delayed=Main.librarydata.getDelayedBooks(); for(BookLending booklending:borrowed) { if(booklending.getTimeLeft(LocalDate.now())==-1) { delayed.add(booklending); borrowed.remove(booklending); Borrower recipient=booklending.getBorrower(); recipient.setNumberOfPenalties((recipient.getNumberOfPenalties()+1)%3); boolean severe=false; if(recipient.getNumberOfPenalties()==0) { recipient.setAbleToBorrow(false); recipient.setDateOfLastPenlty(LocalDate.now()); /**add to withpenalty list**/ ArrayList<Borrower> p=Main.librarydata.getWithPenalty(); if(p.indexOf(recipient)==-1)//if doesn't exist {p.add(recipient);} severe=true; } //message to be sent String text1="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa"; String text2="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa.Logw epanalambanomenwn kathisterhsewn" + "den mporeite na daneisteite gia 30 meres"; Message warning=null; if(!severe) {warning=new Message(text1,Main.librarian);}else {warning=new Message(text2,Main.librarian);} Message.messageToBorrower(recipient, warning); } } } public static void undoPenalties() { ArrayList<Borrower> penalties=Main.librarydata.getWithPenalty(); for(Borrower b:penalties) { if(b.getDateOfLastPenlty().plusDays(14)==LocalDate.now()) { b.setAbleToBorrow(true); penalties.remove(b); String text="Mporeite na daneisteite 3ana"; Message inform=new Message(text,Main.librarian); Message.messageToBorrower(b, inform); } } } } }
AlexMitsis/LibSoft
src/SystemNotification.java
1,124
/*Κλάση <SystemNοtifications> Η κλάση αυτή αφορά τις ενέργειες του συστήματος οι οποίες εξαρτώνται άμεσα απο τον χρόνο. Συγκεκριμένα εξυπηρετεί τις περιπτώσεις χρήσης: Penalty - Use Case Code: 26 (X02),Warning - Use Case Code: 25 (X03)*/
block_comment
el
import java.time.LocalDate; import java.util.ArrayList; import java.util.TimerTask; /*Κλάση <SUF>*/ public class SystemNotification extends TimerTask { //synarthsh-thread gia ton taktiko elegxo twn kyrwsewn.kaleitai sthn main public static void checkforActions() { Warning.checkforWarning(); Penalty.checkforPenalty(); Penalty.undoPenalties(); } @Override public void run() { // TODO Auto-generated method stub SystemNotification.checkforActions(); } //------------------------------------------------------// private static class Warning{ public static void checkforWarning() { int timeleft=3; ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); //gia kathe daneizomeno for(BookLending booklending:borrowed) {if(booklending.getTimeLeft(LocalDate.now().plusDays(3))==timeleft){ String text="To vivlio"+booklending.getBook().getTitle()+"prepei na epistrafei se 3 meres"; Borrower recipient=booklending.getBorrower(); Message warning=new Message(text,Main.librarian); Message.messageToBorrower(recipient, warning); } } } } private static class Penalty{ public static void checkforPenalty() { ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); ArrayList<BookLending> delayed=Main.librarydata.getDelayedBooks(); for(BookLending booklending:borrowed) { if(booklending.getTimeLeft(LocalDate.now())==-1) { delayed.add(booklending); borrowed.remove(booklending); Borrower recipient=booklending.getBorrower(); recipient.setNumberOfPenalties((recipient.getNumberOfPenalties()+1)%3); boolean severe=false; if(recipient.getNumberOfPenalties()==0) { recipient.setAbleToBorrow(false); recipient.setDateOfLastPenlty(LocalDate.now()); /**add to withpenalty list**/ ArrayList<Borrower> p=Main.librarydata.getWithPenalty(); if(p.indexOf(recipient)==-1)//if doesn't exist {p.add(recipient);} severe=true; } //message to be sent String text1="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa"; String text2="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa.Logw epanalambanomenwn kathisterhsewn" + "den mporeite na daneisteite gia 30 meres"; Message warning=null; if(!severe) {warning=new Message(text1,Main.librarian);}else {warning=new Message(text2,Main.librarian);} Message.messageToBorrower(recipient, warning); } } } public static void undoPenalties() { ArrayList<Borrower> penalties=Main.librarydata.getWithPenalty(); for(Borrower b:penalties) { if(b.getDateOfLastPenlty().plusDays(14)==LocalDate.now()) { b.setAbleToBorrow(true); penalties.remove(b); String text="Mporeite na daneisteite 3ana"; Message inform=new Message(text,Main.librarian); Message.messageToBorrower(b, inform); } } } } }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5