file_id stringlengths 3 9 | content stringlengths 207 36.5k | repo stringlengths 9 109 | path stringlengths 8 157 | token_length int64 91 8.11k | original_comment stringlengths 7 3.46k | comment_type stringclasses 2 values | detected_lang stringclasses 1 value | prompt stringlengths 137 36.4k |
|---|---|---|---|---|---|---|---|---|
5474_4 | package com.unipi.vnikolis.unipismartalert;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection;
import com.unipi.vnikolis.unipismartalert.model.Values;
import java.util.Objects;
/**
* The backend code for Maps Activity
*/
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FirebaseDatabase firebaseDatabase;
DatabaseReference dropDanger, possiblyDanger;
MainActivity mainActivity = new MainActivity();
Thread t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
firebaseDatabase = FirebaseDatabase.getInstance();
possiblyDanger = firebaseDatabase.getReference("PossiblyDanger");
dropDanger = possiblyDanger.child("DropDanger");
}
/**
* Κλείνοντας την εφαρμογή εαν υπάρχει νήμα να σταματήσει την λειτουργία του
*/
@Override
protected void onDestroy() {
super.onDestroy();
if(t != null) {
t.interrupt();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(MainActivity.isMapsButtonPressed) { //εαν πατηθεί το κουμπί "Maps"
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
t = new Thread(new Runnable() {
@Override
public void run() {
putTheMarkers(dropDanger);
}
});
t.start();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}else if(ShowStatistics.isItemsButtonClicked){
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
putTheMarkersFromList();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
}
/**
* Τοποθετεί όλα τα σημάδια της
* κατηγορίας BigDanger επάνω στον χάρτη
*/
public void putTheMarkers(DatabaseReference reference){
reference.addValueEventListener(new ValueEventListener() {
Values v;
LatLng coordinates;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα
{
for (DataSnapshot i : dataSnapshot.getChildren()) {
v = i.getValue(Values.class);
assert v != null;
coordinates = new LatLng(Double.parseDouble(v.getLatitude()), Double.parseDouble(v.getLongitude()));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates));
markerOptions.position(coordinates);
markerOptions.snippet(v.CorrectDate());
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 10)));
}
}
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
/**
* Παίρνει κάθε γραμμή της ViewList και εμφανίζει
* το σημάδι επάνω στον χάρτη
*/
public void putTheMarkersFromList(){
try {
String latitude = Objects.requireNonNull(getIntent().getExtras()).getString("latitude");
String longitude = getIntent().getExtras().getString("longitude");
String date = getIntent().getExtras().getString("date");
double latitudeToDouble = Double.parseDouble(latitude);
double longitudeToDouble = Double.parseDouble(longitude);
LatLng coordinates = new LatLng(latitudeToDouble, longitudeToDouble);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates ));
markerOptions.position(coordinates);
markerOptions.snippet(date);
mMap.addMarker(markerOptions);
//εστίαση στο συγκεκριμένο σημείο του χάρτη
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 15)));
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
}
| 3ngk1sha/DangerDetect | app/src/main/java/com/unipi/vnikolis/unipismartalert/MapsActivity.java | 1,814 | //εαν πατηθεί το κουμπί "Maps" | line_comment | el | package com.unipi.vnikolis.unipismartalert;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection;
import com.unipi.vnikolis.unipismartalert.model.Values;
import java.util.Objects;
/**
* The backend code for Maps Activity
*/
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FirebaseDatabase firebaseDatabase;
DatabaseReference dropDanger, possiblyDanger;
MainActivity mainActivity = new MainActivity();
Thread t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
firebaseDatabase = FirebaseDatabase.getInstance();
possiblyDanger = firebaseDatabase.getReference("PossiblyDanger");
dropDanger = possiblyDanger.child("DropDanger");
}
/**
* Κλείνοντας την εφαρμογή εαν υπάρχει νήμα να σταματήσει την λειτουργία του
*/
@Override
protected void onDestroy() {
super.onDestroy();
if(t != null) {
t.interrupt();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(MainActivity.isMapsButtonPressed) { //εα<SUF>
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
t = new Thread(new Runnable() {
@Override
public void run() {
putTheMarkers(dropDanger);
}
});
t.start();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}else if(ShowStatistics.isItemsButtonClicked){
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
putTheMarkersFromList();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
}
/**
* Τοποθετεί όλα τα σημάδια της
* κατηγορίας BigDanger επάνω στον χάρτη
*/
public void putTheMarkers(DatabaseReference reference){
reference.addValueEventListener(new ValueEventListener() {
Values v;
LatLng coordinates;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα
{
for (DataSnapshot i : dataSnapshot.getChildren()) {
v = i.getValue(Values.class);
assert v != null;
coordinates = new LatLng(Double.parseDouble(v.getLatitude()), Double.parseDouble(v.getLongitude()));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates));
markerOptions.position(coordinates);
markerOptions.snippet(v.CorrectDate());
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 10)));
}
}
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
/**
* Παίρνει κάθε γραμμή της ViewList και εμφανίζει
* το σημάδι επάνω στον χάρτη
*/
public void putTheMarkersFromList(){
try {
String latitude = Objects.requireNonNull(getIntent().getExtras()).getString("latitude");
String longitude = getIntent().getExtras().getString("longitude");
String date = getIntent().getExtras().getString("date");
double latitudeToDouble = Double.parseDouble(latitude);
double longitudeToDouble = Double.parseDouble(longitude);
LatLng coordinates = new LatLng(latitudeToDouble, longitudeToDouble);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates ));
markerOptions.position(coordinates);
markerOptions.snippet(date);
mMap.addMarker(markerOptions);
//εστίαση στο συγκεκριμένο σημείο του χάρτη
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 15)));
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
}
|
5457_0 | package info.android_angel.navigationdrawer.model_movie_get_latest;
/**
* Created by ANGELOS on 2017.
*
* Δεν έχει κάτι το object. Το αφήνω κενό.
*
*/
public class MovieGetLatest_spoken_languages {
}
| ANGELOS-TSILAFAKIS/NavigationDrawerPublic | app/src/main/java/info/android_angel/navigationdrawer/model_movie_get_latest/MovieGetLatest_spoken_languages.java | 91 | /**
* Created by ANGELOS on 2017.
*
* Δεν έχει κάτι το object. Το αφήνω κενό.
*
*/ | block_comment | el | package info.android_angel.navigationdrawer.model_movie_get_latest;
/**
* Cre<SUF>*/
public class MovieGetLatest_spoken_languages {
}
|
17272_21 | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"});
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"});
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} | Abbe98/corelib | corelib-schemaorg/src/test/java/eu/europeana/corelib/edm/utils/MockFullBean.java | 6,557 | //el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"}); | line_comment | el | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"});
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el<SUF>
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} |
11039_4 | 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 | //Παίρνουμε τα cookies | 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();
//Πα<SUF>
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
}
}
|
32051_29 | package com.kospeac.smartgreecealert;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static Activity mainActivity;
UsbService mUsbService = new UsbService();
FirebaseService mFirebaseService;
String type;
Button sosBtn;
Button fireBtn;
Button abortBtn;
public TextView mainTitle;
public TextView sosTitle;
CountDownTimer countDownTimer;
CountDownTimer countDownSOS;
boolean countDownTimerIsRunning = false;
boolean sosStatus = false;
private FallDetectionHandler falldetection;
private SeismicDetectionHandler seismicdetection;
private final static int REQUESTCODE = 325;
LocationManager mLocationManager;
Uri notification;
Ringtone r;
private LocationListener locationService;
private Boolean prevStatus;
Double longitude, latitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = this;
mFirebaseService = FirebaseService.getInstance();
mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationService = new LocationService();
sosBtn = findViewById(R.id.btn_sos);
fireBtn = findViewById(R.id.btn_fire);
abortBtn = findViewById(R.id.btn_abort);
mainTitle = findViewById(R.id.main_title);
sosTitle = findViewById(R.id.sos_text);
sosBtn.setOnClickListener(this);
fireBtn.setOnClickListener(this);
abortBtn.setOnClickListener(this);
checkPermissions();
try {
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
} catch (Exception e) {
e.printStackTrace();
}
this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE"));
mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() {
@Override
public void onStatusChanged(boolean newStatus) {
if(newStatus){
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "earthquakeEventDetected";
if (falldetection != null && FallDetectionHandler.getListenerStatus()) {
falldetection.unregisterListener();
}
mainTitle.setText(R.string.main_title2);
setupEarthquakeDetection(); // EarthquakeDetection
}
}else {
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "fallDetectionEvent";
if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) {
System.out.println(seismicdetection);
seismicdetection.unregisterListener();
}
mainTitle.setText(R.string.main_title1);
setupFallDetection(); // FallDetection
}
}
}
});
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity
super.onDestroy();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_sos: // SOS
sosStatus = true;
sosTitle.setText(R.string.sos_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("SOS");
break;
case R.id.btn_fire: // FIRE button
sosTitle.setText(R.string.fire_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("FIRE");
break;
case R.id.btn_abort: // κουμπι Abort
if(type == "fallDetectionEvent" && countDownTimerIsRunning) {
cancelTimer();
Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
} else if(sosStatus){ // αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση
cancelSOSTimer();
handleEvent("AbortEvent");
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.topbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_statistics:
Intent goToStatistics = new Intent(this,Statistics.class);
startActivity(goToStatistics); // Νεο acitvity Statistics
return true;
case R.id.menu_contacts:
Intent goToContacts = new Intent(this,ContactsActivity.class);
startActivity(goToContacts); // Νεο acitvity Contacts
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkPermissions() {
List<String> PERMISSIONS = new ArrayList<>();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
}else{
System.out.println("GPS ENABLED");
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
}
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
PERMISSIONS.add(Manifest.permission.SEND_SMS);
}
if(!PERMISSIONS.isEmpty()){
String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]);
ActivityCompat.requestPermissions(this,
array,
REQUESTCODE);
}
}
//get location from the GPS service provider. Needs permission.
protected void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location location = null;
for(String provider : providers){
Location l = mLocationManager.getLastKnownLocation(provider);
location = l;
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
break;
}
}
if (location == null) {
latitude = -1.0;
longitude = -1.0;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(this, permission)
== PackageManager.PERMISSION_GRANTED) {
if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
getLocation();
}
}
}
}
/* setupFallDetection
* Create object and listener (from device accelerometer) when we are in fallDetection state.
* When status is true we have a user fall and we deactivate/unregister the listener
* and we enable a CountDownTimer of 30 secs in order to abort event.
* */
private void setupFallDetection() {
falldetection = new FallDetectionHandler(this);
falldetection.setFallDetectionListener(new FallDetectionListener() {
@Override
public void onStatusChanged(boolean fallDetectionStatus) {
if(fallDetectionStatus) {
falldetection.unregisterListener();
countDownTimerIsRunning = true;
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση
r.play();
mainTitle.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event
countDownTimerIsRunning = false;
r.stop();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
handleEvent("fallDetectionEvent");
}
}.start();
}
}
});
}
private void cancelTimer(){ //ακυρωση timer για το fall detection
countDownTimer.cancel();
r.stop();
}
private void cancelSOSTimer(){ //ακυρωση timer για το SOS button
countDownSOS.onFinish();
countDownSOS.cancel();
}
// setupEarthquakeDetection
private void setupEarthquakeDetection() {
seismicdetection = new SeismicDetectionHandler(this);
seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() {
@Override
public void onStatusChanged(boolean seismicDetectionStatus) {
if(seismicDetectionStatus) {
seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος
handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type
}
}
});
}
// handleEvent
private void handleEvent( String type){
String eventType = type;
final double latd,lond;
//check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider
if(LocationService.latitude !=0 & LocationService.longitude!=0) {
latd = LocationService.latitude;
lond = LocationService.latitude;
}
else
{
getLocation();
latd = latitude;
lond = longitude;
}
String lat = Double.toString(latd);
String lon = Double.toString(lond);
final long timestamp = System.currentTimeMillis();
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp);
String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString();
mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database
if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου
Notification notification = new Notification(mainActivity);
notification.sendNotification(type, lat, lon, date); // αποστολη SMS
}
if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event
mFirebaseService.getEvents();
mFirebaseService.setFirebaseListener(new FirebaseListener() {
@Override
public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents.
if(newStatus.equals("allEvents")){
List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection
boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond);
if(seismicStatus){
handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση
new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ
.setTitle("Earthquake!")
.setMessage("An Earthquake is taking place, please seek help!!")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}else {
//αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake
if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
}
}
});
}
}
}
| Afrodith/SmartAlertGreece | app/src/main/java/com/kospeac/smartgreecealert/MainActivity.java | 3,938 | //αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake | line_comment | el | package com.kospeac.smartgreecealert;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static Activity mainActivity;
UsbService mUsbService = new UsbService();
FirebaseService mFirebaseService;
String type;
Button sosBtn;
Button fireBtn;
Button abortBtn;
public TextView mainTitle;
public TextView sosTitle;
CountDownTimer countDownTimer;
CountDownTimer countDownSOS;
boolean countDownTimerIsRunning = false;
boolean sosStatus = false;
private FallDetectionHandler falldetection;
private SeismicDetectionHandler seismicdetection;
private final static int REQUESTCODE = 325;
LocationManager mLocationManager;
Uri notification;
Ringtone r;
private LocationListener locationService;
private Boolean prevStatus;
Double longitude, latitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = this;
mFirebaseService = FirebaseService.getInstance();
mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationService = new LocationService();
sosBtn = findViewById(R.id.btn_sos);
fireBtn = findViewById(R.id.btn_fire);
abortBtn = findViewById(R.id.btn_abort);
mainTitle = findViewById(R.id.main_title);
sosTitle = findViewById(R.id.sos_text);
sosBtn.setOnClickListener(this);
fireBtn.setOnClickListener(this);
abortBtn.setOnClickListener(this);
checkPermissions();
try {
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
} catch (Exception e) {
e.printStackTrace();
}
this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE"));
mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() {
@Override
public void onStatusChanged(boolean newStatus) {
if(newStatus){
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "earthquakeEventDetected";
if (falldetection != null && FallDetectionHandler.getListenerStatus()) {
falldetection.unregisterListener();
}
mainTitle.setText(R.string.main_title2);
setupEarthquakeDetection(); // EarthquakeDetection
}
}else {
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "fallDetectionEvent";
if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) {
System.out.println(seismicdetection);
seismicdetection.unregisterListener();
}
mainTitle.setText(R.string.main_title1);
setupFallDetection(); // FallDetection
}
}
}
});
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity
super.onDestroy();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_sos: // SOS
sosStatus = true;
sosTitle.setText(R.string.sos_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("SOS");
break;
case R.id.btn_fire: // FIRE button
sosTitle.setText(R.string.fire_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("FIRE");
break;
case R.id.btn_abort: // κουμπι Abort
if(type == "fallDetectionEvent" && countDownTimerIsRunning) {
cancelTimer();
Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
} else if(sosStatus){ // αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση
cancelSOSTimer();
handleEvent("AbortEvent");
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.topbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_statistics:
Intent goToStatistics = new Intent(this,Statistics.class);
startActivity(goToStatistics); // Νεο acitvity Statistics
return true;
case R.id.menu_contacts:
Intent goToContacts = new Intent(this,ContactsActivity.class);
startActivity(goToContacts); // Νεο acitvity Contacts
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkPermissions() {
List<String> PERMISSIONS = new ArrayList<>();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
}else{
System.out.println("GPS ENABLED");
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
}
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
PERMISSIONS.add(Manifest.permission.SEND_SMS);
}
if(!PERMISSIONS.isEmpty()){
String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]);
ActivityCompat.requestPermissions(this,
array,
REQUESTCODE);
}
}
//get location from the GPS service provider. Needs permission.
protected void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location location = null;
for(String provider : providers){
Location l = mLocationManager.getLastKnownLocation(provider);
location = l;
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
break;
}
}
if (location == null) {
latitude = -1.0;
longitude = -1.0;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(this, permission)
== PackageManager.PERMISSION_GRANTED) {
if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
getLocation();
}
}
}
}
/* setupFallDetection
* Create object and listener (from device accelerometer) when we are in fallDetection state.
* When status is true we have a user fall and we deactivate/unregister the listener
* and we enable a CountDownTimer of 30 secs in order to abort event.
* */
private void setupFallDetection() {
falldetection = new FallDetectionHandler(this);
falldetection.setFallDetectionListener(new FallDetectionListener() {
@Override
public void onStatusChanged(boolean fallDetectionStatus) {
if(fallDetectionStatus) {
falldetection.unregisterListener();
countDownTimerIsRunning = true;
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση
r.play();
mainTitle.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event
countDownTimerIsRunning = false;
r.stop();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
handleEvent("fallDetectionEvent");
}
}.start();
}
}
});
}
private void cancelTimer(){ //ακυρωση timer για το fall detection
countDownTimer.cancel();
r.stop();
}
private void cancelSOSTimer(){ //ακυρωση timer για το SOS button
countDownSOS.onFinish();
countDownSOS.cancel();
}
// setupEarthquakeDetection
private void setupEarthquakeDetection() {
seismicdetection = new SeismicDetectionHandler(this);
seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() {
@Override
public void onStatusChanged(boolean seismicDetectionStatus) {
if(seismicDetectionStatus) {
seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος
handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type
}
}
});
}
// handleEvent
private void handleEvent( String type){
String eventType = type;
final double latd,lond;
//check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider
if(LocationService.latitude !=0 & LocationService.longitude!=0) {
latd = LocationService.latitude;
lond = LocationService.latitude;
}
else
{
getLocation();
latd = latitude;
lond = longitude;
}
String lat = Double.toString(latd);
String lon = Double.toString(lond);
final long timestamp = System.currentTimeMillis();
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp);
String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString();
mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database
if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου
Notification notification = new Notification(mainActivity);
notification.sendNotification(type, lat, lon, date); // αποστολη SMS
}
if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event
mFirebaseService.getEvents();
mFirebaseService.setFirebaseListener(new FirebaseListener() {
@Override
public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents.
if(newStatus.equals("allEvents")){
List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection
boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond);
if(seismicStatus){
handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση
new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ
.setTitle("Earthquake!")
.setMessage("An Earthquake is taking place, please seek help!!")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}else {
//αμ<SUF>
if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
}
}
});
}
}
}
|
18080_13 | package gr.aueb;
import org.apiguardian.api.API;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
/*The BonusContentTest class is a test class that contains test methods for testing the functionality of the BonusContent class.
It tests various scenarios such as null or empty inputs, list size, and output validation. */
public class BonusContentTest {
private static String youtubeApiKey;
/*
* testSearchAndPrintVideo_NullSearchQuery: Tests the searchAndPrintVideo method
* with a null search query.
* Expects an IllegalArgumentException to be thrown with the message
* "Search Query cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullSearchQuery() throws URISyntaxException {
String searchQuery = null;
String category = "Fun facts";
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("Search Query cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_EmptyCategory: Tests the searchAndPrintVideo method
* with an empty category.
* Expects an IllegalArgumentException to be thrown with the message
* "category cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_EmptyCategory() throws URISyntaxException {
String searchQuery = "Pulp Fiction";
String category = null;
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("category cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_NullApiKey: Tests the searchAndPrintVideo method with
* a null API key.
* Expects an IllegalArgumentException to be thrown with the message
* "ApiKey cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullApiKey() throws URISyntaxException {
String searchQuery = "Barbie";
String category = "Behind the Scenes";
String apiKey = null;
try {
BonusContent.searchAndPrintVideo(searchQuery, category, apiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("ApiKey cannot be null or empty.", e.getMessage());
}
}
/*
* testCheckItemsSize_NotEmptyList: Tests the checkItemsSize method with a
* non-empty list.
* Expects the list size to be greater than 0.
*/
@Test
public void testCheckItemsSize_NotEmptyList() {
List<Object> items = new ArrayList<>();
items.add(new Object()); // Προσθέτουμε ένα στοιχείο στη λίστα
assertTrue(items.size() > 0);
}
/*
* testCheckItemsSize_EmptyList: Tests the checkItemsSize method with an empty
* list.
* Expects the list size to be 0.
*/
@Test
public void testCheckItemsSize_EmptyList() {
List<Object> items = new ArrayList<>();
assertFalse(items.size() > 0);
}
/*
* testIterateAndPrint_NonEmptyList: Tests the iterateAndPrintWrapper method
* with a non-empty list.
* Verifies that the expected output is printed to the console.
*/
@Test
public void testIterateAndPrint_NonEmptyList() {
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος περιέχει τα αναμενόμενα κείμενα
String expectedOutput = String.format("Item 1%sItem 2%sItem 3%s", System.lineSeparator(),
System.lineSeparator(), System.lineSeparator());
assertEquals(expectedOutput, outContent.toString());
}
/*
* testIterateAndPrint_EmptyList: Tests the iterateAndPrintWrapper method with
* an empty list.
* Verifies that no output is printed to the console.
*/
@Test
public void testIterateAndPrint_EmptyList() {
List<String> items = new ArrayList<>();
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος είναι κενή
assertEquals("", outContent.toString());
}
// Wrapper γύρω από την iterateAndPrint για την κλάση δοκιμών
private static void iterateAndPrintWrapper(List<String> items) {
for (String item : items) {
System.out.println(item);
}
}
} | Aglag257/Java2_AIApp | app/src/test/java/gr/aueb/BonusContentTest.java | 1,653 | // Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών | line_comment | el | package gr.aueb;
import org.apiguardian.api.API;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
/*The BonusContentTest class is a test class that contains test methods for testing the functionality of the BonusContent class.
It tests various scenarios such as null or empty inputs, list size, and output validation. */
public class BonusContentTest {
private static String youtubeApiKey;
/*
* testSearchAndPrintVideo_NullSearchQuery: Tests the searchAndPrintVideo method
* with a null search query.
* Expects an IllegalArgumentException to be thrown with the message
* "Search Query cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullSearchQuery() throws URISyntaxException {
String searchQuery = null;
String category = "Fun facts";
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("Search Query cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_EmptyCategory: Tests the searchAndPrintVideo method
* with an empty category.
* Expects an IllegalArgumentException to be thrown with the message
* "category cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_EmptyCategory() throws URISyntaxException {
String searchQuery = "Pulp Fiction";
String category = null;
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("category cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_NullApiKey: Tests the searchAndPrintVideo method with
* a null API key.
* Expects an IllegalArgumentException to be thrown with the message
* "ApiKey cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullApiKey() throws URISyntaxException {
String searchQuery = "Barbie";
String category = "Behind the Scenes";
String apiKey = null;
try {
BonusContent.searchAndPrintVideo(searchQuery, category, apiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("ApiKey cannot be null or empty.", e.getMessage());
}
}
/*
* testCheckItemsSize_NotEmptyList: Tests the checkItemsSize method with a
* non-empty list.
* Expects the list size to be greater than 0.
*/
@Test
public void testCheckItemsSize_NotEmptyList() {
List<Object> items = new ArrayList<>();
items.add(new Object()); // Προσθέτουμε ένα στοιχείο στη λίστα
assertTrue(items.size() > 0);
}
/*
* testCheckItemsSize_EmptyList: Tests the checkItemsSize method with an empty
* list.
* Expects the list size to be 0.
*/
@Test
public void testCheckItemsSize_EmptyList() {
List<Object> items = new ArrayList<>();
assertFalse(items.size() > 0);
}
/*
* testIterateAndPrint_NonEmptyList: Tests the iterateAndPrintWrapper method
* with a non-empty list.
* Verifies that the expected output is printed to the console.
*/
@Test
public void testIterateAndPrint_NonEmptyList() {
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο 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));
// Κα<SUF>
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος είναι κενή
assertEquals("", outContent.toString());
}
// Wrapper γύρω από την iterateAndPrint για την κλάση δοκιμών
private static void iterateAndPrintWrapper(List<String> items) {
for (String item : items) {
System.out.println(item);
}
}
} |
10206_35 | package com.example.hangmangame;
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(){
/*Rou<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_0 | 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 | // Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα | 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() {
// Εδ<SUF>
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");
}
}
|
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;\r\nimport java.util.ArrayList;\r\nimport java.util.TimerTask;\r\n\r\n/*(...TRUNCATED) | AlexMitsis/LibSoft | src/SystemNotification.java | 1,124 | "/*Κλάση <SystemNοtifications>\r\nΗ κλάση αυτή αφορά τις ενέργειες (...TRUNCATED) | block_comment | el | "import java.time.LocalDate;\r\nimport java.util.ArrayList;\r\nimport java.util.TimerTask;\r\n\r\n/*(...TRUNCATED) |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5