file_id stringlengths 3 9 | content stringlengths 296 36.5k | repo stringlengths 9 109 | path stringlengths 8 163 | token_length int64 125 8.11k | original_comment stringlengths 8 3.46k | comment_type stringclasses 2
values | detected_lang stringclasses 1
value | prompt stringlengths 269 36.4k |
|---|---|---|---|---|---|---|---|---|
5474_5 | 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 | //ελεγχος εαν υπάρχει σύνδεση Internet | 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) { //εαν πατηθεί το κουμπί "Maps"
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγ<SUF>
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");
}
}
}
|
15716_9 | package info.android_angel.navigationdrawer.adapter;
/**
* Created by ANGELOS on 2017.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import info.android_angel.navigationdrawer.R;
import info.android_angel.navigationdrawer.model.TV;
public class TVAdapter extends RecyclerView.Adapter<TVAdapter.TVViewHolder> {
private List<TV> tvs;
private int rowLayout;
private Context context;
public static class TVViewHolder extends RecyclerView.ViewHolder {
LinearLayout tvLayout;
//title
private TextView tv_title;
//release_date
private TextView tv_release_date;
//overview
private TextView tv_overview;
//vote_average
private TextView tv_vote_average;
// private ImageView poster_path;
private ImageView tv_poster_path;
private TextView tv_id;
public TVViewHolder(View v) {
super(v);
tvLayout = (LinearLayout) v.findViewById(R.id.tvs_layout);
tv_title = (TextView) v.findViewById(R.id.tv_title_view);
tv_release_date = (TextView) v.findViewById(R.id.tv_release_date_view);
tv_overview = (TextView) v.findViewById(R.id.tv_overview_view);
tv_vote_average = (TextView) v.findViewById(R.id.tv_vote_average_view);
//if (posterPath == null)
tv_poster_path = (ImageView) itemView.findViewById(R.id.tv_poster_path_view);
//album_id
tv_id = (TextView) v.findViewById(R.id.tv_id);
}
}
public TVAdapter(List<TV> tvs, int rowLayout, Context context) {
//super(rowLayout, context);
this.tvs = tvs;
this.rowLayout = rowLayout;
this.context = context;
}
@Override
public TVAdapter.TVViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new TVViewHolder(view);
}
@Override
public void onBindViewHolder(TVViewHolder holder, final int position) {
holder.tv_title.setText(tvs.get(position).getname());
//Προηγούμενο παράδειγμα
//holder.data.setText(tvs.get(position).getReleaseDate());
holder.tv_release_date.setText(tvs.get(position).getfirst_air_date());
holder.tv_overview.setText(tvs.get(position).getOverview());
holder.tv_vote_average.setText(tvs.get(position).getVoteAverage().toString());
//album_id
holder.tv_id.setText(tvs.get(position).getId().toString());
//https://square.github.io/picasso/
Picasso.with(holder.itemView.getContext()).load("https://image.tmdb.org/t/p/w300" + tvs.get(position).getPosterPath()).into(holder.tv_poster_path);
}
@Override
public int getItemCount() {
return tvs.size();
}
} | ANGELOS-TSILAFAKIS/NavigationDrawerPublic | app/src/main/java/info/android_angel/navigationdrawer/adapter/TVAdapter.java | 851 | //Προηγούμενο παράδειγμα | line_comment | el | package info.android_angel.navigationdrawer.adapter;
/**
* Created by ANGELOS on 2017.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import info.android_angel.navigationdrawer.R;
import info.android_angel.navigationdrawer.model.TV;
public class TVAdapter extends RecyclerView.Adapter<TVAdapter.TVViewHolder> {
private List<TV> tvs;
private int rowLayout;
private Context context;
public static class TVViewHolder extends RecyclerView.ViewHolder {
LinearLayout tvLayout;
//title
private TextView tv_title;
//release_date
private TextView tv_release_date;
//overview
private TextView tv_overview;
//vote_average
private TextView tv_vote_average;
// private ImageView poster_path;
private ImageView tv_poster_path;
private TextView tv_id;
public TVViewHolder(View v) {
super(v);
tvLayout = (LinearLayout) v.findViewById(R.id.tvs_layout);
tv_title = (TextView) v.findViewById(R.id.tv_title_view);
tv_release_date = (TextView) v.findViewById(R.id.tv_release_date_view);
tv_overview = (TextView) v.findViewById(R.id.tv_overview_view);
tv_vote_average = (TextView) v.findViewById(R.id.tv_vote_average_view);
//if (posterPath == null)
tv_poster_path = (ImageView) itemView.findViewById(R.id.tv_poster_path_view);
//album_id
tv_id = (TextView) v.findViewById(R.id.tv_id);
}
}
public TVAdapter(List<TV> tvs, int rowLayout, Context context) {
//super(rowLayout, context);
this.tvs = tvs;
this.rowLayout = rowLayout;
this.context = context;
}
@Override
public TVAdapter.TVViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new TVViewHolder(view);
}
@Override
public void onBindViewHolder(TVViewHolder holder, final int position) {
holder.tv_title.setText(tvs.get(position).getname());
//Προη<SUF>
//holder.data.setText(tvs.get(position).getReleaseDate());
holder.tv_release_date.setText(tvs.get(position).getfirst_air_date());
holder.tv_overview.setText(tvs.get(position).getOverview());
holder.tv_vote_average.setText(tvs.get(position).getVoteAverage().toString());
//album_id
holder.tv_id.setText(tvs.get(position).getId().toString());
//https://square.github.io/picasso/
Picasso.with(holder.itemView.getContext()).load("https://image.tmdb.org/t/p/w300" + tvs.get(position).getPosterPath()).into(holder.tv_poster_path);
}
@Override
public int getItemCount() {
return tvs.size();
}
} |
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.d<SUF>
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} |
11039_5 | package gr.rambou.myicarus;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
public class Icarus implements Serializable {
private final String Username, Password;
public Map<String, String> Cookies;
private String StudentFullName, ID, StudentName, Surname;
//private Document Page;
private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons;
public Icarus(String username, String password) {
this.Username = username;
this.Password = password;
this.StudentFullName = null;
this.Cookies = null;
}
public boolean login() {
try {
//ενεργοποιούμε το SSL
enableSSLSocket();
//Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε
Connection.Response res = Jsoup
.connect("https://icarus-icsd.aegean.gr/authentication.php")
.timeout(10 * 1000)
.data("username", Username, "pwd", Password)
.method(Connection.Method.POST)
.execute();
//Παίρνουμε τα cookies
Cookies = res.cookies();
//Αποθηκεύουμε το περιεχόμενο της σελίδας
Document Page = res.parse();
//Ελέγχουμε αν συνδεθήκαμε
Elements name = Page.select("div#header_login").select("u");
if (name.hasText()) {
//Παίρνουμε το ονοματεπώνυμο του φοιτητή
StudentFullName = name.html();
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
Pattern r = Pattern.compile("[0-9-/-]{5,16}");
String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim();
Matcher m = r.matcher(line);
if (m.find()) {
ID = m.group(0);
}
//Παίρνουμε τους βαθμούς του φοιτητή
LoadMarks(Page);
return true;
}
} catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) {
Log.v("Icarus Class", ex.toString());
}
return false;
}
public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) {
if (papers.length != 11) {
return false;
}
String sendmethod;
if (sendtype.equals(SendType.FAX)) {
sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:";
} else if (sendtype.equals(SendType.COURIER)) {
sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:";
} else {
sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης";
}
//We create the Data to be Send
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addTextBody("aitisi_student_id", getID());
mpEntity.addTextBody("aitisi_surname", getSurname());
mpEntity.addTextBody("aitisi_name", getStudentName());
mpEntity.addTextBody("aitisi_father", fatherName);
mpEntity.addTextBody("aitisi_semester", cemester.toString());
mpEntity.addTextBody("aitisi_address", address);
mpEntity.addTextBody("aitisi_phone", phone);
mpEntity.addTextBody("aitisi_send_method", sendmethod);
mpEntity.addTextBody("aitisi_send_address", send_address);
mpEntity.addTextBody("prints_no[]", papers[0]);
mpEntity.addTextBody("prints_no[]", papers[1]);
mpEntity.addTextBody("prints_no[]", papers[2]);
mpEntity.addTextBody("prints_no[]", papers[3]);
mpEntity.addTextBody("prints_no[]", papers[4]);
mpEntity.addTextBody("prints_no[]", papers[5]);
mpEntity.addTextBody("prints_no[]", papers[6]);
mpEntity.addTextBody("prints_no[]", papers[7]);
mpEntity.addTextBody("prints_no[]", papers[8]);
mpEntity.addTextBody("prints_no[]", papers[9]);
mpEntity.addTextBody("aitisi_allo", papers[10]);
mpEntity.addTextBody("send", "");
HttpEntity entity = mpEntity.build();
//We send the request
HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php");
post.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
//Gets new/old cookies and set them in store and store to CTX
CookieStore Store = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID"));
cookie.setPath("//");
cookie.setDomain("icarus-icsd.aegean.gr");
Store.addCookie(cookie);
HttpContext CTX = new BasicHttpContext();
CTX.setAttribute(ClientContext.COOKIE_STORE, Store);
HttpResponse response = null;
try {
response = client.execute(post, CTX);
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
}
//Check if user credentials are ok
if (response == null) {
return false;
}
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 200) {
return false;
}
try {
String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7");
Document res = Jsoup.parse(html);
if (res.getElementsByClass("success").isEmpty()) {
return false;
}
} catch (IOException | org.apache.http.ParseException ex) {
return false;
}
return true;
}
public void LoadMarks(Document response) {
All_Lessons = new ArrayList<>();
Succeed_Lessons = new ArrayList<>();
Exams_Lessons = new ArrayList<>();
if (response == null) {
try {
//We send the request
response = Jsoup
.connect("https://icarus-icsd.aegean.gr/student_main.php")
.cookies(Cookies)
.get();
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
return;
}
}
//Start Catching Lessons
Elements sGrades = response.getElementById("succeeded_grades").select("tr");
Elements aGrades = response.getElementById("analytic_grades").select("tr");
Elements eGrades = response.getElementById("exetastiki_grades").select("tr");
for (Element a : sGrades) {
if (!a.select("td").isEmpty()) {
Succeed_Lessons.add(getLesson(a));
}
}
for (Element a : eGrades) {
if (!a.select("td").isEmpty()) {
Exams_Lessons.add(getLesson(a));
if (a.select("td").get(6).text().trim().compareTo("") != 0)
All_Lessons.add(getLesson(a));
}
}
for (Element a : aGrades) {
if (!a.select("td").isEmpty()) {
All_Lessons.add(getLesson(a));
}
}
}
private Lesson getLesson(Element a) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String ID = a.select("td").get(1).text();
String Title = a.select("td").get(2).text();
Double Mark = 0.0;
try {
Mark = Double.valueOf(a.select("td").get(3).text());
} catch (Exception ex) {
}
String Cemester = a.select("td").get(4).text();
Date Statement = null, Exam = null;
try {
Statement = formatter.parse(a.select("td").get(5).text().trim());
Exam = formatter.parse(a.select("td").get(6).text().trim());
} catch (ParseException ex) {
}
Lesson.LessonStatus Status;
switch (a.select("td").get(7).text().trim()) {
case "Επιτυχία":
Status = Lesson.LessonStatus.PASSED;
break;
case "Αποτυχία":
Status = Lesson.LessonStatus.FAILED;
break;
case "Ακύρωση":
Status = Lesson.LessonStatus.CANCELLED;
break;
default:
Status = Lesson.LessonStatus.NOT_GIVEN;
break;
}
return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status);
}
public ArrayList<Lesson> getSucceed_Lessons() {
return Succeed_Lessons;
}
public ArrayList<Lesson> getAll_Lessons() {
return All_Lessons;
}
public Object[] getAll_Lessons_array() {
return All_Lessons.toArray();
}
public ArrayList<Lesson> getExams_Lessons() {
return Exams_Lessons;
}
public String getStudentFullName() {
return StudentFullName;
}
public String getID() {
return ID;
}
public String getStudentName() {
return StudentFullName.split(" ")[0];
}
public String getSurname() {
return StudentFullName.split(" ")[1];
}
private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
//HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true);
SSLContext context;
context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
public enum SendType {
OFFICE, COURIER, FAX
}
public enum PaperType {
bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo,
stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma,
allo
}
}
| AegeanHawks/MobileIcarus | app/src/main/java/gr/rambou/myicarus/Icarus.java | 3,246 | //Αποθηκεύουμε το περιεχόμενο της σελίδας | line_comment | el | package gr.rambou.myicarus;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
public class Icarus implements Serializable {
private final String Username, Password;
public Map<String, String> Cookies;
private String StudentFullName, ID, StudentName, Surname;
//private Document Page;
private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons;
public Icarus(String username, String password) {
this.Username = username;
this.Password = password;
this.StudentFullName = null;
this.Cookies = null;
}
public boolean login() {
try {
//ενεργοποιούμε το SSL
enableSSLSocket();
//Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε
Connection.Response res = Jsoup
.connect("https://icarus-icsd.aegean.gr/authentication.php")
.timeout(10 * 1000)
.data("username", Username, "pwd", Password)
.method(Connection.Method.POST)
.execute();
//Παίρνουμε τα cookies
Cookies = res.cookies();
//Αποθ<SUF>
Document Page = res.parse();
//Ελέγχουμε αν συνδεθήκαμε
Elements name = Page.select("div#header_login").select("u");
if (name.hasText()) {
//Παίρνουμε το ονοματεπώνυμο του φοιτητή
StudentFullName = name.html();
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
Pattern r = Pattern.compile("[0-9-/-]{5,16}");
String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim();
Matcher m = r.matcher(line);
if (m.find()) {
ID = m.group(0);
}
//Παίρνουμε τους βαθμούς του φοιτητή
LoadMarks(Page);
return true;
}
} catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) {
Log.v("Icarus Class", ex.toString());
}
return false;
}
public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) {
if (papers.length != 11) {
return false;
}
String sendmethod;
if (sendtype.equals(SendType.FAX)) {
sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:";
} else if (sendtype.equals(SendType.COURIER)) {
sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:";
} else {
sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης";
}
//We create the Data to be Send
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addTextBody("aitisi_student_id", getID());
mpEntity.addTextBody("aitisi_surname", getSurname());
mpEntity.addTextBody("aitisi_name", getStudentName());
mpEntity.addTextBody("aitisi_father", fatherName);
mpEntity.addTextBody("aitisi_semester", cemester.toString());
mpEntity.addTextBody("aitisi_address", address);
mpEntity.addTextBody("aitisi_phone", phone);
mpEntity.addTextBody("aitisi_send_method", sendmethod);
mpEntity.addTextBody("aitisi_send_address", send_address);
mpEntity.addTextBody("prints_no[]", papers[0]);
mpEntity.addTextBody("prints_no[]", papers[1]);
mpEntity.addTextBody("prints_no[]", papers[2]);
mpEntity.addTextBody("prints_no[]", papers[3]);
mpEntity.addTextBody("prints_no[]", papers[4]);
mpEntity.addTextBody("prints_no[]", papers[5]);
mpEntity.addTextBody("prints_no[]", papers[6]);
mpEntity.addTextBody("prints_no[]", papers[7]);
mpEntity.addTextBody("prints_no[]", papers[8]);
mpEntity.addTextBody("prints_no[]", papers[9]);
mpEntity.addTextBody("aitisi_allo", papers[10]);
mpEntity.addTextBody("send", "");
HttpEntity entity = mpEntity.build();
//We send the request
HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php");
post.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
//Gets new/old cookies and set them in store and store to CTX
CookieStore Store = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID"));
cookie.setPath("//");
cookie.setDomain("icarus-icsd.aegean.gr");
Store.addCookie(cookie);
HttpContext CTX = new BasicHttpContext();
CTX.setAttribute(ClientContext.COOKIE_STORE, Store);
HttpResponse response = null;
try {
response = client.execute(post, CTX);
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
}
//Check if user credentials are ok
if (response == null) {
return false;
}
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 200) {
return false;
}
try {
String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7");
Document res = Jsoup.parse(html);
if (res.getElementsByClass("success").isEmpty()) {
return false;
}
} catch (IOException | org.apache.http.ParseException ex) {
return false;
}
return true;
}
public void LoadMarks(Document response) {
All_Lessons = new ArrayList<>();
Succeed_Lessons = new ArrayList<>();
Exams_Lessons = new ArrayList<>();
if (response == null) {
try {
//We send the request
response = Jsoup
.connect("https://icarus-icsd.aegean.gr/student_main.php")
.cookies(Cookies)
.get();
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
return;
}
}
//Start Catching Lessons
Elements sGrades = response.getElementById("succeeded_grades").select("tr");
Elements aGrades = response.getElementById("analytic_grades").select("tr");
Elements eGrades = response.getElementById("exetastiki_grades").select("tr");
for (Element a : sGrades) {
if (!a.select("td").isEmpty()) {
Succeed_Lessons.add(getLesson(a));
}
}
for (Element a : eGrades) {
if (!a.select("td").isEmpty()) {
Exams_Lessons.add(getLesson(a));
if (a.select("td").get(6).text().trim().compareTo("") != 0)
All_Lessons.add(getLesson(a));
}
}
for (Element a : aGrades) {
if (!a.select("td").isEmpty()) {
All_Lessons.add(getLesson(a));
}
}
}
private Lesson getLesson(Element a) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String ID = a.select("td").get(1).text();
String Title = a.select("td").get(2).text();
Double Mark = 0.0;
try {
Mark = Double.valueOf(a.select("td").get(3).text());
} catch (Exception ex) {
}
String Cemester = a.select("td").get(4).text();
Date Statement = null, Exam = null;
try {
Statement = formatter.parse(a.select("td").get(5).text().trim());
Exam = formatter.parse(a.select("td").get(6).text().trim());
} catch (ParseException ex) {
}
Lesson.LessonStatus Status;
switch (a.select("td").get(7).text().trim()) {
case "Επιτυχία":
Status = Lesson.LessonStatus.PASSED;
break;
case "Αποτυχία":
Status = Lesson.LessonStatus.FAILED;
break;
case "Ακύρωση":
Status = Lesson.LessonStatus.CANCELLED;
break;
default:
Status = Lesson.LessonStatus.NOT_GIVEN;
break;
}
return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status);
}
public ArrayList<Lesson> getSucceed_Lessons() {
return Succeed_Lessons;
}
public ArrayList<Lesson> getAll_Lessons() {
return All_Lessons;
}
public Object[] getAll_Lessons_array() {
return All_Lessons.toArray();
}
public ArrayList<Lesson> getExams_Lessons() {
return Exams_Lessons;
}
public String getStudentFullName() {
return StudentFullName;
}
public String getID() {
return ID;
}
public String getStudentName() {
return StudentFullName.split(" ")[0];
}
public String getSurname() {
return StudentFullName.split(" ")[1];
}
private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
//HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true);
SSLContext context;
context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
public enum SendType {
OFFICE, COURIER, FAX
}
public enum PaperType {
bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo,
stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma,
allo
}
}
|
32051_17 | 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 | //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type | 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"); //κατα<SUF>
}
}
});
}
// 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();
}
}
}
}
});
}
}
}
|
2452_2 | package gr.aueb;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LoginFrame extends JFrame implements ActionListener {
static String username;
JFrame frm = new JFrame("Filmbro");
JLabel welcomeMess = new JLabel("Hello, log in to your account.");
Container container = getContentPane();
JLabel userLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
JTextField userTextField = new JTextField(" e.g. Username");
JPasswordField passwordField = new JPasswordField();
DarkButton loginButton = new DarkButton("LOGIN");
DarkButton backButton = new DarkButton("BACK");
JCheckBox showPassword = new JCheckBox("Show Password");
JLabel picLabel = new JLabel(new ImageIcon("logo.png")); // an theloume na baloyme eikona
JMenuBar mb = new JMenuBar();
LoginFrame() {
initComponents();
}
private void initComponents() {
setTitle("Java");
setBounds(10, 10, 600, 600);
frm.setJMenuBar(mb);
setLocationRelativeTo(null); // center the application window
setVisible(true);
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
setBackground(20,20,20);
setFont();
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
resizeComponents();
}
});
}
public void setLayoutManager() {
container.setLayout(null);
}
private void setBackground(int a, int b, int c) {
container.setBackground(new Color(a, b, c));
showPassword.setBackground(new Color(a, b, c));
}
private void setFont() {
welcomeMess.setFont(new Font("Tahoma", 0, 16));
welcomeMess.setForeground(new Color(230, 120, 50));
userLabel.setForeground(new Color(230, 120, 50));
passwordLabel.setForeground(new Color(230, 120, 50));
showPassword.setForeground(new Color(230, 120, 50));
}
public void setLocationAndSize() {
userLabel.setBounds(50, 150, 100, 30);
passwordLabel.setBounds(50, 200, 100, 30);
userTextField.setBounds(150, 150, 150, 30);
passwordField.setBounds(150, 200, 150, 30);
showPassword.setBounds(150, 240, 150, 30);
loginButton.setBounds(125, 300, 100, 30);
welcomeMess.setBounds(70, 50, 230, 150);
picLabel.setBounds(100, 10, 150, 90);
backButton.setBounds(20, 490, 80, 30);
}
public void addComponentsToContainer() {
container.add(userLabel);
container.add(welcomeMess);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(picLabel);
container.add(backButton);
}
public void addActionEvent() {
loginButton.addActionListener(this);
showPassword.addActionListener(this);
backButton.addActionListener(this);
userTextField.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
userTextField.setText("");
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == backButton) {
MenuBar m = new MenuBar(new MenuFrame());
dispose();
}
if (e.getSource() == showPassword) {
if (showPassword.isSelected()) {
passwordField.setEchoChar((char) 0);
}else {
passwordField.setEchoChar('*');
}
}
}
public void resizeComponents() {
int width = this.getWidth();
int centerOffset = width / 4; // Προσαρμόζετε τον παράγοντα ανάλογα με την πόσο πρέπει να μετακινηθούν τα στοιχεία.
userLabel.setBounds(centerOffset, 150, 100, 30);
passwordLabel.setBounds(centerOffset, 200, 100, 30);
userTextField.setBounds(centerOffset + 100, 150, 150, 30);
passwordField.setBounds(centerOffset + 100, 200, 150, 30);
showPassword.setBounds(centerOffset + 100, 240, 150, 30);
loginButton.setBounds(centerOffset +85, 300, 140, 30); // Προσαρμόστε ανάλογα για την ευθυγράμμιση.
welcomeMess.setBounds(centerOffset, 50, 230, 150);
picLabel.setBounds(centerOffset + 50, 10, 150, 90);
backButton.setBounds(20, 490, 80, 30);
}
} | Aglag257/Java2_AIApp | app/src/unused_code/LoginFrame.java | 1,431 | // Προσαρμόζετε τον παράγοντα ανάλογα με την πόσο πρέπει να μετακινηθούν τα στοιχεία. | line_comment | el | package gr.aueb;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LoginFrame extends JFrame implements ActionListener {
static String username;
JFrame frm = new JFrame("Filmbro");
JLabel welcomeMess = new JLabel("Hello, log in to your account.");
Container container = getContentPane();
JLabel userLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
JTextField userTextField = new JTextField(" e.g. Username");
JPasswordField passwordField = new JPasswordField();
DarkButton loginButton = new DarkButton("LOGIN");
DarkButton backButton = new DarkButton("BACK");
JCheckBox showPassword = new JCheckBox("Show Password");
JLabel picLabel = new JLabel(new ImageIcon("logo.png")); // an theloume na baloyme eikona
JMenuBar mb = new JMenuBar();
LoginFrame() {
initComponents();
}
private void initComponents() {
setTitle("Java");
setBounds(10, 10, 600, 600);
frm.setJMenuBar(mb);
setLocationRelativeTo(null); // center the application window
setVisible(true);
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
setBackground(20,20,20);
setFont();
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
resizeComponents();
}
});
}
public void setLayoutManager() {
container.setLayout(null);
}
private void setBackground(int a, int b, int c) {
container.setBackground(new Color(a, b, c));
showPassword.setBackground(new Color(a, b, c));
}
private void setFont() {
welcomeMess.setFont(new Font("Tahoma", 0, 16));
welcomeMess.setForeground(new Color(230, 120, 50));
userLabel.setForeground(new Color(230, 120, 50));
passwordLabel.setForeground(new Color(230, 120, 50));
showPassword.setForeground(new Color(230, 120, 50));
}
public void setLocationAndSize() {
userLabel.setBounds(50, 150, 100, 30);
passwordLabel.setBounds(50, 200, 100, 30);
userTextField.setBounds(150, 150, 150, 30);
passwordField.setBounds(150, 200, 150, 30);
showPassword.setBounds(150, 240, 150, 30);
loginButton.setBounds(125, 300, 100, 30);
welcomeMess.setBounds(70, 50, 230, 150);
picLabel.setBounds(100, 10, 150, 90);
backButton.setBounds(20, 490, 80, 30);
}
public void addComponentsToContainer() {
container.add(userLabel);
container.add(welcomeMess);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(picLabel);
container.add(backButton);
}
public void addActionEvent() {
loginButton.addActionListener(this);
showPassword.addActionListener(this);
backButton.addActionListener(this);
userTextField.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
userTextField.setText("");
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == backButton) {
MenuBar m = new MenuBar(new MenuFrame());
dispose();
}
if (e.getSource() == showPassword) {
if (showPassword.isSelected()) {
passwordField.setEchoChar((char) 0);
}else {
passwordField.setEchoChar('*');
}
}
}
public void resizeComponents() {
int width = this.getWidth();
int centerOffset = width / 4; // Προσ<SUF>
userLabel.setBounds(centerOffset, 150, 100, 30);
passwordLabel.setBounds(centerOffset, 200, 100, 30);
userTextField.setBounds(centerOffset + 100, 150, 150, 30);
passwordField.setBounds(centerOffset + 100, 200, 150, 30);
showPassword.setBounds(centerOffset + 100, 240, 150, 30);
loginButton.setBounds(centerOffset +85, 300, 140, 30); // Προσαρμόστε ανάλογα για την ευθυγράμμιση.
welcomeMess.setBounds(centerOffset, 50, 230, 150);
picLabel.setBounds(centerOffset + 50, 10, 150, 90);
backButton.setBounds(20, 490, 80, 30);
}
} |
10161_0 | package com.example.hangmangame;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import static com.example.hangmangame.Controller.gamewords_5;
import static com.example.hangmangame.Controller.results_5;
import static com.example.hangmangame.Controller.Attempts_per_gameword;
/*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5
τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες:
επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή
υπολογιστής).
*/
public class Rounds{
@FXML
private Label Gameword_1;
@FXML
private Label Gameword_2;
@FXML
private Label Gameword_3;
@FXML
private Label Gameword_4;
@FXML
private Label Gameword_5;
@FXML
private Label Results_1;
@FXML
private Label Results_2;
@FXML
private Label Results_3;
@FXML
private Label Results_4;
@FXML
private Label Results_5;
@FXML
private Label Attempts_1;
@FXML
private Label Attempts_2;
@FXML
private Label Attempts_3;
@FXML
private Label Attempts_4;
@FXML
private Label Attempts_5;
@FXML
public void Round_Setup() {
if(!Controller.Playing) {
Gameword_1.setText("PLEASE");
Gameword_5.setText("PLEASE");
Results_1.setText("DICTIONARY");
Results_5.setText("DICTIONARY");
Attempts_1.setText("LOAD");
Attempts_5.setText("LOAD");
return;
}
//Call the method that we created in the controller
Gameword_1.setText(gamewords_5.get(4));
Gameword_2.setText(gamewords_5.get(3));
Gameword_3.setText(gamewords_5.get(2));
Gameword_4.setText(gamewords_5.get(1));
Gameword_5.setText(gamewords_5.get(0));
Results_1.setText(results_5.get(4));
Results_2.setText(results_5.get(3));
Results_3.setText(results_5.get(2));
Results_4.setText(results_5.get(1));
Results_5.setText(results_5.get(0));
Attempts_1.setText(String.valueOf(Attempts_per_gameword.get(4)));
Attempts_2.setText(String.valueOf(Attempts_per_gameword.get(3)));
Attempts_3.setText(String.valueOf(Attempts_per_gameword.get(2)));
Attempts_4.setText(String.valueOf(Attempts_per_gameword.get(1)));
Attempts_5.setText(String.valueOf(Attempts_per_gameword.get(0)));
}
}
| Aglogallos/Hangman-Game-JavaFx | Hangman_Game/Hangman-Game/src/main/java/com/example/hangmangame/Rounds.java | 821 | /*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5
τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες:
επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή
υπολογιστής).
*/ | block_comment | el | package com.example.hangmangame;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import static com.example.hangmangame.Controller.gamewords_5;
import static com.example.hangmangame.Controller.results_5;
import static com.example.hangmangame.Controller.Attempts_per_gameword;
/*Round<SUF>*/
public class Rounds{
@FXML
private Label Gameword_1;
@FXML
private Label Gameword_2;
@FXML
private Label Gameword_3;
@FXML
private Label Gameword_4;
@FXML
private Label Gameword_5;
@FXML
private Label Results_1;
@FXML
private Label Results_2;
@FXML
private Label Results_3;
@FXML
private Label Results_4;
@FXML
private Label Results_5;
@FXML
private Label Attempts_1;
@FXML
private Label Attempts_2;
@FXML
private Label Attempts_3;
@FXML
private Label Attempts_4;
@FXML
private Label Attempts_5;
@FXML
public void Round_Setup() {
if(!Controller.Playing) {
Gameword_1.setText("PLEASE");
Gameword_5.setText("PLEASE");
Results_1.setText("DICTIONARY");
Results_5.setText("DICTIONARY");
Attempts_1.setText("LOAD");
Attempts_5.setText("LOAD");
return;
}
//Call the method that we created in the controller
Gameword_1.setText(gamewords_5.get(4));
Gameword_2.setText(gamewords_5.get(3));
Gameword_3.setText(gamewords_5.get(2));
Gameword_4.setText(gamewords_5.get(1));
Gameword_5.setText(gamewords_5.get(0));
Results_1.setText(results_5.get(4));
Results_2.setText(results_5.get(3));
Results_3.setText(results_5.get(2));
Results_4.setText(results_5.get(1));
Results_5.setText(results_5.get(0));
Attempts_1.setText(String.valueOf(Attempts_per_gameword.get(4)));
Attempts_2.setText(String.valueOf(Attempts_per_gameword.get(3)));
Attempts_3.setText(String.valueOf(Attempts_per_gameword.get(2)));
Attempts_4.setText(String.valueOf(Attempts_per_gameword.get(1)));
Attempts_5.setText(String.valueOf(Attempts_per_gameword.get(0)));
}
}
|
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;
import java.util.ArrayList;
import java.util.TimerTask;
/*Κλάση <SystemNοtifications>
Η κλάση αυτή αφορά τις ενέργειες του συστήματος οι οποίες εξαρτώνται άμεσα απο τον χρόνο.
Συγκεκριμένα εξυπηρετεί τις περιπτώσεις χρήσης:
Penalty - Use Case Code: 26 (X02),Warning - Use Case Code: 25 (X03)*/
public class SystemNotification extends TimerTask {
//synarthsh-thread gia ton taktiko elegxo twn kyrwsewn.kaleitai sthn main
public static void checkforActions() {
Warning.checkforWarning();
Penalty.checkforPenalty();
Penalty.undoPenalties();
}
@Override
public void run() {
// TODO Auto-generated method stub
SystemNotification.checkforActions();
}
//------------------------------------------------------//
private static class Warning{
public static void checkforWarning()
{ int timeleft=3;
ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks();
//gia kathe daneizomeno
for(BookLending booklending:borrowed)
{if(booklending.getTimeLeft(LocalDate.now().plusDays(3))==timeleft){
String text="To vivlio"+booklending.getBook().getTitle()+"prepei na epistrafei se 3 meres";
Borrower recipient=booklending.getBorrower();
Message warning=new Message(text,Main.librarian);
Message.messageToBorrower(recipient, warning);
}
}
}
}
private static class Penalty{
public static void checkforPenalty()
{
ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks();
ArrayList<BookLending> delayed=Main.librarydata.getDelayedBooks();
for(BookLending booklending:borrowed) {
if(booklending.getTimeLeft(LocalDate.now())==-1) {
delayed.add(booklending);
borrowed.remove(booklending);
Borrower recipient=booklending.getBorrower();
recipient.setNumberOfPenalties((recipient.getNumberOfPenalties()+1)%3);
boolean severe=false;
if(recipient.getNumberOfPenalties()==0) {
recipient.setAbleToBorrow(false);
recipient.setDateOfLastPenlty(LocalDate.now());
/**add to withpenalty list**/
ArrayList<Borrower> p=Main.librarydata.getWithPenalty();
if(p.indexOf(recipient)==-1)//if doesn't exist
{p.add(recipient);}
severe=true;
}
//message to be sent
String text1="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa";
String text2="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa.Logw epanalambanomenwn kathisterhsewn"
+ "den mporeite na daneisteite gia 30 meres";
Message warning=null;
if(!severe) {warning=new Message(text1,Main.librarian);}else {warning=new Message(text2,Main.librarian);}
Message.messageToBorrower(recipient, warning);
}
}
}
public static void undoPenalties() {
ArrayList<Borrower> penalties=Main.librarydata.getWithPenalty();
for(Borrower b:penalties) {
if(b.getDateOfLastPenlty().plusDays(14)==LocalDate.now()) {
b.setAbleToBorrow(true);
penalties.remove(b);
String text="Mporeite na daneisteite 3ana";
Message inform=new Message(text,Main.librarian);
Message.messageToBorrower(b, inform);
}
}
}
}
}
| AlexMitsis/LibSoft | src/SystemNotification.java | 1,124 | /*Κλάση <SystemNοtifications>
Η κλάση αυτή αφορά τις ενέργειες του συστήματος οι οποίες εξαρτώνται άμεσα απο τον χρόνο.
Συγκεκριμένα εξυπηρετεί τις περιπτώσεις χρήσης:
Penalty - Use Case Code: 26 (X02),Warning - Use Case Code: 25 (X03)*/ | block_comment | el | import java.time.LocalDate;
import java.util.ArrayList;
import java.util.TimerTask;
/*Κλάση<SUF>*/
public class SystemNotification extends TimerTask {
//synarthsh-thread gia ton taktiko elegxo twn kyrwsewn.kaleitai sthn main
public static void checkforActions() {
Warning.checkforWarning();
Penalty.checkforPenalty();
Penalty.undoPenalties();
}
@Override
public void run() {
// TODO Auto-generated method stub
SystemNotification.checkforActions();
}
//------------------------------------------------------//
private static class Warning{
public static void checkforWarning()
{ int timeleft=3;
ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks();
//gia kathe daneizomeno
for(BookLending booklending:borrowed)
{if(booklending.getTimeLeft(LocalDate.now().plusDays(3))==timeleft){
String text="To vivlio"+booklending.getBook().getTitle()+"prepei na epistrafei se 3 meres";
Borrower recipient=booklending.getBorrower();
Message warning=new Message(text,Main.librarian);
Message.messageToBorrower(recipient, warning);
}
}
}
}
private static class Penalty{
public static void checkforPenalty()
{
ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks();
ArrayList<BookLending> delayed=Main.librarydata.getDelayedBooks();
for(BookLending booklending:borrowed) {
if(booklending.getTimeLeft(LocalDate.now())==-1) {
delayed.add(booklending);
borrowed.remove(booklending);
Borrower recipient=booklending.getBorrower();
recipient.setNumberOfPenalties((recipient.getNumberOfPenalties()+1)%3);
boolean severe=false;
if(recipient.getNumberOfPenalties()==0) {
recipient.setAbleToBorrow(false);
recipient.setDateOfLastPenlty(LocalDate.now());
/**add to withpenalty list**/
ArrayList<Borrower> p=Main.librarydata.getWithPenalty();
if(p.indexOf(recipient)==-1)//if doesn't exist
{p.add(recipient);}
severe=true;
}
//message to be sent
String text1="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa";
String text2="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa.Logw epanalambanomenwn kathisterhsewn"
+ "den mporeite na daneisteite gia 30 meres";
Message warning=null;
if(!severe) {warning=new Message(text1,Main.librarian);}else {warning=new Message(text2,Main.librarian);}
Message.messageToBorrower(recipient, warning);
}
}
}
public static void undoPenalties() {
ArrayList<Borrower> penalties=Main.librarydata.getWithPenalty();
for(Borrower b:penalties) {
if(b.getDateOfLastPenlty().plusDays(14)==LocalDate.now()) {
b.setAbleToBorrow(true);
penalties.remove(b);
String text="Mporeite na daneisteite 3ana";
Message inform=new Message(text,Main.librarian);
Message.messageToBorrower(b, inform);
}
}
}
}
}
|
13673_4 | package gr.aueb.dmst.T21;
import java.util.Scanner;
public class TestApp {
static App app = new App(); // make app global and static
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Run the program (1)\nExit (0)");
int choice = sc.nextInt();
String input1 = "";
String input2 = "";
String input3 = "";
//String input4 = "";
//String input5 = "";
String input6 = "";
String expectedOutput = "";
//new object for RegistrationForm
while (choice == 1) {
System.out.println("productionYear");
input1 = sc.nextLine();
sc.nextLine(); // Διαβάζει την αλλαγή γραμμής που παρέμεινε στο buffer
System.out.println("model");
input2 = sc.nextLine();
System.out.println("brand");
input3 = sc.nextLine();
/*
System.out.println("key1");
input4 = sc.nextLine();
System.out.println("key2");
input5 = sc.nextLine();
*/
System.out.println("key3");
input6 = sc.nextLine();
System.out.println("Expected output");
expectedOutput = sc.nextLine();
//check the true value
chatGPT ch = new chatGPT();
String message = "Give me details about " + input6 + ", " + input3 + " " + input2 + " " + input1 + "."; //question for AI
String answer = ch.chatGPT(message);
if (answer.equals(expectedOutput)) {
System.out.println("Test passed");
} else {
System.out.println("Test failed");
//print both outputs
System.out.println("Expected output: " + expectedOutput);
System.out.println("Actual output: " + answer);
}
System.out.println("For continue press 1, for exit press 0");
choice = sc.nextInt();
}
}
}
| Alexandra-Stath/Finding-Spare-Parts-Using-AI | Finding-Spare-Parts-Using-AI/src/main/java/gr/aueb/dmst/T21/TestApp.java | 498 | // Διαβάζει την αλλαγή γραμμής που παρέμεινε στο buffer | line_comment | el | package gr.aueb.dmst.T21;
import java.util.Scanner;
public class TestApp {
static App app = new App(); // make app global and static
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Run the program (1)\nExit (0)");
int choice = sc.nextInt();
String input1 = "";
String input2 = "";
String input3 = "";
//String input4 = "";
//String input5 = "";
String input6 = "";
String expectedOutput = "";
//new object for RegistrationForm
while (choice == 1) {
System.out.println("productionYear");
input1 = sc.nextLine();
sc.nextLine(); // Διαβ<SUF>
System.out.println("model");
input2 = sc.nextLine();
System.out.println("brand");
input3 = sc.nextLine();
/*
System.out.println("key1");
input4 = sc.nextLine();
System.out.println("key2");
input5 = sc.nextLine();
*/
System.out.println("key3");
input6 = sc.nextLine();
System.out.println("Expected output");
expectedOutput = sc.nextLine();
//check the true value
chatGPT ch = new chatGPT();
String message = "Give me details about " + input6 + ", " + input3 + " " + input2 + " " + input1 + "."; //question for AI
String answer = ch.chatGPT(message);
if (answer.equals(expectedOutput)) {
System.out.println("Test passed");
} else {
System.out.println("Test failed");
//print both outputs
System.out.println("Expected output: " + expectedOutput);
System.out.println("Actual output: " + answer);
}
System.out.println("For continue press 1, for exit press 0");
choice = sc.nextInt();
}
}
}
|
6470_6 | package javaproject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LessonFrame extends JFrame
{
//Μέρος δηλώσεων
private ArrayList<Lesson> mlessons=new ArrayList<Lesson>();
private ArrayList<Lesson> showup=new ArrayList<Lesson>();
private JButton addButton,showButton,saveButton,loadButton,removeButton,choosemesterButton;
private JTextArea showArea;
public String removal,givesemester;
int temp=0;
//Προσθέτουμε το μάθημα
void addLesson()
{
mlessons.add(new Lesson());
}
//Δημιουργία εμφάνισης μαθήματος
void showLessons()
{
String text="";
for(Lesson x :mlessons)
{
text+=x+"\n";
}
showArea.setText(text);
}
//Αποθυκέυοντας τα μαθήματα
void saveLessons()
{
JFileChooser chooser=new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try {
String filename=chooser.getSelectedFile().getAbsolutePath();
FileWriter fw=null;
fw = new FileWriter(filename);
PrintWriter pw=new PrintWriter(fw);
for(Lesson x:mlessons)
{
pw.println(""+x);
}
fw.close();
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Φορτώνοντας τα μαθήματα
void loadLessons()
{
JFileChooser chooser=new JFileChooser();
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try {
String filename=chooser.getSelectedFile().getAbsolutePath();
FileReader rw=new FileReader(filename);
Scanner in=new Scanner(rw);
mlessons=new ArrayList<Lesson>();
while(in.hasNextLine())
{
String line=in.nextLine();
String[] parts=line.split(",");
mlessons.add(new Lesson(parts[0],parts[1],parts[2]));
}
} catch (IOException ex)
{
}
}
}
//Επιλογή Εξαμήνου και εύρεση εξαμήνου
Lesson findSemester() {
givesemester = JOptionPane.showInputDialog("Παρακαλώ δώστε κωδικό εξαμήνου");
for(Lesson x: mlessons) {
if(x.getsemester().equals(givesemester)) {
showup.add(x);
}
}
return null;
}
//Διαγράφοντας ένα μάθημα
void removeLesson(){
removal = JOptionPane.showInputDialog("Παρακαλώ δώστε κωδικό μαθήματος");
//οσο ο μαθητής υπάρχει
boolean found =true;
while(found)
{
found=false;
for(int i=0;i<mlessons.size();i++)
{
if(temp==0){
if(mlessons.get(i).getkwdikos().equals(removal))
{
mlessons.remove(i);
found=true;
temp=1;
break;
}
}
}
}
//Συνθήκη βρέθηκε τελεστής temp=1 αληθές , 0=ψευδές
if(temp==0){
JOptionPane.showMessageDialog(null,"Ο κωδικός μαθήματος δεν βρέθηκε!");
}
else if(temp==1){
JOptionPane.showMessageDialog(null,"Βρέθηκε ο κωδικός μαθήματος, παρακαλώ πατήστε 'Εμφάνιση' ");
temp=0;
}
}
//Φτιάχνοντας τα κουμπιά
void makeButtons()
{
//ΚΟΥΜΠΙ ΝΕΟ ΜΑΘΗΜΑ
JPanel buttonPanel=new JPanel();
buttonPanel.setLayout(new GridLayout(1,2));
addButton=new JButton("Νέο Μάθημα");
addButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
addLesson();
}
});
buttonPanel.add(addButton);
showButton=new JButton("Εμφάνιση");
buttonPanel.add(showButton);
showButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
showLessons();
}
});
//ΚΟΥΜΠΙ ΑΠΟΘΥΚΕΥΣΗ
saveButton=new JButton("Αποθύκευση");
buttonPanel.add(saveButton);
saveButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
saveLessons();
}
});
//ΚΟΥΜΠΙ ΦΟΡΤΩΣΗΣ
loadButton=new JButton("Φόρτωση");
buttonPanel.add(loadButton);
loadButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
loadLessons();
}
});
//ΚΟΥΜΠΙ ΔΙΑΓΡΑΦΗ ΜΑΘΗΜΑΤΟΣ
removeButton = new JButton("Διαγραφή Μαθήματος");
buttonPanel.add(removeButton);
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
removeLesson();
}
});
//ΚΟΥΜΠΙ ΕΠΙΛΟΓΗΣ ΕΞΑΜΗΝΟΥ
choosemesterButton = new JButton("Επιλογή Εξάμηνου");
buttonPanel.add(choosemesterButton);
choosemesterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
findSemester();
JOptionPane.showMessageDialog(null,"Βρέθηκαν μαθήματα:"+showup);
showup.clear();
}
});
add(buttonPanel);
}
//Δημιουργόντας το LessonFrame
public LessonFrame(String title)
{
super(title);
setSize(850,300);
setLayout(new GridLayout(3,1));
setResizable(true);
makeButtons();
showArea=new JTextArea("");
showArea.setRows(5);
showArea.setColumns(25);
showArea.setEditable(false);
JScrollPane sp=new JScrollPane(showArea);
add(sp);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
| AlexandrosPanag/My_Java_Projects | Lesson Enrollment Project/LessonFrame.java | 1,942 | //Διαγράφοντας ένα μάθημα
| line_comment | el | package javaproject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LessonFrame extends JFrame
{
//Μέρος δηλώσεων
private ArrayList<Lesson> mlessons=new ArrayList<Lesson>();
private ArrayList<Lesson> showup=new ArrayList<Lesson>();
private JButton addButton,showButton,saveButton,loadButton,removeButton,choosemesterButton;
private JTextArea showArea;
public String removal,givesemester;
int temp=0;
//Προσθέτουμε το μάθημα
void addLesson()
{
mlessons.add(new Lesson());
}
//Δημιουργία εμφάνισης μαθήματος
void showLessons()
{
String text="";
for(Lesson x :mlessons)
{
text+=x+"\n";
}
showArea.setText(text);
}
//Αποθυκέυοντας τα μαθήματα
void saveLessons()
{
JFileChooser chooser=new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try {
String filename=chooser.getSelectedFile().getAbsolutePath();
FileWriter fw=null;
fw = new FileWriter(filename);
PrintWriter pw=new PrintWriter(fw);
for(Lesson x:mlessons)
{
pw.println(""+x);
}
fw.close();
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Φορτώνοντας τα μαθήματα
void loadLessons()
{
JFileChooser chooser=new JFileChooser();
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try {
String filename=chooser.getSelectedFile().getAbsolutePath();
FileReader rw=new FileReader(filename);
Scanner in=new Scanner(rw);
mlessons=new ArrayList<Lesson>();
while(in.hasNextLine())
{
String line=in.nextLine();
String[] parts=line.split(",");
mlessons.add(new Lesson(parts[0],parts[1],parts[2]));
}
} catch (IOException ex)
{
}
}
}
//Επιλογή Εξαμήνου και εύρεση εξαμήνου
Lesson findSemester() {
givesemester = JOptionPane.showInputDialog("Παρακαλώ δώστε κωδικό εξαμήνου");
for(Lesson x: mlessons) {
if(x.getsemester().equals(givesemester)) {
showup.add(x);
}
}
return null;
}
//Διαγ<SUF>
void removeLesson(){
removal = JOptionPane.showInputDialog("Παρακαλώ δώστε κωδικό μαθήματος");
//οσο ο μαθητής υπάρχει
boolean found =true;
while(found)
{
found=false;
for(int i=0;i<mlessons.size();i++)
{
if(temp==0){
if(mlessons.get(i).getkwdikos().equals(removal))
{
mlessons.remove(i);
found=true;
temp=1;
break;
}
}
}
}
//Συνθήκη βρέθηκε τελεστής temp=1 αληθές , 0=ψευδές
if(temp==0){
JOptionPane.showMessageDialog(null,"Ο κωδικός μαθήματος δεν βρέθηκε!");
}
else if(temp==1){
JOptionPane.showMessageDialog(null,"Βρέθηκε ο κωδικός μαθήματος, παρακαλώ πατήστε 'Εμφάνιση' ");
temp=0;
}
}
//Φτιάχνοντας τα κουμπιά
void makeButtons()
{
//ΚΟΥΜΠΙ ΝΕΟ ΜΑΘΗΜΑ
JPanel buttonPanel=new JPanel();
buttonPanel.setLayout(new GridLayout(1,2));
addButton=new JButton("Νέο Μάθημα");
addButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
addLesson();
}
});
buttonPanel.add(addButton);
showButton=new JButton("Εμφάνιση");
buttonPanel.add(showButton);
showButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
showLessons();
}
});
//ΚΟΥΜΠΙ ΑΠΟΘΥΚΕΥΣΗ
saveButton=new JButton("Αποθύκευση");
buttonPanel.add(saveButton);
saveButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
saveLessons();
}
});
//ΚΟΥΜΠΙ ΦΟΡΤΩΣΗΣ
loadButton=new JButton("Φόρτωση");
buttonPanel.add(loadButton);
loadButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
loadLessons();
}
});
//ΚΟΥΜΠΙ ΔΙΑΓΡΑΦΗ ΜΑΘΗΜΑΤΟΣ
removeButton = new JButton("Διαγραφή Μαθήματος");
buttonPanel.add(removeButton);
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
removeLesson();
}
});
//ΚΟΥΜΠΙ ΕΠΙΛΟΓΗΣ ΕΞΑΜΗΝΟΥ
choosemesterButton = new JButton("Επιλογή Εξάμηνου");
buttonPanel.add(choosemesterButton);
choosemesterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
findSemester();
JOptionPane.showMessageDialog(null,"Βρέθηκαν μαθήματα:"+showup);
showup.clear();
}
});
add(buttonPanel);
}
//Δημιουργόντας το LessonFrame
public LessonFrame(String title)
{
super(title);
setSize(850,300);
setLayout(new GridLayout(3,1));
setResizable(true);
makeButtons();
showArea=new JTextArea("");
showArea.setRows(5);
showArea.setColumns(25);
showArea.setEditable(false);
JScrollPane sp=new JScrollPane(showArea);
add(sp);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
|
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4