file_id stringlengths 3 9 | content stringlengths 207 36.5k | repo stringlengths 9 109 | path stringlengths 8 157 | token_length int64 91 8.11k | original_comment stringlengths 7 3.46k | comment_type stringclasses 2 values | detected_lang stringclasses 1 value | prompt stringlengths 137 36.4k |
|---|---|---|---|---|---|---|---|---|
5474_4 | package com.unipi.vnikolis.unipismartalert;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection;
import com.unipi.vnikolis.unipismartalert.model.Values;
import java.util.Objects;
/**
* The backend code for Maps Activity
*/
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FirebaseDatabase firebaseDatabase;
DatabaseReference dropDanger, possiblyDanger;
MainActivity mainActivity = new MainActivity();
Thread t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
firebaseDatabase = FirebaseDatabase.getInstance();
possiblyDanger = firebaseDatabase.getReference("PossiblyDanger");
dropDanger = possiblyDanger.child("DropDanger");
}
/**
* Κλείνοντας την εφαρμογή εαν υπάρχει νήμα να σταματήσει την λειτουργία του
*/
@Override
protected void onDestroy() {
super.onDestroy();
if(t != null) {
t.interrupt();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(MainActivity.isMapsButtonPressed) { //εαν πατηθεί το κουμπί "Maps"
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
t = new Thread(new Runnable() {
@Override
public void run() {
putTheMarkers(dropDanger);
}
});
t.start();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}else if(ShowStatistics.isItemsButtonClicked){
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
putTheMarkersFromList();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
}
/**
* Τοποθετεί όλα τα σημάδια της
* κατηγορίας BigDanger επάνω στον χάρτη
*/
public void putTheMarkers(DatabaseReference reference){
reference.addValueEventListener(new ValueEventListener() {
Values v;
LatLng coordinates;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα
{
for (DataSnapshot i : dataSnapshot.getChildren()) {
v = i.getValue(Values.class);
assert v != null;
coordinates = new LatLng(Double.parseDouble(v.getLatitude()), Double.parseDouble(v.getLongitude()));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates));
markerOptions.position(coordinates);
markerOptions.snippet(v.CorrectDate());
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 10)));
}
}
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
/**
* Παίρνει κάθε γραμμή της ViewList και εμφανίζει
* το σημάδι επάνω στον χάρτη
*/
public void putTheMarkersFromList(){
try {
String latitude = Objects.requireNonNull(getIntent().getExtras()).getString("latitude");
String longitude = getIntent().getExtras().getString("longitude");
String date = getIntent().getExtras().getString("date");
double latitudeToDouble = Double.parseDouble(latitude);
double longitudeToDouble = Double.parseDouble(longitude);
LatLng coordinates = new LatLng(latitudeToDouble, longitudeToDouble);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates ));
markerOptions.position(coordinates);
markerOptions.snippet(date);
mMap.addMarker(markerOptions);
//εστίαση στο συγκεκριμένο σημείο του χάρτη
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 15)));
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
}
| 3ngk1sha/DangerDetect | app/src/main/java/com/unipi/vnikolis/unipismartalert/MapsActivity.java | 1,814 | //εαν πατηθεί το κουμπί "Maps" | line_comment | el | package com.unipi.vnikolis.unipismartalert;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection;
import com.unipi.vnikolis.unipismartalert.model.Values;
import java.util.Objects;
/**
* The backend code for Maps Activity
*/
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FirebaseDatabase firebaseDatabase;
DatabaseReference dropDanger, possiblyDanger;
MainActivity mainActivity = new MainActivity();
Thread t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
firebaseDatabase = FirebaseDatabase.getInstance();
possiblyDanger = firebaseDatabase.getReference("PossiblyDanger");
dropDanger = possiblyDanger.child("DropDanger");
}
/**
* Κλείνοντας την εφαρμογή εαν υπάρχει νήμα να σταματήσει την λειτουργία του
*/
@Override
protected void onDestroy() {
super.onDestroy();
if(t != null) {
t.interrupt();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(MainActivity.isMapsButtonPressed) { //εα<SUF>
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
t = new Thread(new Runnable() {
@Override
public void run() {
putTheMarkers(dropDanger);
}
});
t.start();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}else if(ShowStatistics.isItemsButtonClicked){
if (CheckInternetConnection.isConnected(MapsActivity.this) && CheckInternetConnection.isConnectedFast(MapsActivity.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet
putTheMarkersFromList();
}else{
Toast.makeText(MapsActivity.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show();
}
}
}
/**
* Τοποθετεί όλα τα σημάδια της
* κατηγορίας BigDanger επάνω στον χάρτη
*/
public void putTheMarkers(DatabaseReference reference){
reference.addValueEventListener(new ValueEventListener() {
Values v;
LatLng coordinates;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα
{
for (DataSnapshot i : dataSnapshot.getChildren()) {
v = i.getValue(Values.class);
assert v != null;
coordinates = new LatLng(Double.parseDouble(v.getLatitude()), Double.parseDouble(v.getLongitude()));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates));
markerOptions.position(coordinates);
markerOptions.snippet(v.CorrectDate());
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 10)));
}
}
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
/**
* Παίρνει κάθε γραμμή της ViewList και εμφανίζει
* το σημάδι επάνω στον χάρτη
*/
public void putTheMarkersFromList(){
try {
String latitude = Objects.requireNonNull(getIntent().getExtras()).getString("latitude");
String longitude = getIntent().getExtras().getString("longitude");
String date = getIntent().getExtras().getString("date");
double latitudeToDouble = Double.parseDouble(latitude);
double longitudeToDouble = Double.parseDouble(longitude);
LatLng coordinates = new LatLng(latitudeToDouble, longitudeToDouble);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
markerOptions.title(mainActivity.findAddress(MapsActivity.this, coordinates ));
markerOptions.position(coordinates);
markerOptions.snippet(date);
mMap.addMarker(markerOptions);
//εστίαση στο συγκεκριμένο σημείο του χάρτη
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 2));
mMap.animateCamera((CameraUpdateFactory.newLatLngZoom(coordinates, 15)));
}catch (Exception e){
e.printStackTrace();
Log.e("SOS", "Something went wrong");
}
}
}
|
5457_0 | package info.android_angel.navigationdrawer.model_movie_get_latest;
/**
* Created by ANGELOS on 2017.
*
* Δεν έχει κάτι το object. Το αφήνω κενό.
*
*/
public class MovieGetLatest_spoken_languages {
}
| ANGELOS-TSILAFAKIS/NavigationDrawerPublic | app/src/main/java/info/android_angel/navigationdrawer/model_movie_get_latest/MovieGetLatest_spoken_languages.java | 91 | /**
* Created by ANGELOS on 2017.
*
* Δεν έχει κάτι το object. Το αφήνω κενό.
*
*/ | block_comment | el | package info.android_angel.navigationdrawer.model_movie_get_latest;
/**
* Cre<SUF>*/
public class MovieGetLatest_spoken_languages {
}
|
17272_21 | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"});
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"});
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} | Abbe98/corelib | corelib-schemaorg/src/test/java/eu/europeana/corelib/edm/utils/MockFullBean.java | 6,557 | //el.dbpedia.org/resource/Γεωργία_(δραστηριότητα)"}); | line_comment | el | package eu.europeana.corelib.edm.utils;
import eu.europeana.corelib.definitions.edm.model.metainfo.ImageOrientation;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.edm.model.metainfo.ImageMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.VideoMetaInfoImpl;
import eu.europeana.corelib.edm.model.metainfo.WebResourceMetaInfoImpl;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.entity.WebResourceImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Given our current FullBean implementation it's not easy to deserialize a FullBean from json string, so for now we
* create a test fullbean by hand.
*
* @author Patrick Ehlert
* <p>
* Created on 10-09-2018
*/
public final class MockFullBean {
private MockFullBean() {
// empty constructor to prevent initialization
}
public static FullBeanImpl mock() {
FullBeanImpl bean = new FullBeanImpl();
bean.setAbout(MockBeanConstants.ABOUT);
bean.setTitle(new String[]{MockBeanConstants.DC_TITLE});
bean.setLanguage(new String[]{MockBeanConstants.LANGUAUGE_NL});
bean.setTimestampCreated(new Date(MockBeanConstants.TIMESTAMP_CREATED));
bean.setTimestampUpdated(new Date(MockBeanConstants.TIMESTAMP_UPDATED));
bean.setEuropeanaCollectionName(new String[]{MockBeanConstants.EUROPEANA_COLLECTION});
setProvidedCHO(bean);
setAgents(bean);
setAggregations(bean);
setEuropeanaAggregation(bean);
setProxies(bean);
setPlaces(bean);
setConcepts(bean);
setTimespans(bean);
return bean;
}
private static void setProxies(FullBeanImpl bean) {
List<ProxyImpl> proxies = new ArrayList<>();
ProxyImpl proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.AGGREGATION_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_1);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_2);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_3);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_4);
proxy.setDcDate(new HashMap<>());
proxy.getDcDate().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDate().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DATE);
proxy.setDcFormat(new HashMap<>());
proxy.getDcFormat().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: hoogte: 675 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("papier: breedte: 522 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: hoogte: 565 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("plaat: breedte: 435 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: hoogte: 376 mm");
proxy.getDcFormat().get(MockBeanConstants.DEF).add("beeld: breedte: 275 mm");
proxy.setDcIdentifier(new HashMap<>());
proxy.getDcIdentifier().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcIdentifier().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_IDENTIFIER);
proxy.setDcTitle(new HashMap<>());
proxy.getDcTitle().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcTitle().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TITLE);
proxy.setDcType(new HashMap<>());
proxy.getDcType().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_1);
proxy.getDcType().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TYPE_2);
proxy.setDctermsAlternative(new HashMap<>());
proxy.getDctermsAlternative().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsAlternative().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_ALTERNATIVE);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_1);
proxy = new ProxyImpl();
proxies.add(proxy);
proxy.setEdmType(DocType.IMAGE.getEnumNameValue());
proxy.setProxyIn(new String[]{MockBeanConstants.EUROPEANA_AGG_ABOUT});
proxy.setProxyFor(MockBeanConstants.ABOUT);
proxy.setDcCreator(new HashMap<>());
proxy.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_5);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_6);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_7);
proxy.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_8);
proxy.setDctermsTemporal(new HashMap<>());
proxy.getDctermsTemporal().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_1);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_2);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_3);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4);
proxy.getDctermsTemporal().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_TEMPORAL_4); //duplicate
proxy.setDctermsCreated(new HashMap<>());
proxy.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDctermsCreated().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_TERMS_CREATED);
proxy.setDcCoverage(new HashMap<>());
proxy.getDcCoverage().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_TEMPORAL);
proxy.getDcCoverage().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_COVERAGE_ABOUT); //allow invalid is false for dcCoverage and this should not get added in temporal coverage, But then it will get added in about
//to test https mapping
proxy.setDcDescription(new HashMap<>());
proxy.getDcDescription().put(MockBeanConstants.DEF, new ArrayList<>());
proxy.getDcDescription().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_DESCRIPTION);
proxy.setAbout(MockBeanConstants.PROXY_ABOUT_2);
bean.setProxies(proxies);
}
private static void setEuropeanaAggregation(FullBeanImpl bean) {
EuropeanaAggregationImpl europeanaAggregation = new EuropeanaAggregationImpl();
europeanaAggregation.setAbout(MockBeanConstants.EUROPEANA_AGG_ABOUT);
europeanaAggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
europeanaAggregation.setDcCreator(new HashMap<>());
europeanaAggregation.getDcCreator().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getDcCreator().get(MockBeanConstants.DEF).add(MockBeanConstants.DC_CREATOR_9);
europeanaAggregation.setEdmCountry(new HashMap<>());
europeanaAggregation.getEdmCountry().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmCountry().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_COUNTRY);
europeanaAggregation.setEdmLanguage(new HashMap<>());
europeanaAggregation.getEdmLanguage().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.LANGUAUGE_NL);
europeanaAggregation.setEdmRights(new HashMap<>());
europeanaAggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
europeanaAggregation.getEdmLanguage().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
europeanaAggregation.setEdmPreview(MockBeanConstants.EDM_PREVIEW);
bean.setEuropeanaAggregation(europeanaAggregation);
}
private static void setAggregations(FullBeanImpl bean) {
List<AggregationImpl> aggregations = new ArrayList<>();
AggregationImpl aggregation = new AggregationImpl();
aggregation.setEdmDataProvider(new HashMap<>());
aggregation.getEdmDataProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmDataProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_1);
//should be present in associated media as Image object
aggregation.setEdmIsShownBy(MockBeanConstants.EDM_IS_SHOWN_BY);
//should be present in associatedMedia as Video object
String[] hasViews = {MockBeanConstants.EDM_IS_SHOWN_AT};
aggregation.setHasView(hasViews);
aggregation.setEdmIsShownAt(MockBeanConstants.EDM_IS_SHOWN_AT);
aggregation.setEdmObject(MockBeanConstants.EDM_IS_SHOWN_BY);
aggregation.setEdmProvider(new HashMap<>());
aggregation.getEdmProvider().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmProvider().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_PROVIDER_2);
aggregation.setEdmRights(new HashMap<>());
aggregation.getEdmRights().put(MockBeanConstants.DEF, new ArrayList<>());
aggregation.getEdmRights().get(MockBeanConstants.DEF).add(MockBeanConstants.EDM_RIGHTS);
aggregation.setAggregatedCHO(MockBeanConstants.ABOUT);
aggregation.setAbout(MockBeanConstants.AGGREGATION_ABOUT);
List<WebResourceImpl> webResources = new ArrayList<>();
WebResourceImpl webResource = new WebResourceImpl();
webResources.add(webResource);
webResource.setDctermsCreated(new HashMap<>());
webResource.getDctermsCreated().put(MockBeanConstants.DEF, new ArrayList<>());
webResource.getDctermsCreated().get(MockBeanConstants.DEF).add("1936-05-11");
//should be present in videoObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_AT);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setBitRate(400);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setDuration(2000L);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setHeight(500);
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setWidth(650);
webResource = new WebResourceImpl();
webResources.add(webResource);
//this weresource will not be added in the schema.org as there is no associatedMedia present for value "testing"
webResource.setAbout("testing");
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setVideoMetaInfo(new VideoMetaInfoImpl());
((VideoMetaInfoImpl) webResource.getWebResourceMetaInfo().getVideoMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_VIDEO);
webResource = new WebResourceImpl();
webResources.add(webResource);
//should be present in ImageObject
webResource.setAbout(MockBeanConstants.EDM_IS_SHOWN_BY);
webResource.setWebResourceMetaInfo(new WebResourceMetaInfoImpl());
((WebResourceMetaInfoImpl) webResource.getWebResourceMetaInfo()).setImageMetaInfo(new ImageMetaInfoImpl());
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setWidth(598);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setHeight(768);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setMimeType(MockBeanConstants.MIME_TYPE_IMAGE);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileFormat("JPEG");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorSpace("sRGB");
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setFileSize(61347L);
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setColorPalette(new String[]{"#DCDCDC", "#2F4F4F", "#FAEBD7", "#FAF0E6", "#F5F5DC", "#696969"});
((ImageMetaInfoImpl) webResource.getWebResourceMetaInfo().getImageMetaInfo()).setOrientation(ImageOrientation.PORTRAIT);
aggregation.setWebResources(webResources);
aggregations.add(aggregation);
bean.setAggregations(aggregations);
}
private static void setAgents(FullBeanImpl bean) {
List<AgentImpl> agents = new ArrayList<>();
AgentImpl agent = new AgentImpl();
agents.add(agent);
// first agent Person
agent.setEnd(new HashMap<>());
agent.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getEnd().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setOwlSameAs(new String[]{"http://purl.org/collections/nl/am/p-10456",
"http://rdf.freebase.com/ns/m.011bn9nx",
"http://sv.dbpedia.org/resource/Leonardo_da_Vincis_uppfinningar",
"http://pl.dbpedia.org/resource/Wynalazki_i_konstrukcje_Leonarda_da_Vinci"});
agent.setRdaGr2DateOfBirth(new HashMap<>());
agent.getRdaGr2DateOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_DATE);
agent.setRdaGr2DateOfDeath(new HashMap<>());
agent.getRdaGr2DateOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_DATE);
agent.setRdaGr2PlaceOfBirth(new HashMap<>());
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_1);
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.DEF).add(MockBeanConstants.BIRTH_PLACE_2);
agent.getRdaGr2PlaceOfBirth().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2PlaceOfBirth().get(MockBeanConstants.EN).add(MockBeanConstants.BIRTH_PLACE_3);
agent.setRdaGr2PlaceOfDeath(new HashMap<>());
agent.getRdaGr2PlaceOfDeath().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_1);
agent.getRdaGr2PlaceOfDeath().get(MockBeanConstants.DEF).add(MockBeanConstants.DEATH_PLACE_2);
agent.setRdaGr2BiographicalInformation(new HashMap<>());
agent.getRdaGr2BiographicalInformation().put(MockBeanConstants.EN, new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get(MockBeanConstants.EN).add("Leonardo da Vinci (1452–1519) was an Italian polymath, regarded as the epitome of the \"Renaissance Man\", displaying skills in numerous diverse areas of study. Whilst most famous for his paintings such as the Mona Lisa and the Last Supper, Leonardo is also renowned in the fields of civil engineering, chemistry, geology, geometry, hydrodynamics, mathematics, mechanical engineering, optics, physics, pyrotechnics, and zoology.While the full extent of his scientific studies has only become recognized in the last 150 years, he was, during his lifetime, employed for his engineering and skill of invention. Many of his designs, such as the movable dikes to protect Venice from invasion, proved too costly or impractical. Some of his smaller inventions entered the world of manufacturing unheralded. As an engineer, Leonardo conceived ideas vastly ahead of his own time, conceptually inventing a helicopter, a tank, the use of concentrated solar power, a calculator, a rudimentary theory of plate tectonics and the double hull. In practice, he greatly advanced the state of knowledge in the fields of anatomy, astronomy, civil engineering, optics, and the study of water (hydrodynamics).Leonardo's most famous drawing, the Vitruvian Man, is a study of the proportions of the human body, linking art and science in a single work that has come to represent Renaissance Humanism.");
agent.getRdaGr2BiographicalInformation().put("pl", new ArrayList<>());
agent.getRdaGr2BiographicalInformation().get("pl").add("Leonardo da Vinci na prawie sześciu tysiącach stron notatek wykonał znacznie więcej projektów technicznych niż prac artystycznych, co wskazuje na to, że inżynieria była niezmiernie ważną dziedziną jego zainteresowań.Giorgio Vasari w Żywotach najsławniejszych malarzy, rzeźbiarzy i architektów pisał o Leonardzie:");
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("Science and inventions of Leonardo da Vinci");
agent.getPrefLabel().put(MockBeanConstants.PL, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.PL).add("Wynalazki i konstrukcje Leonarda da Vinci");
agent.setAltLabel(new HashMap<>());
agent.getAltLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getAltLabel().get(MockBeanConstants.EN).add("Leonardo da Vinci");
agent.setAbout(MockBeanConstants.DC_CREATOR_6);
//adding second agent Orgainsation
agent = new AgentImpl();
agents.add(agent);
agent.setPrefLabel(new HashMap<>());
agent.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.EN).add("European museums");
agent.getPrefLabel().put(MockBeanConstants.FR, new ArrayList<>());
agent.getPrefLabel().get(MockBeanConstants.FR).add("Musées européens");
agent.setRdaGr2DateOfTermination(new HashMap<>());
agent.getRdaGr2DateOfTermination().put(MockBeanConstants.DEF, new ArrayList<>());
agent.getRdaGr2DateOfTermination().get(MockBeanConstants.DEF).add(MockBeanConstants.DISOLUTION_DATE);
agent.setAbout(MockBeanConstants.DC_CREATOR_8);
bean.setAgents(agents);
}
private static void setProvidedCHO(FullBeanImpl bean) {
List<ProvidedCHOImpl> providedCHOs = new ArrayList<>();
ProvidedCHOImpl providedCHO = new ProvidedCHOImpl();
providedCHO.setAbout(MockBeanConstants.ABOUT);
providedCHOs.add(providedCHO);
bean.setProvidedCHOs(providedCHOs);
}
public static void setTimespans(FullBeanImpl bean) {
List<TimespanImpl> timespans = new ArrayList<>();
TimespanImpl timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("Tue Jan 01 00:19:32 CET 1901");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("Sun Dec 31 01:00:00 CET 2000");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_1);
timespan = new TimespanImpl();
timespans.add(timespan);
timespan.setBegin(new HashMap<>());
timespan.getBegin().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getBegin().get(MockBeanConstants.DEF).add("1901-01-01");
timespan.setEnd(new HashMap<>());
timespan.getEnd().put(MockBeanConstants.DEF, new ArrayList<>());
timespan.getEnd().get(MockBeanConstants.DEF).add("1902-01-01");
timespan.setAbout(MockBeanConstants.DC_TERMS_TEMPORAL_2);
bean.setTimespans(timespans);
}
private static void setConcepts(FullBeanImpl bean) {
List<ConceptImpl> concepts = new ArrayList<>();
ConceptImpl concept = new ConceptImpl();
concepts.add(concept);
concept.setRelated(new String[]{"http://dbpedia.org/resource/Category:Agriculture"});
concept.setExactMatch(new String[]{"http://bg.dbpedia.org/resource/Селско_стопанство",
"http://ia.dbpedia.org/resource/Agricultura",
"http://sl.dbpedia.org/resource/Kmetijstvo",
"http://pnb.dbpedia.org/resource/وائی_بیجی",
"http://el<SUF>
concept.setPrefLabel(new HashMap<>());
concept.getPrefLabel().put("no", new ArrayList<>());
concept.getPrefLabel().get("no").add(MockBeanConstants.CONCEPT_PREF_LABEL_1);
concept.getPrefLabel().put("de", new ArrayList<>());
concept.getPrefLabel().get("de").add(MockBeanConstants.CONCEPT_PREF_LABEL_2);
concept.setNote(new HashMap<>());
concept.getNote().put("no", new ArrayList<>());
concept.getNote().get("no").add(MockBeanConstants.CONCEPT_NOTE_1);
concept.getNote().put("de", new ArrayList<>());
concept.getNote().get("de").add(MockBeanConstants.CONCEPT_NOTE_2);
concept.setAbout(MockBeanConstants.DC_CREATOR_4);
bean.setConcepts(concepts);
}
private static void setPlaces(FullBeanImpl bean) {
List<PlaceImpl> places = new ArrayList<>();
PlaceImpl place = new PlaceImpl();
places.add(place);
place.setIsPartOf(new HashMap<>());
place.getIsPartOf().put(MockBeanConstants.DEF, new ArrayList<>());
place.getIsPartOf().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_IS_PART);
place.setLatitude(46.0F);
place.setAltitude(70.0F);
place.setLongitude(2.0F);
place.setDcTermsHasPart(new HashMap<>());
place.getDcTermsHasPart().put(MockBeanConstants.DEF, new ArrayList<>());
place.getDcTermsHasPart().get(MockBeanConstants.DEF).add(MockBeanConstants.PLACE_HAS_PART);
place.setOwlSameAs(new String[]{MockBeanConstants.PLACE_SAME_OWL_AS});
place.setPrefLabel(new HashMap<>());
place.getPrefLabel().put(MockBeanConstants.EN, new ArrayList<>());
place.getPrefLabel().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setAltLabel(new HashMap<>());
place.getAltLabel().put(MockBeanConstants.IT, new ArrayList<>());
place.getAltLabel().get(MockBeanConstants.IT).add(MockBeanConstants.PLACE_PREF_LABEL);
place.setNote(new HashMap<>());
place.getNote().put(MockBeanConstants.EN, new ArrayList<>());
place.getNote().get(MockBeanConstants.EN).add(MockBeanConstants.PLACE_NOTE);
place.setAbout(MockBeanConstants.DC_CREATOR_7);
bean.setPlaces(places);
}
} |
11039_4 | package gr.rambou.myicarus;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
public class Icarus implements Serializable {
private final String Username, Password;
public Map<String, String> Cookies;
private String StudentFullName, ID, StudentName, Surname;
//private Document Page;
private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons;
public Icarus(String username, String password) {
this.Username = username;
this.Password = password;
this.StudentFullName = null;
this.Cookies = null;
}
public boolean login() {
try {
//ενεργοποιούμε το SSL
enableSSLSocket();
//Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε
Connection.Response res = Jsoup
.connect("https://icarus-icsd.aegean.gr/authentication.php")
.timeout(10 * 1000)
.data("username", Username, "pwd", Password)
.method(Connection.Method.POST)
.execute();
//Παίρνουμε τα cookies
Cookies = res.cookies();
//Αποθηκεύουμε το περιεχόμενο της σελίδας
Document Page = res.parse();
//Ελέγχουμε αν συνδεθήκαμε
Elements name = Page.select("div#header_login").select("u");
if (name.hasText()) {
//Παίρνουμε το ονοματεπώνυμο του φοιτητή
StudentFullName = name.html();
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
Pattern r = Pattern.compile("[0-9-/-]{5,16}");
String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim();
Matcher m = r.matcher(line);
if (m.find()) {
ID = m.group(0);
}
//Παίρνουμε τους βαθμούς του φοιτητή
LoadMarks(Page);
return true;
}
} catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) {
Log.v("Icarus Class", ex.toString());
}
return false;
}
public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) {
if (papers.length != 11) {
return false;
}
String sendmethod;
if (sendtype.equals(SendType.FAX)) {
sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:";
} else if (sendtype.equals(SendType.COURIER)) {
sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:";
} else {
sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης";
}
//We create the Data to be Send
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addTextBody("aitisi_student_id", getID());
mpEntity.addTextBody("aitisi_surname", getSurname());
mpEntity.addTextBody("aitisi_name", getStudentName());
mpEntity.addTextBody("aitisi_father", fatherName);
mpEntity.addTextBody("aitisi_semester", cemester.toString());
mpEntity.addTextBody("aitisi_address", address);
mpEntity.addTextBody("aitisi_phone", phone);
mpEntity.addTextBody("aitisi_send_method", sendmethod);
mpEntity.addTextBody("aitisi_send_address", send_address);
mpEntity.addTextBody("prints_no[]", papers[0]);
mpEntity.addTextBody("prints_no[]", papers[1]);
mpEntity.addTextBody("prints_no[]", papers[2]);
mpEntity.addTextBody("prints_no[]", papers[3]);
mpEntity.addTextBody("prints_no[]", papers[4]);
mpEntity.addTextBody("prints_no[]", papers[5]);
mpEntity.addTextBody("prints_no[]", papers[6]);
mpEntity.addTextBody("prints_no[]", papers[7]);
mpEntity.addTextBody("prints_no[]", papers[8]);
mpEntity.addTextBody("prints_no[]", papers[9]);
mpEntity.addTextBody("aitisi_allo", papers[10]);
mpEntity.addTextBody("send", "");
HttpEntity entity = mpEntity.build();
//We send the request
HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php");
post.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
//Gets new/old cookies and set them in store and store to CTX
CookieStore Store = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID"));
cookie.setPath("//");
cookie.setDomain("icarus-icsd.aegean.gr");
Store.addCookie(cookie);
HttpContext CTX = new BasicHttpContext();
CTX.setAttribute(ClientContext.COOKIE_STORE, Store);
HttpResponse response = null;
try {
response = client.execute(post, CTX);
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
}
//Check if user credentials are ok
if (response == null) {
return false;
}
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 200) {
return false;
}
try {
String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7");
Document res = Jsoup.parse(html);
if (res.getElementsByClass("success").isEmpty()) {
return false;
}
} catch (IOException | org.apache.http.ParseException ex) {
return false;
}
return true;
}
public void LoadMarks(Document response) {
All_Lessons = new ArrayList<>();
Succeed_Lessons = new ArrayList<>();
Exams_Lessons = new ArrayList<>();
if (response == null) {
try {
//We send the request
response = Jsoup
.connect("https://icarus-icsd.aegean.gr/student_main.php")
.cookies(Cookies)
.get();
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
return;
}
}
//Start Catching Lessons
Elements sGrades = response.getElementById("succeeded_grades").select("tr");
Elements aGrades = response.getElementById("analytic_grades").select("tr");
Elements eGrades = response.getElementById("exetastiki_grades").select("tr");
for (Element a : sGrades) {
if (!a.select("td").isEmpty()) {
Succeed_Lessons.add(getLesson(a));
}
}
for (Element a : eGrades) {
if (!a.select("td").isEmpty()) {
Exams_Lessons.add(getLesson(a));
if (a.select("td").get(6).text().trim().compareTo("") != 0)
All_Lessons.add(getLesson(a));
}
}
for (Element a : aGrades) {
if (!a.select("td").isEmpty()) {
All_Lessons.add(getLesson(a));
}
}
}
private Lesson getLesson(Element a) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String ID = a.select("td").get(1).text();
String Title = a.select("td").get(2).text();
Double Mark = 0.0;
try {
Mark = Double.valueOf(a.select("td").get(3).text());
} catch (Exception ex) {
}
String Cemester = a.select("td").get(4).text();
Date Statement = null, Exam = null;
try {
Statement = formatter.parse(a.select("td").get(5).text().trim());
Exam = formatter.parse(a.select("td").get(6).text().trim());
} catch (ParseException ex) {
}
Lesson.LessonStatus Status;
switch (a.select("td").get(7).text().trim()) {
case "Επιτυχία":
Status = Lesson.LessonStatus.PASSED;
break;
case "Αποτυχία":
Status = Lesson.LessonStatus.FAILED;
break;
case "Ακύρωση":
Status = Lesson.LessonStatus.CANCELLED;
break;
default:
Status = Lesson.LessonStatus.NOT_GIVEN;
break;
}
return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status);
}
public ArrayList<Lesson> getSucceed_Lessons() {
return Succeed_Lessons;
}
public ArrayList<Lesson> getAll_Lessons() {
return All_Lessons;
}
public Object[] getAll_Lessons_array() {
return All_Lessons.toArray();
}
public ArrayList<Lesson> getExams_Lessons() {
return Exams_Lessons;
}
public String getStudentFullName() {
return StudentFullName;
}
public String getID() {
return ID;
}
public String getStudentName() {
return StudentFullName.split(" ")[0];
}
public String getSurname() {
return StudentFullName.split(" ")[1];
}
private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
//HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true);
SSLContext context;
context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
public enum SendType {
OFFICE, COURIER, FAX
}
public enum PaperType {
bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo,
stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma,
allo
}
}
| AegeanHawks/MobileIcarus | app/src/main/java/gr/rambou/myicarus/Icarus.java | 3,246 | //Παίρνουμε τα cookies | line_comment | el | package gr.rambou.myicarus;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
public class Icarus implements Serializable {
private final String Username, Password;
public Map<String, String> Cookies;
private String StudentFullName, ID, StudentName, Surname;
//private Document Page;
private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons;
public Icarus(String username, String password) {
this.Username = username;
this.Password = password;
this.StudentFullName = null;
this.Cookies = null;
}
public boolean login() {
try {
//ενεργοποιούμε το SSL
enableSSLSocket();
//Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε
Connection.Response res = Jsoup
.connect("https://icarus-icsd.aegean.gr/authentication.php")
.timeout(10 * 1000)
.data("username", Username, "pwd", Password)
.method(Connection.Method.POST)
.execute();
//Πα<SUF>
Cookies = res.cookies();
//Αποθηκεύουμε το περιεχόμενο της σελίδας
Document Page = res.parse();
//Ελέγχουμε αν συνδεθήκαμε
Elements name = Page.select("div#header_login").select("u");
if (name.hasText()) {
//Παίρνουμε το ονοματεπώνυμο του φοιτητή
StudentFullName = name.html();
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
Pattern r = Pattern.compile("[0-9-/-]{5,16}");
String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim();
Matcher m = r.matcher(line);
if (m.find()) {
ID = m.group(0);
}
//Παίρνουμε τους βαθμούς του φοιτητή
LoadMarks(Page);
return true;
}
} catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) {
Log.v("Icarus Class", ex.toString());
}
return false;
}
public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) {
if (papers.length != 11) {
return false;
}
String sendmethod;
if (sendtype.equals(SendType.FAX)) {
sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:";
} else if (sendtype.equals(SendType.COURIER)) {
sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:";
} else {
sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης";
}
//We create the Data to be Send
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addTextBody("aitisi_student_id", getID());
mpEntity.addTextBody("aitisi_surname", getSurname());
mpEntity.addTextBody("aitisi_name", getStudentName());
mpEntity.addTextBody("aitisi_father", fatherName);
mpEntity.addTextBody("aitisi_semester", cemester.toString());
mpEntity.addTextBody("aitisi_address", address);
mpEntity.addTextBody("aitisi_phone", phone);
mpEntity.addTextBody("aitisi_send_method", sendmethod);
mpEntity.addTextBody("aitisi_send_address", send_address);
mpEntity.addTextBody("prints_no[]", papers[0]);
mpEntity.addTextBody("prints_no[]", papers[1]);
mpEntity.addTextBody("prints_no[]", papers[2]);
mpEntity.addTextBody("prints_no[]", papers[3]);
mpEntity.addTextBody("prints_no[]", papers[4]);
mpEntity.addTextBody("prints_no[]", papers[5]);
mpEntity.addTextBody("prints_no[]", papers[6]);
mpEntity.addTextBody("prints_no[]", papers[7]);
mpEntity.addTextBody("prints_no[]", papers[8]);
mpEntity.addTextBody("prints_no[]", papers[9]);
mpEntity.addTextBody("aitisi_allo", papers[10]);
mpEntity.addTextBody("send", "");
HttpEntity entity = mpEntity.build();
//We send the request
HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php");
post.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
//Gets new/old cookies and set them in store and store to CTX
CookieStore Store = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID"));
cookie.setPath("//");
cookie.setDomain("icarus-icsd.aegean.gr");
Store.addCookie(cookie);
HttpContext CTX = new BasicHttpContext();
CTX.setAttribute(ClientContext.COOKIE_STORE, Store);
HttpResponse response = null;
try {
response = client.execute(post, CTX);
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
}
//Check if user credentials are ok
if (response == null) {
return false;
}
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 200) {
return false;
}
try {
String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7");
Document res = Jsoup.parse(html);
if (res.getElementsByClass("success").isEmpty()) {
return false;
}
} catch (IOException | org.apache.http.ParseException ex) {
return false;
}
return true;
}
public void LoadMarks(Document response) {
All_Lessons = new ArrayList<>();
Succeed_Lessons = new ArrayList<>();
Exams_Lessons = new ArrayList<>();
if (response == null) {
try {
//We send the request
response = Jsoup
.connect("https://icarus-icsd.aegean.gr/student_main.php")
.cookies(Cookies)
.get();
} catch (IOException ex) {
Log.v(Icarus.class.getName().toString(), ex.toString());
return;
}
}
//Start Catching Lessons
Elements sGrades = response.getElementById("succeeded_grades").select("tr");
Elements aGrades = response.getElementById("analytic_grades").select("tr");
Elements eGrades = response.getElementById("exetastiki_grades").select("tr");
for (Element a : sGrades) {
if (!a.select("td").isEmpty()) {
Succeed_Lessons.add(getLesson(a));
}
}
for (Element a : eGrades) {
if (!a.select("td").isEmpty()) {
Exams_Lessons.add(getLesson(a));
if (a.select("td").get(6).text().trim().compareTo("") != 0)
All_Lessons.add(getLesson(a));
}
}
for (Element a : aGrades) {
if (!a.select("td").isEmpty()) {
All_Lessons.add(getLesson(a));
}
}
}
private Lesson getLesson(Element a) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String ID = a.select("td").get(1).text();
String Title = a.select("td").get(2).text();
Double Mark = 0.0;
try {
Mark = Double.valueOf(a.select("td").get(3).text());
} catch (Exception ex) {
}
String Cemester = a.select("td").get(4).text();
Date Statement = null, Exam = null;
try {
Statement = formatter.parse(a.select("td").get(5).text().trim());
Exam = formatter.parse(a.select("td").get(6).text().trim());
} catch (ParseException ex) {
}
Lesson.LessonStatus Status;
switch (a.select("td").get(7).text().trim()) {
case "Επιτυχία":
Status = Lesson.LessonStatus.PASSED;
break;
case "Αποτυχία":
Status = Lesson.LessonStatus.FAILED;
break;
case "Ακύρωση":
Status = Lesson.LessonStatus.CANCELLED;
break;
default:
Status = Lesson.LessonStatus.NOT_GIVEN;
break;
}
return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status);
}
public ArrayList<Lesson> getSucceed_Lessons() {
return Succeed_Lessons;
}
public ArrayList<Lesson> getAll_Lessons() {
return All_Lessons;
}
public Object[] getAll_Lessons_array() {
return All_Lessons.toArray();
}
public ArrayList<Lesson> getExams_Lessons() {
return Exams_Lessons;
}
public String getStudentFullName() {
return StudentFullName;
}
public String getID() {
return ID;
}
public String getStudentName() {
return StudentFullName.split(" ")[0];
}
public String getSurname() {
return StudentFullName.split(" ")[1];
}
private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
//HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true);
SSLContext context;
context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
public enum SendType {
OFFICE, COURIER, FAX
}
public enum PaperType {
bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo,
stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma,
allo
}
}
|
32051_29 | package com.kospeac.smartgreecealert;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static Activity mainActivity;
UsbService mUsbService = new UsbService();
FirebaseService mFirebaseService;
String type;
Button sosBtn;
Button fireBtn;
Button abortBtn;
public TextView mainTitle;
public TextView sosTitle;
CountDownTimer countDownTimer;
CountDownTimer countDownSOS;
boolean countDownTimerIsRunning = false;
boolean sosStatus = false;
private FallDetectionHandler falldetection;
private SeismicDetectionHandler seismicdetection;
private final static int REQUESTCODE = 325;
LocationManager mLocationManager;
Uri notification;
Ringtone r;
private LocationListener locationService;
private Boolean prevStatus;
Double longitude, latitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = this;
mFirebaseService = FirebaseService.getInstance();
mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationService = new LocationService();
sosBtn = findViewById(R.id.btn_sos);
fireBtn = findViewById(R.id.btn_fire);
abortBtn = findViewById(R.id.btn_abort);
mainTitle = findViewById(R.id.main_title);
sosTitle = findViewById(R.id.sos_text);
sosBtn.setOnClickListener(this);
fireBtn.setOnClickListener(this);
abortBtn.setOnClickListener(this);
checkPermissions();
try {
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
} catch (Exception e) {
e.printStackTrace();
}
this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE"));
mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() {
@Override
public void onStatusChanged(boolean newStatus) {
if(newStatus){
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "earthquakeEventDetected";
if (falldetection != null && FallDetectionHandler.getListenerStatus()) {
falldetection.unregisterListener();
}
mainTitle.setText(R.string.main_title2);
setupEarthquakeDetection(); // EarthquakeDetection
}
}else {
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "fallDetectionEvent";
if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) {
System.out.println(seismicdetection);
seismicdetection.unregisterListener();
}
mainTitle.setText(R.string.main_title1);
setupFallDetection(); // FallDetection
}
}
}
});
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity
super.onDestroy();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_sos: // SOS
sosStatus = true;
sosTitle.setText(R.string.sos_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("SOS");
break;
case R.id.btn_fire: // FIRE button
sosTitle.setText(R.string.fire_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("FIRE");
break;
case R.id.btn_abort: // κουμπι Abort
if(type == "fallDetectionEvent" && countDownTimerIsRunning) {
cancelTimer();
Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
} else if(sosStatus){ // αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση
cancelSOSTimer();
handleEvent("AbortEvent");
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.topbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_statistics:
Intent goToStatistics = new Intent(this,Statistics.class);
startActivity(goToStatistics); // Νεο acitvity Statistics
return true;
case R.id.menu_contacts:
Intent goToContacts = new Intent(this,ContactsActivity.class);
startActivity(goToContacts); // Νεο acitvity Contacts
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkPermissions() {
List<String> PERMISSIONS = new ArrayList<>();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
}else{
System.out.println("GPS ENABLED");
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
}
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
PERMISSIONS.add(Manifest.permission.SEND_SMS);
}
if(!PERMISSIONS.isEmpty()){
String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]);
ActivityCompat.requestPermissions(this,
array,
REQUESTCODE);
}
}
//get location from the GPS service provider. Needs permission.
protected void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location location = null;
for(String provider : providers){
Location l = mLocationManager.getLastKnownLocation(provider);
location = l;
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
break;
}
}
if (location == null) {
latitude = -1.0;
longitude = -1.0;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(this, permission)
== PackageManager.PERMISSION_GRANTED) {
if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
getLocation();
}
}
}
}
/* setupFallDetection
* Create object and listener (from device accelerometer) when we are in fallDetection state.
* When status is true we have a user fall and we deactivate/unregister the listener
* and we enable a CountDownTimer of 30 secs in order to abort event.
* */
private void setupFallDetection() {
falldetection = new FallDetectionHandler(this);
falldetection.setFallDetectionListener(new FallDetectionListener() {
@Override
public void onStatusChanged(boolean fallDetectionStatus) {
if(fallDetectionStatus) {
falldetection.unregisterListener();
countDownTimerIsRunning = true;
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση
r.play();
mainTitle.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event
countDownTimerIsRunning = false;
r.stop();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
handleEvent("fallDetectionEvent");
}
}.start();
}
}
});
}
private void cancelTimer(){ //ακυρωση timer για το fall detection
countDownTimer.cancel();
r.stop();
}
private void cancelSOSTimer(){ //ακυρωση timer για το SOS button
countDownSOS.onFinish();
countDownSOS.cancel();
}
// setupEarthquakeDetection
private void setupEarthquakeDetection() {
seismicdetection = new SeismicDetectionHandler(this);
seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() {
@Override
public void onStatusChanged(boolean seismicDetectionStatus) {
if(seismicDetectionStatus) {
seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος
handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type
}
}
});
}
// handleEvent
private void handleEvent( String type){
String eventType = type;
final double latd,lond;
//check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider
if(LocationService.latitude !=0 & LocationService.longitude!=0) {
latd = LocationService.latitude;
lond = LocationService.latitude;
}
else
{
getLocation();
latd = latitude;
lond = longitude;
}
String lat = Double.toString(latd);
String lon = Double.toString(lond);
final long timestamp = System.currentTimeMillis();
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp);
String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString();
mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database
if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου
Notification notification = new Notification(mainActivity);
notification.sendNotification(type, lat, lon, date); // αποστολη SMS
}
if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event
mFirebaseService.getEvents();
mFirebaseService.setFirebaseListener(new FirebaseListener() {
@Override
public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents.
if(newStatus.equals("allEvents")){
List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection
boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond);
if(seismicStatus){
handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση
new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ
.setTitle("Earthquake!")
.setMessage("An Earthquake is taking place, please seek help!!")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}else {
//αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake
if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
}
}
});
}
}
}
| Afrodith/SmartAlertGreece | app/src/main/java/com/kospeac/smartgreecealert/MainActivity.java | 3,938 | //αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake | line_comment | el | package com.kospeac.smartgreecealert;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static Activity mainActivity;
UsbService mUsbService = new UsbService();
FirebaseService mFirebaseService;
String type;
Button sosBtn;
Button fireBtn;
Button abortBtn;
public TextView mainTitle;
public TextView sosTitle;
CountDownTimer countDownTimer;
CountDownTimer countDownSOS;
boolean countDownTimerIsRunning = false;
boolean sosStatus = false;
private FallDetectionHandler falldetection;
private SeismicDetectionHandler seismicdetection;
private final static int REQUESTCODE = 325;
LocationManager mLocationManager;
Uri notification;
Ringtone r;
private LocationListener locationService;
private Boolean prevStatus;
Double longitude, latitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = this;
mFirebaseService = FirebaseService.getInstance();
mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationService = new LocationService();
sosBtn = findViewById(R.id.btn_sos);
fireBtn = findViewById(R.id.btn_fire);
abortBtn = findViewById(R.id.btn_abort);
mainTitle = findViewById(R.id.main_title);
sosTitle = findViewById(R.id.sos_text);
sosBtn.setOnClickListener(this);
fireBtn.setOnClickListener(this);
abortBtn.setOnClickListener(this);
checkPermissions();
try {
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
} catch (Exception e) {
e.printStackTrace();
}
this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE"));
mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() {
@Override
public void onStatusChanged(boolean newStatus) {
if(newStatus){
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "earthquakeEventDetected";
if (falldetection != null && FallDetectionHandler.getListenerStatus()) {
falldetection.unregisterListener();
}
mainTitle.setText(R.string.main_title2);
setupEarthquakeDetection(); // EarthquakeDetection
}
}else {
if(prevStatus == null || prevStatus != newStatus ) {
prevStatus = newStatus;
type = "fallDetectionEvent";
if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) {
System.out.println(seismicdetection);
seismicdetection.unregisterListener();
}
mainTitle.setText(R.string.main_title1);
setupFallDetection(); // FallDetection
}
}
}
});
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity
super.onDestroy();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_sos: // SOS
sosStatus = true;
sosTitle.setText(R.string.sos_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("SOS");
break;
case R.id.btn_fire: // FIRE button
sosTitle.setText(R.string.fire_title);
countDownSOS = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sosTitle.setText("");
sosStatus = false;
}
}.start();
handleEvent("FIRE");
break;
case R.id.btn_abort: // κουμπι Abort
if(type == "fallDetectionEvent" && countDownTimerIsRunning) {
cancelTimer();
Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
} else if(sosStatus){ // αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση
cancelSOSTimer();
handleEvent("AbortEvent");
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.topbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_statistics:
Intent goToStatistics = new Intent(this,Statistics.class);
startActivity(goToStatistics); // Νεο acitvity Statistics
return true;
case R.id.menu_contacts:
Intent goToContacts = new Intent(this,ContactsActivity.class);
startActivity(goToContacts); // Νεο acitvity Contacts
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkPermissions() {
List<String> PERMISSIONS = new ArrayList<>();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
}else{
System.out.println("GPS ENABLED");
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
}
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
PERMISSIONS.add(Manifest.permission.SEND_SMS);
}
if(!PERMISSIONS.isEmpty()){
String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]);
ActivityCompat.requestPermissions(this,
array,
REQUESTCODE);
}
}
//get location from the GPS service provider. Needs permission.
protected void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location location = null;
for(String provider : providers){
Location l = mLocationManager.getLastKnownLocation(provider);
location = l;
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
break;
}
}
if (location == null) {
latitude = -1.0;
longitude = -1.0;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(this, permission)
== PackageManager.PERMISSION_GRANTED) {
if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationService);
getLocation();
}
}
}
}
/* setupFallDetection
* Create object and listener (from device accelerometer) when we are in fallDetection state.
* When status is true we have a user fall and we deactivate/unregister the listener
* and we enable a CountDownTimer of 30 secs in order to abort event.
* */
private void setupFallDetection() {
falldetection = new FallDetectionHandler(this);
falldetection.setFallDetectionListener(new FallDetectionListener() {
@Override
public void onStatusChanged(boolean fallDetectionStatus) {
if(fallDetectionStatus) {
falldetection.unregisterListener();
countDownTimerIsRunning = true;
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση
r.play();
mainTitle.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event
countDownTimerIsRunning = false;
r.stop();
mainTitle.setText(R.string.main_title1);
falldetection.registerListener();
handleEvent("fallDetectionEvent");
}
}.start();
}
}
});
}
private void cancelTimer(){ //ακυρωση timer για το fall detection
countDownTimer.cancel();
r.stop();
}
private void cancelSOSTimer(){ //ακυρωση timer για το SOS button
countDownSOS.onFinish();
countDownSOS.cancel();
}
// setupEarthquakeDetection
private void setupEarthquakeDetection() {
seismicdetection = new SeismicDetectionHandler(this);
seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() {
@Override
public void onStatusChanged(boolean seismicDetectionStatus) {
if(seismicDetectionStatus) {
seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος
handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type
}
}
});
}
// handleEvent
private void handleEvent( String type){
String eventType = type;
final double latd,lond;
//check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider
if(LocationService.latitude !=0 & LocationService.longitude!=0) {
latd = LocationService.latitude;
lond = LocationService.latitude;
}
else
{
getLocation();
latd = latitude;
lond = longitude;
}
String lat = Double.toString(latd);
String lon = Double.toString(lond);
final long timestamp = System.currentTimeMillis();
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp);
String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString();
mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database
if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου
Notification notification = new Notification(mainActivity);
notification.sendNotification(type, lat, lon, date); // αποστολη SMS
}
if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event
mFirebaseService.getEvents();
mFirebaseService.setFirebaseListener(new FirebaseListener() {
@Override
public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents.
if(newStatus.equals("allEvents")){
List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection
boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond);
if(seismicStatus){
handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση
new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ
.setTitle("Earthquake!")
.setMessage("An Earthquake is taking place, please seek help!!")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}else {
//αμ<SUF>
if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){
seismicdetection.registerListener();
}
}
}
}
});
}
}
}
|
18080_13 | package gr.aueb;
import org.apiguardian.api.API;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
/*The BonusContentTest class is a test class that contains test methods for testing the functionality of the BonusContent class.
It tests various scenarios such as null or empty inputs, list size, and output validation. */
public class BonusContentTest {
private static String youtubeApiKey;
/*
* testSearchAndPrintVideo_NullSearchQuery: Tests the searchAndPrintVideo method
* with a null search query.
* Expects an IllegalArgumentException to be thrown with the message
* "Search Query cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullSearchQuery() throws URISyntaxException {
String searchQuery = null;
String category = "Fun facts";
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("Search Query cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_EmptyCategory: Tests the searchAndPrintVideo method
* with an empty category.
* Expects an IllegalArgumentException to be thrown with the message
* "category cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_EmptyCategory() throws URISyntaxException {
String searchQuery = "Pulp Fiction";
String category = null;
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("category cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_NullApiKey: Tests the searchAndPrintVideo method with
* a null API key.
* Expects an IllegalArgumentException to be thrown with the message
* "ApiKey cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullApiKey() throws URISyntaxException {
String searchQuery = "Barbie";
String category = "Behind the Scenes";
String apiKey = null;
try {
BonusContent.searchAndPrintVideo(searchQuery, category, apiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("ApiKey cannot be null or empty.", e.getMessage());
}
}
/*
* testCheckItemsSize_NotEmptyList: Tests the checkItemsSize method with a
* non-empty list.
* Expects the list size to be greater than 0.
*/
@Test
public void testCheckItemsSize_NotEmptyList() {
List<Object> items = new ArrayList<>();
items.add(new Object()); // Προσθέτουμε ένα στοιχείο στη λίστα
assertTrue(items.size() > 0);
}
/*
* testCheckItemsSize_EmptyList: Tests the checkItemsSize method with an empty
* list.
* Expects the list size to be 0.
*/
@Test
public void testCheckItemsSize_EmptyList() {
List<Object> items = new ArrayList<>();
assertFalse(items.size() > 0);
}
/*
* testIterateAndPrint_NonEmptyList: Tests the iterateAndPrintWrapper method
* with a non-empty list.
* Verifies that the expected output is printed to the console.
*/
@Test
public void testIterateAndPrint_NonEmptyList() {
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος περιέχει τα αναμενόμενα κείμενα
String expectedOutput = String.format("Item 1%sItem 2%sItem 3%s", System.lineSeparator(),
System.lineSeparator(), System.lineSeparator());
assertEquals(expectedOutput, outContent.toString());
}
/*
* testIterateAndPrint_EmptyList: Tests the iterateAndPrintWrapper method with
* an empty list.
* Verifies that no output is printed to the console.
*/
@Test
public void testIterateAndPrint_EmptyList() {
List<String> items = new ArrayList<>();
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος είναι κενή
assertEquals("", outContent.toString());
}
// Wrapper γύρω από την iterateAndPrint για την κλάση δοκιμών
private static void iterateAndPrintWrapper(List<String> items) {
for (String item : items) {
System.out.println(item);
}
}
} | Aglag257/Java2_AIApp | app/src/test/java/gr/aueb/BonusContentTest.java | 1,653 | // Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών | line_comment | el | package gr.aueb;
import org.apiguardian.api.API;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
/*The BonusContentTest class is a test class that contains test methods for testing the functionality of the BonusContent class.
It tests various scenarios such as null or empty inputs, list size, and output validation. */
public class BonusContentTest {
private static String youtubeApiKey;
/*
* testSearchAndPrintVideo_NullSearchQuery: Tests the searchAndPrintVideo method
* with a null search query.
* Expects an IllegalArgumentException to be thrown with the message
* "Search Query cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullSearchQuery() throws URISyntaxException {
String searchQuery = null;
String category = "Fun facts";
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("Search Query cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_EmptyCategory: Tests the searchAndPrintVideo method
* with an empty category.
* Expects an IllegalArgumentException to be thrown with the message
* "category cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_EmptyCategory() throws URISyntaxException {
String searchQuery = "Pulp Fiction";
String category = null;
File youtubeFile = new File("c:/Users/Βασιλης/OneDrive/Υπολογιστής/apiKeys/youtube_key.txt");
try (BufferedReader br = new BufferedReader(new FileReader(youtubeFile))) {
youtubeApiKey = br.readLine();
} catch (Exception e) {
System.err.println("Error reading YouTube API key file.");
System.exit(1);
}
try {
BonusContent.searchAndPrintVideo(searchQuery, category, youtubeApiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("category cannot be null or empty.", e.getMessage());
}
}
/*
* testSearchAndPrintVideo_NullApiKey: Tests the searchAndPrintVideo method with
* a null API key.
* Expects an IllegalArgumentException to be thrown with the message
* "ApiKey cannot be null or empty."
*/
@Test
public void testSearchAndPrintVideo_NullApiKey() throws URISyntaxException {
String searchQuery = "Barbie";
String category = "Behind the Scenes";
String apiKey = null;
try {
BonusContent.searchAndPrintVideo(searchQuery, category, apiKey);
fail("Expected IllegalArgumentException, but no exception was thrown.");
} catch (IllegalArgumentException e) {
assertEquals("ApiKey cannot be null or empty.", e.getMessage());
}
}
/*
* testCheckItemsSize_NotEmptyList: Tests the checkItemsSize method with a
* non-empty list.
* Expects the list size to be greater than 0.
*/
@Test
public void testCheckItemsSize_NotEmptyList() {
List<Object> items = new ArrayList<>();
items.add(new Object()); // Προσθέτουμε ένα στοιχείο στη λίστα
assertTrue(items.size() > 0);
}
/*
* testCheckItemsSize_EmptyList: Tests the checkItemsSize method with an empty
* list.
* Expects the list size to be 0.
*/
@Test
public void testCheckItemsSize_EmptyList() {
List<Object> items = new ArrayList<>();
assertFalse(items.size() > 0);
}
/*
* testIterateAndPrint_NonEmptyList: Tests the iterateAndPrintWrapper method
* with a non-empty list.
* Verifies that the expected output is printed to the console.
*/
@Test
public void testIterateAndPrint_NonEmptyList() {
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Καλείστε τη στατική μέθοδο wrapper στην κλάση δοκιμών
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος περιέχει τα αναμενόμενα κείμενα
String expectedOutput = String.format("Item 1%sItem 2%sItem 3%s", System.lineSeparator(),
System.lineSeparator(), System.lineSeparator());
assertEquals(expectedOutput, outContent.toString());
}
/*
* testIterateAndPrint_EmptyList: Tests the iterateAndPrintWrapper method with
* an empty list.
* Verifies that no output is printed to the console.
*/
@Test
public void testIterateAndPrint_EmptyList() {
List<String> items = new ArrayList<>();
// Εκτέλεση της μεθόδου iterateAndPrint και αποθήκευση της έξοδου
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
// Κα<SUF>
BonusContentTest.iterateAndPrintWrapper(items);
// Ελέγχουμε αν η έξοδος είναι κενή
assertEquals("", outContent.toString());
}
// Wrapper γύρω από την iterateAndPrint για την κλάση δοκιμών
private static void iterateAndPrintWrapper(List<String> items) {
for (String item : items) {
System.out.println(item);
}
}
} |
10206_35 | package com.example.hangmangame;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*;
import java.util.*;
import static com.example.hangmangame.LoadDictionary.*;
public class Controller {
public static boolean Playing;
@FXML
private Label AvailableWordsLabel;
@FXML
private Label Dictionary;
@FXML
private ImageView ImageView;
@FXML
private Label Possible_Letters_Label;
@FXML
private HBox word_hbox;
@FXML
private Label TotalPoints;
@FXML
private Label Success_Rate;
@FXML
private void open_up_add_dictionary(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Dictionary Settings");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening add_dictionary Scene");
}
}
@FXML
private void open_up_load_dictionary(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Load Dictionary");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Load Dictionary Scene");
}
}
@FXML
private void solution_dialog(){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Solution");
alert.setHeaderText(null);
if(Playing) alert.setContentText("Solution is " + game_word);
else alert.setContentText("You are not playing !");
alert.showAndWait();
}
public List<Button> word_buttons = new ArrayList<>();
public static String game_word;
public int Number_of_Letters_left;
public int lives;
public List<Button> Invisible_Key_Buttons = new ArrayList<>();
public boolean initialise = false;
@FXML
public void start() {
if(!initialise){
initialise_rounds();
}
lives = 6;
SetImage(lives);
game_word = get_random_word();
Number_of_Letters_left = game_word.length();
Playing = true;
Successful_Attempts = 0.0F;
Total_Attempts = 0.0F;
Success_Rate.setText("0%");
Available_Words();
if (game_word.equals("empty")) {
Dictionary.setText("Load Dictionary!");
return;
}
//Reset
Possible_letters.clear();
//Set invisible keys to visible
if (!Invisible_Key_Buttons.isEmpty()) {
for (Button invisible_key_button : Invisible_Key_Buttons) {
invisible_key_button.setVisible(true);
}
}
Dictionary.setText(title);
System.out.println(title);
//create a list of buttons
word_hbox.getChildren().removeAll(word_buttons);
word_buttons.clear();
for (int i = 0; i < game_word.length(); i++) {
word_buttons.add(new Button("_"));
//word_buttons.add(new Button(String.valueOf(game_word.charAt(i))));
word_hbox.getChildren().add(word_buttons.get(i));
word_buttons.get(i).setStyle("-fx-font-size: 2em; ");
/* when clicked it should display the most common letters in the position of the letter in the Dictionary */
word_buttons.get(i).setOnAction(actionEvent -> {
//... do something in here.
});
}
Same_length_stats();
}
public List<String> Possible_letters = new ArrayList<>();
public List<Integer> Quantity_of_Letter = new ArrayList<>();
public Vector<String> same_length_words = new Vector<>();
public List<Element> elements = new ArrayList<Element>();
public void Same_length_stats() {
/* Find words with equal length with game_word */
same_length_words.clear();
elements.clear();
for (String word : words) {
if (word.length() == game_word.length() && !word.equals(game_word)) {
same_length_words.add(word);
}
}
// counter to keep track of how many
int[][] CharCounter = new int[game_word.length()][26];
/* set all counters to zero */
// we have 26 counters for every letter of the game word
for (int i = 0; i < game_word.length(); i++) {
for (int z = 0; z < 26; z++) {
CharCounter[i][z] = 0;
}
}
// Now we count
for (int i = 0; i < game_word.length(); i++) {
for (String word : same_length_words) {
int temp = (int) word.charAt(i) - 65; //Capital Letters
CharCounter[i][temp]++;
}
}
// add every counter to a List in order to keep track of them when we sort them
for (int i = 0; i < game_word.length(); i++) { //i = position
for (int z = 0; z < 26; z++) { //z = letter
elements.add(new Element(i, z, CharCounter[i][z]));
//System.out.println(CharCounter[i][z]);
}
}
Collections.sort(elements);
// reverse so we get the big numbers at front
Collections.reverse(elements);
for (int i = 0; i < game_word.length(); i++) {
Possible_letters.add("");
System.out.println("---------LOOP " + String.valueOf(i) + "----------" );
System.out.println(i);
for (Element element : elements) {
if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0
char letter = (char) (element.letter + 65);
System.out.println(letter + " quantity :" + String.valueOf(element.quantity));
Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " ");
}
}
int java_is_dumb = i; //lamda expressions need final expressions
word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));});
System.out.println(Possible_letters.get(i));
}
}
public void Available_Words() {
AvailableWordsLabel.setText(String.valueOf(words.size()));
}
public float Successful_Attempts;
public float Total_Attempts;
public void Success_Rate(){
if (Successful_Attempts == 0){
Success_Rate.setText("0%");
return;
} else if (Successful_Attempts==Total_Attempts) {
Success_Rate.setText("100%");
return;
}
float Success_rate = 100*Successful_Attempts/Total_Attempts;;
String Success_Rate_Text = String.valueOf(Success_rate);
String Label = "";
for (int i = 0; i < 4; i++) {
Label += String.valueOf(Success_Rate_Text.charAt(i));
}
Success_Rate.setText(Label+" %");
}
public int Score = 0;
public void Update_Score(int position){
int total_same_length_words = same_length_words.size();
int Element_letter = ((int) game_word.charAt(position)) - 65;
//we have to convert it to the way we added it 26*i + z
//int quantity_of_letter = elements.get(26*position + Element_letter).quantity;
int quantity_of_letter = 0;
for(Element element:elements){
if(element.letter == Element_letter && element.position==position){
quantity_of_letter = element.quantity;
}
}
float percentage = (float)quantity_of_letter / (float) total_same_length_words;
System.out.println("Total words, quantity of letter , percentage");
System.out.println(total_same_length_words);
System.out.println(quantity_of_letter);
System.out.println(percentage);
//System.out.println(Element_letter+65);
if(percentage >= 0.6) {
Score += 5;
} else if(percentage >= 0.4){
Score += 10;
} else if(percentage >= 0.25){
Score += 15;
} else
Score += 30;
}
@FXML
public void Try_this_Letter(Event event) {
if (!Playing) {
return; //If we ain't playing do nothing
}
System.out.println(event.getTarget());
Button btn = (Button) event.getSource(); //temp value
String button_char = btn.getId();
System.out.println(btn.getId()); //get id
btn.setVisible(false);
Invisible_Key_Buttons.add(btn);
/* ChecK if the character exist in the game word */
boolean success = false;
Total_Attempts++;
for (int i = 0; i < game_word.length(); i++) {
if (button_char.equals(String.valueOf(game_word.charAt(i)))) {
//reveal the letters that exist in the words
success = true;
Number_of_Letters_left--;
word_buttons.get(i).setText(button_char);
Update_Score(i); //we scored at position i
TotalPoints.setText(String.valueOf(Score));
if (Number_of_Letters_left < 1) {
System.out.println("Congratulations");
//win = true
Update_Rounds(true);
win_game(true);
}
}
}
if(!success){
lives--;
SetImage(lives);
//game_over();
if (lives < 1) {
//win = false
Playing = false;
Update_Rounds(false);
System.out.println("You lost :(");
win_game(false);
}
} else Successful_Attempts++;
Success_Rate();
}
public void win_game(boolean win){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
if(win) {
alert.setTitle("Congratulations");
alert.setHeaderText("You Won !");
alert.setContentText("Ready for the next one ?");
File myObj = new File("./images/win.png");
Image image = new Image(myObj.getAbsolutePath());
alert.setGraphic(new ImageView(image));
} else {
alert.setTitle("Tough luck");
alert.setHeaderText("You Lost ...");
alert.setContentText("Want to try again ?");
File myObj = new File("./images/lost.png");
Image image = new Image(myObj.getAbsolutePath());
alert.setGraphic(new ImageView(image));
}
ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeNextWord);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeNextWord){
start();
}
}
public void SetImage(int lives) {
File myObj = new File("./images/" + String.valueOf(lives) + ".jpg");
Image image = new Image(myObj.getAbsolutePath());
ImageView.setImage(image);
}
@FXML
public void exit_app(){
Platform.exit();
}
@FXML
public void open_Dictionary_Details(ActionEvent event){
/*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το
ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9
γράμματα και 10 ή περισσότερα γράμματα */
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Dictionary Details");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Dictionary Details Scene");
}
}
public static Vector<String> gamewords_5 = new Vector<>();
public static Vector<String> results_5 = new Vector<>();
public static Vector<String> Attempts_per_gameword = new Vector<>();
public void initialise_rounds() {
for (int i = 0; i < 5; i++) {
gamewords_5.add("---");
results_5.add("---");
Attempts_per_gameword.add("---");
}
initialise = true;
}
public void Update_Rounds(Boolean win) {
//gamewords
gamewords_5.remove(0);
gamewords_5.add(game_word);
//results
results_5.remove(0);
if(win){
results_5.add("Victory");
}
else {
results_5.add("Defeat");
}
//attempts
Attempts_per_gameword.remove(0);
Attempts_per_gameword.add(String.valueOf((int) Total_Attempts));
}
@FXML
public void Instructions(){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("instructions.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Stage stage = new Stage();
stage.setTitle("Instructions");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Instructions Scene");
}
}
@FXML
public void Rounds(){
/*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5
τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες:
επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή
υπολογιστής).
*/
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("rounds.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Rounds Details");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Rounds Scene");
}
}
}
| Aglogallos/Hangman-Game-JavaFx | Hangman_Game/Hangman-Game/src/main/java/com/example/hangmangame/Controller.java | 3,768 | /*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5
τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες:
επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή
υπολογιστής).
*/ | block_comment | el | package com.example.hangmangame;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*;
import java.util.*;
import static com.example.hangmangame.LoadDictionary.*;
public class Controller {
public static boolean Playing;
@FXML
private Label AvailableWordsLabel;
@FXML
private Label Dictionary;
@FXML
private ImageView ImageView;
@FXML
private Label Possible_Letters_Label;
@FXML
private HBox word_hbox;
@FXML
private Label TotalPoints;
@FXML
private Label Success_Rate;
@FXML
private void open_up_add_dictionary(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Dictionary Settings");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening add_dictionary Scene");
}
}
@FXML
private void open_up_load_dictionary(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Load Dictionary");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Load Dictionary Scene");
}
}
@FXML
private void solution_dialog(){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Solution");
alert.setHeaderText(null);
if(Playing) alert.setContentText("Solution is " + game_word);
else alert.setContentText("You are not playing !");
alert.showAndWait();
}
public List<Button> word_buttons = new ArrayList<>();
public static String game_word;
public int Number_of_Letters_left;
public int lives;
public List<Button> Invisible_Key_Buttons = new ArrayList<>();
public boolean initialise = false;
@FXML
public void start() {
if(!initialise){
initialise_rounds();
}
lives = 6;
SetImage(lives);
game_word = get_random_word();
Number_of_Letters_left = game_word.length();
Playing = true;
Successful_Attempts = 0.0F;
Total_Attempts = 0.0F;
Success_Rate.setText("0%");
Available_Words();
if (game_word.equals("empty")) {
Dictionary.setText("Load Dictionary!");
return;
}
//Reset
Possible_letters.clear();
//Set invisible keys to visible
if (!Invisible_Key_Buttons.isEmpty()) {
for (Button invisible_key_button : Invisible_Key_Buttons) {
invisible_key_button.setVisible(true);
}
}
Dictionary.setText(title);
System.out.println(title);
//create a list of buttons
word_hbox.getChildren().removeAll(word_buttons);
word_buttons.clear();
for (int i = 0; i < game_word.length(); i++) {
word_buttons.add(new Button("_"));
//word_buttons.add(new Button(String.valueOf(game_word.charAt(i))));
word_hbox.getChildren().add(word_buttons.get(i));
word_buttons.get(i).setStyle("-fx-font-size: 2em; ");
/* when clicked it should display the most common letters in the position of the letter in the Dictionary */
word_buttons.get(i).setOnAction(actionEvent -> {
//... do something in here.
});
}
Same_length_stats();
}
public List<String> Possible_letters = new ArrayList<>();
public List<Integer> Quantity_of_Letter = new ArrayList<>();
public Vector<String> same_length_words = new Vector<>();
public List<Element> elements = new ArrayList<Element>();
public void Same_length_stats() {
/* Find words with equal length with game_word */
same_length_words.clear();
elements.clear();
for (String word : words) {
if (word.length() == game_word.length() && !word.equals(game_word)) {
same_length_words.add(word);
}
}
// counter to keep track of how many
int[][] CharCounter = new int[game_word.length()][26];
/* set all counters to zero */
// we have 26 counters for every letter of the game word
for (int i = 0; i < game_word.length(); i++) {
for (int z = 0; z < 26; z++) {
CharCounter[i][z] = 0;
}
}
// Now we count
for (int i = 0; i < game_word.length(); i++) {
for (String word : same_length_words) {
int temp = (int) word.charAt(i) - 65; //Capital Letters
CharCounter[i][temp]++;
}
}
// add every counter to a List in order to keep track of them when we sort them
for (int i = 0; i < game_word.length(); i++) { //i = position
for (int z = 0; z < 26; z++) { //z = letter
elements.add(new Element(i, z, CharCounter[i][z]));
//System.out.println(CharCounter[i][z]);
}
}
Collections.sort(elements);
// reverse so we get the big numbers at front
Collections.reverse(elements);
for (int i = 0; i < game_word.length(); i++) {
Possible_letters.add("");
System.out.println("---------LOOP " + String.valueOf(i) + "----------" );
System.out.println(i);
for (Element element : elements) {
if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0
char letter = (char) (element.letter + 65);
System.out.println(letter + " quantity :" + String.valueOf(element.quantity));
Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " ");
}
}
int java_is_dumb = i; //lamda expressions need final expressions
word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));});
System.out.println(Possible_letters.get(i));
}
}
public void Available_Words() {
AvailableWordsLabel.setText(String.valueOf(words.size()));
}
public float Successful_Attempts;
public float Total_Attempts;
public void Success_Rate(){
if (Successful_Attempts == 0){
Success_Rate.setText("0%");
return;
} else if (Successful_Attempts==Total_Attempts) {
Success_Rate.setText("100%");
return;
}
float Success_rate = 100*Successful_Attempts/Total_Attempts;;
String Success_Rate_Text = String.valueOf(Success_rate);
String Label = "";
for (int i = 0; i < 4; i++) {
Label += String.valueOf(Success_Rate_Text.charAt(i));
}
Success_Rate.setText(Label+" %");
}
public int Score = 0;
public void Update_Score(int position){
int total_same_length_words = same_length_words.size();
int Element_letter = ((int) game_word.charAt(position)) - 65;
//we have to convert it to the way we added it 26*i + z
//int quantity_of_letter = elements.get(26*position + Element_letter).quantity;
int quantity_of_letter = 0;
for(Element element:elements){
if(element.letter == Element_letter && element.position==position){
quantity_of_letter = element.quantity;
}
}
float percentage = (float)quantity_of_letter / (float) total_same_length_words;
System.out.println("Total words, quantity of letter , percentage");
System.out.println(total_same_length_words);
System.out.println(quantity_of_letter);
System.out.println(percentage);
//System.out.println(Element_letter+65);
if(percentage >= 0.6) {
Score += 5;
} else if(percentage >= 0.4){
Score += 10;
} else if(percentage >= 0.25){
Score += 15;
} else
Score += 30;
}
@FXML
public void Try_this_Letter(Event event) {
if (!Playing) {
return; //If we ain't playing do nothing
}
System.out.println(event.getTarget());
Button btn = (Button) event.getSource(); //temp value
String button_char = btn.getId();
System.out.println(btn.getId()); //get id
btn.setVisible(false);
Invisible_Key_Buttons.add(btn);
/* ChecK if the character exist in the game word */
boolean success = false;
Total_Attempts++;
for (int i = 0; i < game_word.length(); i++) {
if (button_char.equals(String.valueOf(game_word.charAt(i)))) {
//reveal the letters that exist in the words
success = true;
Number_of_Letters_left--;
word_buttons.get(i).setText(button_char);
Update_Score(i); //we scored at position i
TotalPoints.setText(String.valueOf(Score));
if (Number_of_Letters_left < 1) {
System.out.println("Congratulations");
//win = true
Update_Rounds(true);
win_game(true);
}
}
}
if(!success){
lives--;
SetImage(lives);
//game_over();
if (lives < 1) {
//win = false
Playing = false;
Update_Rounds(false);
System.out.println("You lost :(");
win_game(false);
}
} else Successful_Attempts++;
Success_Rate();
}
public void win_game(boolean win){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
if(win) {
alert.setTitle("Congratulations");
alert.setHeaderText("You Won !");
alert.setContentText("Ready for the next one ?");
File myObj = new File("./images/win.png");
Image image = new Image(myObj.getAbsolutePath());
alert.setGraphic(new ImageView(image));
} else {
alert.setTitle("Tough luck");
alert.setHeaderText("You Lost ...");
alert.setContentText("Want to try again ?");
File myObj = new File("./images/lost.png");
Image image = new Image(myObj.getAbsolutePath());
alert.setGraphic(new ImageView(image));
}
ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeNextWord);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeNextWord){
start();
}
}
public void SetImage(int lives) {
File myObj = new File("./images/" + String.valueOf(lives) + ".jpg");
Image image = new Image(myObj.getAbsolutePath());
ImageView.setImage(image);
}
@FXML
public void exit_app(){
Platform.exit();
}
@FXML
public void open_Dictionary_Details(ActionEvent event){
/*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το
ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9
γράμματα και 10 ή περισσότερα γράμματα */
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Dictionary Details");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Dictionary Details Scene");
}
}
public static Vector<String> gamewords_5 = new Vector<>();
public static Vector<String> results_5 = new Vector<>();
public static Vector<String> Attempts_per_gameword = new Vector<>();
public void initialise_rounds() {
for (int i = 0; i < 5; i++) {
gamewords_5.add("---");
results_5.add("---");
Attempts_per_gameword.add("---");
}
initialise = true;
}
public void Update_Rounds(Boolean win) {
//gamewords
gamewords_5.remove(0);
gamewords_5.add(game_word);
//results
results_5.remove(0);
if(win){
results_5.add("Victory");
}
else {
results_5.add("Defeat");
}
//attempts
Attempts_per_gameword.remove(0);
Attempts_per_gameword.add(String.valueOf((int) Total_Attempts));
}
@FXML
public void Instructions(){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("instructions.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Stage stage = new Stage();
stage.setTitle("Instructions");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Instructions Scene");
}
}
@FXML
public void Rounds(){
/*Rou<SUF>*/
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("rounds.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("Rounds Details");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
System.out.println("Error opening Rounds Scene");
}
}
}
|
6074_0 | package booking;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class AvailabilityOfAccommodations implements Runnable{
private Map<String, ReservationDateRange> roomAvailability;
@Override
public void run() {
// Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα
while (true) {
// Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα
try {
Thread.sleep(1000); // Περιμένει 1 δευτερόλεπτο πριν συνεχίσει
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public AvailabilityOfAccommodations() {
this.roomAvailability = new HashMap<>();
}
public Map<String, ReservationDateRange> getRoomAvailability() {
return roomAvailability;
}
/**
* Initial input to map from JSONfile
*
* @param path
*/
public void addRoomAsAvailableFromJSON(Path path) {
AccommodationList accommodationList = new AccommodationList(path);
for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) {
roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange());
}
}
/**
* From Manager input to map
*
* @param roomName
* @param from
* @param to
*/
public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) {
System.out.println("..................function: addRoomAsAvailableFromManager...............................");
boolean exist = false;
for (String key : roomAvailability.keySet()) {
if (key.equals(roomName)) {
roomAvailability.put(roomName, new ReservationDateRange(from, to));
exist = true;
}
}
if (exist) {
System.out.println("The room " + roomName + " successfully inserted as available");
} else {
System.out.println("The specific room " + roomName + " does not exist.");
}
}
/**
* booking of a room - client function
*
* @param roomName
*/
public synchronized void bookingOfRoom(String roomName) {
System.out.println("..................function: bookingOfRoom...............................");
boolean booking = false;
for (String key : roomAvailability.keySet()) {
ReservationDateRange range = roomAvailability.get(key);
if (key.equals(roomName))
if (range.isAvailable()) {
range.setAvailable(false);
booking = true;
}
}
if (booking) {
System.out.println("The " + roomName + " is successfully booked.");
} else {
System.out.println("The " + roomName + " is not available.");
}
}
@Override
public String toString() {
return "Manager{" +
"roomAvailability=" + roomAvailability +
'}';
}
public static void main(String[] args) {
// Default gemisma tou list apo JSON file
AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object
// Default gemisma tou map apo JSON file
AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object
ReservationDate from = new ReservationDate(20, 4, 2024);
ReservationDate to = new ReservationDate(30, 4, 2024);
availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map
availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to);
// ta typwnei opws akrivws ta exei parei apo to JSON
for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) {
System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key));
}
// O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou
availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to);
for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) {
System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key));
}
// booking of a room
availabilityOfAccommodations.bookingOfRoom("235");
availabilityOfAccommodations.bookingOfRoom("500");
}
}
| AikVant/distributed_booking_2024 | src/main/java/booking/AvailabilityOfAccommodations.java | 1,206 | // Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα | line_comment | el | package booking;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class AvailabilityOfAccommodations implements Runnable{
private Map<String, ReservationDateRange> roomAvailability;
@Override
public void run() {
// Εδ<SUF>
while (true) {
// Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα
try {
Thread.sleep(1000); // Περιμένει 1 δευτερόλεπτο πριν συνεχίσει
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public AvailabilityOfAccommodations() {
this.roomAvailability = new HashMap<>();
}
public Map<String, ReservationDateRange> getRoomAvailability() {
return roomAvailability;
}
/**
* Initial input to map from JSONfile
*
* @param path
*/
public void addRoomAsAvailableFromJSON(Path path) {
AccommodationList accommodationList = new AccommodationList(path);
for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) {
roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange());
}
}
/**
* From Manager input to map
*
* @param roomName
* @param from
* @param to
*/
public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) {
System.out.println("..................function: addRoomAsAvailableFromManager...............................");
boolean exist = false;
for (String key : roomAvailability.keySet()) {
if (key.equals(roomName)) {
roomAvailability.put(roomName, new ReservationDateRange(from, to));
exist = true;
}
}
if (exist) {
System.out.println("The room " + roomName + " successfully inserted as available");
} else {
System.out.println("The specific room " + roomName + " does not exist.");
}
}
/**
* booking of a room - client function
*
* @param roomName
*/
public synchronized void bookingOfRoom(String roomName) {
System.out.println("..................function: bookingOfRoom...............................");
boolean booking = false;
for (String key : roomAvailability.keySet()) {
ReservationDateRange range = roomAvailability.get(key);
if (key.equals(roomName))
if (range.isAvailable()) {
range.setAvailable(false);
booking = true;
}
}
if (booking) {
System.out.println("The " + roomName + " is successfully booked.");
} else {
System.out.println("The " + roomName + " is not available.");
}
}
@Override
public String toString() {
return "Manager{" +
"roomAvailability=" + roomAvailability +
'}';
}
public static void main(String[] args) {
// Default gemisma tou list apo JSON file
AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object
// Default gemisma tou map apo JSON file
AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object
ReservationDate from = new ReservationDate(20, 4, 2024);
ReservationDate to = new ReservationDate(30, 4, 2024);
availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map
availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to);
// ta typwnei opws akrivws ta exei parei apo to JSON
for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) {
System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key));
}
// O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou
availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to);
for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) {
System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key));
}
// booking of a room
availabilityOfAccommodations.bookingOfRoom("235");
availabilityOfAccommodations.bookingOfRoom("500");
}
}
|
7912_8 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sphy141.probase.utils;
/**
*
* @author Alan
*/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class CryptoUtils {
private static final String key = "sphy141groupbuy!";
public static String hashString(String password) {
try {
// Create an instance of the SHA-256 algorithm
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// Convert the password string to bytes
byte[] passwordBytes = password.getBytes();
// Calculate the hash value of the password bytes
byte[] hashBytes = digest.digest(passwordBytes);
// Convert the hash bytes to a hexadecimal string
StringBuilder sb = new StringBuilder();
for (byte hashByte : hashBytes) {
sb.append(String.format("%02x", hashByte));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// Handle the exception
e.printStackTrace();
}
return null;
}//hashString
/*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης
χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/
public static String encrypt(String plainText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}//hashAESString
public static String decrypt(String encryptedText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}//hashAESString
public static String encryptDouble(double number) {
try {
String plainText = Double.toString(number);
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static double decryptDouble(String encryptedText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decryptedBytes);
return Double.parseDouble(decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
return 0.0;
}
}//class
| Alan-III/GroupBuy | groupBuyNetbeans/src/main/java/com/sphy141/probase/utils/CryptoUtils.java | 989 | /*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης
χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/ | block_comment | el | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sphy141.probase.utils;
/**
*
* @author Alan
*/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class CryptoUtils {
private static final String key = "sphy141groupbuy!";
public static String hashString(String password) {
try {
// Create an instance of the SHA-256 algorithm
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// Convert the password string to bytes
byte[] passwordBytes = password.getBytes();
// Calculate the hash value of the password bytes
byte[] hashBytes = digest.digest(passwordBytes);
// Convert the hash bytes to a hexadecimal string
StringBuilder sb = new StringBuilder();
for (byte hashByte : hashBytes) {
sb.append(String.format("%02x", hashByte));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// Handle the exception
e.printStackTrace();
}
return null;
}//hashString
/*επε<SUF>*/
public static String encrypt(String plainText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}//hashAESString
public static String decrypt(String encryptedText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}//hashAESString
public static String encryptDouble(double number) {
try {
String plainText = Double.toString(number);
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static double decryptDouble(String encryptedText) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decryptedBytes);
return Double.parseDouble(decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
return 0.0;
}
}//class
|
5142_0 | import java.time.LocalDate;
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();
}
}
}
|
7767_19 | //Δημιουργία κατηγορίας Enroll
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 EnrollFrame extends JFrame
{
//Κομμάτι δηλώσεων
private ArrayList<Enrolls> menrolls=new ArrayList<Enrolls>();
private ArrayList<Enrolls> showup=new ArrayList<Enrolls>();
private ArrayList<Enrolls> student=new ArrayList<Enrolls>();
private JButton addButton,showButton,saveButton,loadButton,removeButton,performanceButton,studentButton;
private JTextArea showArea;
public String removal,giveperformance,givenam;
int temp=0;
double avg=0;
//Προσθέτοντας Enroll
void addEnroll()
{
menrolls.add(new Enrolls());
}
//Εμφάνιση μαθητή
Enrolls findStudent(){
givenam = JOptionPane.showInputDialog("Παρακαλώ δώστε AM φοιτητή");
int cnt=0;
for(Enrolls x: menrolls) {
if(x.getam().equals(givenam)) {
student.add(x);
cnt++;
avg+=x.getgrade();
}
}
avg=avg/cnt;
return null;
}
//Εύρεση επιδόσεων
Enrolls findPerformances() {
giveperformance = JOptionPane.showInputDialog("Παρακαλώ δώστε κωδικό μαθήματος");
for(Enrolls x: menrolls) {
if(x.getkwdikos().equals(giveperformance)) {
showup.add(x);
}
}
return null;
}
//Εμφανίζοντας Enroll
void showEnroll()
{
String text="";
for(Enrolls x :menrolls)
{
text+=x+"\n";
}
showArea.setText(text);
}
//Αποθυκεύοντας Enroll
void saveEnroll()
{
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(Enrolls x:menrolls)
{
pw.println(""+x);
}
fw.close();
} catch (IOException ex) {
Logger.getLogger(EnrollFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Φορτώνοντας Enroll
void loadEnrolls()
{
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);
menrolls=new ArrayList<Enrolls>();
while(in.hasNextLine())
{
String line=in.nextLine();
String[] parts=line.split(",");
menrolls.add(new Enrolls(parts[0],parts[1],Double.parseDouble(parts[2])));
}
} catch (IOException ex)
{
}
}
}
//Διαγράφοντας μαθητή σύμφωνα με ΑΜ
void removeStudent(){
removal = JOptionPane.showInputDialog("Παρακαλώ δώστε ΑΜ φοιτητή");
//οσο ο μαθητής υπάρχει
boolean found =true;
while(found)
{
found=false;
for(int i=0;i<menrolls.size();i++)
{
if(temp==0){
if(menrolls.get(i).getam().equals(removal))
{
menrolls.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)
{
addEnroll();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΕΜΦΑΝΙΣΗ
buttonPanel.add(addButton);
showButton=new JButton("Εμφάνιση");
buttonPanel.add(showButton);
showButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
showEnroll();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΑΠΟΘΥΚΕΥΣΗ
saveButton=new JButton("Αποθύκευση");
buttonPanel.add(saveButton);
saveButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
saveEnroll();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΦΟΡΤΩΣΗ
loadButton=new JButton("Φόρτωση");
buttonPanel.add(loadButton);
loadButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
loadEnrolls();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΔΙΑΓΡΑΦΗ ΜΑΘΗΤΗ
removeButton = new JButton("Διαγραφή Μαθητή");
buttonPanel.add(removeButton);
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
removeStudent();
}
});
//ΚΟΥΜΠΙ ΕΜΦΑΝΙΣΗΣ ΕΠΙΔΟΣΕΩΝ
performanceButton = new JButton("Εμφάνιση Επιδόσεων");
buttonPanel.add(performanceButton);
performanceButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
findPerformances();
JOptionPane.showMessageDialog(null,"Βρέθηκαν επιδόσεις:"+showup);
showup.clear();
}
});
//ΚΟΥΜΠΙ ΕΜΦΑΝΙΣΗΣ ΜΑΘΗΤΗ
studentButton = new JButton("Εμφάνιση Μαθητή");
buttonPanel.add(studentButton);
studentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
findStudent();
JOptionPane.showMessageDialog(null,"Βρέθηκαν μαθητής:"+student+" και έχει μέσο όρο: "+avg);
student.clear();
}
});
add(buttonPanel);
}
//Φτιάχνοντας το EnrollFrame
public EnrollFrame(String title)
{
super(title);
setSize(1000,400);
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/EnrollFrame.java | 2,426 | //Φτιάχνοντας το EnrollFrame
| line_comment | el | //Δημιουργία κατηγορίας Enroll
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 EnrollFrame extends JFrame
{
//Κομμάτι δηλώσεων
private ArrayList<Enrolls> menrolls=new ArrayList<Enrolls>();
private ArrayList<Enrolls> showup=new ArrayList<Enrolls>();
private ArrayList<Enrolls> student=new ArrayList<Enrolls>();
private JButton addButton,showButton,saveButton,loadButton,removeButton,performanceButton,studentButton;
private JTextArea showArea;
public String removal,giveperformance,givenam;
int temp=0;
double avg=0;
//Προσθέτοντας Enroll
void addEnroll()
{
menrolls.add(new Enrolls());
}
//Εμφάνιση μαθητή
Enrolls findStudent(){
givenam = JOptionPane.showInputDialog("Παρακαλώ δώστε AM φοιτητή");
int cnt=0;
for(Enrolls x: menrolls) {
if(x.getam().equals(givenam)) {
student.add(x);
cnt++;
avg+=x.getgrade();
}
}
avg=avg/cnt;
return null;
}
//Εύρεση επιδόσεων
Enrolls findPerformances() {
giveperformance = JOptionPane.showInputDialog("Παρακαλώ δώστε κωδικό μαθήματος");
for(Enrolls x: menrolls) {
if(x.getkwdikos().equals(giveperformance)) {
showup.add(x);
}
}
return null;
}
//Εμφανίζοντας Enroll
void showEnroll()
{
String text="";
for(Enrolls x :menrolls)
{
text+=x+"\n";
}
showArea.setText(text);
}
//Αποθυκεύοντας Enroll
void saveEnroll()
{
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(Enrolls x:menrolls)
{
pw.println(""+x);
}
fw.close();
} catch (IOException ex) {
Logger.getLogger(EnrollFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Φορτώνοντας Enroll
void loadEnrolls()
{
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);
menrolls=new ArrayList<Enrolls>();
while(in.hasNextLine())
{
String line=in.nextLine();
String[] parts=line.split(",");
menrolls.add(new Enrolls(parts[0],parts[1],Double.parseDouble(parts[2])));
}
} catch (IOException ex)
{
}
}
}
//Διαγράφοντας μαθητή σύμφωνα με ΑΜ
void removeStudent(){
removal = JOptionPane.showInputDialog("Παρακαλώ δώστε ΑΜ φοιτητή");
//οσο ο μαθητής υπάρχει
boolean found =true;
while(found)
{
found=false;
for(int i=0;i<menrolls.size();i++)
{
if(temp==0){
if(menrolls.get(i).getam().equals(removal))
{
menrolls.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)
{
addEnroll();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΕΜΦΑΝΙΣΗ
buttonPanel.add(addButton);
showButton=new JButton("Εμφάνιση");
buttonPanel.add(showButton);
showButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
showEnroll();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΑΠΟΘΥΚΕΥΣΗ
saveButton=new JButton("Αποθύκευση");
buttonPanel.add(saveButton);
saveButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
saveEnroll();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΦΟΡΤΩΣΗ
loadButton=new JButton("Φόρτωση");
buttonPanel.add(loadButton);
loadButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
loadEnrolls();
}
});
//ΔΗΜΙΟΥΡΓΩΝΤΑΣ ΚΟΥΜΠΙ ΔΙΑΓΡΑΦΗ ΜΑΘΗΤΗ
removeButton = new JButton("Διαγραφή Μαθητή");
buttonPanel.add(removeButton);
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
removeStudent();
}
});
//ΚΟΥΜΠΙ ΕΜΦΑΝΙΣΗΣ ΕΠΙΔΟΣΕΩΝ
performanceButton = new JButton("Εμφάνιση Επιδόσεων");
buttonPanel.add(performanceButton);
performanceButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
findPerformances();
JOptionPane.showMessageDialog(null,"Βρέθηκαν επιδόσεις:"+showup);
showup.clear();
}
});
//ΚΟΥΜΠΙ ΕΜΦΑΝΙΣΗΣ ΜΑΘΗΤΗ
studentButton = new JButton("Εμφάνιση Μαθητή");
buttonPanel.add(studentButton);
studentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
findStudent();
JOptionPane.showMessageDialog(null,"Βρέθηκαν μαθητής:"+student+" και έχει μέσο όρο: "+avg);
student.clear();
}
});
add(buttonPanel);
}
//Φτ<SUF>
public EnrollFrame(String title)
{
super(title);
setSize(1000,400);
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);
}
} |
42422_0 | /**
* @author Πλέσσιας Αλέξανδρος (ΑΜ.:2025201100068).
*/
package Files;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Question1And4_1 is the implementation of question 1 and 4.1.
* Create a temp treeMap where store ONLY member's terms and tf-idf (or freq) after
* sort them and write in file ONLY first N-terms repeat the process for each member.
*/
public class Question1And4_1 {
private final File resultsFile;
private final HashMap<String, TreeMap<String, ArrayList<Float>>> allMembersDictionary;
private final int N;
// Constractor.
public Question1And4_1( int N, File resultsFile, HashMap<String, TreeMap<String, ArrayList<Float>>> allMembersDictionary) {
this.resultsFile = resultsFile;
this.allMembersDictionary = allMembersDictionary;
this.N = N;
}
public void doQuenstion1() {
try (FileWriter fw = new FileWriter(resultsFile + File.separator + "prof-description.txt")) {
fw.append(" DEP's Name: (term,tfidf) N-pairs");
fw.append(System.getProperty("line.separator"));
fw.append(System.getProperty("line.separator"));
for (Map.Entry<String, TreeMap<String, ArrayList<Float>>> wordTDocument : allMembersDictionary.entrySet()) {
TreeMap<String, ArrayList<Float>> documentTWordCount = wordTDocument.getValue();
String DEPmember = wordTDocument.getKey();
String formatedDEPmember = String.format("%13s", DEPmember);
fw.append(formatedDEPmember + ": ");
// Create temp hashtree for TERM, TF-IDF ONLY !!!
TreeMap<String, Float> memberTermAndTFIDF = new TreeMap<>();
for (Map.Entry<String, ArrayList<Float>> documentToFrequency : documentTWordCount.entrySet()) {
memberTermAndTFIDF.put(documentToFrequency.getKey(), documentToFrequency.getValue().get(2));
}
// Use list for better/easyiest use of TreeMap(TERM, TF-IDF).
List<Map.Entry<String, Float>> sortedTermAndTFIDF = new ArrayList<>(memberTermAndTFIDF.entrySet());
// Comparator by value
Collections.sort(sortedTermAndTFIDF, new Comparator<Map.Entry<String, Float>>() {
@Override
public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) {
return -(o1.getValue().compareTo(o2.getValue())); // Invert for descending order(max to min).
}
});
// Write ONLY the first N elements i.e. the most important.
for (int i = 0; i < N; i++) {
String term = sortedTermAndTFIDF.get(i).getKey();
Float tfidf = sortedTermAndTFIDF.get(i).getValue();
fw.append("(" + term + "," + tfidf + ") ");
}
fw.append(System.getProperty("line.separator"));
fw.flush(); // Clean buffer.
}
fw.close();
System.out.println("Question 1 executed !!!");
} catch (IOException ex) {
System.err.println("Could Write to: " + resultsFile + File.separator + "prof-description.txt");
ex.getMessage();
}
}
public void doQuenstion4_1() {
try (FileWriter fw = new FileWriter(resultsFile + File.separator + "prof-description-Question4.txt")) {
fw.append(" DEP's Name: (term,freq) N-pairs");
fw.append(System.getProperty("line.separator"));
fw.append(System.getProperty("line.separator"));
for (Map.Entry<String, TreeMap<String, ArrayList<Float>>> wordTDocument : allMembersDictionary.entrySet()) {
TreeMap<String, ArrayList<Float>> documentTWordCount = wordTDocument.getValue();
String DEPmember = wordTDocument.getKey();
String formatedDEPmember = String.format("%13s", DEPmember);
fw.append(formatedDEPmember + ": ");
// Create temp hashtree for TERM, FREQ ONLY !!!
TreeMap<String, Float> memberTermAndTFIDF = new TreeMap<>();
for (Map.Entry<String, ArrayList<Float>> documentToFrequency : documentTWordCount.entrySet()) {
memberTermAndTFIDF.put(documentToFrequency.getKey(), documentToFrequency.getValue().get(0));
}
// Use list for better/easyiest use of TreeMap(TERM, FREQ).
List<Map.Entry<String, Float>> sortedTermAndTFIDF = new ArrayList<>(memberTermAndTFIDF.entrySet());
// Comparator by value
Collections.sort(sortedTermAndTFIDF, new Comparator<Map.Entry<String, Float>>() {
@Override
public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) {
return -(o1.getValue().compareTo(o2.getValue())); // Invert for descending order(max to min).
}
});
// Write ONLY the first N elements i.e. the most important.
for (int i = 0; i < N; i++) {
String term = sortedTermAndTFIDF.get(i).getKey();
Float tfidf = sortedTermAndTFIDF.get(i).getValue();
fw.append("(" + term + "," + tfidf + ") ");
}
fw.append(System.getProperty("line.separator"));
fw.flush(); // Clean buffer.
}
fw.close();
System.out.println("Question 4.1 executed !!!");
} catch (IOException ex) {
System.err.println("Could Write to: " + resultsFile + File.separator + "prof-description.txt");
ex.getMessage();
}
}
}
| AlexandrosPlessias/IR-CosineSimilarity-vs-Freq | src/Files/Question1And4_1.java | 1,464 | /**
* @author Πλέσσιας Αλέξανδρος (ΑΜ.:2025201100068).
*/ | block_comment | el | /**
* @au<SUF>*/
package Files;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Question1And4_1 is the implementation of question 1 and 4.1.
* Create a temp treeMap where store ONLY member's terms and tf-idf (or freq) after
* sort them and write in file ONLY first N-terms repeat the process for each member.
*/
public class Question1And4_1 {
private final File resultsFile;
private final HashMap<String, TreeMap<String, ArrayList<Float>>> allMembersDictionary;
private final int N;
// Constractor.
public Question1And4_1( int N, File resultsFile, HashMap<String, TreeMap<String, ArrayList<Float>>> allMembersDictionary) {
this.resultsFile = resultsFile;
this.allMembersDictionary = allMembersDictionary;
this.N = N;
}
public void doQuenstion1() {
try (FileWriter fw = new FileWriter(resultsFile + File.separator + "prof-description.txt")) {
fw.append(" DEP's Name: (term,tfidf) N-pairs");
fw.append(System.getProperty("line.separator"));
fw.append(System.getProperty("line.separator"));
for (Map.Entry<String, TreeMap<String, ArrayList<Float>>> wordTDocument : allMembersDictionary.entrySet()) {
TreeMap<String, ArrayList<Float>> documentTWordCount = wordTDocument.getValue();
String DEPmember = wordTDocument.getKey();
String formatedDEPmember = String.format("%13s", DEPmember);
fw.append(formatedDEPmember + ": ");
// Create temp hashtree for TERM, TF-IDF ONLY !!!
TreeMap<String, Float> memberTermAndTFIDF = new TreeMap<>();
for (Map.Entry<String, ArrayList<Float>> documentToFrequency : documentTWordCount.entrySet()) {
memberTermAndTFIDF.put(documentToFrequency.getKey(), documentToFrequency.getValue().get(2));
}
// Use list for better/easyiest use of TreeMap(TERM, TF-IDF).
List<Map.Entry<String, Float>> sortedTermAndTFIDF = new ArrayList<>(memberTermAndTFIDF.entrySet());
// Comparator by value
Collections.sort(sortedTermAndTFIDF, new Comparator<Map.Entry<String, Float>>() {
@Override
public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) {
return -(o1.getValue().compareTo(o2.getValue())); // Invert for descending order(max to min).
}
});
// Write ONLY the first N elements i.e. the most important.
for (int i = 0; i < N; i++) {
String term = sortedTermAndTFIDF.get(i).getKey();
Float tfidf = sortedTermAndTFIDF.get(i).getValue();
fw.append("(" + term + "," + tfidf + ") ");
}
fw.append(System.getProperty("line.separator"));
fw.flush(); // Clean buffer.
}
fw.close();
System.out.println("Question 1 executed !!!");
} catch (IOException ex) {
System.err.println("Could Write to: " + resultsFile + File.separator + "prof-description.txt");
ex.getMessage();
}
}
public void doQuenstion4_1() {
try (FileWriter fw = new FileWriter(resultsFile + File.separator + "prof-description-Question4.txt")) {
fw.append(" DEP's Name: (term,freq) N-pairs");
fw.append(System.getProperty("line.separator"));
fw.append(System.getProperty("line.separator"));
for (Map.Entry<String, TreeMap<String, ArrayList<Float>>> wordTDocument : allMembersDictionary.entrySet()) {
TreeMap<String, ArrayList<Float>> documentTWordCount = wordTDocument.getValue();
String DEPmember = wordTDocument.getKey();
String formatedDEPmember = String.format("%13s", DEPmember);
fw.append(formatedDEPmember + ": ");
// Create temp hashtree for TERM, FREQ ONLY !!!
TreeMap<String, Float> memberTermAndTFIDF = new TreeMap<>();
for (Map.Entry<String, ArrayList<Float>> documentToFrequency : documentTWordCount.entrySet()) {
memberTermAndTFIDF.put(documentToFrequency.getKey(), documentToFrequency.getValue().get(0));
}
// Use list for better/easyiest use of TreeMap(TERM, FREQ).
List<Map.Entry<String, Float>> sortedTermAndTFIDF = new ArrayList<>(memberTermAndTFIDF.entrySet());
// Comparator by value
Collections.sort(sortedTermAndTFIDF, new Comparator<Map.Entry<String, Float>>() {
@Override
public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) {
return -(o1.getValue().compareTo(o2.getValue())); // Invert for descending order(max to min).
}
});
// Write ONLY the first N elements i.e. the most important.
for (int i = 0; i < N; i++) {
String term = sortedTermAndTFIDF.get(i).getKey();
Float tfidf = sortedTermAndTFIDF.get(i).getValue();
fw.append("(" + term + "," + tfidf + ") ");
}
fw.append(System.getProperty("line.separator"));
fw.flush(); // Clean buffer.
}
fw.close();
System.out.println("Question 4.1 executed !!!");
} catch (IOException ex) {
System.err.println("Could Write to: " + resultsFile + File.separator + "prof-description.txt");
ex.getMessage();
}
}
}
|
2170_4 | package gui;
/*
Η κλάση αναπαριστά μια καρτέλα με όλα τα καταλύματα που βρέθηκαν να πληρούν τα κριτήρια αναζήτησης του χρήστη
@author Anestis Zotos
*/
import api.Accommodation;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class FoundAccommodationsFrame {
private JFrame frame;
public FoundAccommodationsFrame(ArrayList<Accommodation> accommodations){
frame=new JFrame("Found Accommodations");
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);
SearchAccommodationsFrame.setVisible(true);
}
});
int i=0;
JButton[] buttons=new JButton[accommodations.size()];
JPanel[] panels=new JPanel[accommodations.size()]; //κάθε panel του πίνακα panels θα αποθηκεύει 5 συστατικα
JLabel[] label1=new JLabel[accommodations.size()];
int[] flag=new int[1]; //βοηθητική μεταβλητή(πίνακας 1 θέσης) που θα μας δείξει σε ποία θέση του arr
// βρίσκεται το accommodation που αντιστοιχεί στο κουμπί που πάτησε ο χρήστης
for(Accommodation ACC: accommodations){
buttons[i]=new JButton("Επιλογή"); //δημιουργία κουμπιών επιλογής των καταλυμάτων,κάθε κουμπί αντιστοιχεί σε ένα κατάλυμα
buttons[i].setBackground(new Color(144,144,144));
buttons[i].setBorder(new LineBorder(Color.BLACK));
buttons[i].setFont(new Font("Serif",Font.BOLD,16));
buttons[i].setActionCommand(Integer.toString(i)); //θέτω ως actioncommand του εκάστοτε κουμπιού την θέση που έχει στον πίνακα buttons
buttons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
flag[0]= Integer.parseInt(e.getActionCommand());
Accommodation acc ;
acc = accommodations.get(flag[0]);
ShowAccommodationPanel pan = new ShowAccommodationPanel(acc);
JFrame showFrame = new JFrame(acc.getName());
showFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
showFrame.setSize(1000,700);
showFrame.setResizable(false);
showFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showFrame.setVisible(false);
setVisible(true);
}
});
showFrame.add(pan.getPanel());
Toolkit t = Toolkit.getDefaultToolkit();
Dimension d = t.getScreenSize();
showFrame.setLocation((d.width - frame.getWidth()) / 2, (d.height - frame.getHeight()) / 2);
showFrame.setVisible(true);
setVisible(false);
}
});
panels[i]=new JPanel();
panels[i].setBackground(new Color(144,144,144));
panels[i].setBorder(BorderFactory.createEmptyBorder(40, 50, 40, 50));
panels[i].setLayout(new GridLayout(5,1));
label1[i]=new JLabel(ACC.getName()); //ονομα καταλύματος
label1[i].setFont(new Font("Serif",Font.BOLD,22));
panels[i].add(label1[i]);
panels[i].add(new JLabel(ACC.getType())); // τύπος καταλύματος
panels[i].add(new JLabel(ACC.getCity())); // πόλη καταλύματος
panels[i].add(new JLabel(String.valueOf(ACC.calculateAverageScore())+"/5")); //μέση βαθμολογία καταλύματος
panels[i].add(buttons[i]);
i++;
}
JPanel panel2=new JPanel();
panel2.setBackground(new Color(49,83,94));
panel2.setLayout(new FlowLayout());
for(i=0;i<accommodations.size();i++)
{
panel2.add(panels[i]);
}
frame.add(panel2);
frame.setSize(1000,700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
}
public void setVisible(boolean b) {
frame.setVisible(b);
}
}
| AnestisZotos/Accommodations-rating-platform | gui/FoundAccommodationsFrame.java | 1,401 | //δημιουργία κουμπιών επιλογής των καταλυμάτων,κάθε κουμπί αντιστοιχεί σε ένα κατάλυμα
| line_comment | el | package gui;
/*
Η κλάση αναπαριστά μια καρτέλα με όλα τα καταλύματα που βρέθηκαν να πληρούν τα κριτήρια αναζήτησης του χρήστη
@author Anestis Zotos
*/
import api.Accommodation;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class FoundAccommodationsFrame {
private JFrame frame;
public FoundAccommodationsFrame(ArrayList<Accommodation> accommodations){
frame=new JFrame("Found Accommodations");
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);
SearchAccommodationsFrame.setVisible(true);
}
});
int i=0;
JButton[] buttons=new JButton[accommodations.size()];
JPanel[] panels=new JPanel[accommodations.size()]; //κάθε panel του πίνακα panels θα αποθηκεύει 5 συστατικα
JLabel[] label1=new JLabel[accommodations.size()];
int[] flag=new int[1]; //βοηθητική μεταβλητή(πίνακας 1 θέσης) που θα μας δείξει σε ποία θέση του arr
// βρίσκεται το accommodation που αντιστοιχεί στο κουμπί που πάτησε ο χρήστης
for(Accommodation ACC: accommodations){
buttons[i]=new JButton("Επιλογή"); //δη<SUF>
buttons[i].setBackground(new Color(144,144,144));
buttons[i].setBorder(new LineBorder(Color.BLACK));
buttons[i].setFont(new Font("Serif",Font.BOLD,16));
buttons[i].setActionCommand(Integer.toString(i)); //θέτω ως actioncommand του εκάστοτε κουμπιού την θέση που έχει στον πίνακα buttons
buttons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
flag[0]= Integer.parseInt(e.getActionCommand());
Accommodation acc ;
acc = accommodations.get(flag[0]);
ShowAccommodationPanel pan = new ShowAccommodationPanel(acc);
JFrame showFrame = new JFrame(acc.getName());
showFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
showFrame.setSize(1000,700);
showFrame.setResizable(false);
showFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
showFrame.setVisible(false);
setVisible(true);
}
});
showFrame.add(pan.getPanel());
Toolkit t = Toolkit.getDefaultToolkit();
Dimension d = t.getScreenSize();
showFrame.setLocation((d.width - frame.getWidth()) / 2, (d.height - frame.getHeight()) / 2);
showFrame.setVisible(true);
setVisible(false);
}
});
panels[i]=new JPanel();
panels[i].setBackground(new Color(144,144,144));
panels[i].setBorder(BorderFactory.createEmptyBorder(40, 50, 40, 50));
panels[i].setLayout(new GridLayout(5,1));
label1[i]=new JLabel(ACC.getName()); //ονομα καταλύματος
label1[i].setFont(new Font("Serif",Font.BOLD,22));
panels[i].add(label1[i]);
panels[i].add(new JLabel(ACC.getType())); // τύπος καταλύματος
panels[i].add(new JLabel(ACC.getCity())); // πόλη καταλύματος
panels[i].add(new JLabel(String.valueOf(ACC.calculateAverageScore())+"/5")); //μέση βαθμολογία καταλύματος
panels[i].add(buttons[i]);
i++;
}
JPanel panel2=new JPanel();
panel2.setBackground(new Color(49,83,94));
panel2.setLayout(new FlowLayout());
for(i=0;i<accommodations.size();i++)
{
panel2.add(panels[i]);
}
frame.add(panel2);
frame.setSize(1000,700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
}
public void setVisible(boolean b) {
frame.setVisible(b);
}
}
|
1073_22 | /*
Όνομα: Άγγελος Τζώρτζης
Α.Μ.: ice18390094
*/
package netprog_project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BankAccountDao {
public static Connection getConnection() {
Connection conn = null;
try {
// Δημιουγρούμε σύνδεση στην βάση μας ανάλογα με ποιά βάση χρησιμοποιόυμε
// και τα στοιχεία της.
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mariadb://localhost:4306/bank", "Tzortzis", "1234");
} catch (ClassNotFoundException | SQLException ex) {
}
return conn;
}
public static int addBankAccount(BankAccount bankAccount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Με την χρήση PreparedStatement που είναι μία ασφαλής μέθοδος,
// περνάμε στην βάση μας τα στοιχεία που εισάγαμε απο το HTML αρχείο
// και δώσαμε τιμές στο αντικέιμενο μας
PreparedStatement ps = conn.prepareStatement("INSERT INTO bank_accounts(firstName, lastName, phoneNumber, email, accountBalance, active) VALUES (?, ?, ?, ?, ?, ?)");
ps.setString(1, bankAccount.getFirstName());
ps.setString(2, bankAccount.getLastName());
ps.setString(3, bankAccount.getPhoneNumber());
ps.setString(4, bankAccount.getEmail());
ps.setInt(5, bankAccount.getAccountBalance());
// Θεωρούμε ότι ο λογαριασμός όταν δημιουργείται είναι ενεργός.
ps.setBoolean(6, true);
// Εκτελούμε την εντολή της SQL.
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
// Επιστρέφουμε το status (ορίζει αν πέτυχε η εντολή μας η όχι).
return status;
}
public static int deposit(BankAccount bankAccount, int amount) {
int status = 0;
// Δημιουργία σύνδεσης ώστε να έχουμε πρόσβαση στην βάση μας.
Connection conn = BankAccountDao.getConnection();
// Προσθέτουμε στον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε.
// εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός και υπάρχει)
try {
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
public static int withdraw(BankAccount bankAccount, int amount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
// Αφαιρούμε από τον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε,
// εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός, υπάρχει, και έχει τα απαραίτητα χρήματα).
try {
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
public static int transfer(BankAccount bankAccountSend, BankAccount bankAccountReceive, int amount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Αρχικά αφαιρούμε το ποσό απο τον λογαριασμό που θέλουμε να στείλει τα χρήματα.
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccountSend.getAccountId());
status = ps.executeUpdate();
// Εφόσον πετύχει αυτή η συναλλαγή το ποσό που αφαιρέθηκε απο τον λογαριασμό το προσθέτουμε στον άλλο.
if (status != 0) {
ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccountReceive.getAccountId());
status = ps.executeUpdate();
}
conn.close();
} catch (SQLException ex) {
}
// Εάν πετύχει αυτή η συναλλαγή θα μας επιστρέψει status = 1 η συνάρτηση.
return status;
}
// Ενεργοποίηση λογαριασμόυ.
public static int activate(BankAccount bankAccount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Ενεργοποιούμε μόνο αν είναι απενεργοποιημένος.
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=true WHERE accountId=? AND active=false");
ps.setInt(1, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
// Απενεργοποίηση λογαριασμού.
public static int deactivate(BankAccount bankAccount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Απενεργοποιούμε μόνο άν είναι ενεργοποιημένος.
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=false WHERE accountId=? AND active=true");
ps.setInt(1, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
// Η παρακάτω συνάρτηση δέχεται ώς όρισμα έναν αριθμό λογαριασμού
public static BankAccount getBankAccount(int accountId) {
// Δημιουργία αντικειμένου ώστε να αποθηκεύσουμε τα στοιχεία μας.
BankAccount bankAccount = new BankAccount();
Connection conn = BankAccountDao.getConnection();
try {
// Εντολή SQL για την εμφάνιση όλων των στοιχείων της εγγραφής του αριθμού λογαριασμού.
PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts WHERE accountId=?");
ps.setInt(1, accountId);
ResultSet rs = ps.executeQuery();
// Περνάμε όλα τα στοιχεία της εγγραφής στο αντικείμενο που δημιουργήσαμε πιο πάνω.
if (rs.next()) {
bankAccount.setAccountId(rs.getInt(1));
bankAccount.setFirstName(rs.getString(2));
bankAccount.setLastName(rs.getString(3));
bankAccount.setPhoneNumber(rs.getString(4));
bankAccount.setEmail(rs.getString(5));
bankAccount.setAccountBalance(rs.getInt(6));
bankAccount.setActive(rs.getBoolean(7));
}
conn.close();
} catch (SQLException ex) {
}
return bankAccount;
}
// Eμφάνιση όλων των εγγραφών του πίνακα.
public static List<BankAccount> getAllAccounts() {
// Φτιάχνουμε αντικείμενο λίστα ώστε να αποθηκεύσουμε τον κάθε λογαριασμό.
List<BankAccount> accountList = new ArrayList<>();
Connection conn = BankAccountDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// Φτιάχνουμε αντικείμο για να περάσουμε τα στοιχεία της εγγραφής σε ένα αντικείμενο.
BankAccount bankAccount = new BankAccount();
bankAccount.setAccountId(rs.getInt(1));
bankAccount.setFirstName(rs.getString(2));
bankAccount.setLastName(rs.getString(3));
bankAccount.setPhoneNumber(rs.getString(4));
bankAccount.setEmail(rs.getString(5));
bankAccount.setAccountBalance(rs.getInt(6));
bankAccount.setActive(rs.getBoolean(7));
// Εφόσον περαστούν όλα τα στοιχεία αποθηκεύουμε το αντικείμενο στην λίστα.
accountList.add(bankAccount);
}
conn.close();
} catch (SQLException ex) {
}
return accountList;
}
public static int deleteAccount(int accountId) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Διαγραφή μίας εγγραφής της επιλογής μας.
PreparedStatement ps = conn.prepareStatement("DELETE FROM bank_accounts WHERE accountId=?");
ps.setInt(1, accountId);
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
}
| Angelos-Tzortzis/University | Netprog_Project/src/java/netprog_project/BankAccountDao.java | 3,067 | // Η παρακάτω συνάρτηση δέχεται ώς όρισμα έναν αριθμό λογαριασμού
| line_comment | el | /*
Όνομα: Άγγελος Τζώρτζης
Α.Μ.: ice18390094
*/
package netprog_project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BankAccountDao {
public static Connection getConnection() {
Connection conn = null;
try {
// Δημιουγρούμε σύνδεση στην βάση μας ανάλογα με ποιά βάση χρησιμοποιόυμε
// και τα στοιχεία της.
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mariadb://localhost:4306/bank", "Tzortzis", "1234");
} catch (ClassNotFoundException | SQLException ex) {
}
return conn;
}
public static int addBankAccount(BankAccount bankAccount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Με την χρήση PreparedStatement που είναι μία ασφαλής μέθοδος,
// περνάμε στην βάση μας τα στοιχεία που εισάγαμε απο το HTML αρχείο
// και δώσαμε τιμές στο αντικέιμενο μας
PreparedStatement ps = conn.prepareStatement("INSERT INTO bank_accounts(firstName, lastName, phoneNumber, email, accountBalance, active) VALUES (?, ?, ?, ?, ?, ?)");
ps.setString(1, bankAccount.getFirstName());
ps.setString(2, bankAccount.getLastName());
ps.setString(3, bankAccount.getPhoneNumber());
ps.setString(4, bankAccount.getEmail());
ps.setInt(5, bankAccount.getAccountBalance());
// Θεωρούμε ότι ο λογαριασμός όταν δημιουργείται είναι ενεργός.
ps.setBoolean(6, true);
// Εκτελούμε την εντολή της SQL.
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
// Επιστρέφουμε το status (ορίζει αν πέτυχε η εντολή μας η όχι).
return status;
}
public static int deposit(BankAccount bankAccount, int amount) {
int status = 0;
// Δημιουργία σύνδεσης ώστε να έχουμε πρόσβαση στην βάση μας.
Connection conn = BankAccountDao.getConnection();
// Προσθέτουμε στον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε.
// εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός και υπάρχει)
try {
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
public static int withdraw(BankAccount bankAccount, int amount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
// Αφαιρούμε από τον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε,
// εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός, υπάρχει, και έχει τα απαραίτητα χρήματα).
try {
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
public static int transfer(BankAccount bankAccountSend, BankAccount bankAccountReceive, int amount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Αρχικά αφαιρούμε το ποσό απο τον λογαριασμό που θέλουμε να στείλει τα χρήματα.
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccountSend.getAccountId());
status = ps.executeUpdate();
// Εφόσον πετύχει αυτή η συναλλαγή το ποσό που αφαιρέθηκε απο τον λογαριασμό το προσθέτουμε στον άλλο.
if (status != 0) {
ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true");
ps.setInt(1, amount);
ps.setInt(2, bankAccountReceive.getAccountId());
status = ps.executeUpdate();
}
conn.close();
} catch (SQLException ex) {
}
// Εάν πετύχει αυτή η συναλλαγή θα μας επιστρέψει status = 1 η συνάρτηση.
return status;
}
// Ενεργοποίηση λογαριασμόυ.
public static int activate(BankAccount bankAccount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Ενεργοποιούμε μόνο αν είναι απενεργοποιημένος.
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=true WHERE accountId=? AND active=false");
ps.setInt(1, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
// Απενεργοποίηση λογαριασμού.
public static int deactivate(BankAccount bankAccount) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Απενεργοποιούμε μόνο άν είναι ενεργοποιημένος.
PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=false WHERE accountId=? AND active=true");
ps.setInt(1, bankAccount.getAccountId());
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
// Η <SUF>
public static BankAccount getBankAccount(int accountId) {
// Δημιουργία αντικειμένου ώστε να αποθηκεύσουμε τα στοιχεία μας.
BankAccount bankAccount = new BankAccount();
Connection conn = BankAccountDao.getConnection();
try {
// Εντολή SQL για την εμφάνιση όλων των στοιχείων της εγγραφής του αριθμού λογαριασμού.
PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts WHERE accountId=?");
ps.setInt(1, accountId);
ResultSet rs = ps.executeQuery();
// Περνάμε όλα τα στοιχεία της εγγραφής στο αντικείμενο που δημιουργήσαμε πιο πάνω.
if (rs.next()) {
bankAccount.setAccountId(rs.getInt(1));
bankAccount.setFirstName(rs.getString(2));
bankAccount.setLastName(rs.getString(3));
bankAccount.setPhoneNumber(rs.getString(4));
bankAccount.setEmail(rs.getString(5));
bankAccount.setAccountBalance(rs.getInt(6));
bankAccount.setActive(rs.getBoolean(7));
}
conn.close();
} catch (SQLException ex) {
}
return bankAccount;
}
// Eμφάνιση όλων των εγγραφών του πίνακα.
public static List<BankAccount> getAllAccounts() {
// Φτιάχνουμε αντικείμενο λίστα ώστε να αποθηκεύσουμε τον κάθε λογαριασμό.
List<BankAccount> accountList = new ArrayList<>();
Connection conn = BankAccountDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// Φτιάχνουμε αντικείμο για να περάσουμε τα στοιχεία της εγγραφής σε ένα αντικείμενο.
BankAccount bankAccount = new BankAccount();
bankAccount.setAccountId(rs.getInt(1));
bankAccount.setFirstName(rs.getString(2));
bankAccount.setLastName(rs.getString(3));
bankAccount.setPhoneNumber(rs.getString(4));
bankAccount.setEmail(rs.getString(5));
bankAccount.setAccountBalance(rs.getInt(6));
bankAccount.setActive(rs.getBoolean(7));
// Εφόσον περαστούν όλα τα στοιχεία αποθηκεύουμε το αντικείμενο στην λίστα.
accountList.add(bankAccount);
}
conn.close();
} catch (SQLException ex) {
}
return accountList;
}
public static int deleteAccount(int accountId) {
int status = 0;
Connection conn = BankAccountDao.getConnection();
try {
// Διαγραφή μίας εγγραφής της επιλογής μας.
PreparedStatement ps = conn.prepareStatement("DELETE FROM bank_accounts WHERE accountId=?");
ps.setInt(1, accountId);
status = ps.executeUpdate();
conn.close();
} catch (SQLException ex) {
}
return status;
}
}
|
1216_6 | package gr.aueb.cf6.myJavaProjects;
import java.util.Scanner;
public class AllroundUnitConverter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int choice;
/* ΑΡΧΗ ΕΛΕΓΧΟΥ ΕΠΙΛΟΓΗΣ ΚΑΙ ΠΡΟΟΔΟΥ ΠΡΟΓΡΑΜΜΑΤΟΣ
https://www.unitconverters.net/ Length / Temp / Area / Volume / Weight / Time
TimeFromSeconds();
CurrencyConvert();
*/
}
public static void Temperature(int){
// Τ(κ) = =τ(c)+ 2731,15 & T(k)= (5 * ( valueFahrenheit - 32 ) / 9) + 273,15
Scanner Temper = new Scanner(System.in);
int valueFahrenheit = 0;
System.out.print("Δώσε την τιμή θερμοκρασίας Fahrenheit σε ακέραια μορφή: ");
valueFahrenheit = in.nextInt();
int valueCelsiou = 0;
float valueKelvin = 0.0;
final int CELSIOU_CONVERSION = 5 * (valueFahrenheit - 32) / 9;
final float KELVIN_CONVERSION = (5 * (valueFahrenheit - 32) / 9) + 273.15;
valueCelsiou = CELSIOU_CONVERSION;
valueKelvin = KELVIN_CONVERSION;
System.out.printf("\nΈδωσες την τιμή %d βαθμούς Fahrenheit που ισοδυναμεί με %d βαθμούς Κελσίου \n", valueFahrenheit, valueCelsiou);
System.out.println("\n\nΟι δοκιμές για τον έλεγχο ορθότητας του προγράμματος έγινε με την υποστήιξη της ιστοσελίδας\n https://www.metric-conversions.org/el/temperature/fahrenheit-to-celsius.htm");
System.out.printf("\nEND OF PROGRAMM Temperature \n\n");
}
public static void TimeFromSeconds() {
Scanner CalcToDate = new Scanner(System.in);
final int secs_per_Minute = 60;
final int secs_per_Hour = 60 * 60;
final int secs_per_Day = 24 * 60 * 60;
int days = 0, hours = 0, minutes = 0, totalSeconds = 0, remainingSeconds = 0;
System.out.print("\nPlease insert total seconds: ");
totalSeconds = CalcToDate.nextInt();
days = totalSeconds / secs_per_Day;
remainingSeconds = totalSeconds % secs_per_Day;
hours = remainingSeconds / secs_per_Hour;
remainingSeconds = remainingSeconds % secs_per_Hour;
minutes = remainingSeconds /secs_per_Minute;
remainingSeconds = remainingSeconds % secs_per_Minute;
System.out.printf("\nTotal Seconds given by User: %,d\nDays: %d, Hours: %02d, Minutes: %02d, Seconds: %02d\n",
totalSeconds, days, hours, minutes, remainingSeconds);
System.out.printf("\nEND OF PROGRAMM TimeFromSeconds \n\n");
}
public static void CurrencyConvert() {
Scanner giveEuros = new Scanner(System.in);
int euros = 0, dollars = 0, totalCents = 0, remainingCents = 0, lr = 0, fr = 0, yien = 0;
final int US_PARITY = 99;
final int LR_PARITY = 99;
final int YIEN_PARITY = 99;
final int FR_PARITY = 99;
System.out.print("\nPLease insert the amount in Euros: ");
// εδω θα ενημερωσουμε το συστημα οτι θα δεχτει απο χρηστη δεδομένα
euros = giveEuros.nextInt();
totalCents = euros * US_PARITY; /* για να δουμε ποσα δολαρια ειναι */
totalLires = euros * LR_PARITY; /* για να δουμε ποσα δολαρια ειναι */
totalYien = euros * YIEN_PARITY; /* για να δουμε ποσα δολαρια ειναι */
totalFrago = euros * FR_PARITY; /* για να δουμε ποσα δολαρια ειναι */
dollars = totalCents / 100;
lr = totalLires / 100;
yien = totalYien / 100;
fr = totalFrago / 100;
remainingCents = dollars % 100;
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalCents, dollars, remainingCents);
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalLires, lr, remainingCents);
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalYien, yien, remainingCents);
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalFrago, fr, remainingCents);
System.out.printf("\nEND OF PROGRAMM CURRENCY \n\n");
}
}
| AntoniouIoannis/new-demo | AllroundUnitConverter.java | 1,628 | /* για να δουμε ποσα δολαρια ειναι */ | block_comment | el | package gr.aueb.cf6.myJavaProjects;
import java.util.Scanner;
public class AllroundUnitConverter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int choice;
/* ΑΡΧΗ ΕΛΕΓΧΟΥ ΕΠΙΛΟΓΗΣ ΚΑΙ ΠΡΟΟΔΟΥ ΠΡΟΓΡΑΜΜΑΤΟΣ
https://www.unitconverters.net/ Length / Temp / Area / Volume / Weight / Time
TimeFromSeconds();
CurrencyConvert();
*/
}
public static void Temperature(int){
// Τ(κ) = =τ(c)+ 2731,15 & T(k)= (5 * ( valueFahrenheit - 32 ) / 9) + 273,15
Scanner Temper = new Scanner(System.in);
int valueFahrenheit = 0;
System.out.print("Δώσε την τιμή θερμοκρασίας Fahrenheit σε ακέραια μορφή: ");
valueFahrenheit = in.nextInt();
int valueCelsiou = 0;
float valueKelvin = 0.0;
final int CELSIOU_CONVERSION = 5 * (valueFahrenheit - 32) / 9;
final float KELVIN_CONVERSION = (5 * (valueFahrenheit - 32) / 9) + 273.15;
valueCelsiou = CELSIOU_CONVERSION;
valueKelvin = KELVIN_CONVERSION;
System.out.printf("\nΈδωσες την τιμή %d βαθμούς Fahrenheit που ισοδυναμεί με %d βαθμούς Κελσίου \n", valueFahrenheit, valueCelsiou);
System.out.println("\n\nΟι δοκιμές για τον έλεγχο ορθότητας του προγράμματος έγινε με την υποστήιξη της ιστοσελίδας\n https://www.metric-conversions.org/el/temperature/fahrenheit-to-celsius.htm");
System.out.printf("\nEND OF PROGRAMM Temperature \n\n");
}
public static void TimeFromSeconds() {
Scanner CalcToDate = new Scanner(System.in);
final int secs_per_Minute = 60;
final int secs_per_Hour = 60 * 60;
final int secs_per_Day = 24 * 60 * 60;
int days = 0, hours = 0, minutes = 0, totalSeconds = 0, remainingSeconds = 0;
System.out.print("\nPlease insert total seconds: ");
totalSeconds = CalcToDate.nextInt();
days = totalSeconds / secs_per_Day;
remainingSeconds = totalSeconds % secs_per_Day;
hours = remainingSeconds / secs_per_Hour;
remainingSeconds = remainingSeconds % secs_per_Hour;
minutes = remainingSeconds /secs_per_Minute;
remainingSeconds = remainingSeconds % secs_per_Minute;
System.out.printf("\nTotal Seconds given by User: %,d\nDays: %d, Hours: %02d, Minutes: %02d, Seconds: %02d\n",
totalSeconds, days, hours, minutes, remainingSeconds);
System.out.printf("\nEND OF PROGRAMM TimeFromSeconds \n\n");
}
public static void CurrencyConvert() {
Scanner giveEuros = new Scanner(System.in);
int euros = 0, dollars = 0, totalCents = 0, remainingCents = 0, lr = 0, fr = 0, yien = 0;
final int US_PARITY = 99;
final int LR_PARITY = 99;
final int YIEN_PARITY = 99;
final int FR_PARITY = 99;
System.out.print("\nPLease insert the amount in Euros: ");
// εδω θα ενημερωσουμε το συστημα οτι θα δεχτει απο χρηστη δεδομένα
euros = giveEuros.nextInt();
totalCents = euros * US_PARITY; /* για να δουμε ποσα δολαρια ειναι */
totalLires = euros * LR_PARITY; /* για να δουμε ποσα δολαρια ειναι */
totalYien = euros * YIEN_PARITY; /* για<SUF>*/
totalFrago = euros * FR_PARITY; /* για να δουμε ποσα δολαρια ειναι */
dollars = totalCents / 100;
lr = totalLires / 100;
yien = totalYien / 100;
fr = totalFrago / 100;
remainingCents = dollars % 100;
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalCents, dollars, remainingCents);
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalLires, lr, remainingCents);
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalYien, yien, remainingCents);
System.out.printf("\n%,d euros = %,d total Cents\n%,d dollars and %d cents \n\n", euros, totalFrago, fr, remainingCents);
System.out.printf("\nEND OF PROGRAMM CURRENCY \n\n");
}
}
|
7411_0 | /*Αντιστοιχεί στον οργανισμό που υποστηρίζει το σύστημα donation.*/
import java.util.ArrayList;
class Organization
{
private String name;
private Admin admin;
private ArrayList<Entity> entityList = new ArrayList<Entity>();
private ArrayList<Donator> donatorList = new ArrayList<Donator>();
private ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>();
private RequestDonationList currentDonations = new RequestDonationList();
Organization(){}
Organization(String name) {
this.name = name;
ArrayList<Entity> entityList = new ArrayList<Entity>();
ArrayList<Donator> donatorList = new ArrayList<Donator>();
ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>();
RequestDonationList currentDonations = new RequestDonationList();
}
public ArrayList<Donator> getDonatorsArrayList() {
return donatorList;
}
public ArrayList<Beneficiary> getBeneficiaryArrayList() {
return beneficiaryList;
}
public void setBeneficiaryList(ArrayList<Beneficiary> beneficiaryList) {
this.beneficiaryList = beneficiaryList;
}
void setAdmin(Admin new_admin) {
admin = new_admin;
}
Admin getAdmin() {
return admin;
}
public RequestDonationList getCurrentDonations() {
return currentDonations;
}
public String getName() {
return name;
}
public void addEntity(Entity new_entity) {
entityList.add(new_entity);
}
public void removeEntity(Entity removed_entity) {
entityList.remove(removed_entity);
}
public void insertDonator(Donator new_donator) {
donatorList.add(new_donator);
}
public void removeDonator(Donator removed_donator) {
donatorList.clear();
}
public void insertBeneficiary(Beneficiary new_beneficiary) {
beneficiaryList.add(new_beneficiary);
}
public void removeBeneficiary(int choice) {
int cnt=0;
for (int i = 0; i < beneficiaryList.size(); i++) {
if((choice-1) == i) {
beneficiaryList.remove(choice-1);
cnt++;
System.out.println("Beneficiary has been deleted!");
}
}
if(cnt==0){
System.out.println("Beneficiary " + name + " not found!"); }
}
public void removeBeneficiaryReceivedList(int choice) {
for (int i = 0; i < beneficiaryList.size(); i++) {
if((choice-1) == i) {
beneficiaryList.get(choice-1).clearRecievedList();
System.out.println("Beneficiary's received list cleared");
}
}
}
public void removeCurrentDonation(int id,double quantity) {
for(RequestDonation index : currentDonations.rdEntities ) {
if(id == index.getEntity().getId()) {
index.setQuantity(index.getQuantity()-quantity);
}
}
}
public void clearBeneficiaryRequests () {
for(Beneficiary index : beneficiaryList) {
index.clearRecievedList();
}
}
//------------------------------------------------------------------LISTING
void listEntities() {
System.out.println("<This is the list of "+ getName() +" Entities>");
System.out.println();
for (Entity index : entityList) {
System.out.println(index.toString());
System.out.println();
}
}
void listBeneficiaries() {
int cnt = 0;
System.out.println("<This is the list of "+ getName() +" Beneficiaries>");
System.out.println();
for (Beneficiary index : beneficiaryList) {
System.out.println(++cnt);
index.viewBeneficiaryDetails();
}
}
void listDonators() {
System.out.println("<This is the list of "+ getName() +" Donators>");
System.out.println();
for (Donator index : donatorList) {
index.viewDonatorDetails();
}
}
void listCurrentDonations() {
System.out.println("<This is the list of "+ getName() +" Current Donations>");
System.out.println();
currentDonations.monitor();
}
void listMaterials() {
int cnt=0;
System.out.println("<This is the list of " + getName() + " Materials>");
System.out.println();
for (Entity index : entityList) {
if (index.getIsMaterial())
System.out.println(++cnt + ". " + index.toString());
System.out.println();
}
}
void listServices() {
int cnt=0;
System.out.println("<This is the list of " + getName() + " Services>");
System.out.println();
for (Entity index : entityList) {
if (!(index.getIsMaterial()))
System.out.println(++cnt + ". " + index.toString());
System.out.println();
}
}
} | Antonis01/OOP_Team_Project_2020-2021 | src/Organisation.java | 1,187 | /*Αντιστοιχεί στον οργανισμό που υποστηρίζει το σύστημα donation.*/ | block_comment | el | /*Αντ<SUF>*/
import java.util.ArrayList;
class Organization
{
private String name;
private Admin admin;
private ArrayList<Entity> entityList = new ArrayList<Entity>();
private ArrayList<Donator> donatorList = new ArrayList<Donator>();
private ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>();
private RequestDonationList currentDonations = new RequestDonationList();
Organization(){}
Organization(String name) {
this.name = name;
ArrayList<Entity> entityList = new ArrayList<Entity>();
ArrayList<Donator> donatorList = new ArrayList<Donator>();
ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>();
RequestDonationList currentDonations = new RequestDonationList();
}
public ArrayList<Donator> getDonatorsArrayList() {
return donatorList;
}
public ArrayList<Beneficiary> getBeneficiaryArrayList() {
return beneficiaryList;
}
public void setBeneficiaryList(ArrayList<Beneficiary> beneficiaryList) {
this.beneficiaryList = beneficiaryList;
}
void setAdmin(Admin new_admin) {
admin = new_admin;
}
Admin getAdmin() {
return admin;
}
public RequestDonationList getCurrentDonations() {
return currentDonations;
}
public String getName() {
return name;
}
public void addEntity(Entity new_entity) {
entityList.add(new_entity);
}
public void removeEntity(Entity removed_entity) {
entityList.remove(removed_entity);
}
public void insertDonator(Donator new_donator) {
donatorList.add(new_donator);
}
public void removeDonator(Donator removed_donator) {
donatorList.clear();
}
public void insertBeneficiary(Beneficiary new_beneficiary) {
beneficiaryList.add(new_beneficiary);
}
public void removeBeneficiary(int choice) {
int cnt=0;
for (int i = 0; i < beneficiaryList.size(); i++) {
if((choice-1) == i) {
beneficiaryList.remove(choice-1);
cnt++;
System.out.println("Beneficiary has been deleted!");
}
}
if(cnt==0){
System.out.println("Beneficiary " + name + " not found!"); }
}
public void removeBeneficiaryReceivedList(int choice) {
for (int i = 0; i < beneficiaryList.size(); i++) {
if((choice-1) == i) {
beneficiaryList.get(choice-1).clearRecievedList();
System.out.println("Beneficiary's received list cleared");
}
}
}
public void removeCurrentDonation(int id,double quantity) {
for(RequestDonation index : currentDonations.rdEntities ) {
if(id == index.getEntity().getId()) {
index.setQuantity(index.getQuantity()-quantity);
}
}
}
public void clearBeneficiaryRequests () {
for(Beneficiary index : beneficiaryList) {
index.clearRecievedList();
}
}
//------------------------------------------------------------------LISTING
void listEntities() {
System.out.println("<This is the list of "+ getName() +" Entities>");
System.out.println();
for (Entity index : entityList) {
System.out.println(index.toString());
System.out.println();
}
}
void listBeneficiaries() {
int cnt = 0;
System.out.println("<This is the list of "+ getName() +" Beneficiaries>");
System.out.println();
for (Beneficiary index : beneficiaryList) {
System.out.println(++cnt);
index.viewBeneficiaryDetails();
}
}
void listDonators() {
System.out.println("<This is the list of "+ getName() +" Donators>");
System.out.println();
for (Donator index : donatorList) {
index.viewDonatorDetails();
}
}
void listCurrentDonations() {
System.out.println("<This is the list of "+ getName() +" Current Donations>");
System.out.println();
currentDonations.monitor();
}
void listMaterials() {
int cnt=0;
System.out.println("<This is the list of " + getName() + " Materials>");
System.out.println();
for (Entity index : entityList) {
if (index.getIsMaterial())
System.out.println(++cnt + ". " + index.toString());
System.out.println();
}
}
void listServices() {
int cnt=0;
System.out.println("<This is the list of " + getName() + " Services>");
System.out.println();
for (Entity index : entityList) {
if (!(index.getIsMaterial()))
System.out.println(++cnt + ". " + index.toString());
System.out.println();
}
}
} |
7770_1 | package gr.uop.gav.mailerdaemon.util;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;
import javax.naming.directory.InitialDirContext;
import java.util.Arrays;
import java.util.Comparator;
public class WebUtil {
public static MXRecord[] resolveMxRecords(String domain) {
MXRecord[] records = new MXRecord[]{};
try {
/*
Σύμφωνα με το RFC5321, δίνουμε προτεραιότητα στα mx records με την μικρότερο αριθμό "προτίμησης"
περισσότερες πληροφορίες https://en.wikipedia.org/wiki/MX_record
*/
Lookup lookup = new Lookup(domain, Type.MX);
Record[] mxRecords = lookup.run();
// Θα κάνουμε sort to records array με αύξουσα σειρά
Arrays.sort(mxRecords, Comparator.comparingInt(record -> ((MXRecord) record).getPriority()));
records = new MXRecord[mxRecords.length];
for(int i = 0; i < mxRecords.length; i++) {
records[i] = (MXRecord) mxRecords[i];
}
return records;
} catch (Exception ex) {
ex.printStackTrace();
return records;
}
}
}
| Arisstath/GAVLab---Email | MailerDaemon/src/main/java/gr/uop/gav/mailerdaemon/util/WebUtil.java | 393 | // Θα κάνουμε sort to records array με αύξουσα σειρά | line_comment | el | package gr.uop.gav.mailerdaemon.util;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;
import javax.naming.directory.InitialDirContext;
import java.util.Arrays;
import java.util.Comparator;
public class WebUtil {
public static MXRecord[] resolveMxRecords(String domain) {
MXRecord[] records = new MXRecord[]{};
try {
/*
Σύμφωνα με το RFC5321, δίνουμε προτεραιότητα στα mx records με την μικρότερο αριθμό "προτίμησης"
περισσότερες πληροφορίες https://en.wikipedia.org/wiki/MX_record
*/
Lookup lookup = new Lookup(domain, Type.MX);
Record[] mxRecords = lookup.run();
// Θα<SUF>
Arrays.sort(mxRecords, Comparator.comparingInt(record -> ((MXRecord) record).getPriority()));
records = new MXRecord[mxRecords.length];
for(int i = 0; i < mxRecords.length; i++) {
records[i] = (MXRecord) mxRecords[i];
}
return records;
} catch (Exception ex) {
ex.printStackTrace();
return records;
}
}
}
|
3664_11 | package com.RapidPharma;
import java.util.*;
import java.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.swing.*;
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.RapidPharma.lista_aitima;
public class Dromologhths extends xristis{
//Επιστρέφονται όλα τα αιτήματα που αφορουν το δρομολογητη
public static ObservableList<Aitima> getaitimata(String ID_DROMOLOGITI) {
private static Statement statement;
aitimata = FXCollections.observableArrayList();
try {
statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement();
ResultSet myRs = statement.executeQuery("select * from Aitima inner join xristis a on ID_dromologiti=a.id where a.id=" + ID_DROMOLOGITI + ";");
if (myRs != null)
while (myRs.next()) {
Aitima aitima_1 = new Aitima();
aitima_1.setid(myRs.getInt(1));
aitima_1.setImerominia(myRs.getInt(2));
aitima_1.setApo_Topothesia(myRs.getString(3));
aitima_1.setPros_Topothesia(myRs.getString(4));
aitima_1.setEidos_Metaforas(myRs.getString(5));
aitima_1.setRequired_Europaletes(myRs.getInt(6));
aitima_1.setstatus(myRs.getInt(7));
aitimata.add(aitima_1);
}
} catch (Exception e) {
e.printStackTrace();
}
return aitimata;
}
public static void Diaxirisi_insert(String id_aitimatos,String id_dromologiti){
Aitima aitima = new Aitima();
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root");
Statement myStmt = myConn.createStatement();
Scanner scanner = new Scanner(System.in);
System.out.println("Εισαγωγή ευροπαλετών:");
int europaletes = scanner.nextInt();
System.out.println("Εισαγωγή ημερομηνίας:");
String imerominia = scanner.nextLine();
ResultSet myRs = myStmt.executeQuery("select sunolo_paletwn from Aitima where id_aitimatos="+id_aitimatos);
anakateuthinsi_CheckBox = new javax.swing.JCheckBox();//checkbox που επιλέγει ο χρήστης ανακατατεύθυνση
boolean checked = anakateuthinsi_CheckBox.getState();
if (anakateuthinsi_CheckBox.getState()) {
System.out.println("Δώσε την περιγραφή του αιτήματος που ανακατευθύνεται:");
String Perigrafi_anakateuthinomenou = scanner.next();
if(Perigrafi_anakateuthinomenou!=null){ //εαν δηλαδή θέλω να ανακατευθύνω ένα τμήμα του αιτήματος
System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:");//αυτό θα αντικατασταθεί απο το GUI
String Aitiologia = scanner.nextLine();
System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:");
int allagi_kwdikou = scanner.nextInt();
ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set perigrafh="+Perigrafi_anakateuthinomenou+" where id_aitimatos=" + id_aitimatos);
aitima.Update_status(id_aitimatos,1);
aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti);
System.out.println("Δώσε το ID του νέου αιτήματος:");
String ID_new_Aitimatos = scanner.next();
System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:");
String Perigrafi_dromologimenou = scanner.next();
ResultSet myRs_2 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos);
String Apo = myRs_2.getString("apo");
String Pros = myRs_2.getString("pros");
String Eidos_metaforas = myRs_2.getString("eidos_metaforas");
Date Imerominia_dhmiourgias = myRs_2.getDate("imerominia_dhmiourgias");
Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou");
int Sunolo_paletwn = myRs_2.getInt("sunolo_paletwn");
int Status = myRs_2.getInt("status");
Boolean Inroute = myRs_2.getBoolean("inroute");
int Route_id = myRs_2.getInt("route_id");
String Id_dimiourgou = myRs_2.getString("ID_dimiourgou");
String Id_dromologiti = myRs_2.getString("ID_dromologiti");
//Το κομμάτι του αιτήματος που θα δρομολογεί τώρα (αυτό που μένει και δεν ανακατευθύνθηκε)
//Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν ανακατευθυνθεί) ,id_aitimatos(το οποίο είναι
// το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δρομολογεί τώρα)
ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_dromologimenou+
",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+
",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti);
ResultSet myRs_4 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + ID_new_Aitimatos);
aitima.Update_status(ID_new_Aitimatos,1);
}else {
System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:");
String Aitiologia = scanner.nextLine();
System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:");
int allagi_kwdikou = scanner.nextInt();
aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti);
}
} else {
if (europaletes==myRs.getInt("sunolo_paletwn")) {
ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + id_aitimatos);
aitima.Update_status(id_aitimatos,1);
}
if (europaletes<myRs.getInt("sunolo_paletwn")){
//Το κομμάτι του αιτήματος που δρομολογείται τωρα
System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:");
String Perigrafi_old = scanner.next();
ResultSet myRs_2 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou="+imerominia+", perigrafh="+Perigrafi_old+" where id_aitimatos=" + id_aitimatos);
aitima.Update_status(id_aitimatos,1);
System.out.println("Δώσε το ID του νέου αιτήματος:");
String ID_new_Aitimatos = scanner.next();
System.out.println("Δώσε την περιγραφή του νέου αιτήματος:");
String Perigrafi_new = scanner.next();
ResultSet myRs_1 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos);
String Apo = myRs_1.getString("apo");
String Pros = myRs_1.getString("pros");
String Eidos_metaforas = myRs_1.getString("eidos_metaforas");
Date Imerominia_dhmiourgias = myRs_1.getDate("imerominia_dhmiourgias");
Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou");
int Sunolo_paletwn = myRs_1.getInt("sunolo_paletwn");
int Status = myRs_1.getInt("status");
String Aitiologia = myRs_1.getString("aitiologia");
Boolean Inroute = myRs_1.getBoolean("inroute");
int Route_id = myRs_1.getInt("route_id");
String Id_dimiourgou = myRs_1.getString("ID_dimiourgou");
String Id_dromologiti = myRs_1.getString("ID_dromologiti");
//Το κομμάτι του αιτήματος που θα δρομολογηθεί αργότερα
//Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν δρομολογηθεί) ,id_aitimatos(το οποίο είναι
// το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δε δρομολογείται τώρα)
ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_new+
",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+
",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti);
aitima.Update_status(ID_new_Aitimatos,4);
}
}
}
catch(Exception exc) {
exc.printStackTrace();
}
}
}
| Asbaharoon/java-project | java_src/dromologhths.java | 3,551 | //Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν δρομολογηθεί) ,id_aitimatos(το οποίο είναι
| line_comment | el | package com.RapidPharma;
import java.util.*;
import java.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.swing.*;
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.RapidPharma.lista_aitima;
public class Dromologhths extends xristis{
//Επιστρέφονται όλα τα αιτήματα που αφορουν το δρομολογητη
public static ObservableList<Aitima> getaitimata(String ID_DROMOLOGITI) {
private static Statement statement;
aitimata = FXCollections.observableArrayList();
try {
statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement();
ResultSet myRs = statement.executeQuery("select * from Aitima inner join xristis a on ID_dromologiti=a.id where a.id=" + ID_DROMOLOGITI + ";");
if (myRs != null)
while (myRs.next()) {
Aitima aitima_1 = new Aitima();
aitima_1.setid(myRs.getInt(1));
aitima_1.setImerominia(myRs.getInt(2));
aitima_1.setApo_Topothesia(myRs.getString(3));
aitima_1.setPros_Topothesia(myRs.getString(4));
aitima_1.setEidos_Metaforas(myRs.getString(5));
aitima_1.setRequired_Europaletes(myRs.getInt(6));
aitima_1.setstatus(myRs.getInt(7));
aitimata.add(aitima_1);
}
} catch (Exception e) {
e.printStackTrace();
}
return aitimata;
}
public static void Diaxirisi_insert(String id_aitimatos,String id_dromologiti){
Aitima aitima = new Aitima();
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root");
Statement myStmt = myConn.createStatement();
Scanner scanner = new Scanner(System.in);
System.out.println("Εισαγωγή ευροπαλετών:");
int europaletes = scanner.nextInt();
System.out.println("Εισαγωγή ημερομηνίας:");
String imerominia = scanner.nextLine();
ResultSet myRs = myStmt.executeQuery("select sunolo_paletwn from Aitima where id_aitimatos="+id_aitimatos);
anakateuthinsi_CheckBox = new javax.swing.JCheckBox();//checkbox που επιλέγει ο χρήστης ανακατατεύθυνση
boolean checked = anakateuthinsi_CheckBox.getState();
if (anakateuthinsi_CheckBox.getState()) {
System.out.println("Δώσε την περιγραφή του αιτήματος που ανακατευθύνεται:");
String Perigrafi_anakateuthinomenou = scanner.next();
if(Perigrafi_anakateuthinomenou!=null){ //εαν δηλαδή θέλω να ανακατευθύνω ένα τμήμα του αιτήματος
System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:");//αυτό θα αντικατασταθεί απο το GUI
String Aitiologia = scanner.nextLine();
System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:");
int allagi_kwdikou = scanner.nextInt();
ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set perigrafh="+Perigrafi_anakateuthinomenou+" where id_aitimatos=" + id_aitimatos);
aitima.Update_status(id_aitimatos,1);
aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti);
System.out.println("Δώσε το ID του νέου αιτήματος:");
String ID_new_Aitimatos = scanner.next();
System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:");
String Perigrafi_dromologimenou = scanner.next();
ResultSet myRs_2 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos);
String Apo = myRs_2.getString("apo");
String Pros = myRs_2.getString("pros");
String Eidos_metaforas = myRs_2.getString("eidos_metaforas");
Date Imerominia_dhmiourgias = myRs_2.getDate("imerominia_dhmiourgias");
Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou");
int Sunolo_paletwn = myRs_2.getInt("sunolo_paletwn");
int Status = myRs_2.getInt("status");
Boolean Inroute = myRs_2.getBoolean("inroute");
int Route_id = myRs_2.getInt("route_id");
String Id_dimiourgou = myRs_2.getString("ID_dimiourgou");
String Id_dromologiti = myRs_2.getString("ID_dromologiti");
//Το κομμάτι του αιτήματος που θα δρομολογεί τώρα (αυτό που μένει και δεν ανακατευθύνθηκε)
//Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν ανακατευθυνθεί) ,id_aitimatos(το οποίο είναι
// το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δρομολογεί τώρα)
ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_dromologimenou+
",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+
",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti);
ResultSet myRs_4 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + ID_new_Aitimatos);
aitima.Update_status(ID_new_Aitimatos,1);
}else {
System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:");
String Aitiologia = scanner.nextLine();
System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:");
int allagi_kwdikou = scanner.nextInt();
aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti);
}
} else {
if (europaletes==myRs.getInt("sunolo_paletwn")) {
ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + id_aitimatos);
aitima.Update_status(id_aitimatos,1);
}
if (europaletes<myRs.getInt("sunolo_paletwn")){
//Το κομμάτι του αιτήματος που δρομολογείται τωρα
System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:");
String Perigrafi_old = scanner.next();
ResultSet myRs_2 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou="+imerominia+", perigrafh="+Perigrafi_old+" where id_aitimatos=" + id_aitimatos);
aitima.Update_status(id_aitimatos,1);
System.out.println("Δώσε το ID του νέου αιτήματος:");
String ID_new_Aitimatos = scanner.next();
System.out.println("Δώσε την περιγραφή του νέου αιτήματος:");
String Perigrafi_new = scanner.next();
ResultSet myRs_1 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos);
String Apo = myRs_1.getString("apo");
String Pros = myRs_1.getString("pros");
String Eidos_metaforas = myRs_1.getString("eidos_metaforas");
Date Imerominia_dhmiourgias = myRs_1.getDate("imerominia_dhmiourgias");
Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou");
int Sunolo_paletwn = myRs_1.getInt("sunolo_paletwn");
int Status = myRs_1.getInt("status");
String Aitiologia = myRs_1.getString("aitiologia");
Boolean Inroute = myRs_1.getBoolean("inroute");
int Route_id = myRs_1.getInt("route_id");
String Id_dimiourgou = myRs_1.getString("ID_dimiourgou");
String Id_dromologiti = myRs_1.getString("ID_dromologiti");
//Το κομμάτι του αιτήματος που θα δρομολογηθεί αργότερα
//Εδ<SUF>
// το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δε δρομολογείται τώρα)
ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_new+
",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+
",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti);
aitima.Update_status(ID_new_Aitimatos,4);
}
}
}
catch(Exception exc) {
exc.printStackTrace();
}
}
}
|
16571_1 | import java.util.Date;
import java.text.*;
//import MyDateLib.java;
public class Foititis {
private static int auxwnArithmos = 0;
private String AM;
private String onomatEpwnymo;
private Date hmeromGennisis;
public Foititis(int etos, String onomatEpwnymo, Date hmeromGennisis) {
auxwnArithmos+=1;
// Δημιουργία αριθμού 3 ψηφίων
DecimalFormat myFormatter = new DecimalFormat("000");
String tempArithm = myFormatter.format(auxwnArithmos);
this.AM= (etos + tempArithm);
this.onomatEpwnymo = onomatEpwnymo;
this.hmeromGennisis = hmeromGennisis;
}
public String toString() {
StringBuffer sb = new StringBuffer(this.AM + " ");
sb.append(this.onomatEpwnymo + " ");
sb.append(dateToStr(this.hmeromGennisis));
return sb.toString();
}
private String dateToStr(Date hmeromGennisis) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String str = df.format(this.hmeromGennisis);
return str;
}
String getAM()
{
return this.AM;
}
String getOnEp()
{
return this.onomatEpwnymo;
}
Date getHmerom()
{
return this.hmeromGennisis;
}
public void setHmerom(Date hmerom)
{
this.hmeromGennisis=hmerom;
}
public void setOnEp(String OnEp)
{
this.onomatEpwnymo=OnEp;
}
}
| Astodialo/A23 | Foititis.java | 458 | // Δημιουργία αριθμού 3 ψηφίων
| line_comment | el | import java.util.Date;
import java.text.*;
//import MyDateLib.java;
public class Foititis {
private static int auxwnArithmos = 0;
private String AM;
private String onomatEpwnymo;
private Date hmeromGennisis;
public Foititis(int etos, String onomatEpwnymo, Date hmeromGennisis) {
auxwnArithmos+=1;
// Δη<SUF>
DecimalFormat myFormatter = new DecimalFormat("000");
String tempArithm = myFormatter.format(auxwnArithmos);
this.AM= (etos + tempArithm);
this.onomatEpwnymo = onomatEpwnymo;
this.hmeromGennisis = hmeromGennisis;
}
public String toString() {
StringBuffer sb = new StringBuffer(this.AM + " ");
sb.append(this.onomatEpwnymo + " ");
sb.append(dateToStr(this.hmeromGennisis));
return sb.toString();
}
private String dateToStr(Date hmeromGennisis) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String str = df.format(this.hmeromGennisis);
return str;
}
String getAM()
{
return this.AM;
}
String getOnEp()
{
return this.onomatEpwnymo;
}
Date getHmerom()
{
return this.hmeromGennisis;
}
public void setHmerom(Date hmerom)
{
this.hmeromGennisis=hmerom;
}
public void setOnEp(String OnEp)
{
this.onomatEpwnymo=OnEp;
}
}
|
30042_5 | package org.hua.dit.oopii_21950_219113.Controller;
import org.hua.dit.oopii_21950_219113.Dao.CityRepository;
import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchCityException;
import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchOpenWeatherCityException;
import org.hua.dit.oopii_21950_219113.Service.CityService;
import org.hua.dit.oopii_21950_219113.Service.TravellersService;
import org.hua.dit.oopii_21950_219113.entitys.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Here in the future we will have the main functionality of the web app, for now we hard coded most of it for the 1st
* deliverable's sake.
*/
//@CrossOrigin(origins= "http://localhost:3000")
@CrossOrigin("*")
@RestController
@RequestMapping(path = "/") //Because we are hard coding data every time we will be showing stats for the same traveller.
public class TravellersController {
/*
NOT RECOMENED BY SPRING, for the purposes of this project we can ignore that because this helps us, as a small team
write and test code faster, also it is an automation which makes the Dependency injection real easy to understand.
*/
@Autowired
private final TravellersService travellersService;
private final CityRepository cityRepository;
/**
*
* @param travellersService initialize the class object with a given TravellerService
* @param cityRepository
*/
public TravellersController(TravellersService travellersService, CityRepository cityRepository) {
this.travellersService = travellersService;
this.cityRepository=cityRepository;
}
@GetMapping(path = "/travellers")
public ArrayList<Traveller> getAllTravellers() throws InterruptedException {
return travellersService.getAllTravellers();
}
@GetMapping( path = "{name}/bestCity")
public City findBestCityForTheUser(@PathVariable("name")String name) throws InterruptedException {
return travellersService.findBestCityForTheUser(name);
}
@GetMapping( path = "{name}/bestCity/collaborate")
public City findBestCityCollaborating(@PathVariable("name")String name) throws InterruptedException {
return travellersService.findBestCityCollaborating(name);
}
@GetMapping(path = "{cityName}/{country}/search")
public City checkCity(@PathVariable("cityName")String cityName,@PathVariable("country")String country){
try {
return travellersService.searchCity(cityName,country);
}catch (NoSuchCityException | InterruptedException e)
{
System.out.println("There is no city with this name!");
e.printStackTrace();
}
return null;
}
@PostMapping( path = "/addYoungTraveller")
public String addNewTraveller(@RequestBody YoungTraveller traveller) throws IOException, InterruptedException {
return travellersService.addNewTraveller(traveller);
}
@PostMapping( path = "/addMiddleTraveller")
public String addNewTraveller(@RequestBody MiddleTraveller traveller) throws IOException, InterruptedException {
return travellersService.addNewTraveller(traveller);
}
@PostMapping( path = "/addElderTraveller")
public String addNewTraveller(@RequestBody ElderTraveller traveller) throws IOException, InterruptedException {
return travellersService.addNewTraveller(traveller);
}
//TODO: για το free ticket θα βαλουμε ενα switch case για του 12 μηνες του χρονου και καθε μηνα θα εχουμε διαφορερικη πολη για free ticket (αυτο θα γινετε στο frontend)
@GetMapping( path = "{cityName}/{country}/freeTicket")
public Traveller findFreeTicket(@PathVariable("cityName") String FreeCityName , @PathVariable("country") String FreeCountry) throws NoSuchCityException, InterruptedException {
return travellersService.findFreeTicket(FreeCityName,FreeCountry);
}
@GetMapping(path = "{name}/{number}/bestCity" )
public ArrayList<City> findXBestCities(@PathVariable String name, @PathVariable Integer number) throws InterruptedException {
return travellersService.findXBestCities(name,number);
}
}
| Athanasioschourlias/Travellers-recomendation-App | src/main/java/org/hua/dit/oopii_21950_219113/Controller/TravellersController.java | 1,189 | //TODO: για το free ticket θα βαλουμε ενα switch case για του 12 μηνες του χρονου και καθε μηνα θα εχουμε διαφορερικη πολη για free ticket (αυτο θα γινετε στο frontend) | line_comment | el | package org.hua.dit.oopii_21950_219113.Controller;
import org.hua.dit.oopii_21950_219113.Dao.CityRepository;
import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchCityException;
import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchOpenWeatherCityException;
import org.hua.dit.oopii_21950_219113.Service.CityService;
import org.hua.dit.oopii_21950_219113.Service.TravellersService;
import org.hua.dit.oopii_21950_219113.entitys.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Here in the future we will have the main functionality of the web app, for now we hard coded most of it for the 1st
* deliverable's sake.
*/
//@CrossOrigin(origins= "http://localhost:3000")
@CrossOrigin("*")
@RestController
@RequestMapping(path = "/") //Because we are hard coding data every time we will be showing stats for the same traveller.
public class TravellersController {
/*
NOT RECOMENED BY SPRING, for the purposes of this project we can ignore that because this helps us, as a small team
write and test code faster, also it is an automation which makes the Dependency injection real easy to understand.
*/
@Autowired
private final TravellersService travellersService;
private final CityRepository cityRepository;
/**
*
* @param travellersService initialize the class object with a given TravellerService
* @param cityRepository
*/
public TravellersController(TravellersService travellersService, CityRepository cityRepository) {
this.travellersService = travellersService;
this.cityRepository=cityRepository;
}
@GetMapping(path = "/travellers")
public ArrayList<Traveller> getAllTravellers() throws InterruptedException {
return travellersService.getAllTravellers();
}
@GetMapping( path = "{name}/bestCity")
public City findBestCityForTheUser(@PathVariable("name")String name) throws InterruptedException {
return travellersService.findBestCityForTheUser(name);
}
@GetMapping( path = "{name}/bestCity/collaborate")
public City findBestCityCollaborating(@PathVariable("name")String name) throws InterruptedException {
return travellersService.findBestCityCollaborating(name);
}
@GetMapping(path = "{cityName}/{country}/search")
public City checkCity(@PathVariable("cityName")String cityName,@PathVariable("country")String country){
try {
return travellersService.searchCity(cityName,country);
}catch (NoSuchCityException | InterruptedException e)
{
System.out.println("There is no city with this name!");
e.printStackTrace();
}
return null;
}
@PostMapping( path = "/addYoungTraveller")
public String addNewTraveller(@RequestBody YoungTraveller traveller) throws IOException, InterruptedException {
return travellersService.addNewTraveller(traveller);
}
@PostMapping( path = "/addMiddleTraveller")
public String addNewTraveller(@RequestBody MiddleTraveller traveller) throws IOException, InterruptedException {
return travellersService.addNewTraveller(traveller);
}
@PostMapping( path = "/addElderTraveller")
public String addNewTraveller(@RequestBody ElderTraveller traveller) throws IOException, InterruptedException {
return travellersService.addNewTraveller(traveller);
}
//TO<SUF>
@GetMapping( path = "{cityName}/{country}/freeTicket")
public Traveller findFreeTicket(@PathVariable("cityName") String FreeCityName , @PathVariable("country") String FreeCountry) throws NoSuchCityException, InterruptedException {
return travellersService.findFreeTicket(FreeCityName,FreeCountry);
}
@GetMapping(path = "{name}/{number}/bestCity" )
public ArrayList<City> findXBestCities(@PathVariable String name, @PathVariable Integer number) throws InterruptedException {
return travellersService.findXBestCities(name,number);
}
}
|
46342_6 | package gr.aueb.dmst.pijavaparty.proderp.dao;
import gr.aueb.dmst.pijavaparty.proderp.entity.COrderItem;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* COrderItemDao.java - a class for interacting and modifying the fields of a
* customer's items.
*
* @author Athina P.
* @see COrderItem
*/
public class COrderItemDao extends Dao implements CompositeEntityI<COrderItem> {
private static final String GETALL = "SELECT * FROM C_order_items";
private static final String GETBYIDS = "SELECT * FROM C_order_items WHERE c_order_id = ? AND product_id = ?";
private static final String GETITEMSPERCORDER = "SELECT * FROM C_order_items WHERE c_order_id = ?";
private static final String INSERT = "INSERT INTO C_order_items VALUES (?, ?, ?)";
private static final String DELETE = "DELETE FROM C_order_items WHERE c_order_id = ? AND product_id = ?";
private COrderDao co = new COrderDao();
private ProductDao pr = new ProductDao();
/**
* Retrieve customer order items from database
*
* @return A COrderItem data type List.
*/
@Override
public List<COrderItem> getAll() {
List<COrderItem> corders = new ArrayList();
Statement st = null;
ResultSet rs = null;
try {
st = getConnection().createStatement();
rs = st.executeQuery(GETALL);
while (rs.next()) {
corders.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)));//δεν υπαρχει η getById στην COrdrDao
}
} catch (SQLException ex) {
Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeStatementAndResultSet(rs, st);
}
return corders;
}
/**
* Get a customer's order item with a specific id.
*
* @param coid COrder's id.
* @param prid Product's id.
* @return A COrderItem data type object.
*/
public COrderItem getByIds(int coid, int prid) {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = getConnection().prepareStatement(GETBYIDS);
pst.setInt(1, coid);
pst.setInt(2, prid);
rs = pst.executeQuery();
if (rs.next()) {
return new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3));
}
} catch (SQLException ex) {
Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeStatementAndResultSet(rs, pst);
}
return null;
}
/**
* Get items of a specific COrder.
*
* @param coid COrder's id.
* @return A COrderItem data type List.
*/
public List<COrderItem> getItemsPerCOrder(int coid) {
List<COrderItem> coi = new ArrayList();
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = getConnection().prepareStatement(GETITEMSPERCORDER);
pst.setInt(1, coid);
rs = pst.executeQuery();
while (rs.next()) {
coi.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)));
}
} catch (SQLException ex) {
Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeStatementAndResultSet(rs, pst);
}
return coi;
}
/**
* Insert a new customer's item.
*
* @param coi An object of type COrderItem.
*/
@Override
public void insert(COrderItem coi) {
PreparedStatement pst = null;
try {
pst = getConnection().prepareStatement(INSERT);
pst.setInt(1, coi.getCorder().getId());
pst.setInt(2, coi.getProduct().getId());
pst.setInt(3, coi.getQuantity());
pst.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει;
} finally {
closeStatementAndResultSet(pst);
}
}
/**
* Delete a customer's item with a specific id.
*
* @param cordId COrder's id.
* @param pId Product's id.
*/
@Override
public void delete(int cordId, int pId) {
PreparedStatement pst = null;
try {
pst = getConnection().prepareStatement(DELETE);
pst.setInt(1, cordId);
pst.setInt(2, pId);
pst.execute();
closeStatementAndResultSet(pst);
} catch (SQLException ex) {
Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει;
} finally {
closeStatementAndResultSet(pst);
}
}
}
| AthinaDavari/JavaAssignment | proderp/src/main/java/gr/aueb/dmst/pijavaparty/proderp/dao/COrderItemDao.java | 1,340 | //εδω τι θα μπει; | line_comment | el | package gr.aueb.dmst.pijavaparty.proderp.dao;
import gr.aueb.dmst.pijavaparty.proderp.entity.COrderItem;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* COrderItemDao.java - a class for interacting and modifying the fields of a
* customer's items.
*
* @author Athina P.
* @see COrderItem
*/
public class COrderItemDao extends Dao implements CompositeEntityI<COrderItem> {
private static final String GETALL = "SELECT * FROM C_order_items";
private static final String GETBYIDS = "SELECT * FROM C_order_items WHERE c_order_id = ? AND product_id = ?";
private static final String GETITEMSPERCORDER = "SELECT * FROM C_order_items WHERE c_order_id = ?";
private static final String INSERT = "INSERT INTO C_order_items VALUES (?, ?, ?)";
private static final String DELETE = "DELETE FROM C_order_items WHERE c_order_id = ? AND product_id = ?";
private COrderDao co = new COrderDao();
private ProductDao pr = new ProductDao();
/**
* Retrieve customer order items from database
*
* @return A COrderItem data type List.
*/
@Override
public List<COrderItem> getAll() {
List<COrderItem> corders = new ArrayList();
Statement st = null;
ResultSet rs = null;
try {
st = getConnection().createStatement();
rs = st.executeQuery(GETALL);
while (rs.next()) {
corders.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)));//δεν υπαρχει η getById στην COrdrDao
}
} catch (SQLException ex) {
Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeStatementAndResultSet(rs, st);
}
return corders;
}
/**
* Get a customer's order item with a specific id.
*
* @param coid COrder's id.
* @param prid Product's id.
* @return A COrderItem data type object.
*/
public COrderItem getByIds(int coid, int prid) {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = getConnection().prepareStatement(GETBYIDS);
pst.setInt(1, coid);
pst.setInt(2, prid);
rs = pst.executeQuery();
if (rs.next()) {
return new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3));
}
} catch (SQLException ex) {
Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeStatementAndResultSet(rs, pst);
}
return null;
}
/**
* Get items of a specific COrder.
*
* @param coid COrder's id.
* @return A COrderItem data type List.
*/
public List<COrderItem> getItemsPerCOrder(int coid) {
List<COrderItem> coi = new ArrayList();
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = getConnection().prepareStatement(GETITEMSPERCORDER);
pst.setInt(1, coid);
rs = pst.executeQuery();
while (rs.next()) {
coi.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)));
}
} catch (SQLException ex) {
Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeStatementAndResultSet(rs, pst);
}
return coi;
}
/**
* Insert a new customer's item.
*
* @param coi An object of type COrderItem.
*/
@Override
public void insert(COrderItem coi) {
PreparedStatement pst = null;
try {
pst = getConnection().prepareStatement(INSERT);
pst.setInt(1, coi.getCorder().getId());
pst.setInt(2, coi.getProduct().getId());
pst.setInt(3, coi.getQuantity());
pst.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδ<SUF>
} finally {
closeStatementAndResultSet(pst);
}
}
/**
* Delete a customer's item with a specific id.
*
* @param cordId COrder's id.
* @param pId Product's id.
*/
@Override
public void delete(int cordId, int pId) {
PreparedStatement pst = null;
try {
pst = getConnection().prepareStatement(DELETE);
pst.setInt(1, cordId);
pst.setInt(2, pId);
pst.execute();
closeStatementAndResultSet(pst);
} catch (SQLException ex) {
Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει;
} finally {
closeStatementAndResultSet(pst);
}
}
}
|
617_7 | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345
*/
public class Greek implements Language {
@Override
public String unknownBeatmap() {
return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ;
}
@Override
public String internalException(String marker) {
return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου."
+" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000"
+ " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε."
+ " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ;
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"))
.then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"));
} else {
String[] messages = {
"Φαίνεσαι σαν να θες μια πρόταση.",
"Πόσο ωραίο να σε βλέπω :)",
"Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)",
"Τι ευχάριστη έκπληξη! ^.^",
"Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3",
"Τι έχεις την διάθεση να κάνεις σήμερα;",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Άγνωστη εντολή \"" + command
+ "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!";
}
@Override
public String noInformationForMods() {
return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή";
}
@Override
public String malformattedMods(String mods) {
return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού...";
}
@Override
public String tryWithMods() {
return "Δοκίμασε αυτό το τραγούδι με μερικά mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;";
}
@Override
public String complaint() {
return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Έλα εδώ εσυ!")
.then(new Action("Αγκαλιάζει " + apiUser.getUserName()));
}
@Override
public String help() {
return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά."
+ " [https://twitter.com/Tillerinobot status και updates]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]";
}
@Override
public String faq() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + ".";
}
@Override
public String mixedNomodAndMods() {
return "Τί εννοείς nomods με mods;";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. "
+ " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help.";
}
@Override
public String notRanked() {
return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο.";
}
@Override
public String invalidAccuracy(String acc) {
return "Άκυρη ακρίβεια: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Συγνώμη, αλλά \"" + invalid
+ "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!";
}
@Override
public String setFormat() {
return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
}
| Banbeucmas/Tillerinobot | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java | 3,297 | //github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; | line_comment | el | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345
*/
public class Greek implements Language {
@Override
public String unknownBeatmap() {
return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ;
}
@Override
public String internalException(String marker) {
return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου."
+" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000"
+ " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε."
+ " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ;
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"))
.then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"));
} else {
String[] messages = {
"Φαίνεσαι σαν να θες μια πρόταση.",
"Πόσο ωραίο να σε βλέπω :)",
"Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)",
"Τι ευχάριστη έκπληξη! ^.^",
"Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3",
"Τι έχεις την διάθεση να κάνεις σήμερα;",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Άγνωστη εντολή \"" + command
+ "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!";
}
@Override
public String noInformationForMods() {
return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή";
}
@Override
public String malformattedMods(String mods) {
return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού...";
}
@Override
public String tryWithMods() {
return "Δοκίμασε αυτό το τραγούδι με μερικά mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;";
}
@Override
public String complaint() {
return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Έλα εδώ εσυ!")
.then(new Action("Αγκαλιάζει " + apiUser.getUserName()));
}
@Override
public String help() {
return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά."
+ " [https://twitter.com/Tillerinobot status και updates]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]";
}
@Override
public String faq() {
return "[https://gi<SUF>
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + ".";
}
@Override
public String mixedNomodAndMods() {
return "Τί εννοείς nomods με mods;";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. "
+ " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help.";
}
@Override
public String notRanked() {
return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο.";
}
@Override
public String invalidAccuracy(String acc) {
return "Άκυρη ακρίβεια: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Συγνώμη, αλλά \"" + invalid
+ "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!";
}
@Override
public String setFormat() {
return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
}
|
28487_5 | /*
* Copyright (C) 2005-2012 BetaCONCEPT Limited
*
* This file is part of Astroboa.
*
* Astroboa is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Astroboa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Astroboa. If not, see <http://www.gnu.org/licenses/>.
*/
package org.betaconceptframework.astroboa.portal.form;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.betaconceptframework.astroboa.api.model.BooleanProperty;
import org.betaconceptframework.astroboa.api.model.CalendarProperty;
import org.betaconceptframework.astroboa.api.model.ContentObject;
import org.betaconceptframework.astroboa.api.model.RepositoryUser;
import org.betaconceptframework.astroboa.api.model.StringProperty;
import org.betaconceptframework.astroboa.api.model.Topic;
import org.betaconceptframework.astroboa.api.model.TopicReferenceProperty;
import org.betaconceptframework.astroboa.api.model.definition.CmsPropertyDefinition;
import org.betaconceptframework.astroboa.api.model.io.FetchLevel;
import org.betaconceptframework.astroboa.api.model.io.ResourceRepresentationType;
import org.betaconceptframework.astroboa.client.AstroboaClient;
import org.betaconceptframework.astroboa.portal.utility.CalendarUtils;
import org.betaconceptframework.astroboa.portal.utility.CmsUtils;
import org.betaconceptframework.astroboa.portal.utility.PortalStringConstants;
import org.betaconceptframework.ui.jsf.utility.JSFUtilities;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.faces.Renderer;
import org.jboss.seam.international.LocaleSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Gregory Chomatas ([email protected])
* @author Savvas Triantafyllou ([email protected])
*
*/
public abstract class AbstractForm<T extends AstroboaClient> {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private Map<String, Object> formParams = new HashMap<String, Object>();
/*
* This map can store values which do not correspond to content object properties,
* like password confirmation input field. It is not used by form infrastructure.
*
* It may be used from implementor as a container for any key, value pair
*/
private Map<String, Object> tempParams = new HashMap<String, Object>();
@Out(required=false)
protected ContentObject formContentObject = null;
@In(value="#{captcha.challengeText}", required=false)
private String challengeText;
@In(value="#{captcha.response}", required=false)
private String challengeResponse;
@In(create=true)
protected Renderer renderer;
@In
protected LocaleSelector localeSelector;
protected List<String> formSubmissionMessageList = new ArrayList<String>();
private Boolean successfulFormSubmission;
@In(create=true)
protected CmsUtils cmsUtils;
@In(create=true)
protected CalendarUtils calendarUtils;
private final static String STATUS_OF_USER_SUBMITTED_FORM = "submittedByExternalUser";
private final static String WORKFLOW_FOR_USER_SUBMITTED_FORM = "webPublishing";
public String submitForm() {
formContentObject = null;
try {
formSubmissionMessageList = new ArrayList<String>();
checkChallengeResponsePhase();
formContentObject = getFormsRepositoryClient().getCmsRepositoryEntityFactory().newObjectForType(getFormType());
applyDefaultValuesPhase(formParams, formContentObject);
validateAndApplyFormValuesPhase(formParams, formContentObject);
// run custom form post processing code before saving
postValidateAndApplyValuesPhase(formParams, formContentObject);
savePhase(formContentObject);
postSavePhase(formParams, formContentObject);
//return "/successfulFormSubmission.xhtml";
successfulFormSubmission = true;
return null;
}
catch (ChallengeValidationException e) {
logger.info("An null or invalid form challenge response was provided");
return null;
}
catch (FormValidationException e) {
logger.warn("An error occured during validation", e);
if (CollectionUtils.isEmpty(formSubmissionMessageList))
{
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null));
}
return null;
}
catch (Exception e) {
logger.error("Failed to save user submitted form", e);
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null));
if (formContentObject != null) {
formContentObject.setId(null);
}
return null;
}
}
private void savePhase(ContentObject formContentObject) throws Exception {
getFormsRepositoryClient().getContentService().save(formContentObject, false, true, null);
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission", null));
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.key.message", new String[]{formContentObject.getId()}));
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.info.message", null));
}
private void checkChallengeResponsePhase() throws ChallengeValidationException{
if (enableCheckForChallengeRespone())
{
if (StringUtils.isBlank(challengeResponse)) {
//String message = "Δεν συμπληρώσατε τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα.";
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null));
throw new ChallengeValidationException("Null Challenge Responce");
}
if (challengeText != null && challengeResponse != null && !challengeResponse.equals(challengeText)) {
//String message = "Δεν συμπληρώσατε σωστά τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα.";
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null));
throw new ChallengeValidationException("challengeText=" + challengeText + " ,challenge responce=" + challengeResponse + " - No Match");
}
}
}
private void validateAndApplyFormValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception {
for (String formParameter : formParams.keySet()) {
applyFormParameterToContentObjectProperty(formContentObject, formParams, formParameter);
}
}
private void applyDefaultValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception {
StringProperty statusProperty = (StringProperty) formContentObject.getCmsProperty("profile.contentObjectStatus");
statusProperty.setSimpleTypeValue(STATUS_OF_USER_SUBMITTED_FORM);
StringProperty workflowProperty = (StringProperty) formContentObject.getCmsProperty("workflow.managedThroughWorkflow");
workflowProperty.setSimpleTypeValue(WORKFLOW_FOR_USER_SUBMITTED_FORM);
// StringProperty commentsProperty = (StringProperty) formContentObject.addChildCmsPropertyTemplate("internalComments");
// commentsProperty.setSimpleTypeValue("External Submitter Name: " + firstName + " " + lastName + "\n" +
// "email: " + email + "\n" +
// "telephone: " + telephone + "\n" +
// "Organization Name: " + organizationName);
//Form submitter is ALWAYS SYSTEM Repository User
RepositoryUser formSubmitter = getFormsRepositoryClient().getRepositoryUserService().getSystemRepositoryUser();
if (formSubmitter == null) {
logger.error("Retrieved a null User for form submitter. Cannot proceed to save submitted event");
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null));
throw new Exception("Retrieved a null User for form submitter. Cannot proceed to save submitted event");
}
formContentObject.setOwner(formSubmitter);
Calendar now = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale());
CalendarProperty createdProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.created");
createdProperty.setSimpleTypeValue(now);
CalendarProperty modifiedProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.modified");
modifiedProperty.setSimpleTypeValue(now);
// supply a default title, language and author
// these may be overwritten by formPostProcessing method
StringProperty titleProperty = (StringProperty) formContentObject.getCmsProperty("profile.title");
titleProperty.setSimpleTypeValue(formContentObject.getTypeDefinition().getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + " " + calendarUtils.convertDateToString(now.getTime(), PortalStringConstants.DATE_FORMAT_PATTERN));
StringProperty languageProperty = (StringProperty) formContentObject.getCmsProperty("profile.language");
languageProperty.addSimpleTypeValue(JSFUtilities.getLocaleAsString());
StringProperty creatorProperty = (StringProperty) formContentObject.getCmsProperty("profile.creator");
creatorProperty.addSimpleTypeValue("anonymous");
applyAccessibilityPropertiesPhase(formContentObject);
}
private void applyFormParameterToContentObjectProperty(ContentObject formContentObject, Map<String, Object> formParameters, String formParameter) throws Exception, FormValidationException {
CmsPropertyDefinition formParameterDefinition =
(CmsPropertyDefinition) getFormsRepositoryClient().getDefinitionService().getCmsDefinition(formContentObject.getContentObjectType()+"."+formParameter, ResourceRepresentationType.DEFINITION_INSTANCE,false);
// check if field is defined
if (formParameterDefinition == null) {
String errorMessage = "For the provided form parameter: " +
formParameter +
", there is no corresponding property in the ContentObject Type:" +
formContentObject.getContentObjectType() +
"which models the form";
throw new FormValidationException(errorMessage);
}
Object formParameterValue = formParameters.get(formParameter);
String requiredFieldErrorMessage = "Το πεδίο " + "'" + formParameterDefinition.getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + "'" +
" είναι υποχρεωτικό. Παρακαλώ βάλτε τιμή";
switch (formParameterDefinition.getValueType()) {
case String:
{
// check if form value is of the appropriate type
if (!(formParameterValue instanceof String)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A String value was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
StringProperty formParameterProperty = (StringProperty) formContentObject.getCmsProperty(formParameter);
if (StringUtils.isBlank((String) formParameterValue)) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
formParameterProperty.setSimpleTypeValue((String)formParameterValue);
}
break;
}
case Date:
{
// check if form value is of the appropriate type
if (!(formParameterValue instanceof Date)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Date value was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && formParameterValue == null) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
CalendarProperty formParameterProperty = (CalendarProperty) formContentObject.getCmsProperty(formParameter);
if (formParameterValue == null) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
Calendar calendar = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale());
calendar.setTime(((Date)formParameters.get(formParameter)));
formParameterProperty.setSimpleTypeValue(calendar);
}
break;
}
case Boolean:
{
// check if form value is of the appropriate type
if (!(formParameterValue instanceof Boolean)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Boolean value was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && formParameterValue == null) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
BooleanProperty formParameterProperty = (BooleanProperty) formContentObject.getCmsProperty(formParameter);
if (formParameterValue == null) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
formParameterProperty.setSimpleTypeValue((Boolean)formParameters.get(formParameter));
}
break;
}
case TopicReference:
{
// check if form value is of the appropriate type
// we expect a string which corresponds to the id of an existing topic
if (!(formParameterValue instanceof String)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A string value corresponding to the id of an existing topic was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
TopicReferenceProperty formParameterProperty = (TopicReferenceProperty) formContentObject.getCmsProperty(formParameter);
if (StringUtils.isBlank((String)formParameterValue)) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
Topic retrievedTopic = getFormsRepositoryClient().getTopicService().getTopic((String) formParameterValue, ResourceRepresentationType.TOPIC_INSTANCE, FetchLevel.ENTITY, false);
if (retrievedTopic == null) {
throw new Exception("Not topic found for the provided topic id:" + formParameterValue);
}
formParameterProperty.setSimpleTypeValue(retrievedTopic);
}
break;
}
default:
throw new Exception("Not supported value type:" + formParameterDefinition.getValueType() + " for parameter:" + formParameter);
}
}
// run custom validation rules and do custom processing to formContentObject or formParams
public abstract void postValidateAndApplyValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception;
// run additional actions after successful form saving, e.g. send email, start a workflow, etc.
public abstract void postSavePhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception;
// called inside applyDefaultValuesPhase and permit custom accessibility setup
protected abstract void applyAccessibilityPropertiesPhase(ContentObject formContentObject);
//called inside checkChallengeResponsePhase and allow users to disable challenge response in case they do
//not display captcha in their form
protected abstract boolean enableCheckForChallengeRespone();
public Map<String, Object> getFormParams() {
return formParams;
}
public abstract String getFormType();
protected abstract T getFormsRepositoryClient();
public ContentObject getFormContentObject() {
return formContentObject;
}
public List<String> getFormSubmissionMessageList() {
return formSubmissionMessageList;
}
public Boolean getSuccessfulFormSubmission() {
return successfulFormSubmission;
}
public void setSuccessfulFormSubmission(Boolean successfulFormSubmission) {
this.successfulFormSubmission = successfulFormSubmission;
}
public Map<String, Object> getTempParams() {
return tempParams;
}
}
| BetaCONCEPT/astroboa | astroboa-portal-commons/src/main/java/org/betaconceptframework/astroboa/portal/form/AbstractForm.java | 4,286 | //String message = "Δεν συμπληρώσατε τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα."; | line_comment | el | /*
* Copyright (C) 2005-2012 BetaCONCEPT Limited
*
* This file is part of Astroboa.
*
* Astroboa is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Astroboa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Astroboa. If not, see <http://www.gnu.org/licenses/>.
*/
package org.betaconceptframework.astroboa.portal.form;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.betaconceptframework.astroboa.api.model.BooleanProperty;
import org.betaconceptframework.astroboa.api.model.CalendarProperty;
import org.betaconceptframework.astroboa.api.model.ContentObject;
import org.betaconceptframework.astroboa.api.model.RepositoryUser;
import org.betaconceptframework.astroboa.api.model.StringProperty;
import org.betaconceptframework.astroboa.api.model.Topic;
import org.betaconceptframework.astroboa.api.model.TopicReferenceProperty;
import org.betaconceptframework.astroboa.api.model.definition.CmsPropertyDefinition;
import org.betaconceptframework.astroboa.api.model.io.FetchLevel;
import org.betaconceptframework.astroboa.api.model.io.ResourceRepresentationType;
import org.betaconceptframework.astroboa.client.AstroboaClient;
import org.betaconceptframework.astroboa.portal.utility.CalendarUtils;
import org.betaconceptframework.astroboa.portal.utility.CmsUtils;
import org.betaconceptframework.astroboa.portal.utility.PortalStringConstants;
import org.betaconceptframework.ui.jsf.utility.JSFUtilities;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.faces.Renderer;
import org.jboss.seam.international.LocaleSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Gregory Chomatas ([email protected])
* @author Savvas Triantafyllou ([email protected])
*
*/
public abstract class AbstractForm<T extends AstroboaClient> {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private Map<String, Object> formParams = new HashMap<String, Object>();
/*
* This map can store values which do not correspond to content object properties,
* like password confirmation input field. It is not used by form infrastructure.
*
* It may be used from implementor as a container for any key, value pair
*/
private Map<String, Object> tempParams = new HashMap<String, Object>();
@Out(required=false)
protected ContentObject formContentObject = null;
@In(value="#{captcha.challengeText}", required=false)
private String challengeText;
@In(value="#{captcha.response}", required=false)
private String challengeResponse;
@In(create=true)
protected Renderer renderer;
@In
protected LocaleSelector localeSelector;
protected List<String> formSubmissionMessageList = new ArrayList<String>();
private Boolean successfulFormSubmission;
@In(create=true)
protected CmsUtils cmsUtils;
@In(create=true)
protected CalendarUtils calendarUtils;
private final static String STATUS_OF_USER_SUBMITTED_FORM = "submittedByExternalUser";
private final static String WORKFLOW_FOR_USER_SUBMITTED_FORM = "webPublishing";
public String submitForm() {
formContentObject = null;
try {
formSubmissionMessageList = new ArrayList<String>();
checkChallengeResponsePhase();
formContentObject = getFormsRepositoryClient().getCmsRepositoryEntityFactory().newObjectForType(getFormType());
applyDefaultValuesPhase(formParams, formContentObject);
validateAndApplyFormValuesPhase(formParams, formContentObject);
// run custom form post processing code before saving
postValidateAndApplyValuesPhase(formParams, formContentObject);
savePhase(formContentObject);
postSavePhase(formParams, formContentObject);
//return "/successfulFormSubmission.xhtml";
successfulFormSubmission = true;
return null;
}
catch (ChallengeValidationException e) {
logger.info("An null or invalid form challenge response was provided");
return null;
}
catch (FormValidationException e) {
logger.warn("An error occured during validation", e);
if (CollectionUtils.isEmpty(formSubmissionMessageList))
{
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null));
}
return null;
}
catch (Exception e) {
logger.error("Failed to save user submitted form", e);
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null));
if (formContentObject != null) {
formContentObject.setId(null);
}
return null;
}
}
private void savePhase(ContentObject formContentObject) throws Exception {
getFormsRepositoryClient().getContentService().save(formContentObject, false, true, null);
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission", null));
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.key.message", new String[]{formContentObject.getId()}));
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.info.message", null));
}
private void checkChallengeResponsePhase() throws ChallengeValidationException{
if (enableCheckForChallengeRespone())
{
if (StringUtils.isBlank(challengeResponse)) {
//St<SUF>
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null));
throw new ChallengeValidationException("Null Challenge Responce");
}
if (challengeText != null && challengeResponse != null && !challengeResponse.equals(challengeText)) {
//String message = "Δεν συμπληρώσατε σωστά τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα.";
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null));
throw new ChallengeValidationException("challengeText=" + challengeText + " ,challenge responce=" + challengeResponse + " - No Match");
}
}
}
private void validateAndApplyFormValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception {
for (String formParameter : formParams.keySet()) {
applyFormParameterToContentObjectProperty(formContentObject, formParams, formParameter);
}
}
private void applyDefaultValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception {
StringProperty statusProperty = (StringProperty) formContentObject.getCmsProperty("profile.contentObjectStatus");
statusProperty.setSimpleTypeValue(STATUS_OF_USER_SUBMITTED_FORM);
StringProperty workflowProperty = (StringProperty) formContentObject.getCmsProperty("workflow.managedThroughWorkflow");
workflowProperty.setSimpleTypeValue(WORKFLOW_FOR_USER_SUBMITTED_FORM);
// StringProperty commentsProperty = (StringProperty) formContentObject.addChildCmsPropertyTemplate("internalComments");
// commentsProperty.setSimpleTypeValue("External Submitter Name: " + firstName + " " + lastName + "\n" +
// "email: " + email + "\n" +
// "telephone: " + telephone + "\n" +
// "Organization Name: " + organizationName);
//Form submitter is ALWAYS SYSTEM Repository User
RepositoryUser formSubmitter = getFormsRepositoryClient().getRepositoryUserService().getSystemRepositoryUser();
if (formSubmitter == null) {
logger.error("Retrieved a null User for form submitter. Cannot proceed to save submitted event");
formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null));
throw new Exception("Retrieved a null User for form submitter. Cannot proceed to save submitted event");
}
formContentObject.setOwner(formSubmitter);
Calendar now = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale());
CalendarProperty createdProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.created");
createdProperty.setSimpleTypeValue(now);
CalendarProperty modifiedProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.modified");
modifiedProperty.setSimpleTypeValue(now);
// supply a default title, language and author
// these may be overwritten by formPostProcessing method
StringProperty titleProperty = (StringProperty) formContentObject.getCmsProperty("profile.title");
titleProperty.setSimpleTypeValue(formContentObject.getTypeDefinition().getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + " " + calendarUtils.convertDateToString(now.getTime(), PortalStringConstants.DATE_FORMAT_PATTERN));
StringProperty languageProperty = (StringProperty) formContentObject.getCmsProperty("profile.language");
languageProperty.addSimpleTypeValue(JSFUtilities.getLocaleAsString());
StringProperty creatorProperty = (StringProperty) formContentObject.getCmsProperty("profile.creator");
creatorProperty.addSimpleTypeValue("anonymous");
applyAccessibilityPropertiesPhase(formContentObject);
}
private void applyFormParameterToContentObjectProperty(ContentObject formContentObject, Map<String, Object> formParameters, String formParameter) throws Exception, FormValidationException {
CmsPropertyDefinition formParameterDefinition =
(CmsPropertyDefinition) getFormsRepositoryClient().getDefinitionService().getCmsDefinition(formContentObject.getContentObjectType()+"."+formParameter, ResourceRepresentationType.DEFINITION_INSTANCE,false);
// check if field is defined
if (formParameterDefinition == null) {
String errorMessage = "For the provided form parameter: " +
formParameter +
", there is no corresponding property in the ContentObject Type:" +
formContentObject.getContentObjectType() +
"which models the form";
throw new FormValidationException(errorMessage);
}
Object formParameterValue = formParameters.get(formParameter);
String requiredFieldErrorMessage = "Το πεδίο " + "'" + formParameterDefinition.getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + "'" +
" είναι υποχρεωτικό. Παρακαλώ βάλτε τιμή";
switch (formParameterDefinition.getValueType()) {
case String:
{
// check if form value is of the appropriate type
if (!(formParameterValue instanceof String)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A String value was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
StringProperty formParameterProperty = (StringProperty) formContentObject.getCmsProperty(formParameter);
if (StringUtils.isBlank((String) formParameterValue)) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
formParameterProperty.setSimpleTypeValue((String)formParameterValue);
}
break;
}
case Date:
{
// check if form value is of the appropriate type
if (!(formParameterValue instanceof Date)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Date value was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && formParameterValue == null) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
CalendarProperty formParameterProperty = (CalendarProperty) formContentObject.getCmsProperty(formParameter);
if (formParameterValue == null) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
Calendar calendar = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale());
calendar.setTime(((Date)formParameters.get(formParameter)));
formParameterProperty.setSimpleTypeValue(calendar);
}
break;
}
case Boolean:
{
// check if form value is of the appropriate type
if (!(formParameterValue instanceof Boolean)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Boolean value was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && formParameterValue == null) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
BooleanProperty formParameterProperty = (BooleanProperty) formContentObject.getCmsProperty(formParameter);
if (formParameterValue == null) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
formParameterProperty.setSimpleTypeValue((Boolean)formParameters.get(formParameter));
}
break;
}
case TopicReference:
{
// check if form value is of the appropriate type
// we expect a string which corresponds to the id of an existing topic
if (!(formParameterValue instanceof String)) {
throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A string value corresponding to the id of an existing topic was expected");
}
// check if no value has been provided for a mandatory property
if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) {
formSubmissionMessageList.add(requiredFieldErrorMessage);
throw new FormValidationException(requiredFieldErrorMessage);
}
TopicReferenceProperty formParameterProperty = (TopicReferenceProperty) formContentObject.getCmsProperty(formParameter);
if (StringUtils.isBlank((String)formParameterValue)) {
formParameterProperty.setSimpleTypeValue(null);
}
else {
Topic retrievedTopic = getFormsRepositoryClient().getTopicService().getTopic((String) formParameterValue, ResourceRepresentationType.TOPIC_INSTANCE, FetchLevel.ENTITY, false);
if (retrievedTopic == null) {
throw new Exception("Not topic found for the provided topic id:" + formParameterValue);
}
formParameterProperty.setSimpleTypeValue(retrievedTopic);
}
break;
}
default:
throw new Exception("Not supported value type:" + formParameterDefinition.getValueType() + " for parameter:" + formParameter);
}
}
// run custom validation rules and do custom processing to formContentObject or formParams
public abstract void postValidateAndApplyValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception;
// run additional actions after successful form saving, e.g. send email, start a workflow, etc.
public abstract void postSavePhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception;
// called inside applyDefaultValuesPhase and permit custom accessibility setup
protected abstract void applyAccessibilityPropertiesPhase(ContentObject formContentObject);
//called inside checkChallengeResponsePhase and allow users to disable challenge response in case they do
//not display captcha in their form
protected abstract boolean enableCheckForChallengeRespone();
public Map<String, Object> getFormParams() {
return formParams;
}
public abstract String getFormType();
protected abstract T getFormsRepositoryClient();
public ContentObject getFormContentObject() {
return formContentObject;
}
public List<String> getFormSubmissionMessageList() {
return formSubmissionMessageList;
}
public Boolean getSuccessfulFormSubmission() {
return successfulFormSubmission;
}
public void setSuccessfulFormSubmission(Boolean successfulFormSubmission) {
this.successfulFormSubmission = successfulFormSubmission;
}
public Map<String, Object> getTempParams() {
return tempParams;
}
}
|
5767_6 | import java.util.Scanner;
public class friday13 {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("Single or Multiple year input ?");
System.out.println("For single year input press (s)");
System.out.println("For multiple year input press (m)");
while (true) {
char selector = input.next().charAt(0);
//Selection Zone //
if (selector=='s') {
System.out.println("Enter the desired year:");
int year = input.nextInt();
int diff = year-2012;
int k = 0;
int extraday;
if(diff >= 0) {
if(diff%4 != 0) {
k = 1;
}
extraday = (diff/4)*5 + (diff%4 + k) ;
extraday = extraday - ((diff+11)/100); // αφαιρει τα δισεκτα που μπηκαν λαθος πριν
extraday = extraday + ((diff+11)/400); // προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη
extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα
}
else {
if(diff%4 != 3) {
k = -1;
}
extraday = ((diff/4)*5)+(diff%4 + k) ;
extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100
extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο
extraday = extraday % 7;
extraday = 8 + extraday ;
}
int month = 1;
int feb = 1;
if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) {
feb = 0;
}
System.out.println("Stay in your bed at the following dates :");
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year );
}
month++;
extraday += 3 ;
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year);
}
month++;
extraday += feb;
int c = 3 ;
for(int i= 3; i<=9 ; i++) {
if (extraday%7 ==0 ) {
System.out.println("13/" + month + "/" + year);
}
extraday = extraday + 3*(i%2) - 2 * ((i%2)-1) ;
month++;
c++ ;
if (c==8) {
i = 4;
}
}
break;
}
else if (selector == 'm') {
System.out.println("Enter the desired years:");
int year = input.nextInt(), year2 = input.nextInt();
int diff ;
int distance = year2 - year ;
System.out.println("Stay in your bed at the following dates :");
for (int i=0 ; i<=distance-1 ; i++) {
diff = year-2012;
int k = 0;
int extraday;
if(diff >= 0) {
if(diff%4 != 0) {
k = 1;
}
extraday = (diff/4)*5 + (diff%4 + k) ;
extraday = extraday - ((diff+11)/100); // αφαιρει τα δισεκτα που μπηκαν λαθος πριν
extraday = extraday + ((diff+11)/400); // προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη
extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα
}
else {
if(diff%4 != 3) {
k = -1;
}
extraday = ((diff/4)*5)+(diff%4 + k) ;
extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100
extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο
extraday = extraday % 7;
extraday = 8 + extraday ;
}
int month = 1;
int feb = 1;
if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) {
feb = 0;
}
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year );
}
month++;
extraday += 3 ;
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year);
}
month++;
extraday += feb;
int c = 3 ;
for (int j =3 ;j<=9 ; j++) {
if (extraday%7 ==0 ) {
System.out.println("13/" + month + "/" + year);
}
extraday = extraday + 3*(j%2) - 2 * ((j%2)-1) ;
month++;
c++ ;
if (c==8) {
j = 4;
}
}
year += 1 ;
}
break;
}
else {
System.out.println("Try again you dumb fuck !");
continue;
}
}
}
}
| Bilkouristas/Friday13th | Friday13finder/src/friday13.java | 1,761 | // αφαιρει τα δισεκτα που μπηκαν λαθος πριν
| line_comment | el | import java.util.Scanner;
public class friday13 {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("Single or Multiple year input ?");
System.out.println("For single year input press (s)");
System.out.println("For multiple year input press (m)");
while (true) {
char selector = input.next().charAt(0);
//Selection Zone //
if (selector=='s') {
System.out.println("Enter the desired year:");
int year = input.nextInt();
int diff = year-2012;
int k = 0;
int extraday;
if(diff >= 0) {
if(diff%4 != 0) {
k = 1;
}
extraday = (diff/4)*5 + (diff%4 + k) ;
extraday = extraday - ((diff+11)/100); // αφαιρει τα δισεκτα που μπηκαν λαθος πριν
extraday = extraday + ((diff+11)/400); // προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη
extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα
}
else {
if(diff%4 != 3) {
k = -1;
}
extraday = ((diff/4)*5)+(diff%4 + k) ;
extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100
extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο
extraday = extraday % 7;
extraday = 8 + extraday ;
}
int month = 1;
int feb = 1;
if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) {
feb = 0;
}
System.out.println("Stay in your bed at the following dates :");
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year );
}
month++;
extraday += 3 ;
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year);
}
month++;
extraday += feb;
int c = 3 ;
for(int i= 3; i<=9 ; i++) {
if (extraday%7 ==0 ) {
System.out.println("13/" + month + "/" + year);
}
extraday = extraday + 3*(i%2) - 2 * ((i%2)-1) ;
month++;
c++ ;
if (c==8) {
i = 4;
}
}
break;
}
else if (selector == 'm') {
System.out.println("Enter the desired years:");
int year = input.nextInt(), year2 = input.nextInt();
int diff ;
int distance = year2 - year ;
System.out.println("Stay in your bed at the following dates :");
for (int i=0 ; i<=distance-1 ; i++) {
diff = year-2012;
int k = 0;
int extraday;
if(diff >= 0) {
if(diff%4 != 0) {
k = 1;
}
extraday = (diff/4)*5 + (diff%4 + k) ;
extraday = extraday - ((diff+11)/100); // αφ<SUF>
extraday = extraday + ((diff+11)/400); // προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη
extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα
}
else {
if(diff%4 != 3) {
k = -1;
}
extraday = ((diff/4)*5)+(diff%4 + k) ;
extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100
extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο
extraday = extraday % 7;
extraday = 8 + extraday ;
}
int month = 1;
int feb = 1;
if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) {
feb = 0;
}
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year );
}
month++;
extraday += 3 ;
if (extraday%7 == 0 ) {
System.out.println("13/" + month + "/" + year);
}
month++;
extraday += feb;
int c = 3 ;
for (int j =3 ;j<=9 ; j++) {
if (extraday%7 ==0 ) {
System.out.println("13/" + month + "/" + year);
}
extraday = extraday + 3*(j%2) - 2 * ((j%2)-1) ;
month++;
c++ ;
if (c==8) {
j = 4;
}
}
year += 1 ;
}
break;
}
else {
System.out.println("Try again you dumb fuck !");
continue;
}
}
}
}
|
1844_8 | package com.example.billy.cainstructionquiz;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.text.DecimalFormat;
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "button";
private static final String ADDBTN = "addButton";
private static final String SUBBTN = "subButton";
private static final String MULTBTN = "multButton";
private static final String DIVBTN = "divButton";
private static final String QUESTION = "Πόσο κάνει ";
private static final String ADDACTION = " σύν ";
private static final String SUBACTION = " μείον ";
private static final String MULTACTION = " επί ";
private static final String DIVACTION = " διά ";
private static final String QUESTIONMARK = ";";
private static final String WINMESSAGE = "Μπράβο!";
private static final String LOSEMESSAGE = "Προσπάθησε ξανά, αυτή την φόρα θα τα καταφέρεις!";
private static final String ERRORMESSAGE = "Προσπάθησε ξανά, έδωσες λάθος αριθμό!";
private static final String EASY = "Εύκολο";
private static final String MEDIUM = "Μέτριο";
private static final String HARD = "Δύσκολο";
private SecureRandom random = new SecureRandom();
private int number1;
private int number2;
private int rightAnswers;
private int rightAddAnswers;
private int rightSubAnswers;
private int rightMultAnswers;
private int rightDivAnswers;
private int wrongAnswers;
private int wrongAddAnswers;
private int wrongSubAnswers;
private int wrongMultAnswers;
private int wrongDivAnswers;
private String action="";
private TextView questionTxtView;
private EditText answerEditText;
private Animation shakeAnimation;
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
private String difficulty;
private String background_color;
@Override
protected void onResume() {
super.onResume();
String background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.RED);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_quiz);
switch(background_color){
case MainActivity.GREEN: rl.setBackgroundResource(R.drawable.blackboard_background_green); break;
case MainActivity.RED: rl.setBackgroundResource(R.drawable.blackboard_background_red); break;
case MainActivity.BLUE: rl.setBackgroundResource(R.drawable.blackboard_background_blue); break;
case MainActivity.PINK: rl.setBackgroundResource(R.drawable.blackboard_background_pink); break;
case MainActivity.PURPLE: rl.setBackgroundResource(R.drawable.blackboard_background_purple); break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.GREEN);
switch(background_color){
case MainActivity.GREEN: setTheme(R.style.AppTheme_Green); break;
case MainActivity.RED: setTheme(R.style.AppTheme_Red); break;
case MainActivity.BLUE: setTheme(R.style.AppTheme_Blue); break;
case MainActivity.PINK: setTheme(R.style.AppTheme_Pink); break;
case MainActivity.PURPLE: setTheme(R.style.AppTheme_Purple); break;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Αρχικοποίηση του animation του κουμπιού
shakeAnimation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake_effect);
questionTxtView = (TextView) findViewById(R.id.questionTxtView);
answerEditText = (EditText) findViewById(R.id.answerEditText);
//KeyListener για να τρέχει την συνάρτηση υπολογισμού και με το πλήκτρο enter.
answerEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
checkProcess();
return true;
}
return false;
}
});
//Αρχικοποίηση του Default SharedPreference Manager και Editor
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPref.edit();
//Εισαγωγή των μεταβλητών από τα SharedPreferrence για τα στατιστικά του παιχνιδιού
int defaultValue = getResources().getInteger(R.integer.answers_default);
rightAnswers = sharedPref.getInt(getString(R.string.right_answers), defaultValue);
rightAddAnswers = sharedPref.getInt(getString(R.string.right_add_answers), defaultValue);
rightSubAnswers = sharedPref.getInt(getString(R.string.right_sub_answers), defaultValue);
rightMultAnswers = sharedPref.getInt(getString(R.string.right_mult_answers), defaultValue);
rightDivAnswers = sharedPref.getInt(getString(R.string.right_div_answers), defaultValue);
wrongAnswers = sharedPref.getInt(getString(R.string.wrong_answers), defaultValue);
wrongAddAnswers = sharedPref.getInt(getString(R.string.wrong_add_answers), defaultValue);
wrongSubAnswers = sharedPref.getInt(getString(R.string.wrong_sub_answers), defaultValue);
wrongMultAnswers = sharedPref.getInt(getString(R.string.wrong_mult_answers), defaultValue);
wrongDivAnswers = sharedPref.getInt(getString(R.string.wrong_div_answers), defaultValue);
//Εισαγωγή της μεταβλητής από τα SharedPreferrence για την δυσκολία του παιχνιδιού
//Σε περίπτωση προβλήματος με την μεταβλητή του SharedPreferrence για την δυσκολία να βάζει αυτόματα εύκολο
difficulty = sharedPref.getString(MainActivity.DIFFICULTY, EASY);
//Αρχικοποίηση των αριθμών για την πράξη βάση της δυσκολίας
setRandoms();
//Εύρεση πράξης από τα στοιχεία που προήρθαν από το προηγούμενο Activity
String buttonString="";
Intent i = getIntent();
Bundle b = i.getExtras();
if(b!=null) {
buttonString = (String) b.get(TAG);
}
switch(buttonString){
case ADDBTN: action=ADDACTION; break;
case SUBBTN: action=SUBACTION; break;
case MULTBTN: action=MULTACTION; break;
case DIVBTN: action=DIVACTION; break;
}
questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK);
}
private void setRandoms(){
switch(difficulty){
case EASY:
number1 = random.nextInt(10 - 1) + 1;
number2 = random.nextInt(10 - 1) + 1;
break;
case MEDIUM:
number1 = random.nextInt(100 - 1) + 1;
number2 = random.nextInt(100 - 1) + 1;
break;
case HARD:
number1 = random.nextInt(1000 - 1) + 1;
number2 = random.nextInt(1000 - 1) + 1;
break;
}
}
// Η συνάρτηση dialog παίρνει μια μεταβλητή integer οπού όταν είναι 0 σημαίνει ότι είναι νικητήριο dialog και όταν είναι 1 είναι ηττημένο dialog
// ενώ όταν είναι -1 (ή οποιοσδήποτε άλλος ακέραιος) σημαίνει οτι υπήρξε κάποιο πρόβλημα με τον αριθμό.
private void dialog(int win_or_lose){
final Dialog dialog = new Dialog(QuizActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
TextView text = (TextView) dialog.findViewById(R.id.textView);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(win_or_lose==0){
text.setText(WINMESSAGE);
rightAnswers++;
editor.putInt(getString(R.string.right_answers), rightAnswers);
image.setImageResource(R.drawable.star);
final MediaPlayer mediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.tada);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
}
});
}else if (win_or_lose==1){
image.setImageResource(R.drawable.sad_face);
text.setText(LOSEMESSAGE);
wrongAnswers++;
editor.putInt(getString(R.string.wrong_answers), wrongAnswers);
}else{
image.setImageResource(R.drawable.error_icon);
text.setText(ERRORMESSAGE);
}
editor.commit();
dialog.show();
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
}, 5000);
}
private void resetValues(){
setRandoms();
answerEditText.setText("");
questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK);
}
private void checkProcess(){
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.HALF_UP);
int counter = 0;
for( int i=0; i<answerEditText.getText().toString().length(); i++ ) {
if( answerEditText.getText().toString().charAt(i) == '.' || answerEditText.getText().toString().charAt(i) == ',') {
counter++;
}
}
if(counter==0 || counter==1) {
String answer_string = df.format(Double.parseDouble(answerEditText.getText().toString())).replace(',','.');
double answer = Double.parseDouble(answer_string);
switch (action) {
case ADDACTION:
if (answer == (number1 + number2)) {
dialog(0);
resetValues();
rightAddAnswers++;
editor.putInt(getString(R.string.right_add_answers), rightAddAnswers);
} else {
dialog(1);
wrongAddAnswers++;
editor.putInt(getString(R.string.wrong_add_answers), wrongAddAnswers);
}
break;
case SUBACTION:
if (answer == (number1 - number2)) {
dialog(0);
resetValues();
rightSubAnswers++;
editor.putInt(getString(R.string.right_sub_answers), rightSubAnswers);
} else {
dialog(1);
wrongSubAnswers++;
editor.putInt(getString(R.string.wrong_sub_answers), wrongSubAnswers);
}
break;
case MULTACTION:
if (answer == (number1 * number2)) {
dialog(0);
resetValues();
rightMultAnswers++;
editor.putInt(getString(R.string.right_mult_answers), rightMultAnswers);
} else {
dialog(1);
wrongMultAnswers++;
editor.putInt(getString(R.string.wrong_mult_answers), wrongMultAnswers);
}
break;
case DIVACTION:
if (answer == Double.parseDouble(df.format((double) number1 / number2).replace(',','.'))) {
dialog(0);
resetValues();
rightDivAnswers++;
editor.putInt(getString(R.string.right_div_answers), rightDivAnswers);
} else {
dialog(1);
wrongDivAnswers++;
editor.putInt(getString(R.string.wrong_div_answers), wrongDivAnswers);
}
break;
}
editor.commit();
}else {
dialog(-1);
}
}
public void checkButtonPressed(View v){
v.startAnimation(shakeAnimation);
checkProcess();
}
}
| Billeclipse/C.A.InstructionQuiz-Project | CAInstructionQuiz/app/src/main/java/com/example/billy/cainstructionquiz/QuizActivity.java | 3,402 | // Η συνάρτηση dialog παίρνει μια μεταβλητή integer οπού όταν είναι 0 σημαίνει ότι είναι νικητήριο dialog και όταν είναι 1 είναι ηττημένο dialog
| line_comment | el | package com.example.billy.cainstructionquiz;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.text.DecimalFormat;
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "button";
private static final String ADDBTN = "addButton";
private static final String SUBBTN = "subButton";
private static final String MULTBTN = "multButton";
private static final String DIVBTN = "divButton";
private static final String QUESTION = "Πόσο κάνει ";
private static final String ADDACTION = " σύν ";
private static final String SUBACTION = " μείον ";
private static final String MULTACTION = " επί ";
private static final String DIVACTION = " διά ";
private static final String QUESTIONMARK = ";";
private static final String WINMESSAGE = "Μπράβο!";
private static final String LOSEMESSAGE = "Προσπάθησε ξανά, αυτή την φόρα θα τα καταφέρεις!";
private static final String ERRORMESSAGE = "Προσπάθησε ξανά, έδωσες λάθος αριθμό!";
private static final String EASY = "Εύκολο";
private static final String MEDIUM = "Μέτριο";
private static final String HARD = "Δύσκολο";
private SecureRandom random = new SecureRandom();
private int number1;
private int number2;
private int rightAnswers;
private int rightAddAnswers;
private int rightSubAnswers;
private int rightMultAnswers;
private int rightDivAnswers;
private int wrongAnswers;
private int wrongAddAnswers;
private int wrongSubAnswers;
private int wrongMultAnswers;
private int wrongDivAnswers;
private String action="";
private TextView questionTxtView;
private EditText answerEditText;
private Animation shakeAnimation;
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
private String difficulty;
private String background_color;
@Override
protected void onResume() {
super.onResume();
String background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.RED);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_quiz);
switch(background_color){
case MainActivity.GREEN: rl.setBackgroundResource(R.drawable.blackboard_background_green); break;
case MainActivity.RED: rl.setBackgroundResource(R.drawable.blackboard_background_red); break;
case MainActivity.BLUE: rl.setBackgroundResource(R.drawable.blackboard_background_blue); break;
case MainActivity.PINK: rl.setBackgroundResource(R.drawable.blackboard_background_pink); break;
case MainActivity.PURPLE: rl.setBackgroundResource(R.drawable.blackboard_background_purple); break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.GREEN);
switch(background_color){
case MainActivity.GREEN: setTheme(R.style.AppTheme_Green); break;
case MainActivity.RED: setTheme(R.style.AppTheme_Red); break;
case MainActivity.BLUE: setTheme(R.style.AppTheme_Blue); break;
case MainActivity.PINK: setTheme(R.style.AppTheme_Pink); break;
case MainActivity.PURPLE: setTheme(R.style.AppTheme_Purple); break;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Αρχικοποίηση του animation του κουμπιού
shakeAnimation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake_effect);
questionTxtView = (TextView) findViewById(R.id.questionTxtView);
answerEditText = (EditText) findViewById(R.id.answerEditText);
//KeyListener για να τρέχει την συνάρτηση υπολογισμού και με το πλήκτρο enter.
answerEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
checkProcess();
return true;
}
return false;
}
});
//Αρχικοποίηση του Default SharedPreference Manager και Editor
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPref.edit();
//Εισαγωγή των μεταβλητών από τα SharedPreferrence για τα στατιστικά του παιχνιδιού
int defaultValue = getResources().getInteger(R.integer.answers_default);
rightAnswers = sharedPref.getInt(getString(R.string.right_answers), defaultValue);
rightAddAnswers = sharedPref.getInt(getString(R.string.right_add_answers), defaultValue);
rightSubAnswers = sharedPref.getInt(getString(R.string.right_sub_answers), defaultValue);
rightMultAnswers = sharedPref.getInt(getString(R.string.right_mult_answers), defaultValue);
rightDivAnswers = sharedPref.getInt(getString(R.string.right_div_answers), defaultValue);
wrongAnswers = sharedPref.getInt(getString(R.string.wrong_answers), defaultValue);
wrongAddAnswers = sharedPref.getInt(getString(R.string.wrong_add_answers), defaultValue);
wrongSubAnswers = sharedPref.getInt(getString(R.string.wrong_sub_answers), defaultValue);
wrongMultAnswers = sharedPref.getInt(getString(R.string.wrong_mult_answers), defaultValue);
wrongDivAnswers = sharedPref.getInt(getString(R.string.wrong_div_answers), defaultValue);
//Εισαγωγή της μεταβλητής από τα SharedPreferrence για την δυσκολία του παιχνιδιού
//Σε περίπτωση προβλήματος με την μεταβλητή του SharedPreferrence για την δυσκολία να βάζει αυτόματα εύκολο
difficulty = sharedPref.getString(MainActivity.DIFFICULTY, EASY);
//Αρχικοποίηση των αριθμών για την πράξη βάση της δυσκολίας
setRandoms();
//Εύρεση πράξης από τα στοιχεία που προήρθαν από το προηγούμενο Activity
String buttonString="";
Intent i = getIntent();
Bundle b = i.getExtras();
if(b!=null) {
buttonString = (String) b.get(TAG);
}
switch(buttonString){
case ADDBTN: action=ADDACTION; break;
case SUBBTN: action=SUBACTION; break;
case MULTBTN: action=MULTACTION; break;
case DIVBTN: action=DIVACTION; break;
}
questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK);
}
private void setRandoms(){
switch(difficulty){
case EASY:
number1 = random.nextInt(10 - 1) + 1;
number2 = random.nextInt(10 - 1) + 1;
break;
case MEDIUM:
number1 = random.nextInt(100 - 1) + 1;
number2 = random.nextInt(100 - 1) + 1;
break;
case HARD:
number1 = random.nextInt(1000 - 1) + 1;
number2 = random.nextInt(1000 - 1) + 1;
break;
}
}
// Η <SUF>
// ενώ όταν είναι -1 (ή οποιοσδήποτε άλλος ακέραιος) σημαίνει οτι υπήρξε κάποιο πρόβλημα με τον αριθμό.
private void dialog(int win_or_lose){
final Dialog dialog = new Dialog(QuizActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
TextView text = (TextView) dialog.findViewById(R.id.textView);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(win_or_lose==0){
text.setText(WINMESSAGE);
rightAnswers++;
editor.putInt(getString(R.string.right_answers), rightAnswers);
image.setImageResource(R.drawable.star);
final MediaPlayer mediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.tada);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
}
});
}else if (win_or_lose==1){
image.setImageResource(R.drawable.sad_face);
text.setText(LOSEMESSAGE);
wrongAnswers++;
editor.putInt(getString(R.string.wrong_answers), wrongAnswers);
}else{
image.setImageResource(R.drawable.error_icon);
text.setText(ERRORMESSAGE);
}
editor.commit();
dialog.show();
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
}, 5000);
}
private void resetValues(){
setRandoms();
answerEditText.setText("");
questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK);
}
private void checkProcess(){
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.HALF_UP);
int counter = 0;
for( int i=0; i<answerEditText.getText().toString().length(); i++ ) {
if( answerEditText.getText().toString().charAt(i) == '.' || answerEditText.getText().toString().charAt(i) == ',') {
counter++;
}
}
if(counter==0 || counter==1) {
String answer_string = df.format(Double.parseDouble(answerEditText.getText().toString())).replace(',','.');
double answer = Double.parseDouble(answer_string);
switch (action) {
case ADDACTION:
if (answer == (number1 + number2)) {
dialog(0);
resetValues();
rightAddAnswers++;
editor.putInt(getString(R.string.right_add_answers), rightAddAnswers);
} else {
dialog(1);
wrongAddAnswers++;
editor.putInt(getString(R.string.wrong_add_answers), wrongAddAnswers);
}
break;
case SUBACTION:
if (answer == (number1 - number2)) {
dialog(0);
resetValues();
rightSubAnswers++;
editor.putInt(getString(R.string.right_sub_answers), rightSubAnswers);
} else {
dialog(1);
wrongSubAnswers++;
editor.putInt(getString(R.string.wrong_sub_answers), wrongSubAnswers);
}
break;
case MULTACTION:
if (answer == (number1 * number2)) {
dialog(0);
resetValues();
rightMultAnswers++;
editor.putInt(getString(R.string.right_mult_answers), rightMultAnswers);
} else {
dialog(1);
wrongMultAnswers++;
editor.putInt(getString(R.string.wrong_mult_answers), wrongMultAnswers);
}
break;
case DIVACTION:
if (answer == Double.parseDouble(df.format((double) number1 / number2).replace(',','.'))) {
dialog(0);
resetValues();
rightDivAnswers++;
editor.putInt(getString(R.string.right_div_answers), rightDivAnswers);
} else {
dialog(1);
wrongDivAnswers++;
editor.putInt(getString(R.string.wrong_div_answers), wrongDivAnswers);
}
break;
}
editor.commit();
}else {
dialog(-1);
}
}
public void checkButtonPressed(View v){
v.startAnimation(shakeAnimation);
checkProcess();
}
}
|
294_0 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Statistics extends JFrame {
private JLabel sumLabel, genreLabel, minLabel, maxLabel;
private JTextArea area;
private ArrayList<Song> songList = new ArrayList<>();
private JButton exitBtn;
public Statistics(){
prepareUI();
}
public void prepareUI() { //Αρχικοποιούμε το UI
this.setSize(780,420);
this.setTitle("Statistics");
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(true); // Αφαιρούμε από τον χρήστη την δυνατότητα να κάνει resize το window
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
sumLabel = new JLabel();
genreLabel = new JLabel();
minLabel = new JLabel();
maxLabel = new JLabel();
exitBtn = new JButton("Exit");
exitBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose(); //Destroy the JFrame object
}
});
area = new JTextArea();
area.setEditable(false);
JLabel columnsLbl = new JLabel("\nSongId" + " " + "Duration" + " " +
"Title" + " " + "Release date" + " " + "Artist" + " "
+ "Genre");
topPanel.add(sumLabel);
topPanel.add(genreLabel);
topPanel.add(minLabel);
topPanel.add(maxLabel);
topPanel.add(columnsLbl);
bottomPanel.add(exitBtn);
loadFromFile("songlist.txt");
setStatistics();
Image icon = Toolkit.getDefaultToolkit().getImage("icon.png");
this.setIconImage(icon);
this.add(topPanel, BorderLayout.PAGE_START);
this.add(area, BorderLayout.CENTER);
this.add(bottomPanel, BorderLayout.PAGE_END);
this.setVisible(true);
}
private void loadFromFile(String fileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
String[] token;
Song song;
while (reader.ready()) {
line = reader.readLine();
area.append(line);
area.append("\n");
//Χωρίζουμε το κάθε field του array list σε διαφορετικά tokens για να μπορούμε να τα επεξεργαστούμε
token = line.split("\t");
if (token.length == 6) {
song = new Song(token[0], token[1], token[2], token[3], token[4], token[5]);
songList.add(song);
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void setStatistics() {
int sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
String titleOfMax = "", titleOfMin = "";
String genreOfMax = "", genreOfMin = "";
for (Song song : songList) {
int duration = Integer.parseInt(song.getDuration());
if (max < duration){
max = duration;
titleOfMax = song.getTitle();
genreOfMax = song.getGenre();
}
if (min > duration){
min = duration;
titleOfMin = song.getTitle();
genreOfMin = song.getGenre();
}
}
//Μετράει τα genres και επιστρέφει χάρτη με κλειδί το όνομα του genre και value το πλήθος του genre
Map<String, Long> result = songList.stream() //απο list σε stream
.map(Song::getGenre) // απο stream σε χάρτη (map)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
Long genreMax = 0L;
String maxGenre = "";
for(String genre:result.keySet()){
if(result.get(genre) > genreMax){
genreMax = result.get(genre);
maxGenre = genre;
}
}
//Τα εμφανίζουμε στο text area
sumLabel.setText("Total songs: " + songList.size());
genreLabel.setText("The genre with the most songs is " + maxGenre + " with a total of " + result.get(maxGenre) + " songs");
minLabel.setText("The title of the song with the least duration is " + titleOfMin + " and the genre is " + genreOfMin);
maxLabel.setText("The title of the song with the most duration is " + titleOfMax + " and the genre is " + genreOfMax);
}
} | C4Terina/University | Songs/src/Statistics.java | 1,294 | //Αρχικοποιούμε το UI | line_comment | el | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Statistics extends JFrame {
private JLabel sumLabel, genreLabel, minLabel, maxLabel;
private JTextArea area;
private ArrayList<Song> songList = new ArrayList<>();
private JButton exitBtn;
public Statistics(){
prepareUI();
}
public void prepareUI() { //Αρ<SUF>
this.setSize(780,420);
this.setTitle("Statistics");
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(true); // Αφαιρούμε από τον χρήστη την δυνατότητα να κάνει resize το window
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
sumLabel = new JLabel();
genreLabel = new JLabel();
minLabel = new JLabel();
maxLabel = new JLabel();
exitBtn = new JButton("Exit");
exitBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose(); //Destroy the JFrame object
}
});
area = new JTextArea();
area.setEditable(false);
JLabel columnsLbl = new JLabel("\nSongId" + " " + "Duration" + " " +
"Title" + " " + "Release date" + " " + "Artist" + " "
+ "Genre");
topPanel.add(sumLabel);
topPanel.add(genreLabel);
topPanel.add(minLabel);
topPanel.add(maxLabel);
topPanel.add(columnsLbl);
bottomPanel.add(exitBtn);
loadFromFile("songlist.txt");
setStatistics();
Image icon = Toolkit.getDefaultToolkit().getImage("icon.png");
this.setIconImage(icon);
this.add(topPanel, BorderLayout.PAGE_START);
this.add(area, BorderLayout.CENTER);
this.add(bottomPanel, BorderLayout.PAGE_END);
this.setVisible(true);
}
private void loadFromFile(String fileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
String[] token;
Song song;
while (reader.ready()) {
line = reader.readLine();
area.append(line);
area.append("\n");
//Χωρίζουμε το κάθε field του array list σε διαφορετικά tokens για να μπορούμε να τα επεξεργαστούμε
token = line.split("\t");
if (token.length == 6) {
song = new Song(token[0], token[1], token[2], token[3], token[4], token[5]);
songList.add(song);
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void setStatistics() {
int sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
String titleOfMax = "", titleOfMin = "";
String genreOfMax = "", genreOfMin = "";
for (Song song : songList) {
int duration = Integer.parseInt(song.getDuration());
if (max < duration){
max = duration;
titleOfMax = song.getTitle();
genreOfMax = song.getGenre();
}
if (min > duration){
min = duration;
titleOfMin = song.getTitle();
genreOfMin = song.getGenre();
}
}
//Μετράει τα genres και επιστρέφει χάρτη με κλειδί το όνομα του genre και value το πλήθος του genre
Map<String, Long> result = songList.stream() //απο list σε stream
.map(Song::getGenre) // απο stream σε χάρτη (map)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
Long genreMax = 0L;
String maxGenre = "";
for(String genre:result.keySet()){
if(result.get(genre) > genreMax){
genreMax = result.get(genre);
maxGenre = genre;
}
}
//Τα εμφανίζουμε στο text area
sumLabel.setText("Total songs: " + songList.size());
genreLabel.setText("The genre with the most songs is " + maxGenre + " with a total of " + result.get(maxGenre) + " songs");
minLabel.setText("The title of the song with the least duration is " + titleOfMin + " and the genre is " + genreOfMin);
maxLabel.setText("The title of the song with the most duration is " + titleOfMax + " and the genre is " + genreOfMax);
}
} |
5147_17 | /*
* This file is part of CoAnSys project.
* Copyright (c) 2012-2015 ICM-UW
*
* CoAnSys is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* CoAnSys is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.similarity.pig.udf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataType;
import org.apache.pig.data.DefaultDataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import pl.edu.icm.coansys.commons.java.DiacriticsRemover;
import pl.edu.icm.coansys.commons.java.PorterStemmer;
import pl.edu.icm.coansys.commons.java.StackTraceExtractor;
public class ExtendedStemmedPairs extends EvalFunc<DataBag> {
@Override
public Schema outputSchema(Schema input) {
try {
Schema termSchema = new Schema(new Schema.FieldSchema("term",
new Schema(new Schema.FieldSchema("value",
DataType.CHARARRAY)), DataType.TUPLE));
return new Schema(new Schema.FieldSchema(getSchemaName(this
.getClass().getName().toLowerCase(), input), termSchema,
DataType.BAG));
} catch (Exception e) {
log.error("Error in the output Schema creation", e);
log.error(StackTraceExtractor.getStackTrace(e));
return null;
}
}
private String TYPE_OF_REMOVAL = "latin";
private static final String SPACE = " ";
private AllLangStopWordFilter stowordsFilter = null;
public ExtendedStemmedPairs() throws IOException {
stowordsFilter = new AllLangStopWordFilter();
}
public ExtendedStemmedPairs(String params) throws IOException {
TYPE_OF_REMOVAL = params;
stowordsFilter = new AllLangStopWordFilter();
}
public List<String> getStemmedPairs(final String text) throws IOException {
String tmp = text.toLowerCase();
tmp = tmp.replaceAll("[_]+", "_");
tmp = tmp.replaceAll("[-]+", "-");
if(!"latin".equals(TYPE_OF_REMOVAL)){
tmp = tmp.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s'])+", SPACE);
}
tmp = tmp.replaceAll("\\s+", SPACE);
tmp = tmp.trim();
List<String> strings = new ArrayList<String>();
if (tmp.length() == 0) {
return strings;
}
PorterStemmer ps = new PorterStemmer();
for (String s : StringUtils.split(tmp, SPACE)) {
s = s.replaceAll("^[/\\-]+", "");
s = s.replaceAll("[\\-/]+$", "");
if("latin".equals(TYPE_OF_REMOVAL)){
s = s.replaceAll("[^a-z\\d\\-_/ ]+", SPACE);
}
if (s.length() <= 3) {
continue;
}
if (!stowordsFilter.isInAllStopwords(s)) {
s = DiacriticsRemover.removeDiacritics(s);
ps.add(s.toCharArray(), s.length());
ps.stem();
strings.add(ps.toString());
}
}
return strings;
}
@Override
public DataBag exec(Tuple input) throws IOException {
if (input == null || input.size() == 0 || input.get(0) == null) {
return null;
}
try {
List<Tuple> tuples = new ArrayList<Tuple>();
String terms = (String) input.get(0);
for (String s : getStemmedPairs(terms)) {
tuples.add(TupleFactory.getInstance().newTuple(s));
}
return new DefaultDataBag(tuples);
} catch (Exception e) {
throw new IOException("Caught exception processing input row ", e);
}
}
public static void main(String[] args) {
String text = "100688";
System.out.println("PartA: "+DiacriticsRemover.removeDiacritics(text));
// PorterStemmer ps = new PorterStemmer();
// for (String s : text.split(SPACE)) {
// System.out.println("PartB1: "+s);
// s = s.replaceAll("^[/\\-]+", "");
// System.out.println("PartB2: "+s);
// s = s.replaceAll("[\\-/]+$", "");
// System.out.println("PartB3: "+s);
// s = s.replaceAll("^[/\\-_0-9]+$", "");
// System.out.println("PartB4: "+s);
// if (s.length() <= 3) {
// continue;
// }
// s = DiacriticsRemover.removeDiacritics(s);
// System.out.println("PartC: "+s);
// ps.add(s.toCharArray(), s.length());
// ps.stem();
// System.out.println("PartD: "+ps.toString());
// }
// String text = "Μεταφορά τεχνολογίας : " + "παράγων αναπτύξεως ή μέσον "
// + "αποδιαρθρώσεως των οικονομικών " + "του τρίτου κόσμου "
// + "ó Techn,ology Techn, ology";
// System.out.println("--------------");
// System.out.println(DiacriticsRemover.removeDiacritics(text));
// System.out.println("--------------");
// System.out.println(text.replaceAll(
// "([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", ""));
// System.out.println("--------------");
// text = text.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", "");
// text = text.replaceAll("\\s+", " ");
//
// PorterStemmer ps = new PorterStemmer();
// for (String s : text.split(SPACE)) {
// s = s.replaceAll("^[/\\-]+", "");
// s = s.replaceAll("[\\-/]+$", "");
// s = s.replaceAll("^[/\\-_0-9]+$", "");
// if (s.length() <= 2) {
// continue;
// }
// s = DiacriticsRemover.removeDiacritics(s);
// ps.add(s.toCharArray(), s.length());
// ps.stem();
// System.out.println(ps.toString());
// }
}
}
| CeON/CoAnSys | document-similarity/document-similarity-logic/src/main/java/pl/edu/icm/coansys/similarity/pig/udf/ExtendedStemmedPairs.java | 1,966 | // String text = "Μεταφορά τεχνολογίας : " + "παράγων αναπτύξεως ή μέσον " | line_comment | el | /*
* This file is part of CoAnSys project.
* Copyright (c) 2012-2015 ICM-UW
*
* CoAnSys is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* CoAnSys is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.similarity.pig.udf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataType;
import org.apache.pig.data.DefaultDataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import pl.edu.icm.coansys.commons.java.DiacriticsRemover;
import pl.edu.icm.coansys.commons.java.PorterStemmer;
import pl.edu.icm.coansys.commons.java.StackTraceExtractor;
public class ExtendedStemmedPairs extends EvalFunc<DataBag> {
@Override
public Schema outputSchema(Schema input) {
try {
Schema termSchema = new Schema(new Schema.FieldSchema("term",
new Schema(new Schema.FieldSchema("value",
DataType.CHARARRAY)), DataType.TUPLE));
return new Schema(new Schema.FieldSchema(getSchemaName(this
.getClass().getName().toLowerCase(), input), termSchema,
DataType.BAG));
} catch (Exception e) {
log.error("Error in the output Schema creation", e);
log.error(StackTraceExtractor.getStackTrace(e));
return null;
}
}
private String TYPE_OF_REMOVAL = "latin";
private static final String SPACE = " ";
private AllLangStopWordFilter stowordsFilter = null;
public ExtendedStemmedPairs() throws IOException {
stowordsFilter = new AllLangStopWordFilter();
}
public ExtendedStemmedPairs(String params) throws IOException {
TYPE_OF_REMOVAL = params;
stowordsFilter = new AllLangStopWordFilter();
}
public List<String> getStemmedPairs(final String text) throws IOException {
String tmp = text.toLowerCase();
tmp = tmp.replaceAll("[_]+", "_");
tmp = tmp.replaceAll("[-]+", "-");
if(!"latin".equals(TYPE_OF_REMOVAL)){
tmp = tmp.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s'])+", SPACE);
}
tmp = tmp.replaceAll("\\s+", SPACE);
tmp = tmp.trim();
List<String> strings = new ArrayList<String>();
if (tmp.length() == 0) {
return strings;
}
PorterStemmer ps = new PorterStemmer();
for (String s : StringUtils.split(tmp, SPACE)) {
s = s.replaceAll("^[/\\-]+", "");
s = s.replaceAll("[\\-/]+$", "");
if("latin".equals(TYPE_OF_REMOVAL)){
s = s.replaceAll("[^a-z\\d\\-_/ ]+", SPACE);
}
if (s.length() <= 3) {
continue;
}
if (!stowordsFilter.isInAllStopwords(s)) {
s = DiacriticsRemover.removeDiacritics(s);
ps.add(s.toCharArray(), s.length());
ps.stem();
strings.add(ps.toString());
}
}
return strings;
}
@Override
public DataBag exec(Tuple input) throws IOException {
if (input == null || input.size() == 0 || input.get(0) == null) {
return null;
}
try {
List<Tuple> tuples = new ArrayList<Tuple>();
String terms = (String) input.get(0);
for (String s : getStemmedPairs(terms)) {
tuples.add(TupleFactory.getInstance().newTuple(s));
}
return new DefaultDataBag(tuples);
} catch (Exception e) {
throw new IOException("Caught exception processing input row ", e);
}
}
public static void main(String[] args) {
String text = "100688";
System.out.println("PartA: "+DiacriticsRemover.removeDiacritics(text));
// PorterStemmer ps = new PorterStemmer();
// for (String s : text.split(SPACE)) {
// System.out.println("PartB1: "+s);
// s = s.replaceAll("^[/\\-]+", "");
// System.out.println("PartB2: "+s);
// s = s.replaceAll("[\\-/]+$", "");
// System.out.println("PartB3: "+s);
// s = s.replaceAll("^[/\\-_0-9]+$", "");
// System.out.println("PartB4: "+s);
// if (s.length() <= 3) {
// continue;
// }
// s = DiacriticsRemover.removeDiacritics(s);
// System.out.println("PartC: "+s);
// ps.add(s.toCharArray(), s.length());
// ps.stem();
// System.out.println("PartD: "+ps.toString());
// }
// St<SUF>
// + "αποδιαρθρώσεως των οικονομικών " + "του τρίτου κόσμου "
// + "ó Techn,ology Techn, ology";
// System.out.println("--------------");
// System.out.println(DiacriticsRemover.removeDiacritics(text));
// System.out.println("--------------");
// System.out.println(text.replaceAll(
// "([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", ""));
// System.out.println("--------------");
// text = text.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", "");
// text = text.replaceAll("\\s+", " ");
//
// PorterStemmer ps = new PorterStemmer();
// for (String s : text.split(SPACE)) {
// s = s.replaceAll("^[/\\-]+", "");
// s = s.replaceAll("[\\-/]+$", "");
// s = s.replaceAll("^[/\\-_0-9]+$", "");
// if (s.length() <= 2) {
// continue;
// }
// s = DiacriticsRemover.removeDiacritics(s);
// ps.add(s.toCharArray(), s.length());
// ps.stem();
// System.out.println(ps.toString());
// }
}
}
|
13502_1 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package apartease;
import java.sql.ResultSetMetaData;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Θεοδόσης
*/
public class Profile extends javax.swing.JFrame implements DBConnection{
/**
* Creates new form Customer_Account
*/
public Profile() {
initComponents();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
try
{
Connection con=DBConnection.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select user_id from LOGIN_STATUS where id = 1");
rs.next();
int user_id = Integer.valueOf(rs.getString(1));
rs=st.executeQuery("select user.id AS 'ID',user.name AS 'Name',user.surname AS 'Surname',user.email AS 'E-mail',user.user_type AS 'Type',user.birth_date AS 'Birth Date',user.description AS 'Description',user.wallet AS 'wallet',building.address AS 'Address',apartment.number AS 'Number' ,apartment.floor AS 'Floor' from user,user_has_apartment,apartment,building where user.id='"+user_id+"' AND user.id=user_has_apartment.user_id AND user_has_apartment.apartment_id=apartment.id AND apartment.Building_id=building.id");
ResultSetMetaData rsmd=rs.getMetaData();
int cols=rsmd.getColumnCount();
String[] colName= new String[cols];
for (int i=0;i<cols;i++)
colName[i]=rsmd.getColumnName(i+1);
model.setColumnIdentifiers(colName);
String no,f_name,l_name,email,u_type,date,description,wallet,address,apart_num,apart_floor;
while(rs.next()){
no=rs.getString(1);
f_name=rs.getString(2);
l_name=rs.getString(3);
email=rs.getString(4);
u_type=rs.getString(5);
date=rs.getString(6);
description=rs.getString(7);
wallet=rs.getString(8);
address=rs.getString(9);
apart_num=rs.getString(10);
apart_floor=rs.getString(11);
String[] row={no,f_name,l_name,email,u_type, date, description,wallet,address,apart_num,apart_floor};
model.addRow(row);
}
st.close();
con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane3 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox<>();
jButton6 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane3.setViewportView(jTable1);
jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
jLabel1.setText("Πληροφορίες Λογαριασμού");
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Όνομα", "Επώνυμο", "E-mail","Περιγραφή"}));
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jButton6.setText("Αποθήκευση");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveProfileButton(evt);
}
});
jTextField1.setText("Πληκτρολογείστε..");
jPanel2.setBackground(new java.awt.Color(204, 204, 204));
jButton7.setText("Αποσύνδεση");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton8.setText("Πίσω");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(16, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(252, 252, 252)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 655, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(272, 272, 272)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jComboBox2, 0, 115, Short.MAX_VALUE)
.addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
.addContainerGap(41, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton6)
.addGap(0, 100, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox2ActionPerformed
private void saveProfileButton(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProfileButton
try
{
String new_value=jTextField1.getText();
Connection con=DBConnection.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select user_id from login_status where id=1");
rs.next();
int user_id = Integer.valueOf(rs.getString(1));
String column=jComboBox2.getSelectedItem().toString();
if(column.equals("Όνομα")){
Statement stmt = connectdata();
if (new_value.length()<45){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set name='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς το όνομα σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}else if(column.equals("Επώνυμο")){
Statement stmt = connectdata();
if (new_value.length()<45){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set surname='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς το επώνυμο σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}else if(column.equals("E-mail")){
Statement stmt = connectdata();
if (new_value.length()<45){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set email='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς το E-mail σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}else if(column.equals("Περιγραφή")){
Statement stmt = connectdata();
if (new_value.length()<100){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set description='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς την περιγραφή σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
}//GEN-LAST:event_saveProfileButton
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
try
{
Statement stmt = connectdata();
stmt.execute("delete from LOGIN_STATUS where id = 1");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
this.dispose();
Welcome_Page ob = new Welcome_Page();
ob.setVisible(true);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
this.dispose();
HomePage ob = new HomePage();
ob.setVisible(true);
}//GEN-LAST:event_jButton8ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Profile().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JComboBox<String> jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
| ChrisLoukas007/ApartEase | ApartEase/src/apartease/Profile.java | 4,552 | /**
*
* @author Θεοδόσης
*/ | block_comment | el | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package apartease;
import java.sql.ResultSetMetaData;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @au<SUF>*/
public class Profile extends javax.swing.JFrame implements DBConnection{
/**
* Creates new form Customer_Account
*/
public Profile() {
initComponents();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
try
{
Connection con=DBConnection.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select user_id from LOGIN_STATUS where id = 1");
rs.next();
int user_id = Integer.valueOf(rs.getString(1));
rs=st.executeQuery("select user.id AS 'ID',user.name AS 'Name',user.surname AS 'Surname',user.email AS 'E-mail',user.user_type AS 'Type',user.birth_date AS 'Birth Date',user.description AS 'Description',user.wallet AS 'wallet',building.address AS 'Address',apartment.number AS 'Number' ,apartment.floor AS 'Floor' from user,user_has_apartment,apartment,building where user.id='"+user_id+"' AND user.id=user_has_apartment.user_id AND user_has_apartment.apartment_id=apartment.id AND apartment.Building_id=building.id");
ResultSetMetaData rsmd=rs.getMetaData();
int cols=rsmd.getColumnCount();
String[] colName= new String[cols];
for (int i=0;i<cols;i++)
colName[i]=rsmd.getColumnName(i+1);
model.setColumnIdentifiers(colName);
String no,f_name,l_name,email,u_type,date,description,wallet,address,apart_num,apart_floor;
while(rs.next()){
no=rs.getString(1);
f_name=rs.getString(2);
l_name=rs.getString(3);
email=rs.getString(4);
u_type=rs.getString(5);
date=rs.getString(6);
description=rs.getString(7);
wallet=rs.getString(8);
address=rs.getString(9);
apart_num=rs.getString(10);
apart_floor=rs.getString(11);
String[] row={no,f_name,l_name,email,u_type, date, description,wallet,address,apart_num,apart_floor};
model.addRow(row);
}
st.close();
con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane3 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox<>();
jButton6 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane3.setViewportView(jTable1);
jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
jLabel1.setText("Πληροφορίες Λογαριασμού");
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Όνομα", "Επώνυμο", "E-mail","Περιγραφή"}));
jComboBox2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox2ActionPerformed(evt);
}
});
jButton6.setText("Αποθήκευση");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveProfileButton(evt);
}
});
jTextField1.setText("Πληκτρολογείστε..");
jPanel2.setBackground(new java.awt.Color(204, 204, 204));
jButton7.setText("Αποσύνδεση");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton8.setText("Πίσω");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(16, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(252, 252, 252)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 655, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(272, 272, 272)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jComboBox2, 0, 115, Short.MAX_VALUE)
.addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
.addContainerGap(41, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton6)
.addGap(0, 100, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox2ActionPerformed
private void saveProfileButton(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProfileButton
try
{
String new_value=jTextField1.getText();
Connection con=DBConnection.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select user_id from login_status where id=1");
rs.next();
int user_id = Integer.valueOf(rs.getString(1));
String column=jComboBox2.getSelectedItem().toString();
if(column.equals("Όνομα")){
Statement stmt = connectdata();
if (new_value.length()<45){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set name='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς το όνομα σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}else if(column.equals("Επώνυμο")){
Statement stmt = connectdata();
if (new_value.length()<45){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set surname='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς το επώνυμο σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}else if(column.equals("E-mail")){
Statement stmt = connectdata();
if (new_value.length()<45){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set email='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς το E-mail σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}else if(column.equals("Περιγραφή")){
Statement stmt = connectdata();
if (new_value.length()<100){
int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να πραγματοποιήσετε αυτή την αλλαγή;");
if (result == 0){
stmt.executeUpdate("update user set description='"+new_value+"' where id='"+user_id+"'");
JOptionPane.showMessageDialog(this,"Αλλάξατε επιτυχώς την περιγραφή σας σε "+new_value+"!");
this.dispose();
Profile ob = new Profile();
ob.setVisible(true);}
else if (result == 1){
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
else{
JOptionPane.showMessageDialog(this,"Ακύρωση ενέργειας");
}
}
else{
JOptionPane.showMessageDialog(this,"Το όριο χαρακτήρων είναι 45. Προσπαθήστε ξανά!");
}
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
}//GEN-LAST:event_saveProfileButton
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
try
{
Statement stmt = connectdata();
stmt.execute("delete from LOGIN_STATUS where id = 1");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
this.dispose();
Welcome_Page ob = new Welcome_Page();
ob.setVisible(true);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
this.dispose();
HomePage ob = new HomePage();
ob.setVisible(true);
}//GEN-LAST:event_jButton8ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Profile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Profile().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JComboBox<String> jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
|
16407_3 | import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
public class Buffer{
private int contents;
//private int size;
//private int front, back;
private int counter = 0;
private Lock lock = new ReentrantLock();
private Condition bufferFull = lock.newCondition();
private Condition bufferEmpty = lock.newCondition();
// Constructor
public Buffer() {
//this.size = s; δεν χρειάζεται αφου το size ειναι 1
contents = 0;
//this.front = 0;
//this.back = size - 1;
}
// Put an item into buffer
public void put(int data) {
lock.lock();
try {
while (counter == 1) {
System.out.println("The buffer is full");
try {
bufferFull.await();
} catch (InterruptedException e) { }
}
contents = data;
counter++;
System.out.println("Prod " + Thread.currentThread().getName() + " No "+ data + " Count = " + counter);
//buffer was empty
bufferEmpty.signalAll();
} finally {
lock.unlock() ;
}
}
// Get an item from bufffer
public int get() {
int data = 0;
lock.lock();
try {
while (counter == 0) {
System.out.println("The buffer is empty");
try {
bufferEmpty.await();
} catch (InterruptedException e) { }
}
data = contents;
System.out.println(" Cons " + Thread.currentThread().getName() + " No "+ data + " Count = " + (counter-1));
counter--;
//buffer was full
bufferFull.signalAll();
} finally {
lock.unlock() ;
}
return data;
}
}
| ChristosPts/University-of-Macedonia | Parallel and Distributed Computing/Lab7/LockBufferSize1/Buffer.java | 501 | //this.size = s; δεν χρειάζεται αφου το size ειναι 1
| line_comment | el | import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
public class Buffer{
private int contents;
//private int size;
//private int front, back;
private int counter = 0;
private Lock lock = new ReentrantLock();
private Condition bufferFull = lock.newCondition();
private Condition bufferEmpty = lock.newCondition();
// Constructor
public Buffer() {
//th<SUF>
contents = 0;
//this.front = 0;
//this.back = size - 1;
}
// Put an item into buffer
public void put(int data) {
lock.lock();
try {
while (counter == 1) {
System.out.println("The buffer is full");
try {
bufferFull.await();
} catch (InterruptedException e) { }
}
contents = data;
counter++;
System.out.println("Prod " + Thread.currentThread().getName() + " No "+ data + " Count = " + counter);
//buffer was empty
bufferEmpty.signalAll();
} finally {
lock.unlock() ;
}
}
// Get an item from bufffer
public int get() {
int data = 0;
lock.lock();
try {
while (counter == 0) {
System.out.println("The buffer is empty");
try {
bufferEmpty.await();
} catch (InterruptedException e) { }
}
data = contents;
System.out.println(" Cons " + Thread.currentThread().getName() + " No "+ data + " Count = " + (counter-1));
counter--;
//buffer was full
bufferFull.signalAll();
} finally {
lock.unlock() ;
}
return data;
}
}
|
352_0 | package regenaration.team4.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import regenaration.team4.WebAppConfig;
import regenaration.team4.entities.Appointment;
import regenaration.team4.entities.Citizen;
import regenaration.team4.entities.User;
import regenaration.team4.repositories.AppointmentRepository;
import regenaration.team4.repositories.CitizenRepository;
import regenaration.team4.repositories.DoctorRepository;
import regenaration.team4.repositories.UserRepository;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class DoctorService {
@Autowired
UserRepository userRepository;
@Autowired
DoctorRepository doctorRepository;
@Autowired
AppointmentRepository appointmentRepository;
@Autowired
CitizenRepository citizenRepository;
@PreAuthorize("hasRole('DOCTOR')")
public List<Appointment> getAppointments(@RequestParam(value = "fromDate", defaultValue = "") String fromDate,
@RequestParam(value = "toDate", defaultValue = "") String toDate,
@RequestParam(value = "description", defaultValue = "") String description,
Principal principal) throws ParseException {
//κανω το string που θα μου φέρουν date type. μαλλον λάθος
User loggedInUser = userRepository.findByUsername(principal.getName());
Date dateFrom=new SimpleDateFormat("dd/MM/yyyy").parse(fromDate);
Date dateTo = new SimpleDateFormat("dd/MM/yyyy").parse(toDate);
if (loggedInUser.getRole() == WebAppConfig.Role.DOCTOR) {
Integer docId = loggedInUser.getDoctor().getDoctor_id();
List<Appointment> appointments = appointmentRepository.findAll();
List<Appointment> response = new ArrayList<>();
for (Appointment a : appointments) {
if (a.getAppointment_date().compareTo(dateFrom) >= 0 && a.getAppointment_date().compareTo(dateTo) <= 0 && a.getDoctor().getDoctor_id() == docId) {
if (a.getAppointment_description().toLowerCase().contains(description.toLowerCase())) {
response.add(a);
}
}
}
return response;
}
return null;
}
//βρες το ραντεβού
@PreAuthorize("hasRole('DOCTOR')")
@PostAuthorize("returnObject.doctor.user.username == authentication.principal.username")
public Optional<Appointment> doctorGetAppointment(@PathVariable Long id) {
return appointmentRepository.findById(id);
}
// βρες τον πολίτη που έχει το ραντεβού
@PreAuthorize("hasRole('DOCTOR')")
public Optional<Citizen> getCitizen(@PathVariable Long id) {
return citizenRepository.findById(id);
}
} | CodeHubGreece/Java4Web2019_SKG_Team4 | project/src/main/java/regenaration/team4/services/DoctorService.java | 792 | //κανω το string που θα μου φέρουν date type. μαλλον λάθος | line_comment | el | package regenaration.team4.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import regenaration.team4.WebAppConfig;
import regenaration.team4.entities.Appointment;
import regenaration.team4.entities.Citizen;
import regenaration.team4.entities.User;
import regenaration.team4.repositories.AppointmentRepository;
import regenaration.team4.repositories.CitizenRepository;
import regenaration.team4.repositories.DoctorRepository;
import regenaration.team4.repositories.UserRepository;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class DoctorService {
@Autowired
UserRepository userRepository;
@Autowired
DoctorRepository doctorRepository;
@Autowired
AppointmentRepository appointmentRepository;
@Autowired
CitizenRepository citizenRepository;
@PreAuthorize("hasRole('DOCTOR')")
public List<Appointment> getAppointments(@RequestParam(value = "fromDate", defaultValue = "") String fromDate,
@RequestParam(value = "toDate", defaultValue = "") String toDate,
@RequestParam(value = "description", defaultValue = "") String description,
Principal principal) throws ParseException {
//κα<SUF>
User loggedInUser = userRepository.findByUsername(principal.getName());
Date dateFrom=new SimpleDateFormat("dd/MM/yyyy").parse(fromDate);
Date dateTo = new SimpleDateFormat("dd/MM/yyyy").parse(toDate);
if (loggedInUser.getRole() == WebAppConfig.Role.DOCTOR) {
Integer docId = loggedInUser.getDoctor().getDoctor_id();
List<Appointment> appointments = appointmentRepository.findAll();
List<Appointment> response = new ArrayList<>();
for (Appointment a : appointments) {
if (a.getAppointment_date().compareTo(dateFrom) >= 0 && a.getAppointment_date().compareTo(dateTo) <= 0 && a.getDoctor().getDoctor_id() == docId) {
if (a.getAppointment_description().toLowerCase().contains(description.toLowerCase())) {
response.add(a);
}
}
}
return response;
}
return null;
}
//βρες το ραντεβού
@PreAuthorize("hasRole('DOCTOR')")
@PostAuthorize("returnObject.doctor.user.username == authentication.principal.username")
public Optional<Appointment> doctorGetAppointment(@PathVariable Long id) {
return appointmentRepository.findById(id);
}
// βρες τον πολίτη που έχει το ραντεβού
@PreAuthorize("hasRole('DOCTOR')")
public Optional<Citizen> getCitizen(@PathVariable Long id) {
return citizenRepository.findById(id);
}
} |
1481_12 | package Games;
/*
* @author Despina-Eleana Chrysou
*/
import GetData.*;
import javax.swing.*;
public class Data extends javax.swing.JApplet {
/** Initializes the applet Data */
@Override
public void init() {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 204, 204));
jLabel1.setFont(new java.awt.Font("Tahoma", 2, 14));
jLabel1.setForeground(new java.awt.Color(51, 0, 51));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Αρχείο: data.txt");
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Δημιούργησε τα δεδομένα");
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Default Path: C:\\temp");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(95, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jLabel1, jLabel2});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(75, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2});
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JOptionPane.showMessageDialog(this, "Περίμενε μέχρι να εμφανιστεί το μήνυμα ότι είναι έτοιμο το αρχείο...");
Jena.GetResults();
/*ReadFromFile GetData = new ReadFromFile();
int [] index1=GetData.index1();
int indexall1=0;
for (int i=0;i<31;i++) {
int k=i+1;
int index2=index1[i]-1;
indexall1=index2+indexall1;
//System.out.println("Το ερώτημα "+k+" έχει "+index2+" εγγραφές");
System.out.println(index2);
}
int index=GetData.indexall();
System.out.println("Όλες οι εγγραφές είναι: "+indexall1);
System.out.println("Αν στο "+indexall1+" προστεθούν και οι 31 γραμμές που περιέχουν τα ερωτήματα, τότε το συνολικό πλήθος γραμμών του πίνακα είναι: "+index);
int arraydimension=index*4;
System.out.println("Το συνολικό πλήθος δεδομένων είναι: "+index+" x 4 (4 στήλες)= "+arraydimension);*/
JOptionPane.showMessageDialog(this, "Eτοιμο το αρχείο 31queries.txt!");
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
| ComradeHadi/DBpedia-Game | ssg/src/Games/Data.java | 1,871 | /*ReadFromFile GetData = new ReadFromFile();
int [] index1=GetData.index1();
int indexall1=0;
for (int i=0;i<31;i++) {
int k=i+1;
int index2=index1[i]-1;
indexall1=index2+indexall1;
//System.out.println("Το ερώτημα "+k+" έχει "+index2+" εγγραφές");
System.out.println(index2);
}
int index=GetData.indexall();
System.out.println("Όλες οι εγγραφές είναι: "+indexall1);
System.out.println("Αν στο "+indexall1+" προστεθούν και οι 31 γραμμές που περιέχουν τα ερωτήματα, τότε το συνολικό πλήθος γραμμών του πίνακα είναι: "+index);
int arraydimension=index*4;
System.out.println("Το συνολικό πλήθος δεδομένων είναι: "+index+" x 4 (4 στήλες)= "+arraydimension);*/ | block_comment | el | package Games;
/*
* @author Despina-Eleana Chrysou
*/
import GetData.*;
import javax.swing.*;
public class Data extends javax.swing.JApplet {
/** Initializes the applet Data */
@Override
public void init() {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 204, 204));
jLabel1.setFont(new java.awt.Font("Tahoma", 2, 14));
jLabel1.setForeground(new java.awt.Color(51, 0, 51));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Αρχείο: data.txt");
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Δημιούργησε τα δεδομένα");
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Default Path: C:\\temp");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(95, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jLabel1, jLabel2});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(75, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2});
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JOptionPane.showMessageDialog(this, "Περίμενε μέχρι να εμφανιστεί το μήνυμα ότι είναι έτοιμο το αρχείο...");
Jena.GetResults();
/*Rea<SUF>*/
JOptionPane.showMessageDialog(this, "Eτοιμο το αρχείο 31queries.txt!");
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
|
17268_0 | package gr.smartcity.hackathon.hackathonproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
/**
* Αυτή η δραστηριότητα υλοποιεί ένα σύνολο ιδιωτικών υπηρεσιών.
*/
public class PrivateServices extends AppCompatActivity {
DatabaseConnection conn;
ECustomUser user ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_private_services);
conn = (DatabaseConnection)getIntent().getSerializableExtra("DB_CONN");
user = (ECustomUser)getIntent().getSerializableExtra("USER_DET");
Button plumbers = (Button)findViewById(R.id.button1);
plumbers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "private");
intent.putExtra("SPEC", "plumber");
startActivity(intent);
}
});
Button freezers = (Button)findViewById(R.id.button2);
freezers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "private");
intent.putExtra("SPEC", "freezer");
startActivity(intent);
}
});
Button gardeners = (Button)findViewById(R.id.button3);
gardeners.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "private");
intent.putExtra("SPEC", "gardener");
startActivity(intent);
}
});
Button allservices = (Button)findViewById(R.id.button4);
allservices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "allprivate");
startActivity(intent);
}
});
}
}
| Crowdhackathon-SmartCity2/GMx2 | 004/eMustoras/HackathonProject/app/src/main/java/gr/smartcity/hackathon/hackathonproject/PrivateServices.java | 650 | /**
* Αυτή η δραστηριότητα υλοποιεί ένα σύνολο ιδιωτικών υπηρεσιών.
*/ | block_comment | el | package gr.smartcity.hackathon.hackathonproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
/**
* Αυτ<SUF>*/
public class PrivateServices extends AppCompatActivity {
DatabaseConnection conn;
ECustomUser user ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_private_services);
conn = (DatabaseConnection)getIntent().getSerializableExtra("DB_CONN");
user = (ECustomUser)getIntent().getSerializableExtra("USER_DET");
Button plumbers = (Button)findViewById(R.id.button1);
plumbers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "private");
intent.putExtra("SPEC", "plumber");
startActivity(intent);
}
});
Button freezers = (Button)findViewById(R.id.button2);
freezers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "private");
intent.putExtra("SPEC", "freezer");
startActivity(intent);
}
});
Button gardeners = (Button)findViewById(R.id.button3);
gardeners.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "private");
intent.putExtra("SPEC", "gardener");
startActivity(intent);
}
});
Button allservices = (Button)findViewById(R.id.button4);
allservices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ServicePreview.class);
intent.putExtra("DB_CONN", conn);
intent.putExtra("USER_DET", user);
intent.putExtra("SER_TYPE", "allprivate");
startActivity(intent);
}
});
}
}
|
7139_1 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Πρόγραμμα που ελέγχει εάν
* το έτος είναι δίσεκτο ή όχι
*
* @author D1MK4L
*/
public class BisectApp {
public static void main(String[] args) {
int year = 0;
final int CONT1 = 4;
final int CONT2 = 100;
final int CONT3 = 400;
boolean bisect = false;
while(!bisect) {
Scanner in = new Scanner(System.in);
System.out.print("Δώσε με ακέραιο αριθμό το έτος: ");
year = in.nextInt();
if ((year % CONT1 == 0) && (year % CONT2 > 0) || (year % CONT3 == 0)) { //Συνθήκη ελέγχου δίσεκτου 'ετους
bisect = true;
}
if (!bisect) {
System.out.println("το " + year + " δεν είναι δίσεκτο!");
} else if (bisect) {
System.out.println("το " + year + " είναι δίσεκτο!");
}
}
}
}
| D1MK4L/coding-factory-5-java | src/gr/aueb/cf/ch3/BisectApp.java | 362 | //Συνθήκη ελέγχου δίσεκτου 'ετους | line_comment | el | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Πρόγραμμα που ελέγχει εάν
* το έτος είναι δίσεκτο ή όχι
*
* @author D1MK4L
*/
public class BisectApp {
public static void main(String[] args) {
int year = 0;
final int CONT1 = 4;
final int CONT2 = 100;
final int CONT3 = 400;
boolean bisect = false;
while(!bisect) {
Scanner in = new Scanner(System.in);
System.out.print("Δώσε με ακέραιο αριθμό το έτος: ");
year = in.nextInt();
if ((year % CONT1 == 0) && (year % CONT2 > 0) || (year % CONT3 == 0)) { //Συ<SUF>
bisect = true;
}
if (!bisect) {
System.out.println("το " + year + " δεν είναι δίσεκτο!");
} else if (bisect) {
System.out.println("το " + year + " είναι δίσεκτο!");
}
}
}
}
|
14842_17 | package net.stemmaweb.stemmaserver.integrationtests;
import junit.framework.TestCase;
import net.stemmaweb.model.*;
import net.stemmaweb.services.GraphDatabaseServiceProvider;
import net.stemmaweb.stemmaserver.Util;
import org.glassfish.jersey.test.JerseyTest;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.test.TestGraphDatabaseFactory;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
public class RelationTypeTest extends TestCase {
private GraphDatabaseService db;
private JerseyTest jerseyTest;
private String tradId;
private HashMap<String,String> readingLookup;
public void setUp() throws Exception {
super.setUp();
db = new GraphDatabaseServiceProvider(new TestGraphDatabaseFactory().newImpermanentDatabase()).getDatabase();
Util.setupTestDB(db, "1");
// Create a JerseyTestServer for the necessary REST API calls
jerseyTest = Util.setupJersey();
Response jerseyResult = Util.createTraditionFromFileOrString(jerseyTest, "Tradition", "LR", "1",
"src/TestFiles/john.csv", "csv");
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
tradId = Util.getValueFromJson(jerseyResult, "tradId");
readingLookup = Util.makeReadingLookup(jerseyTest, tradId);
}
public void testInitialRelationTypes() {
// Initially, the only defined relation type should be the "collated" one for the CSV input.
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtypes")
.request()
.get();
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
List<RelationTypeModel> allRelTypes = jerseyResult.readEntity(new GenericType<>() {});
assertEquals(1, allRelTypes.size());
assertEquals("collated", allRelTypes.get(0).getName());
}
public void testCreateRelationAddType() {
// Find the 'legei' readings to relate
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship, check that there is a suitable relationship type created
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setDisplayform("λέγει");
newRel.setType("spelling");
newRel.setIs_significant("no");
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
// Now check that the spelling relation type has been created
List<RelationTypeModel> allRelTypes = jerseyTest.target("/tradition/" + tradId + "/relationtypes")
.request()
.get(new GenericType<>() {});
assertEquals(2, allRelTypes.size());
RelationTypeModel rtm = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request().get(RelationTypeModel.class);
assertEquals("spelling", rtm.getName());
assertEquals(1, rtm.getBindlevel());
assertTrue(rtm.getIs_colocation());
}
private void checkExpectedRelations(HashSet<String> createdRels, HashSet<String> expectedLinks) {
try (Transaction tx = db.beginTx()) {
for (String rid : createdRels) {
Relationship link = db.getRelationshipById(Long.valueOf(rid));
String lookfor = String.format("%s -> %s: %s",
link.getStartNode().getId(), link.getEndNode().getId(), link.getProperty("type"));
String lookrev = String.format("%s -> %s: %s",
link.getEndNode().getId(), link.getStartNode().getId(), link.getProperty("type"));
String message = String.format("looking for %s in %s", lookfor,
java.util.Arrays.toString(expectedLinks.toArray()));
assertTrue(message,expectedLinks.remove(lookfor) ^ expectedLinks.remove(lookrev));
}
tx.success();
}
assertTrue(expectedLinks.isEmpty());
}
public void testAddExplicitRelationType() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship type of our own
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("spelling");
rtm.setDescription("A weaker version of the spelling relationship");
rtm.setIs_colocation(true);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// Now use it
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setDisplayform("λέγει");
newRel.setType("spelling");
newRel.setIs_significant("no");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
// Check that our relation type hasn't changed
List<RelationTypeModel> allRelTypes = jerseyTest.target("/tradition/" + tradId + "/relationtypes")
.request()
.get(new GenericType<>() {});
assertEquals(2, allRelTypes.size());
RelationTypeModel spel = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request().get(RelationTypeModel.class);
assertEquals("spelling", spel.getName());
assertEquals("A weaker version of the spelling relationship", spel.getDescription());
assertEquals(10, spel.getBindlevel());
}
public void testAddDefaultType() {
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("spelling");
rtm.setDefaultsettings(true);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request(MediaType.APPLICATION_JSON).put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
RelationTypeModel created = jerseyResult.readEntity(RelationTypeModel.class);
assertEquals("spelling", created.getName());
assertNull(created.getDefaultsettings());
assertEquals("These are the same reading, spelled differently.", created.getDescription());
assertEquals(1, created.getBindlevel());
assertTrue(created.getIs_colocation());
assertTrue(created.getIs_transitive());
// Now try setting the same default relation again, which should fail
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request(MediaType.APPLICATION_JSON).put(Entity.json(rtm));
assertEquals(Response.Status.CONFLICT.getStatusCode(), jerseyResult.getStatus());
}
public void testNonGeneralizable() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship type of our own
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("important");
rtm.setDescription("Something we care about for our own reasons");
rtm.setIs_colocation(true);
rtm.setIs_generalizable(false);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/important")
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// Now use it
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setType("important");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CONFLICT.getStatusCode(), jerseyResult.getStatus());
}
public void testUseRegular() {
// Set a normal form
String auTw = readingLookup.getOrDefault("αυΤω/3", "17");
String autwi = readingLookup.getOrDefault("αὐτῷ/3", "17");
KeyPropertyModel kp = new KeyPropertyModel();
kp.setKey("normal_form");
kp.setProperty("αυτῶ");
ReadingChangePropertyModel newNormal = new ReadingChangePropertyModel();
newNormal.addProperty(kp);
Response jerseyResult = jerseyTest.target("/reading/" + auTw)
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(newNormal));
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
// Now make the relation
RelationModel newRel = new RelationModel();
newRel.setSource(autwi);
newRel.setTarget(auTw);
newRel.setType("grammatical");
newRel.setScope("tradition");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// and check that the normal form αυτῶ was found at rank 28.
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
assertEquals(0, result.getReadings().size());
for (RelationModel rm : result.getRelations()) {
if (rm.getSource().equals(autwi)) continue;
ReadingModel otherRankReading = jerseyTest.target("/reading/" + rm.getTarget())
.request()
.get(new GenericType<ReadingModel>() {});
assertEquals("αυτῶ", otherRankReading.getText());
}
}
public void testSimpleTransitivity() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
String Legei = readingLookup.getOrDefault("Λεγει/1", "17");
// Collect relationship IDs
HashSet<String> createdRels = new HashSet<>();
HashSet<String> expectedLinks = new HashSet<>();
// Set the first link
RelationModel newRel = new RelationModel();
newRel.setSource(legei);
newRel.setTarget(Legei);
newRel.setScope("local");
newRel.setType("spelling");
expectedLinks.add(String.format("%s -> %s: spelling", legei, Legei));
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
// Set the second link
newRel.setTarget(legeiAcute);
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
expectedLinks.add(String.format("%s -> %s: spelling", legei, legeiAcute));
expectedLinks.add(String.format("%s -> %s: spelling", Legei, legeiAcute));
checkExpectedRelations(createdRels, expectedLinks);
}
public void testBindlevelTransitivity() {
// Use πάλιν at 12 and 55
String palin = readingLookup.getOrDefault("παλιν/12", "17");
String pali_ = readingLookup.getOrDefault("παλι¯/12", "17");
String Palin = readingLookup.getOrDefault("Παλιν/12", "17");
String palinac = readingLookup.getOrDefault("πάλιν/12", "17");
String palin58 = readingLookup.getOrDefault("παλιν/55", "17");
String pali_58 = readingLookup.getOrDefault("παλι¯/55", "17");
String Palin58 = readingLookup.getOrDefault("Παλιν/55", "17");
String palinac58 = readingLookup.getOrDefault("πάλιν/55", "17");
// Collect relationship IDs
HashSet<String> createdRels = new HashSet<>();
HashSet<String> expectedLinks = new HashSet<>();
// Set the first link
RelationModel newRel = new RelationModel();
newRel.setSource(palin);
newRel.setTarget(Palin);
newRel.setScope("tradition");
newRel.setType("orthographic");
expectedLinks.add(String.format("%s -> %s: orthographic", palin, Palin));
expectedLinks.add(String.format("%s -> %s: orthographic", palin58, Palin58));
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
// Set the second link, should result in one extra per rank
newRel.setTarget(pali_);
newRel.setType("spelling");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(4, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
expectedLinks.add(String.format("%s -> %s: spelling", palin, pali_));
expectedLinks.add(String.format("%s -> %s: spelling", palin58, pali_58));
expectedLinks.add(String.format("%s -> %s: spelling", Palin, pali_));
expectedLinks.add(String.format("%s -> %s: spelling", Palin58, pali_58));
// Set the third link, should result in two extra per rank
newRel.setSource(Palin);
newRel.setTarget(palinac);
newRel.setType("orthographic");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(6, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
expectedLinks.add(String.format("%s -> %s: orthographic", Palin, palinac));
expectedLinks.add(String.format("%s -> %s: orthographic", Palin58, palinac58));
expectedLinks.add(String.format("%s -> %s: spelling", pali_, palinac));
expectedLinks.add(String.format("%s -> %s: spelling", pali_58, palinac58));
expectedLinks.add(String.format("%s -> %s: orthographic", palin, palinac));
expectedLinks.add(String.format("%s -> %s: orthographic", palin58, palinac58));
checkExpectedRelations(createdRels, expectedLinks);
}
public void testTransitivityReRanking() {
// Use the εὑρίσκω variants at ranks 22 and 24/25
String eurisko22 = readingLookup.getOrDefault("εὑρίσκω/22", "17");
String euricko22 = readingLookup.getOrDefault("ε̣υριϲκω/22", "17");
String euricko24 = readingLookup.getOrDefault("ευριϲκω/24", "17");
String eurecko24 = readingLookup.getOrDefault("ευρηϲκω/24", "17");
String ricko25 = readingLookup.getOrDefault("ριϲκω/25", "17");
HashSet<String> testReadings = new HashSet<>();
// Remove all the 'collated' relations and then re-rank from the beginning.
for (RelationModel rm : jerseyTest.target("/tradition/" + tradId + "/relations")
.request().get(new GenericType<List<RelationModel>>() {})) {
if (rm.getType().equals("collated")) {
Response rd = jerseyTest.target("/tradition/" + tradId + "/relation/remove")
.request(MediaType.APPLICATION_JSON).post(Entity.json(rm));
assertEquals(Response.Status.OK.getStatusCode(), rd.getStatus());
}
}
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/initRanks")
.request()
.get();
assertEquals("success", Util.getValueFromJson(jerseyResult, "result"));
// First make the same-rank relations
RelationModel newRel = new RelationModel();
newRel.setSource(eurisko22);
newRel.setTarget(euricko22);
newRel.setScope("local");
newRel.setType("orthographic");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
assertEquals(0, result.getReadings().size());
testReadings.add(eurisko22);
testReadings.add(euricko22);
try (Transaction tx = db.beginTx()) {
for (String nid : testReadings) {
Node n = db.getNodeById(Long.parseLong(nid));
assertEquals(22L, n.getProperty("rank"));
}
tx.success();
}
newRel.setSource(euricko24);
newRel.setTarget(eurecko24);
newRel.setType("spelling");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
assertEquals(0, result.getReadings().size());
testReadings.add(euricko24);
testReadings.add(eurecko24);
// Now join them together, and test that the appropriate ranks changed
newRel.setTarget(eurisko22);
newRel.setType("orthographic");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(4, result.getRelations().size());
assertEquals(8, result.getReadings().size());
try (Transaction tx = db.beginTx()) {
for (String nid : testReadings) {
Node n = db.getNodeById(Long.parseLong(nid));
assertEquals(24L, n.getProperty("rank"));
}
tx.success();
}
// Now add in an "other" relation, which is *not* transitive, to make sure the ranks still update.
newRel.setTarget(ricko25);
newRel.setType("other");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
// This will affect readings all the way to the end node.
assertTrue(result.getReadings().size() > 100);
Optional<ReadingModel> optEnd = result.getReadings().stream().filter(ReadingModel::getIs_end).findAny();
assertTrue(optEnd.isPresent());
assertEquals(Long.valueOf(69), optEnd.get().getRank());
testReadings.add(ricko25);
try (Transaction tx = db.beginTx()) {
for (String nid : testReadings) {
Node n = db.getNodeById(Long.parseLong(nid));
assertEquals(25L, n.getProperty("rank"));
}
tx.success();
}
}
public void testRelTypeDelete() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship type of our own
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("accents");
rtm.setDescription("Readings are the same but for diacriticals");
rtm.setIs_colocation(true);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/accents")
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// Now use it
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setDisplayform("λέγει");
newRel.setType("accents");
newRel.setIs_significant("no");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
// Now try to delete the relation type, even though relations exist
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/accents")
.request().delete();
assertEquals(Response.Status.CONFLICT.getStatusCode(), jerseyResult.getStatus());
// Delete the relations in question
for (RelationModel rm : result.getRelations()) {
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation/remove")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(rm));
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
}
// Try again to delete the relation type, which should work
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/accents")
.request().delete();
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
RelationTypeModel deletedRt = jerseyResult.readEntity(RelationTypeModel.class);
assertEquals(rtm.getName(), deletedRt.getName());
// Now, for fun, try to delete a nonexistent relation type
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/diacriticals")
.request().delete();
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), jerseyResult.getStatus());
}
public void tearDown() throws Exception {
db.shutdown();
jerseyTest.tearDown();
super.tearDown();
}
}
| DHUniWien/tradition_repo | src/test/java/net/stemmaweb/stemmaserver/integrationtests/RelationTypeTest.java | 6,300 | // Use πάλιν at 12 and 55 | line_comment | el | package net.stemmaweb.stemmaserver.integrationtests;
import junit.framework.TestCase;
import net.stemmaweb.model.*;
import net.stemmaweb.services.GraphDatabaseServiceProvider;
import net.stemmaweb.stemmaserver.Util;
import org.glassfish.jersey.test.JerseyTest;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.test.TestGraphDatabaseFactory;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
public class RelationTypeTest extends TestCase {
private GraphDatabaseService db;
private JerseyTest jerseyTest;
private String tradId;
private HashMap<String,String> readingLookup;
public void setUp() throws Exception {
super.setUp();
db = new GraphDatabaseServiceProvider(new TestGraphDatabaseFactory().newImpermanentDatabase()).getDatabase();
Util.setupTestDB(db, "1");
// Create a JerseyTestServer for the necessary REST API calls
jerseyTest = Util.setupJersey();
Response jerseyResult = Util.createTraditionFromFileOrString(jerseyTest, "Tradition", "LR", "1",
"src/TestFiles/john.csv", "csv");
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
tradId = Util.getValueFromJson(jerseyResult, "tradId");
readingLookup = Util.makeReadingLookup(jerseyTest, tradId);
}
public void testInitialRelationTypes() {
// Initially, the only defined relation type should be the "collated" one for the CSV input.
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtypes")
.request()
.get();
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
List<RelationTypeModel> allRelTypes = jerseyResult.readEntity(new GenericType<>() {});
assertEquals(1, allRelTypes.size());
assertEquals("collated", allRelTypes.get(0).getName());
}
public void testCreateRelationAddType() {
// Find the 'legei' readings to relate
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship, check that there is a suitable relationship type created
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setDisplayform("λέγει");
newRel.setType("spelling");
newRel.setIs_significant("no");
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
// Now check that the spelling relation type has been created
List<RelationTypeModel> allRelTypes = jerseyTest.target("/tradition/" + tradId + "/relationtypes")
.request()
.get(new GenericType<>() {});
assertEquals(2, allRelTypes.size());
RelationTypeModel rtm = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request().get(RelationTypeModel.class);
assertEquals("spelling", rtm.getName());
assertEquals(1, rtm.getBindlevel());
assertTrue(rtm.getIs_colocation());
}
private void checkExpectedRelations(HashSet<String> createdRels, HashSet<String> expectedLinks) {
try (Transaction tx = db.beginTx()) {
for (String rid : createdRels) {
Relationship link = db.getRelationshipById(Long.valueOf(rid));
String lookfor = String.format("%s -> %s: %s",
link.getStartNode().getId(), link.getEndNode().getId(), link.getProperty("type"));
String lookrev = String.format("%s -> %s: %s",
link.getEndNode().getId(), link.getStartNode().getId(), link.getProperty("type"));
String message = String.format("looking for %s in %s", lookfor,
java.util.Arrays.toString(expectedLinks.toArray()));
assertTrue(message,expectedLinks.remove(lookfor) ^ expectedLinks.remove(lookrev));
}
tx.success();
}
assertTrue(expectedLinks.isEmpty());
}
public void testAddExplicitRelationType() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship type of our own
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("spelling");
rtm.setDescription("A weaker version of the spelling relationship");
rtm.setIs_colocation(true);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// Now use it
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setDisplayform("λέγει");
newRel.setType("spelling");
newRel.setIs_significant("no");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
// Check that our relation type hasn't changed
List<RelationTypeModel> allRelTypes = jerseyTest.target("/tradition/" + tradId + "/relationtypes")
.request()
.get(new GenericType<>() {});
assertEquals(2, allRelTypes.size());
RelationTypeModel spel = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request().get(RelationTypeModel.class);
assertEquals("spelling", spel.getName());
assertEquals("A weaker version of the spelling relationship", spel.getDescription());
assertEquals(10, spel.getBindlevel());
}
public void testAddDefaultType() {
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("spelling");
rtm.setDefaultsettings(true);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request(MediaType.APPLICATION_JSON).put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
RelationTypeModel created = jerseyResult.readEntity(RelationTypeModel.class);
assertEquals("spelling", created.getName());
assertNull(created.getDefaultsettings());
assertEquals("These are the same reading, spelled differently.", created.getDescription());
assertEquals(1, created.getBindlevel());
assertTrue(created.getIs_colocation());
assertTrue(created.getIs_transitive());
// Now try setting the same default relation again, which should fail
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/spelling")
.request(MediaType.APPLICATION_JSON).put(Entity.json(rtm));
assertEquals(Response.Status.CONFLICT.getStatusCode(), jerseyResult.getStatus());
}
public void testNonGeneralizable() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship type of our own
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("important");
rtm.setDescription("Something we care about for our own reasons");
rtm.setIs_colocation(true);
rtm.setIs_generalizable(false);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/important")
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// Now use it
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setType("important");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CONFLICT.getStatusCode(), jerseyResult.getStatus());
}
public void testUseRegular() {
// Set a normal form
String auTw = readingLookup.getOrDefault("αυΤω/3", "17");
String autwi = readingLookup.getOrDefault("αὐτῷ/3", "17");
KeyPropertyModel kp = new KeyPropertyModel();
kp.setKey("normal_form");
kp.setProperty("αυτῶ");
ReadingChangePropertyModel newNormal = new ReadingChangePropertyModel();
newNormal.addProperty(kp);
Response jerseyResult = jerseyTest.target("/reading/" + auTw)
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(newNormal));
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
// Now make the relation
RelationModel newRel = new RelationModel();
newRel.setSource(autwi);
newRel.setTarget(auTw);
newRel.setType("grammatical");
newRel.setScope("tradition");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// and check that the normal form αυτῶ was found at rank 28.
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
assertEquals(0, result.getReadings().size());
for (RelationModel rm : result.getRelations()) {
if (rm.getSource().equals(autwi)) continue;
ReadingModel otherRankReading = jerseyTest.target("/reading/" + rm.getTarget())
.request()
.get(new GenericType<ReadingModel>() {});
assertEquals("αυτῶ", otherRankReading.getText());
}
}
public void testSimpleTransitivity() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
String Legei = readingLookup.getOrDefault("Λεγει/1", "17");
// Collect relationship IDs
HashSet<String> createdRels = new HashSet<>();
HashSet<String> expectedLinks = new HashSet<>();
// Set the first link
RelationModel newRel = new RelationModel();
newRel.setSource(legei);
newRel.setTarget(Legei);
newRel.setScope("local");
newRel.setType("spelling");
expectedLinks.add(String.format("%s -> %s: spelling", legei, Legei));
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
// Set the second link
newRel.setTarget(legeiAcute);
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
expectedLinks.add(String.format("%s -> %s: spelling", legei, legeiAcute));
expectedLinks.add(String.format("%s -> %s: spelling", Legei, legeiAcute));
checkExpectedRelations(createdRels, expectedLinks);
}
public void testBindlevelTransitivity() {
// Us<SUF>
String palin = readingLookup.getOrDefault("παλιν/12", "17");
String pali_ = readingLookup.getOrDefault("παλι¯/12", "17");
String Palin = readingLookup.getOrDefault("Παλιν/12", "17");
String palinac = readingLookup.getOrDefault("πάλιν/12", "17");
String palin58 = readingLookup.getOrDefault("παλιν/55", "17");
String pali_58 = readingLookup.getOrDefault("παλι¯/55", "17");
String Palin58 = readingLookup.getOrDefault("Παλιν/55", "17");
String palinac58 = readingLookup.getOrDefault("πάλιν/55", "17");
// Collect relationship IDs
HashSet<String> createdRels = new HashSet<>();
HashSet<String> expectedLinks = new HashSet<>();
// Set the first link
RelationModel newRel = new RelationModel();
newRel.setSource(palin);
newRel.setTarget(Palin);
newRel.setScope("tradition");
newRel.setType("orthographic");
expectedLinks.add(String.format("%s -> %s: orthographic", palin, Palin));
expectedLinks.add(String.format("%s -> %s: orthographic", palin58, Palin58));
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
// Set the second link, should result in one extra per rank
newRel.setTarget(pali_);
newRel.setType("spelling");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(4, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
expectedLinks.add(String.format("%s -> %s: spelling", palin, pali_));
expectedLinks.add(String.format("%s -> %s: spelling", palin58, pali_58));
expectedLinks.add(String.format("%s -> %s: spelling", Palin, pali_));
expectedLinks.add(String.format("%s -> %s: spelling", Palin58, pali_58));
// Set the third link, should result in two extra per rank
newRel.setSource(Palin);
newRel.setTarget(palinac);
newRel.setType("orthographic");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(6, result.getRelations().size());
assertEquals(0, result.getReadings().size());
result.getRelations().forEach(x -> createdRels.add(x.getId()));
expectedLinks.add(String.format("%s -> %s: orthographic", Palin, palinac));
expectedLinks.add(String.format("%s -> %s: orthographic", Palin58, palinac58));
expectedLinks.add(String.format("%s -> %s: spelling", pali_, palinac));
expectedLinks.add(String.format("%s -> %s: spelling", pali_58, palinac58));
expectedLinks.add(String.format("%s -> %s: orthographic", palin, palinac));
expectedLinks.add(String.format("%s -> %s: orthographic", palin58, palinac58));
checkExpectedRelations(createdRels, expectedLinks);
}
public void testTransitivityReRanking() {
// Use the εὑρίσκω variants at ranks 22 and 24/25
String eurisko22 = readingLookup.getOrDefault("εὑρίσκω/22", "17");
String euricko22 = readingLookup.getOrDefault("ε̣υριϲκω/22", "17");
String euricko24 = readingLookup.getOrDefault("ευριϲκω/24", "17");
String eurecko24 = readingLookup.getOrDefault("ευρηϲκω/24", "17");
String ricko25 = readingLookup.getOrDefault("ριϲκω/25", "17");
HashSet<String> testReadings = new HashSet<>();
// Remove all the 'collated' relations and then re-rank from the beginning.
for (RelationModel rm : jerseyTest.target("/tradition/" + tradId + "/relations")
.request().get(new GenericType<List<RelationModel>>() {})) {
if (rm.getType().equals("collated")) {
Response rd = jerseyTest.target("/tradition/" + tradId + "/relation/remove")
.request(MediaType.APPLICATION_JSON).post(Entity.json(rm));
assertEquals(Response.Status.OK.getStatusCode(), rd.getStatus());
}
}
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/initRanks")
.request()
.get();
assertEquals("success", Util.getValueFromJson(jerseyResult, "result"));
// First make the same-rank relations
RelationModel newRel = new RelationModel();
newRel.setSource(eurisko22);
newRel.setTarget(euricko22);
newRel.setScope("local");
newRel.setType("orthographic");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
assertEquals(0, result.getReadings().size());
testReadings.add(eurisko22);
testReadings.add(euricko22);
try (Transaction tx = db.beginTx()) {
for (String nid : testReadings) {
Node n = db.getNodeById(Long.parseLong(nid));
assertEquals(22L, n.getProperty("rank"));
}
tx.success();
}
newRel.setSource(euricko24);
newRel.setTarget(eurecko24);
newRel.setType("spelling");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
assertEquals(0, result.getReadings().size());
testReadings.add(euricko24);
testReadings.add(eurecko24);
// Now join them together, and test that the appropriate ranks changed
newRel.setTarget(eurisko22);
newRel.setType("orthographic");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(4, result.getRelations().size());
assertEquals(8, result.getReadings().size());
try (Transaction tx = db.beginTx()) {
for (String nid : testReadings) {
Node n = db.getNodeById(Long.parseLong(nid));
assertEquals(24L, n.getProperty("rank"));
}
tx.success();
}
// Now add in an "other" relation, which is *not* transitive, to make sure the ranks still update.
newRel.setTarget(ricko25);
newRel.setType("other");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(1, result.getRelations().size());
// This will affect readings all the way to the end node.
assertTrue(result.getReadings().size() > 100);
Optional<ReadingModel> optEnd = result.getReadings().stream().filter(ReadingModel::getIs_end).findAny();
assertTrue(optEnd.isPresent());
assertEquals(Long.valueOf(69), optEnd.get().getRank());
testReadings.add(ricko25);
try (Transaction tx = db.beginTx()) {
for (String nid : testReadings) {
Node n = db.getNodeById(Long.parseLong(nid));
assertEquals(25L, n.getProperty("rank"));
}
tx.success();
}
}
public void testRelTypeDelete() {
String legeiAcute = readingLookup.getOrDefault("λέγει/1", "17");
String legei = readingLookup.getOrDefault("λεγει/1", "17");
// Make a relationship type of our own
RelationTypeModel rtm = new RelationTypeModel();
rtm.setName("accents");
rtm.setDescription("Readings are the same but for diacriticals");
rtm.setIs_colocation(true);
Response jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/accents")
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(rtm));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
// Now use it
RelationModel newRel = new RelationModel();
newRel.setSource(legeiAcute);
newRel.setTarget(legei);
newRel.setScope("tradition");
newRel.setDisplayform("λέγει");
newRel.setType("accents");
newRel.setIs_significant("no");
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(newRel));
assertEquals(Response.Status.CREATED.getStatusCode(), jerseyResult.getStatus());
GraphModel result = jerseyResult.readEntity(new GenericType<GraphModel>() {});
assertEquals(2, result.getRelations().size());
// Now try to delete the relation type, even though relations exist
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/accents")
.request().delete();
assertEquals(Response.Status.CONFLICT.getStatusCode(), jerseyResult.getStatus());
// Delete the relations in question
for (RelationModel rm : result.getRelations()) {
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relation/remove")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(rm));
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
}
// Try again to delete the relation type, which should work
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/accents")
.request().delete();
assertEquals(Response.Status.OK.getStatusCode(), jerseyResult.getStatus());
RelationTypeModel deletedRt = jerseyResult.readEntity(RelationTypeModel.class);
assertEquals(rtm.getName(), deletedRt.getName());
// Now, for fun, try to delete a nonexistent relation type
jerseyResult = jerseyTest.target("/tradition/" + tradId + "/relationtype/diacriticals")
.request().delete();
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), jerseyResult.getStatus());
}
public void tearDown() throws Exception {
db.shutdown();
jerseyTest.tearDown();
super.tearDown();
}
}
|
629_7 | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345
*/
public class Greek implements Language {
@Override
public String unknownBeatmap() {
return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ;
}
@Override
public String internalException(String marker) {
return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου."
+" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000"
+ " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε."
+ " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ;
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"))
.then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"));
} else {
String[] messages = {
"Φαίνεσαι σαν να θες μια πρόταση.",
"Πόσο ωραίο να σε βλέπω :)",
"Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)",
"Τι ευχάριστη έκπληξη! ^.^",
"Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3",
"Τι έχεις την διάθεση να κάνεις σήμερα;",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Άγνωστη εντολή \"" + command
+ "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!";
}
@Override
public String noInformationForMods() {
return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή";
}
@Override
public String malformattedMods(String mods) {
return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού...";
}
@Override
public String tryWithMods() {
return "Δοκίμασε αυτό το τραγούδι με μερικά mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;";
}
@Override
public String complaint() {
return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Έλα εδώ εσυ!")
.then(new Action("Αγκαλιάζει " + apiUser.getUserName()));
}
@Override
public String help() {
return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά."
+ " [https://twitter.com/Tillerinobot status και updates]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]";
}
@Override
public String faq() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + ".";
}
@Override
public String mixedNomodAndMods() {
return "Τί εννοείς nomods με mods;";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. "
+ " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help.";
}
@Override
public String notRanked() {
return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο.";
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Άκυρη ακρίβεια: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Συγνώμη, αλλά \"" + invalid
+ "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!";
}
@Override
public String setFormat() {
return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
}
| Deardrops/Tillerinobot | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java | 3,361 | //github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; | line_comment | el | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345
*/
public class Greek implements Language {
@Override
public String unknownBeatmap() {
return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ;
}
@Override
public String internalException(String marker) {
return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου."
+" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000"
+ " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε."
+ " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ;
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"))
.then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"));
} else {
String[] messages = {
"Φαίνεσαι σαν να θες μια πρόταση.",
"Πόσο ωραίο να σε βλέπω :)",
"Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)",
"Τι ευχάριστη έκπληξη! ^.^",
"Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3",
"Τι έχεις την διάθεση να κάνεις σήμερα;",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Άγνωστη εντολή \"" + command
+ "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!";
}
@Override
public String noInformationForMods() {
return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή";
}
@Override
public String malformattedMods(String mods) {
return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού...";
}
@Override
public String tryWithMods() {
return "Δοκίμασε αυτό το τραγούδι με μερικά mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;";
}
@Override
public String complaint() {
return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Έλα εδώ εσυ!")
.then(new Action("Αγκαλιάζει " + apiUser.getUserName()));
}
@Override
public String help() {
return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά."
+ " [https://twitter.com/Tillerinobot status και updates]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]";
}
@Override
public String faq() {
return "[https://gi<SUF>
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + ".";
}
@Override
public String mixedNomodAndMods() {
return "Τί εννοείς nomods με mods;";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. "
+ " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help.";
}
@Override
public String notRanked() {
return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο.";
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Άκυρη ακρίβεια: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Συγνώμη, αλλά \"" + invalid
+ "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!";
}
@Override
public String setFormat() {
return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
}
|
1654_0 | public class RoomTypeE extends RoomTypeC//Δωμάτιο τύπου C,αλλά με έκπτωση 50% ανά άτομο μετά την τρίτη μέρα.
{
public double getPriceOfRoom()//Μέθοδος για τον υπολογισμό των εσόδων δωματίου τύπου E,λαμβάνοντας υπόψη τα ελάχιστα//
{ //άτομα και μέρες,καθώς και την έκπτωση.
int i=0;
double moneyEarnedFromRoom=0; //Μεταβλητή για έσοδα από δωμάτιο.
double discountPerPerson; //Μεταβλητή για έκπτωση ανά άτομο.
for(i=1; i<31; i++)
{
if(roomAvailability[i]!=null)
{
if(i<=3)
{
discountPerPerson = (getPricePerPerson() / 2 );
moneyEarnedFromRoom+=(roomAvailability[i].getPeopleNum()*( getPricePerPerson() - discountPerPerson));
continue;
}
moneyEarnedFromRoom = (moneyEarnedFromRoom + (roomAvailability[i].getPeopleNum() * getPricePerPerson()));
}
}
return moneyEarnedFromRoom;
}
}
| DimitrisKostorrizos/UndergraduateCeidProjects | Project Οντοκεντρικός Προγραμματισμός/Java Project/Hotel Project, Swing/RoomTypeE.java | 420 | //Δωμάτιο τύπου C,αλλά με έκπτωση 50% ανά άτομο μετά την τρίτη μέρα. | line_comment | el | public class RoomTypeE extends RoomTypeC//Δω<SUF>
{
public double getPriceOfRoom()//Μέθοδος για τον υπολογισμό των εσόδων δωματίου τύπου E,λαμβάνοντας υπόψη τα ελάχιστα//
{ //άτομα και μέρες,καθώς και την έκπτωση.
int i=0;
double moneyEarnedFromRoom=0; //Μεταβλητή για έσοδα από δωμάτιο.
double discountPerPerson; //Μεταβλητή για έκπτωση ανά άτομο.
for(i=1; i<31; i++)
{
if(roomAvailability[i]!=null)
{
if(i<=3)
{
discountPerPerson = (getPricePerPerson() / 2 );
moneyEarnedFromRoom+=(roomAvailability[i].getPeopleNum()*( getPricePerPerson() - discountPerPerson));
continue;
}
moneyEarnedFromRoom = (moneyEarnedFromRoom + (roomAvailability[i].getPeopleNum() * getPricePerPerson()));
}
}
return moneyEarnedFromRoom;
}
}
|
3866_9 | package application;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.LinkedList;
import java.util.Queue;
public class Main extends Application {
class SearchInfo {
int option;
String searchTerm;
public SearchInfo(int option, String searchTerm) {
this.option = option;
this.searchTerm = searchTerm;
}
}
private Queue<SearchInfo> recentSearches = new LinkedList<>();
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Country App");
// Δημιουργία κουμπιών
Button button1 = new Button("Όλες οι χώρες");
Button button2 = new Button("Αναζήτηση χώρας με χρήση του ονόματός της");
Button button3 = new Button("Αναζήτηση χωρών που μιλούν συγκεκριμένες γλώσσες");
Button button4 = new Button("Αναζήτηση χωρών που χρησιμοποιούν συγκεκριμένο νόμισμα");
Button button5 = new Button("5 τελευταίες αναζητήσεις");
// Προσθήκη λειτουργιών για τα κουμπιά
button1.setOnAction(e -> showAllCountries(primaryStage, 1, null));
button2.setOnAction(e -> showSearchDialog(primaryStage, 2,"Αναζήτηση χώρας", "Εισάγετε το όνομα της χώρας στα αγγλικά (πχ. Greece ή Spain κλπ):"));
button3.setOnAction(e -> showSearchDialog(primaryStage, 3, "Αναζήτηση γλώσσας", "Εισάγετε τη γλώσσα στα αγγλικά (πχ. Greek ή Spanish κλπ"));
button4.setOnAction(e -> showSearchDialog(primaryStage, 4, "Αναζήτηση νομίσματος", "Εισάγετε το νόμισμα (πχ. EU ή eu ή eur ή euro ή aud κλπ:"));
button5.setOnAction(e -> showRecentSearches());
// Δημιουργία και ρύθμιση του layout
VBox vbox = new VBox(20); // Το 10 είναι το κενό μεταξύ των κουμπιών
vbox.setPadding(new Insets(10, 50, 50, 50)); // Ρύθμιση των εξωτερικών περιθωρίων
vbox.setAlignment(Pos.CENTER); // Ορισμός της θέσης του vbox ως ΚΕΝΤΡΟ
// Προσθήκη των κουμπιών στο layout
vbox.getChildren().addAll(button1, button2, button3, button4, button5);
// Δημιουργία της σκηνής
Scene scene = new Scene(vbox, 700, 550);
// Ορισμός της σκηνής για το παράθυρο
primaryStage.setScene(scene);
// Εμφάνιση του παραθύρου
primaryStage.show();
}
// Μέθοδος για την εμφάνιση των πρόσφατων αναζητήσεων (5η επιλογή)
private void showRecentSearches() {
VBox recentSearchesLayout = new VBox(10);
if (recentSearches.isEmpty()) {
Label label = new Label();
label.setText("Δεν υπάρχει καμία αναζήτηση");
recentSearchesLayout.getChildren().add(label);
} else {
for (SearchInfo searchInfo : recentSearches) {
Button button = new Button();
switch (searchInfo.option) {
case 1:
button.setText("Όλες οι χώρες");
break;
case 2:
button.setText("Αναζήτηση " + searchInfo.searchTerm + " με χρήση του ονόματός της");
break;
case 3:
button.setText("Χώρες που μιλούν " + searchInfo.searchTerm);
break;
case 4:
button.setText("Χώρες που χρησιμοποιούν το " + searchInfo.searchTerm);
break;
default:
button.setText("5 τελευταίες αναζητήσεις: " + searchInfo.searchTerm);
break;
}
button.setOnAction(e -> showAllCountries(new Stage(), searchInfo.option, searchInfo.searchTerm));
recentSearchesLayout.getChildren().add(button);
}
}
Scene recentSearchesScene = new Scene(recentSearchesLayout, 300, 200);
Stage recentSearchesStage = new Stage();
recentSearchesStage.setTitle("5 Πρόσφατες Αναζητήσεις");
recentSearchesStage.setScene(recentSearchesScene);
recentSearchesStage.show();
}
private void showSearchDialog(Stage primaryStage, int option, String title, String prompt) {
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle(title);
dialog.setHeaderText(null);
dialog.setContentText(prompt);
dialog.showAndWait().ifPresent(result -> showAllCountries(primaryStage, option, result));
}
// Μέθοδος για την εμφάνιση όλων των χωρών
private void showAllCountries(Stage primaryStage, int option, String SearchTerm) {
try {
// Δημιουργία νέας σκηνής που περιέχει τις χώρες
CountriesResult countriesResult = new CountriesResult(option,SearchTerm);
// Προσθήκη της επιλογής στις πρόσφατες αναζητήσεις
recentSearches.offer(new SearchInfo(option, SearchTerm));
// Εάν υπερβαίνουν τον αριθμό των 5, αφαίρεση της παλαιότερης
if (recentSearches.size() > 5) {
recentSearches.poll();
}
// Δημιουργία νέου παραθύρου
Stage resultsStage = new Stage();
Scene resultsScene = new Scene(countriesResult, 600, 400);
resultsStage.setScene(resultsScene);
// Εμφάνιση του παραθύρου
resultsStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Η main μέθοδος για την εκκίνηση της εφαρμογής
public static void main(String[] args) {
launch(args);
}
} | DimitrisManolopoulos/Countries-App | src/application/Main.java | 2,164 | // Εμφάνιση του παραθύρου | line_comment | el | package application;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.LinkedList;
import java.util.Queue;
public class Main extends Application {
class SearchInfo {
int option;
String searchTerm;
public SearchInfo(int option, String searchTerm) {
this.option = option;
this.searchTerm = searchTerm;
}
}
private Queue<SearchInfo> recentSearches = new LinkedList<>();
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Country App");
// Δημιουργία κουμπιών
Button button1 = new Button("Όλες οι χώρες");
Button button2 = new Button("Αναζήτηση χώρας με χρήση του ονόματός της");
Button button3 = new Button("Αναζήτηση χωρών που μιλούν συγκεκριμένες γλώσσες");
Button button4 = new Button("Αναζήτηση χωρών που χρησιμοποιούν συγκεκριμένο νόμισμα");
Button button5 = new Button("5 τελευταίες αναζητήσεις");
// Προσθήκη λειτουργιών για τα κουμπιά
button1.setOnAction(e -> showAllCountries(primaryStage, 1, null));
button2.setOnAction(e -> showSearchDialog(primaryStage, 2,"Αναζήτηση χώρας", "Εισάγετε το όνομα της χώρας στα αγγλικά (πχ. Greece ή Spain κλπ):"));
button3.setOnAction(e -> showSearchDialog(primaryStage, 3, "Αναζήτηση γλώσσας", "Εισάγετε τη γλώσσα στα αγγλικά (πχ. Greek ή Spanish κλπ"));
button4.setOnAction(e -> showSearchDialog(primaryStage, 4, "Αναζήτηση νομίσματος", "Εισάγετε το νόμισμα (πχ. EU ή eu ή eur ή euro ή aud κλπ:"));
button5.setOnAction(e -> showRecentSearches());
// Δημιουργία και ρύθμιση του layout
VBox vbox = new VBox(20); // Το 10 είναι το κενό μεταξύ των κουμπιών
vbox.setPadding(new Insets(10, 50, 50, 50)); // Ρύθμιση των εξωτερικών περιθωρίων
vbox.setAlignment(Pos.CENTER); // Ορισμός της θέσης του vbox ως ΚΕΝΤΡΟ
// Προσθήκη των κουμπιών στο layout
vbox.getChildren().addAll(button1, button2, button3, button4, button5);
// Δημιουργία της σκηνής
Scene scene = new Scene(vbox, 700, 550);
// Ορισμός της σκηνής για το παράθυρο
primaryStage.setScene(scene);
// Εμ<SUF>
primaryStage.show();
}
// Μέθοδος για την εμφάνιση των πρόσφατων αναζητήσεων (5η επιλογή)
private void showRecentSearches() {
VBox recentSearchesLayout = new VBox(10);
if (recentSearches.isEmpty()) {
Label label = new Label();
label.setText("Δεν υπάρχει καμία αναζήτηση");
recentSearchesLayout.getChildren().add(label);
} else {
for (SearchInfo searchInfo : recentSearches) {
Button button = new Button();
switch (searchInfo.option) {
case 1:
button.setText("Όλες οι χώρες");
break;
case 2:
button.setText("Αναζήτηση " + searchInfo.searchTerm + " με χρήση του ονόματός της");
break;
case 3:
button.setText("Χώρες που μιλούν " + searchInfo.searchTerm);
break;
case 4:
button.setText("Χώρες που χρησιμοποιούν το " + searchInfo.searchTerm);
break;
default:
button.setText("5 τελευταίες αναζητήσεις: " + searchInfo.searchTerm);
break;
}
button.setOnAction(e -> showAllCountries(new Stage(), searchInfo.option, searchInfo.searchTerm));
recentSearchesLayout.getChildren().add(button);
}
}
Scene recentSearchesScene = new Scene(recentSearchesLayout, 300, 200);
Stage recentSearchesStage = new Stage();
recentSearchesStage.setTitle("5 Πρόσφατες Αναζητήσεις");
recentSearchesStage.setScene(recentSearchesScene);
recentSearchesStage.show();
}
private void showSearchDialog(Stage primaryStage, int option, String title, String prompt) {
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle(title);
dialog.setHeaderText(null);
dialog.setContentText(prompt);
dialog.showAndWait().ifPresent(result -> showAllCountries(primaryStage, option, result));
}
// Μέθοδος για την εμφάνιση όλων των χωρών
private void showAllCountries(Stage primaryStage, int option, String SearchTerm) {
try {
// Δημιουργία νέας σκηνής που περιέχει τις χώρες
CountriesResult countriesResult = new CountriesResult(option,SearchTerm);
// Προσθήκη της επιλογής στις πρόσφατες αναζητήσεις
recentSearches.offer(new SearchInfo(option, SearchTerm));
// Εάν υπερβαίνουν τον αριθμό των 5, αφαίρεση της παλαιότερης
if (recentSearches.size() > 5) {
recentSearches.poll();
}
// Δημιουργία νέου παραθύρου
Stage resultsStage = new Stage();
Scene resultsScene = new Scene(countriesResult, 600, 400);
resultsStage.setScene(resultsScene);
// Εμφάνιση του παραθύρου
resultsStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Η main μέθοδος για την εκκίνηση της εφαρμογής
public static void main(String[] args) {
launch(args);
}
} |
3482_0 | import java.util.*;
public class Actor {
public String name;
private List<Integer> movieIds;
public Actor(String name) {
this.name = name;
movieIds = new ArrayList<Integer>();
}
public void addId(Integer id) {
this.movieIds.add(id);
}
//Δημιουργία inverted string
public String toString() {
String result = "";
result += name + ":";
//Για κάθε id στην λίστα, προσθήκη στο string
//και προσθήκη διαχωριστικού εκτός του τελευταίου id
for (int i = 0; i < movieIds.size() ; i++) {
result += movieIds.get(i);
if (i != movieIds.size() - 1) result += ";";
}
return result;
}
}
| DimosthenisK/Java_Excercise_2016 | src/Actor.java | 239 | //Δημιουργία inverted string | line_comment | el | import java.util.*;
public class Actor {
public String name;
private List<Integer> movieIds;
public Actor(String name) {
this.name = name;
movieIds = new ArrayList<Integer>();
}
public void addId(Integer id) {
this.movieIds.add(id);
}
//Δη<SUF>
public String toString() {
String result = "";
result += name + ":";
//Για κάθε id στην λίστα, προσθήκη στο string
//και προσθήκη διαχωριστικού εκτός του τελευταίου id
for (int i = 0; i < movieIds.size() ; i++) {
result += movieIds.get(i);
if (i != movieIds.size() - 1) result += ";";
}
return result;
}
}
|
3265_3 | import java.util.Scanner;
import java.io.*;
import java.util.*;
public class UrbanRoute
{
//attributes
/* στον πίνακα point σε κάθε γραμμή αναγράφεται το γνωστό σημείο της πόλης και οι συντεταγμένες του
(ενδεικτικά παρακάτω φαίνονται 2 σημεία της πόλης)*/
private String[][] point = { {"hospital","38.242126","22.072720"} , {"city hall","38.250093","22.087763"} };
public enum type { BusStop,point }
private type start;
private type end;
private Line line;
private int maxTotalTime;
private String day;
private String timeZone;
public enum TypeOfDir{ OUTWARD,RETURN}
private TypeOfDir direction;
private int walkingMeters;
private String[] days = {"Monday","Thuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
private String[] timezones = {"07:00-09:00","09:00-11:00","11:00-13:00","13:00-15:00",
"15:00-17:00","17:00-19:00","19:00-21:00","21:00-23-00","23:00-00:00"};
//constructor
public UrbanRoute(type start,type end,Line line,String day,String time,TypeOfDir dir)
{
this.start = start;
this.end = end;
this.line = line;
this.day = day;
this.timeZone = time;
this.direction = dir;
}
public boolean checkRoute()
{
//αν η τοποθεσία της αφετηρίας βρίσκεται πριν την τοποθεσία του τερματισμού
if(this.start.location[0] < this.end.location[0] && this.start.location[1] < this.end.location[1])
{ System.out.println ("Correct Route");
System.out.println(days);
System.out.println(timezones);
return 1;
}
//αν βρίσκεται μετά την τοποθεσία του τερματισμού
else
{ System.out.println ("Incorrect Route. Choose again start-end!");
return 0;
}
}
public int calcDuration()
{
int duration = 0;
/*Υπολογισμός της απόστασης μεταξύ της αφετηρίας και του τερματισμού και απόδοση
μιας αρχικής τιμής στο duration */
/* αν η ώρα της διαδρομής κυμαίνεται από τις 1 εως τις 5 το απόγευμα τότε η διάρκεια
της αυξάνεται κατα 7 λεπτά */
if (this.timeZone = "13:00-15:00" || this.timeZone = "15:00-17:00")
{ duration = duration + 7;}
/* αν η μέρα της διαδρομής είναι καθημερινή τότε η διάρκεια της αυξάνεται
κατά 3 λεπτά */
if (this.day = "Monday" || this.day = "Tuesday" || this.day = "Wednesday" ||
this.day = "Thursday" || this.day = "Friday")
{ duration = duration + 3; }
return duration;
}
public Boolean checkIfExist()
{ /*Το σύστημα ελέγχει για μια συγκεκριμένη διαδρομή αν υπάρχει δρομολόγιο της γραμμής
(προς τη συγκεκριμένη κατεύθυνση της διαδρομής) που να εκτελείτε την ημέρα και ώρα που επέλεξε ο χρήστης*/
boolean[][] routes;
int numDay;
int time;
//αποδίδεται ενας int αριθμός στην ημέρα που επέλεξε ο χρήστης να κάνει την διαδρομή του
switch (this.day)
{
case "Monday" : numDay = 0; break;
case "Tuesday" : numDay = 1; break;
case "Wednesday" : numDay = 2; break;
case "Thursday" : numDay = 3; break;
case "Friday" : numDay = 4; break;
case "Saturday" : numDay = 5; break;
case "Sunday" : numDay = 6; break;
}
//αποδίδεται ενας int αριθμός στην χρονική ζώνη που επέλεξε ο χρήστης να κάνει την διαδρομή του
switch (this.timeZone)
{
case "07:00-09:00" : time = 0; break;
case "09:00-11:00" : time = 1; break;
case "11:00-13:00" : time = 2; break;
case "13:00-15:00" : time = 3; break;
case "15:00-17:00": time = 4; break;
case "17:00-19:00": time = 5; break;
case "19:00-21:00": time = 6; break;
case "21:00-23:00": time = 7; break;
case "23:00-00:00": time = 8; break;
}
if( this.direction == "OUTWARD")
{ routes = this.line.outwardRoutes; }
else
{ routes = this.line.returnRoutes; }
// ελέγχει αν την ημέρα και ώρα που επέλεξε ο χρήστης υπάρχει δρομολόγιο
if (routes[day][time] == true ) { return true; }
else { return false;}
}
public void insertTimeandMeters()
{
Scanner obj = new Scanner (System.in);
System.out.println("Enter maxTotalTime for your route:");
this.maxTotalTime = obj.nextInt();
System.out.println("Enter max number of meters, you want to walk:");
this.walkingMeters = obj.nextInt();
}
public boolean trailFeasibility()
{ //υπολογίζει χρόνο(time) και μέτρα περπατήματος(meters) που χρειάζονται για να διανυθεί η απόσταση της διαδρομής
// αν ο χρονος και τα μέτρα έχουν τιμές μικρότερες από αυτές που εισήγαγε ο χρήστης
if (time < this.maxTotalTime && meters < this.walkingMeters)
{ return 1;}
else { return 0;}
}
public void bestRoute()
{ //εύρεση βέλτιστης διαδρομής με βάση το maxTotalTime,walkingMeters και την συνολικη διαδρομή του χρήστη
}
public void display()
{ //εμφανίζει τις gui οθόνες με κάποια διασύνδεση της java με html
}
}
| Dionisisarg/B.A.S | B.A.S-master/UrbanRoute.java | 2,353 | //αν η τοποθεσία της αφετηρίας βρίσκεται πριν την τοποθεσία του τερματισμού | line_comment | el | import java.util.Scanner;
import java.io.*;
import java.util.*;
public class UrbanRoute
{
//attributes
/* στον πίνακα point σε κάθε γραμμή αναγράφεται το γνωστό σημείο της πόλης και οι συντεταγμένες του
(ενδεικτικά παρακάτω φαίνονται 2 σημεία της πόλης)*/
private String[][] point = { {"hospital","38.242126","22.072720"} , {"city hall","38.250093","22.087763"} };
public enum type { BusStop,point }
private type start;
private type end;
private Line line;
private int maxTotalTime;
private String day;
private String timeZone;
public enum TypeOfDir{ OUTWARD,RETURN}
private TypeOfDir direction;
private int walkingMeters;
private String[] days = {"Monday","Thuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
private String[] timezones = {"07:00-09:00","09:00-11:00","11:00-13:00","13:00-15:00",
"15:00-17:00","17:00-19:00","19:00-21:00","21:00-23-00","23:00-00:00"};
//constructor
public UrbanRoute(type start,type end,Line line,String day,String time,TypeOfDir dir)
{
this.start = start;
this.end = end;
this.line = line;
this.day = day;
this.timeZone = time;
this.direction = dir;
}
public boolean checkRoute()
{
//αν<SUF>
if(this.start.location[0] < this.end.location[0] && this.start.location[1] < this.end.location[1])
{ System.out.println ("Correct Route");
System.out.println(days);
System.out.println(timezones);
return 1;
}
//αν βρίσκεται μετά την τοποθεσία του τερματισμού
else
{ System.out.println ("Incorrect Route. Choose again start-end!");
return 0;
}
}
public int calcDuration()
{
int duration = 0;
/*Υπολογισμός της απόστασης μεταξύ της αφετηρίας και του τερματισμού και απόδοση
μιας αρχικής τιμής στο duration */
/* αν η ώρα της διαδρομής κυμαίνεται από τις 1 εως τις 5 το απόγευμα τότε η διάρκεια
της αυξάνεται κατα 7 λεπτά */
if (this.timeZone = "13:00-15:00" || this.timeZone = "15:00-17:00")
{ duration = duration + 7;}
/* αν η μέρα της διαδρομής είναι καθημερινή τότε η διάρκεια της αυξάνεται
κατά 3 λεπτά */
if (this.day = "Monday" || this.day = "Tuesday" || this.day = "Wednesday" ||
this.day = "Thursday" || this.day = "Friday")
{ duration = duration + 3; }
return duration;
}
public Boolean checkIfExist()
{ /*Το σύστημα ελέγχει για μια συγκεκριμένη διαδρομή αν υπάρχει δρομολόγιο της γραμμής
(προς τη συγκεκριμένη κατεύθυνση της διαδρομής) που να εκτελείτε την ημέρα και ώρα που επέλεξε ο χρήστης*/
boolean[][] routes;
int numDay;
int time;
//αποδίδεται ενας int αριθμός στην ημέρα που επέλεξε ο χρήστης να κάνει την διαδρομή του
switch (this.day)
{
case "Monday" : numDay = 0; break;
case "Tuesday" : numDay = 1; break;
case "Wednesday" : numDay = 2; break;
case "Thursday" : numDay = 3; break;
case "Friday" : numDay = 4; break;
case "Saturday" : numDay = 5; break;
case "Sunday" : numDay = 6; break;
}
//αποδίδεται ενας int αριθμός στην χρονική ζώνη που επέλεξε ο χρήστης να κάνει την διαδρομή του
switch (this.timeZone)
{
case "07:00-09:00" : time = 0; break;
case "09:00-11:00" : time = 1; break;
case "11:00-13:00" : time = 2; break;
case "13:00-15:00" : time = 3; break;
case "15:00-17:00": time = 4; break;
case "17:00-19:00": time = 5; break;
case "19:00-21:00": time = 6; break;
case "21:00-23:00": time = 7; break;
case "23:00-00:00": time = 8; break;
}
if( this.direction == "OUTWARD")
{ routes = this.line.outwardRoutes; }
else
{ routes = this.line.returnRoutes; }
// ελέγχει αν την ημέρα και ώρα που επέλεξε ο χρήστης υπάρχει δρομολόγιο
if (routes[day][time] == true ) { return true; }
else { return false;}
}
public void insertTimeandMeters()
{
Scanner obj = new Scanner (System.in);
System.out.println("Enter maxTotalTime for your route:");
this.maxTotalTime = obj.nextInt();
System.out.println("Enter max number of meters, you want to walk:");
this.walkingMeters = obj.nextInt();
}
public boolean trailFeasibility()
{ //υπολογίζει χρόνο(time) και μέτρα περπατήματος(meters) που χρειάζονται για να διανυθεί η απόσταση της διαδρομής
// αν ο χρονος και τα μέτρα έχουν τιμές μικρότερες από αυτές που εισήγαγε ο χρήστης
if (time < this.maxTotalTime && meters < this.walkingMeters)
{ return 1;}
else { return 0;}
}
public void bestRoute()
{ //εύρεση βέλτιστης διαδρομής με βάση το maxTotalTime,walkingMeters και την συνολικη διαδρομή του χρήστη
}
public void display()
{ //εμφανίζει τις gui οθόνες με κάποια διασύνδεση της java με html
}
}
|
33122_16 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JDialog.java to edit this template
*/
package wifipasswords;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
*
* @author dionysis
*/
public class QrScanner extends javax.swing.JDialog implements Runnable,ThreadFactory {
private WebcamPanel panel =null;
private Webcam webcam=null;
private static MyJFrame myFrame;
private static final long serialVersionUID =6441489157408381878L;
private ExecutorService executor = Executors.newSingleThreadExecutor(this);
private WifiProfile profile;
private volatile boolean stop;
private CountDownLatch latch;
/**
* Creates new form QrScanner
*/
public QrScanner(java.awt.Frame parent, boolean modal,MyJFrame myFrame) {
super(parent, modal);
this.myFrame=myFrame;
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.stop=false;
initComponents();
initWebcam();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jPanel3 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Σαρωτής QR Code");
setBackground(new java.awt.Color(113, 143, 164));
jPanel1.setBackground(getBackground());
jPanel1.setMaximumSize(new java.awt.Dimension(397, 419));
jPanel1.setMinimumSize(new java.awt.Dimension(397, 419));
jPanel2.setVisible(false);
jPanel2.setBackground(new java.awt.Color(113, 143, 164));
jLabel1.setBackground(new java.awt.Color(175, 217, 245));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton1.setText("Σύνδεση");
jButton1.setFocusable(false);
jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(74, 74, 74)
.addComponent(jButton1)
.addGap(74, 74, 74)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap())
);
jPanel4.setBackground(getBackground());
List<Webcam> filteredWebcams = new ArrayList<>();
Webcam[] webcams = Webcam.getWebcams().toArray(new Webcam[0]);
for (Webcam webcam : webcams) {
if (!webcam.getName().contains("OBS Virtual")) {
filteredWebcams.add(webcam);
}
}
Webcam[] updatedWebcams = filteredWebcams.toArray(new Webcam[0]);
String[] webcamNames = new String[updatedWebcams.length];
for (int i = 0; i < updatedWebcams.length; i++) {
webcamNames[i] = updatedWebcams[i].getName();
}
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(webcamNames));
jComboBox1.setSelectedIndex(0);
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jPanel3.setBackground(new java.awt.Color(113, 143, 164));
jPanel3.setMaximumSize(new java.awt.Dimension(373, 280));
jPanel3.setMinimumSize(new java.awt.Dimension(373, 280));
jPanel3.setPreferredSize(new java.awt.Dimension(373, 280));
jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(7, 7, 7))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(86, 86, 86))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1)))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
// Set the SSID and password
String ssid = profile.getName();
String password = profile.getPassword();
// Create the XML content
String xmlContent = "<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>"
+ ssid + "</name><SSIDConfig><SSID><name>" + ssid + "</name></SSID></SSIDConfig><connectionType>ESS</connectionType>"
+ "<connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication>"
+ "<encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType>"
+ "<protected>false</protected><keyMaterial>" + password + "</keyMaterial></sharedKey></security></MSM>"
+ "<MacRandomization xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v3\"><enableRandomization>false</enableRandomization>"
+ "</MacRandomization></WLANProfile>";
// Create the temporary XML file
String xmlFilePath = System.getProperty("java.io.tmpdir") + ssid + "-wireless-profile-generated.xml";
Files.write(Paths.get(xmlFilePath), xmlContent.getBytes());
// Execute the commands
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan add profile filename=\"" + xmlFilePath + "\"");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
process.waitFor();
processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan connect name=\"" + ssid + "\"");
processBuilder.redirectErrorStream(true);
process = processBuilder.start();
// Capture the output of the command
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append(System.lineSeparator());
}
}
process.waitFor();
// Check if the connection was successful
boolean isConnected = output.toString().contains("Connection request was completed successfully");
// Delete the temporary XML file
Files.deleteIfExists(Paths.get(xmlFilePath));
if (isConnected) {
clearOnExit();
myFrame.getConnectedProfile();
} else {
clearOnExit();
myFrame.notConnectedMessage();//JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException | InterruptedException e) {
clearOnExit();
myFrame.notConnectedMessage();//JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
initWebcam(Webcam.getWebcamByName((String)jComboBox1.getSelectedItem()));
}//GEN-LAST:event_jComboBox1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration//GEN-END:variables
private void initWebcam(){
webcam = Webcam.getWebcams().get(0); // Get the default webcam
Dimension size = WebcamResolution.VGA.getSize();
webcam.setViewSize(size);
panel = new WebcamPanel(webcam);
panel.setPreferredSize(size);
panel.setFPSDisplayed(true);
jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280));
executor = Executors.newSingleThreadExecutor(this);
executor.execute(this);
}
private void initWebcam(Webcam webcam2){
stop=true;
if (executor != null) {
executor.shutdown();
}
webcam.close();
webcam = webcam2; // Get the default webcam
Dimension[] resolutions = webcam.getViewSizes(); // Get the available resolutions
Dimension size = WebcamResolution.VGA.getSize();
webcam.setViewSize(size);
panel = new WebcamPanel(webcam);
panel.setPreferredSize(size);
panel = new WebcamPanel(webcam);
panel.setPreferredSize(size);
panel.setFPSDisplayed(true);
panel.repaint();
panel.revalidate();
jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280));
jPanel3.repaint();
jPanel3.revalidate();
stop=false;
executor = Executors.newSingleThreadExecutor(this);
executor.execute(this);
}
@Override
public void run() {
do{
if(stop&& Thread.currentThread().isInterrupted()){
break;
}
try{
Thread.sleep(100);
}
catch(Exception e){
e.printStackTrace();
}
Result result =null;
BufferedImage image=null;
if(webcam.isOpen()){
if((image=webcam.getImage())==null){
continue;
}
if(image!=null){
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try{
result = new MultiFormatReader().decode(bitmap);
}
catch(Exception e){
//
}
if(result!=null){
jPanel2.setVisible(true);
int startIndexSSID = result.getText().indexOf("S:") + 2; // Add 2 to skip "S:"
int endIndexSSID = result.getText().indexOf(";", startIndexSSID);
int startIndexPASS = result.getText().indexOf("P:") + 2; // Add 2 to skip "P:"
int endIndexPASS = result.getText().indexOf(";", startIndexPASS);
profile = new WifiProfile(result.getText().substring(startIndexSSID, endIndexSSID),result.getText().substring(startIndexPASS, endIndexPASS));
// Extract the SSID value from the string
String ssid = result.getText().substring(startIndexSSID, endIndexSSID);
jLabel1.setText(ssid);
}}}
}while(!stop&&!Thread.currentThread().isInterrupted());
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r,"My Thread");
t.setDaemon(true);
return t;
}
public void clearOnExit(){
stop=true;
webcam.close();
if (executor != null) {
executor.shutdown();
}
this.dispose();
}
// Call this method to stop all other threads
public void forceShutdown(){
if (executor != null) {
executor.shutdownNow();
}
}
}
| DionysisTheodosis/JavaAps | WifiPasswords1.3/src/wifipasswords/QrScanner.java | 4,329 | //JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE); | line_comment | el | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JDialog.java to edit this template
*/
package wifipasswords;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
*
* @author dionysis
*/
public class QrScanner extends javax.swing.JDialog implements Runnable,ThreadFactory {
private WebcamPanel panel =null;
private Webcam webcam=null;
private static MyJFrame myFrame;
private static final long serialVersionUID =6441489157408381878L;
private ExecutorService executor = Executors.newSingleThreadExecutor(this);
private WifiProfile profile;
private volatile boolean stop;
private CountDownLatch latch;
/**
* Creates new form QrScanner
*/
public QrScanner(java.awt.Frame parent, boolean modal,MyJFrame myFrame) {
super(parent, modal);
this.myFrame=myFrame;
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.stop=false;
initComponents();
initWebcam();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jPanel3 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Σαρωτής QR Code");
setBackground(new java.awt.Color(113, 143, 164));
jPanel1.setBackground(getBackground());
jPanel1.setMaximumSize(new java.awt.Dimension(397, 419));
jPanel1.setMinimumSize(new java.awt.Dimension(397, 419));
jPanel2.setVisible(false);
jPanel2.setBackground(new java.awt.Color(113, 143, 164));
jLabel1.setBackground(new java.awt.Color(175, 217, 245));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton1.setText("Σύνδεση");
jButton1.setFocusable(false);
jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(74, 74, 74)
.addComponent(jButton1)
.addGap(74, 74, 74)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap())
);
jPanel4.setBackground(getBackground());
List<Webcam> filteredWebcams = new ArrayList<>();
Webcam[] webcams = Webcam.getWebcams().toArray(new Webcam[0]);
for (Webcam webcam : webcams) {
if (!webcam.getName().contains("OBS Virtual")) {
filteredWebcams.add(webcam);
}
}
Webcam[] updatedWebcams = filteredWebcams.toArray(new Webcam[0]);
String[] webcamNames = new String[updatedWebcams.length];
for (int i = 0; i < updatedWebcams.length; i++) {
webcamNames[i] = updatedWebcams[i].getName();
}
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(webcamNames));
jComboBox1.setSelectedIndex(0);
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jPanel3.setBackground(new java.awt.Color(113, 143, 164));
jPanel3.setMaximumSize(new java.awt.Dimension(373, 280));
jPanel3.setMinimumSize(new java.awt.Dimension(373, 280));
jPanel3.setPreferredSize(new java.awt.Dimension(373, 280));
jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(7, 7, 7))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(86, 86, 86))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1)))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
// Set the SSID and password
String ssid = profile.getName();
String password = profile.getPassword();
// Create the XML content
String xmlContent = "<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>"
+ ssid + "</name><SSIDConfig><SSID><name>" + ssid + "</name></SSID></SSIDConfig><connectionType>ESS</connectionType>"
+ "<connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication>"
+ "<encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType>"
+ "<protected>false</protected><keyMaterial>" + password + "</keyMaterial></sharedKey></security></MSM>"
+ "<MacRandomization xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v3\"><enableRandomization>false</enableRandomization>"
+ "</MacRandomization></WLANProfile>";
// Create the temporary XML file
String xmlFilePath = System.getProperty("java.io.tmpdir") + ssid + "-wireless-profile-generated.xml";
Files.write(Paths.get(xmlFilePath), xmlContent.getBytes());
// Execute the commands
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan add profile filename=\"" + xmlFilePath + "\"");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
process.waitFor();
processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan connect name=\"" + ssid + "\"");
processBuilder.redirectErrorStream(true);
process = processBuilder.start();
// Capture the output of the command
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append(System.lineSeparator());
}
}
process.waitFor();
// Check if the connection was successful
boolean isConnected = output.toString().contains("Connection request was completed successfully");
// Delete the temporary XML file
Files.deleteIfExists(Paths.get(xmlFilePath));
if (isConnected) {
clearOnExit();
myFrame.getConnectedProfile();
} else {
clearOnExit();
myFrame.notConnectedMessage();//JO<SUF>
}
} catch (IOException | InterruptedException e) {
clearOnExit();
myFrame.notConnectedMessage();//JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
initWebcam(Webcam.getWebcamByName((String)jComboBox1.getSelectedItem()));
}//GEN-LAST:event_jComboBox1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration//GEN-END:variables
private void initWebcam(){
webcam = Webcam.getWebcams().get(0); // Get the default webcam
Dimension size = WebcamResolution.VGA.getSize();
webcam.setViewSize(size);
panel = new WebcamPanel(webcam);
panel.setPreferredSize(size);
panel.setFPSDisplayed(true);
jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280));
executor = Executors.newSingleThreadExecutor(this);
executor.execute(this);
}
private void initWebcam(Webcam webcam2){
stop=true;
if (executor != null) {
executor.shutdown();
}
webcam.close();
webcam = webcam2; // Get the default webcam
Dimension[] resolutions = webcam.getViewSizes(); // Get the available resolutions
Dimension size = WebcamResolution.VGA.getSize();
webcam.setViewSize(size);
panel = new WebcamPanel(webcam);
panel.setPreferredSize(size);
panel = new WebcamPanel(webcam);
panel.setPreferredSize(size);
panel.setFPSDisplayed(true);
panel.repaint();
panel.revalidate();
jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280));
jPanel3.repaint();
jPanel3.revalidate();
stop=false;
executor = Executors.newSingleThreadExecutor(this);
executor.execute(this);
}
@Override
public void run() {
do{
if(stop&& Thread.currentThread().isInterrupted()){
break;
}
try{
Thread.sleep(100);
}
catch(Exception e){
e.printStackTrace();
}
Result result =null;
BufferedImage image=null;
if(webcam.isOpen()){
if((image=webcam.getImage())==null){
continue;
}
if(image!=null){
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try{
result = new MultiFormatReader().decode(bitmap);
}
catch(Exception e){
//
}
if(result!=null){
jPanel2.setVisible(true);
int startIndexSSID = result.getText().indexOf("S:") + 2; // Add 2 to skip "S:"
int endIndexSSID = result.getText().indexOf(";", startIndexSSID);
int startIndexPASS = result.getText().indexOf("P:") + 2; // Add 2 to skip "P:"
int endIndexPASS = result.getText().indexOf(";", startIndexPASS);
profile = new WifiProfile(result.getText().substring(startIndexSSID, endIndexSSID),result.getText().substring(startIndexPASS, endIndexPASS));
// Extract the SSID value from the string
String ssid = result.getText().substring(startIndexSSID, endIndexSSID);
jLabel1.setText(ssid);
}}}
}while(!stop&&!Thread.currentThread().isInterrupted());
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r,"My Thread");
t.setDaemon(true);
return t;
}
public void clearOnExit(){
stop=true;
webcam.close();
if (executor != null) {
executor.shutdown();
}
this.dispose();
}
// Call this method to stop all other threads
public void forceShutdown(){
if (executor != null) {
executor.shutdownNow();
}
}
}
|
26425_0 | package elak.readinghood.backend.api;
import org.junit.Test;
import java.io.IOException;
import java.util.HashSet;
import static org.junit.Assert.assertEquals;
/**
* Created by Δημήτρης Σβίγγας + Αλέξανδρος Χαλκίδης on 2/9/2018.
*/
public class AppManagerTest {
@Test
public void createThread() throws Exception {
try {
System.out.println(AppManager.getStartUpManager().login("[email protected]", "a"));
AppManager.setUserProfile();
HashSet<String> tags = new HashSet<String>();
tags.add("No_Spaces");
String test1 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags);
tags.clear();
tags.add("With Spaces");
String test2 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags);
tags.clear();
tags.add("No_Spaces");
String test3 = AppManager.createThread("#Title is-not_empty@", " ", tags);
tags.clear();
tags.add("With Spaces");
String test4 = AppManager.createThread("#Title is-not_empty@", " ", tags);
tags.clear();
tags.add("No_Spaces");
String test5 = AppManager.createThread(" ", "Hello world!", tags);
tags.clear();
tags.add("With Spaces");
String test6 = AppManager.createThread(" ", "Hello world!", tags);
tags.clear();
tags.add("No_Spaces");
String test7 = AppManager.createThread("#Title is-not_empty@", "", tags);
tags.clear();
tags.add("With Spaces");
String test8 = AppManager.createThread("#Title is-not_empty@", "", tags);
tags.clear();
tags.add("No_Spaces");
String test9 = AppManager.createThread("", "Hello mother i am here", tags);
tags.clear();
tags.add("With Spaces");
String test10 = AppManager.createThread("", "Hello mother i am here", tags);
tags.clear();
tags.add("No_Spaces");
String test11 = AppManager.createThread("!", "@", tags);
tags.clear();
tags.add("With Spaces");
String test12 = AppManager.createThread("!", "@", tags);
tags.clear();
tags.add("No_Spaces");
String test13 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!12345", tags);//255 leters
//tags.clear();
//tags.add("No_Spaces");
//String test14 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!123456", tags);//256 leters
tags.clear();
tags.add("No_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_Spacess12345");//255 letters
String test15 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags);
//tags.clear();
//tags.add("No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!123456");//256 letters
//String test16 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags);
tags.clear();
tags.add("No_Spaces");
String test17 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%12345", "Hello mother i am here", tags);//255 letters
//tags.clear();
//tags.add("No_Spaces");
//String test18 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%123456", "Hello mother i am here", tags);//256 letters
tags.clear();
tags.add("");
String test19 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add(" ");
String test20 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add("!");
String test21 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
String test22 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add("n_");
String test23 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add("_n");
String test24 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
assertEquals(test1, "Success");
assertEquals(test2, "Wrong hashTagFormat");
assertEquals(test3, "Fill the fields");
assertEquals(test4, "Fill the fields");
assertEquals(test5, "Fill the fields");
assertEquals(test6, "Fill the fields");
assertEquals(test7, "Fill the fields");
assertEquals(test8, "Fill the fields");
assertEquals(test9, "Fill the fields");
assertEquals(test10, "Fill the fields");
assertEquals(test11, "Success");
assertEquals(test12, "Wrong hashTagFormat");
assertEquals(test13, "Success");
//assertEquals(test14, "IOException"");
assertEquals(test15, "Success");
//assertEquals(test16, "IOException"");
assertEquals(test17, "Success");
//assertEquals(test18, "IOException");
//assertEquals(test19, "Fill the fields");
assertEquals(test20, "Wrong hashTagFormat");
assertEquals(test21, "Wrong hashTagFormat");
assertEquals(test22, "Thread must contain at least one hashTag");
assertEquals(test23, "Wrong hashTagFormat");
assertEquals(test24, "Wrong hashTagFormat");
} catch (NullPointerException e) {
e.printStackTrace();
throw new NullPointerException();
} catch (IOException e2){
throw new IOException();
} catch (Exception e3) {
e3.printStackTrace();
throw new Exception();
}
}
}
| DrMerfy/ReadingHood-Android-Client | app/src/test/java/elak/readinghood/AppManagerTest.java | 2,250 | /**
* Created by Δημήτρης Σβίγγας + Αλέξανδρος Χαλκίδης on 2/9/2018.
*/ | block_comment | el | package elak.readinghood.backend.api;
import org.junit.Test;
import java.io.IOException;
import java.util.HashSet;
import static org.junit.Assert.assertEquals;
/**
* Cre<SUF>*/
public class AppManagerTest {
@Test
public void createThread() throws Exception {
try {
System.out.println(AppManager.getStartUpManager().login("[email protected]", "a"));
AppManager.setUserProfile();
HashSet<String> tags = new HashSet<String>();
tags.add("No_Spaces");
String test1 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags);
tags.clear();
tags.add("With Spaces");
String test2 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags);
tags.clear();
tags.add("No_Spaces");
String test3 = AppManager.createThread("#Title is-not_empty@", " ", tags);
tags.clear();
tags.add("With Spaces");
String test4 = AppManager.createThread("#Title is-not_empty@", " ", tags);
tags.clear();
tags.add("No_Spaces");
String test5 = AppManager.createThread(" ", "Hello world!", tags);
tags.clear();
tags.add("With Spaces");
String test6 = AppManager.createThread(" ", "Hello world!", tags);
tags.clear();
tags.add("No_Spaces");
String test7 = AppManager.createThread("#Title is-not_empty@", "", tags);
tags.clear();
tags.add("With Spaces");
String test8 = AppManager.createThread("#Title is-not_empty@", "", tags);
tags.clear();
tags.add("No_Spaces");
String test9 = AppManager.createThread("", "Hello mother i am here", tags);
tags.clear();
tags.add("With Spaces");
String test10 = AppManager.createThread("", "Hello mother i am here", tags);
tags.clear();
tags.add("No_Spaces");
String test11 = AppManager.createThread("!", "@", tags);
tags.clear();
tags.add("With Spaces");
String test12 = AppManager.createThread("!", "@", tags);
tags.clear();
tags.add("No_Spaces");
String test13 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!12345", tags);//255 leters
//tags.clear();
//tags.add("No_Spaces");
//String test14 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!123456", tags);//256 leters
tags.clear();
tags.add("No_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_Spacess12345");//255 letters
String test15 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags);
//tags.clear();
//tags.add("No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!123456");//256 letters
//String test16 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags);
tags.clear();
tags.add("No_Spaces");
String test17 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%12345", "Hello mother i am here", tags);//255 letters
//tags.clear();
//tags.add("No_Spaces");
//String test18 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%123456", "Hello mother i am here", tags);//256 letters
tags.clear();
tags.add("");
String test19 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add(" ");
String test20 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add("!");
String test21 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
String test22 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add("n_");
String test23 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
tags.add("_n");
String test24 = AppManager.createThread("Hello World", "Hello world!", tags);
tags.clear();
assertEquals(test1, "Success");
assertEquals(test2, "Wrong hashTagFormat");
assertEquals(test3, "Fill the fields");
assertEquals(test4, "Fill the fields");
assertEquals(test5, "Fill the fields");
assertEquals(test6, "Fill the fields");
assertEquals(test7, "Fill the fields");
assertEquals(test8, "Fill the fields");
assertEquals(test9, "Fill the fields");
assertEquals(test10, "Fill the fields");
assertEquals(test11, "Success");
assertEquals(test12, "Wrong hashTagFormat");
assertEquals(test13, "Success");
//assertEquals(test14, "IOException"");
assertEquals(test15, "Success");
//assertEquals(test16, "IOException"");
assertEquals(test17, "Success");
//assertEquals(test18, "IOException");
//assertEquals(test19, "Fill the fields");
assertEquals(test20, "Wrong hashTagFormat");
assertEquals(test21, "Wrong hashTagFormat");
assertEquals(test22, "Thread must contain at least one hashTag");
assertEquals(test23, "Wrong hashTagFormat");
assertEquals(test24, "Wrong hashTagFormat");
} catch (NullPointerException e) {
e.printStackTrace();
throw new NullPointerException();
} catch (IOException e2){
throw new IOException();
} catch (Exception e3) {
e3.printStackTrace();
throw new Exception();
}
}
}
|
41970_11 | package android.gr.katastima;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.api.services.people.v1.PeopleScopes;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static Context context;
public static Activity activity;
public static GoogleSignInAccount account;
public static GoogleApiClient mGoogleApiClient;
public static int CUR_POINTS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
activity = this;
//Permission to read external storage
if(ContextCompat.checkSelfPermission(this,
android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
20);
}
else {
ServerCommunication.init();
}
Functions.LOCATION_FINDER = new LocationFinder(context, this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestServerAuthCode(getString(R.string.server_client_id))
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.requestScopes(new Scope(Scopes.PROFILE))
.requestScopes(new Scope(PeopleScopes.USER_BIRTHDAY_READ))
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == 20) {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ServerCommunication.init();
}
}
}
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
// Check if already signed in
account = GoogleSignIn.getLastSignedInAccount(context);
if(account != null) {
ServerCommunication.PointGetter task = new ServerCommunication.PointGetter(false);
task.execute(account.getEmail(), getString(R.string.appId), getString(R.string.userId));
}
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
GoogleApiAvailability gaa = GoogleApiAvailability.getInstance();
Dialog dialog = gaa.getErrorDialog(this, connectionResult.getErrorCode(), 101);
dialog.show();
}
@Override
public void onConnected(@Nullable Bundle bundle) {}
@Override
public void onConnectionSuspended(int i) {}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 4 total pages.
return 4;
}
public Fragment setItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Home";
case 1:
return "Catalog";
case 2:
return "Offers";
case 3:
return "Map";
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
int section = getArguments().getInt(ARG_SECTION_NUMBER);
if (section == 1) { // Home
try {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
Resources res = context.getResources();
ImageView img = (ImageView) rootView.findViewById(R.id.shopImage);
DisplayMetrics dm = Resources.getSystem().getDisplayMetrics();
int reqW = dm.widthPixels;
int reqH = Functions.convertDpToPx(200);
img.setImageBitmap(Functions.getScaledBitmap(res,
res.getIdentifier(context.getString(R.string.shop_image), "drawable", context.getPackageName()),
reqW, reqH));
}
catch(InflateException e) {}
} else if (section == 2) { // Τιμοκατάλογος
rootView = inflater.inflate(R.layout.fragment_timokatalogos, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.list_of_products);
ProductListAdapter listAdapter = new ProductListAdapter(getActivity(),
Functions.calcProductlist(getActivity()));
listView.setAdapter(listAdapter);
} else if (section == 3) { // Προσφορές
if(MainActivity.account != null) { // If user has logged in
rootView = inflater.inflate(R.layout.fragment_gifts, container, false);
final TextView textView = (TextView) rootView.findViewById(R.id.pointsTxt);
ListView listView = (ListView) rootView.findViewById(R.id.list_of_gifts);
final ArrayList<Gift> gifts = Functions.calcGiftlist(getActivity());
GiftListAdapter listAdapter = new GiftListAdapter(getActivity(),
gifts);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(MainActivity.CUR_POINTS >= Integer.parseInt(gifts.get(position).points)) {
ServerCommunication.CodeCreation task = new ServerCommunication.CodeCreation();
task.execute(
account.getEmail(),
getString(R.string.appId),
getString(R.string.userId),
gifts.get(position).points);
}
else {
Toast.makeText(context,"Not enough points..", Toast.LENGTH_SHORT).show();
}
}
});
final Button b = (Button) rootView.findViewById(R.id.checkInBtn);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsOn = Functions.LOCATION_FINDER.checkIfGpsIsEnabled();
if(gpsOn) {
Location l = Functions.LOCATION_FINDER.getLocation();
if(l != null) {
String[] details = Functions.getMapDetails(context);
float distance = Functions.getDistance(Double.parseDouble(details[1]), Double.parseDouble(details[2]), l.getLatitude(), l.getLongitude());
if(distance <= Integer.parseInt(getString(R.string.distance_from_shop))) {
ServerCommunication.PointSetter task = new ServerCommunication.PointSetter();
task.execute(MainActivity.account.getEmail(),getString(R.string.appId), getString(R.string.userId), "5");
}
else Toast.makeText(context, "Too far. Distance: " + distance, Toast.LENGTH_SHORT).show();
}
else Toast.makeText(context, "Try again..", Toast.LENGTH_SHORT).show();
}
}
});
String points = "POINTS(" + MainActivity.CUR_POINTS + ")";
textView.setText(points);
}
else { // Show sign in button
rootView = inflater.inflate(R.layout.fragment_google_signin, container, false);
SignInButton signInButton = (SignInButton) rootView.findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setColorScheme(SignInButton.COLOR_DARK);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
}
}
else if(section == 4) { // Map
rootView = inflater.inflate(R.layout.fragment_maps, container, false);
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
String[] details = Functions.getMapDetails(context);
LatLng place = new LatLng(Float.parseFloat(details[1]), Float.parseFloat(details[2]));
googleMap.addMarker(new MarkerOptions().position(place).title(details[0]));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place, 16f));
}
});
fm.beginTransaction().replace(R.id.rl_map, mapFragment).commit();
}
return rootView;
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
MainActivity.activity.startActivityForResult(signInIntent, 100);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100) {
GoogleSignInResult result =
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess()) {
account = result.getSignInAccount();
ServerCommunication.PeopleTask task = new ServerCommunication.PeopleTask(this, account.getIdToken(), account.getEmail());
task.execute(account.getServerAuthCode());
}
}
}
public void updateUi(String response) {
if(response != null) {
if(response.equals("Illegal")) {
account = null;
}
else if(response.equals("legal")) {
ServerCommunication.PointGetter task = new ServerCommunication.PointGetter(true);
task.execute(account.getEmail(), getString(R.string.appId), getString(R.string.userId));
// Update ui
mSectionsPagerAdapter.setItem(2);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(2);
}
}
else account = null;
}
public static void updatePointTxtView() {
try {
TextView textView = (TextView) activity.findViewById(R.id.pointsTxt);
Log.e("POINTS", MainActivity.CUR_POINTS + "");
textView.setText("POINTS(" +MainActivity.CUR_POINTS + ")");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| ETS-Android5/nodejsandroidproduction | Android Studio Project/app/src/main/java/android/gr/katastima/MainActivity.java | 3,325 | // Προσφορές | line_comment | el | package android.gr.katastima;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.api.services.people.v1.PeopleScopes;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static Context context;
public static Activity activity;
public static GoogleSignInAccount account;
public static GoogleApiClient mGoogleApiClient;
public static int CUR_POINTS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
activity = this;
//Permission to read external storage
if(ContextCompat.checkSelfPermission(this,
android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
20);
}
else {
ServerCommunication.init();
}
Functions.LOCATION_FINDER = new LocationFinder(context, this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestServerAuthCode(getString(R.string.server_client_id))
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.requestScopes(new Scope(Scopes.PROFILE))
.requestScopes(new Scope(PeopleScopes.USER_BIRTHDAY_READ))
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == 20) {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ServerCommunication.init();
}
}
}
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
// Check if already signed in
account = GoogleSignIn.getLastSignedInAccount(context);
if(account != null) {
ServerCommunication.PointGetter task = new ServerCommunication.PointGetter(false);
task.execute(account.getEmail(), getString(R.string.appId), getString(R.string.userId));
}
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
GoogleApiAvailability gaa = GoogleApiAvailability.getInstance();
Dialog dialog = gaa.getErrorDialog(this, connectionResult.getErrorCode(), 101);
dialog.show();
}
@Override
public void onConnected(@Nullable Bundle bundle) {}
@Override
public void onConnectionSuspended(int i) {}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 4 total pages.
return 4;
}
public Fragment setItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Home";
case 1:
return "Catalog";
case 2:
return "Offers";
case 3:
return "Map";
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
int section = getArguments().getInt(ARG_SECTION_NUMBER);
if (section == 1) { // Home
try {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
Resources res = context.getResources();
ImageView img = (ImageView) rootView.findViewById(R.id.shopImage);
DisplayMetrics dm = Resources.getSystem().getDisplayMetrics();
int reqW = dm.widthPixels;
int reqH = Functions.convertDpToPx(200);
img.setImageBitmap(Functions.getScaledBitmap(res,
res.getIdentifier(context.getString(R.string.shop_image), "drawable", context.getPackageName()),
reqW, reqH));
}
catch(InflateException e) {}
} else if (section == 2) { // Τιμοκατάλογος
rootView = inflater.inflate(R.layout.fragment_timokatalogos, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.list_of_products);
ProductListAdapter listAdapter = new ProductListAdapter(getActivity(),
Functions.calcProductlist(getActivity()));
listView.setAdapter(listAdapter);
} else if (section == 3) { // Πρ<SUF>
if(MainActivity.account != null) { // If user has logged in
rootView = inflater.inflate(R.layout.fragment_gifts, container, false);
final TextView textView = (TextView) rootView.findViewById(R.id.pointsTxt);
ListView listView = (ListView) rootView.findViewById(R.id.list_of_gifts);
final ArrayList<Gift> gifts = Functions.calcGiftlist(getActivity());
GiftListAdapter listAdapter = new GiftListAdapter(getActivity(),
gifts);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(MainActivity.CUR_POINTS >= Integer.parseInt(gifts.get(position).points)) {
ServerCommunication.CodeCreation task = new ServerCommunication.CodeCreation();
task.execute(
account.getEmail(),
getString(R.string.appId),
getString(R.string.userId),
gifts.get(position).points);
}
else {
Toast.makeText(context,"Not enough points..", Toast.LENGTH_SHORT).show();
}
}
});
final Button b = (Button) rootView.findViewById(R.id.checkInBtn);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsOn = Functions.LOCATION_FINDER.checkIfGpsIsEnabled();
if(gpsOn) {
Location l = Functions.LOCATION_FINDER.getLocation();
if(l != null) {
String[] details = Functions.getMapDetails(context);
float distance = Functions.getDistance(Double.parseDouble(details[1]), Double.parseDouble(details[2]), l.getLatitude(), l.getLongitude());
if(distance <= Integer.parseInt(getString(R.string.distance_from_shop))) {
ServerCommunication.PointSetter task = new ServerCommunication.PointSetter();
task.execute(MainActivity.account.getEmail(),getString(R.string.appId), getString(R.string.userId), "5");
}
else Toast.makeText(context, "Too far. Distance: " + distance, Toast.LENGTH_SHORT).show();
}
else Toast.makeText(context, "Try again..", Toast.LENGTH_SHORT).show();
}
}
});
String points = "POINTS(" + MainActivity.CUR_POINTS + ")";
textView.setText(points);
}
else { // Show sign in button
rootView = inflater.inflate(R.layout.fragment_google_signin, container, false);
SignInButton signInButton = (SignInButton) rootView.findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setColorScheme(SignInButton.COLOR_DARK);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
}
}
else if(section == 4) { // Map
rootView = inflater.inflate(R.layout.fragment_maps, container, false);
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
String[] details = Functions.getMapDetails(context);
LatLng place = new LatLng(Float.parseFloat(details[1]), Float.parseFloat(details[2]));
googleMap.addMarker(new MarkerOptions().position(place).title(details[0]));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place, 16f));
}
});
fm.beginTransaction().replace(R.id.rl_map, mapFragment).commit();
}
return rootView;
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
MainActivity.activity.startActivityForResult(signInIntent, 100);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100) {
GoogleSignInResult result =
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess()) {
account = result.getSignInAccount();
ServerCommunication.PeopleTask task = new ServerCommunication.PeopleTask(this, account.getIdToken(), account.getEmail());
task.execute(account.getServerAuthCode());
}
}
}
public void updateUi(String response) {
if(response != null) {
if(response.equals("Illegal")) {
account = null;
}
else if(response.equals("legal")) {
ServerCommunication.PointGetter task = new ServerCommunication.PointGetter(true);
task.execute(account.getEmail(), getString(R.string.appId), getString(R.string.userId));
// Update ui
mSectionsPagerAdapter.setItem(2);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(2);
}
}
else account = null;
}
public static void updatePointTxtView() {
try {
TextView textView = (TextView) activity.findViewById(R.id.pointsTxt);
Log.e("POINTS", MainActivity.CUR_POINTS + "");
textView.setText("POINTS(" +MainActivity.CUR_POINTS + ")");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
3201_40 | package com.eaw1805.orders;
import com.eaw1805.data.constants.AchievementConstants;
import com.eaw1805.data.constants.ArmyConstants;
import com.eaw1805.data.constants.GoodConstants;
import com.eaw1805.data.constants.NewsConstants;
import com.eaw1805.data.constants.OrderConstants;
import com.eaw1805.data.constants.ProductionSiteConstants;
import com.eaw1805.data.constants.ProfileConstants;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.constants.RelationConstants;
import com.eaw1805.data.constants.ReportConstants;
import com.eaw1805.data.constants.VPConstants;
import com.eaw1805.data.managers.NationManager;
import com.eaw1805.data.managers.NewsManager;
import com.eaw1805.data.managers.RelationsManager;
import com.eaw1805.data.managers.ReportManager;
import com.eaw1805.data.managers.army.ArmyManager;
import com.eaw1805.data.managers.army.BattalionManager;
import com.eaw1805.data.managers.army.BrigadeManager;
import com.eaw1805.data.managers.army.CommanderManager;
import com.eaw1805.data.managers.army.CorpManager;
import com.eaw1805.data.managers.army.SpyManager;
import com.eaw1805.data.managers.economy.TradeCityManager;
import com.eaw1805.data.model.Game;
import com.eaw1805.data.model.Nation;
import com.eaw1805.data.model.NationsRelation;
import com.eaw1805.data.model.News;
import com.eaw1805.data.model.PlayerOrder;
import com.eaw1805.data.model.Report;
import com.eaw1805.data.model.army.Army;
import com.eaw1805.data.model.army.Battalion;
import com.eaw1805.data.model.army.Brigade;
import com.eaw1805.data.model.army.Commander;
import com.eaw1805.data.model.army.Corp;
import com.eaw1805.data.model.army.Spy;
import com.eaw1805.data.model.economy.BaggageTrain;
import com.eaw1805.data.model.economy.TradeCity;
import com.eaw1805.data.model.fleet.Ship;
import com.eaw1805.data.model.map.CarrierInfo;
import com.eaw1805.data.model.map.Sector;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract implementation of an order processor.
*/
public abstract class AbstractOrderProcessor
implements OrderInterface, OrderConstants, NewsConstants, ReportConstants, VPConstants,
RelationConstants, RegionConstants {
/**
* a log4j logger to print messages.
*/
private static final Logger LOGGER = LogManager.getLogger(AbstractOrderProcessor.class);
/**
* The object containing the player order.
*/
private PlayerOrder order;
/**
* The parent object.
*/
private final transient OrderProcessor parent;
private final transient Game game;
/**
* nation relations.
*/
private static Map<Nation, Map<Nation, NationsRelation>> relationsMap;
/**
* Default constructor.
*
* @param myParent the parent object that invoked us.
*/
public AbstractOrderProcessor(final OrderProcessor myParent) {
parent = myParent;
game = myParent.getGame();
if (relationsMap == null) {
// Retrieve nation relations
relationsMap = mapNationRelation(getParent().getGame());
}
}
/**
* Default constructor.
*
* @param myGame the parent object that invoked us.
*/
public AbstractOrderProcessor(final Game myGame) {
game = myGame;
parent = null;
if (relationsMap == null) {
// Retrieve nation relations
relationsMap = mapNationRelation(getParent().getGame());
}
}
/**
* Returns the order object.
*
* @return the order object.
*/
public final PlayerOrder getOrder() {
return order;
}
/**
* Sets the particular thisOrder.
*
* @param thisOrder the new PlayerOrder instance.
*/
public final void setOrder(final PlayerOrder thisOrder) {
this.order = thisOrder;
}
/**
* Τhe parent object that invoked us.
*
* @return the parent object that invoked us.
*/
public OrderProcessor getParent() {
return parent;
}
public Game getGame() {
return game;
}
public void reloadRelations() {
relationsMap.clear();
// Retrieve nation relations
relationsMap = mapNationRelation(getParent().getGame());
}
/**
* Get the Relations from the database that corresponds to the input
* parameters.
*
* @param owner the Owner of the Report object.
* @param target the Target of the Report object.
* @return an Entity object.
*/
public NationsRelation getByNations(final Nation owner, final Nation target) {
return relationsMap.get(owner).get(target);
}
private Map<Nation, Map<Nation, NationsRelation>> mapNationRelation(final Game thisGame) {
final Map<Nation, Map<Nation, NationsRelation>> mapRelations = new HashMap<Nation, Map<Nation, NationsRelation>>();
final List<Nation> lstNations = NationManager.getInstance().list();
for (final Nation nation : lstNations) {
final List<NationsRelation> lstRelations = RelationsManager.getInstance().listByGameNation(thisGame, nation);
final Map<Nation, NationsRelation> nationRelations = new HashMap<Nation, NationsRelation>();
for (final NationsRelation relation : lstRelations) {
nationRelations.put(relation.getTarget(), relation);
}
mapRelations.put(nation, nationRelations);
}
return mapRelations;
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param type the type of the news entry.
* @param isGlobal if the news entry will appear to public.
* @param baseNewsId the base news entry.
* @param announcement the value of the news entry.
* @return the ID of the new entry.
*/
protected final int news(final Nation nation,
final Nation subject,
final int type,
final boolean isGlobal,
final int baseNewsId,
final String announcement) {
return news(game, nation, subject, type, isGlobal, baseNewsId, announcement);
}
/**
* Add a news entry for this turn.
*
* @param game the game of the news entry.
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param type the type of the news entry.
* @param isGlobal if the news entry will appear to public.
* @param baseNewsId the base news entry.
* @param announcement the value of the news entry.
* @return the ID of the new entry.
*/
protected final int news(final Game game,
final Nation nation,
final Nation subject,
final int type,
final boolean isGlobal,
final int baseNewsId,
final String announcement) {
final News thisNewsEntry = new News();
thisNewsEntry.setGame(game);
thisNewsEntry.setTurn(game.getTurn());
thisNewsEntry.setNation(nation);
thisNewsEntry.setSubject(subject);
thisNewsEntry.setType(type);
thisNewsEntry.setBaseNewsId(baseNewsId);
thisNewsEntry.setAnnouncement(false);
thisNewsEntry.setGlobal(isGlobal);
thisNewsEntry.setText(announcement);
NewsManager.getInstance().add(thisNewsEntry);
return thisNewsEntry.getNewsId();
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param type the type of the news entry.
* @param isGlobal the entry will appear on the public news.
* @param announcement the value of the news entry to appear for the nation.
* @param announcementAll the value of the news entry to appear for all others.
*/
protected void newsGlobal(final Nation nation,
final int type,
final boolean isGlobal,
final String announcement,
final String announcementAll) {
final int baseNewsId = news(game, nation, nation, type, false, 0, announcement);
final List<Nation> lstNations = getParent().getGameEngine().getAliveNations();
boolean global = isGlobal;
for (final Nation thirdNation : lstNations) {
if (thirdNation.getId() == nation.getId()) {
continue;
}
news(game, thirdNation, nation, type, global, baseNewsId, announcementAll);
global &= false;
}
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
* @param announcementSubject the value of the news entry to appear for the subject.
* @param announcementAll the value of the news entry to appear for all others.
*/
protected void newsGlobal(final Nation nation,
final Nation subject,
final int type,
final String announcementNation,
final String announcementSubject,
final String announcementAll) {
final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation);
news(game, subject, nation, type, false, baseNewsId, announcementSubject);
boolean isGlobal = true;
final List<Nation> lstNations = getParent().getGameEngine().getAliveNations();
for (final Nation thirdNation : lstNations) {
if (thirdNation.getId() == nation.getId()
|| thirdNation.getId() == subject.getId()) {
continue;
}
news(game, thirdNation, nation, type, isGlobal, baseNewsId, announcementAll);
isGlobal &= false;
}
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
* @param announcementSubject the value of the news entry to appear for the subject.
*/
protected void newsPair(final Nation nation,
final Nation subject,
final int type,
final String announcementNation,
final String announcementSubject) {
final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation);
news(game, subject, nation, type, false, baseNewsId, announcementSubject);
}
/**
* Add a news entry for this turn.
*
* @param game the game of the news entry.
* @param nation the owner of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
*/
protected void newsSingle(final Game game,
final Nation nation,
final int type,
final String announcementNation) {
news(game, nation, nation, type, false, 0, announcementNation);
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
*/
protected void newsSingle(final Nation nation,
final int type,
final String announcementNation) {
news(game, nation, nation, type, false, 0, announcementNation);
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param additionalId an additional identifier specific to this news entry.
* @param announcementNation the value of the news entry to appear for the nation.
*/
protected void newsSingle(final Nation nation,
final int type,
final int additionalId,
final String announcementNation) {
news(game, nation, nation, type, false, additionalId, announcementNation);
}
/**
* Add a report entry for this turn.
*
* @param key the key of the report entry.
* @param value the value of the report entry.
*/
protected final void report(final String key, final String value) {
final Report thisReport = new Report();
thisReport.setGame(game);
thisReport.setTurn(game.getTurn());
thisReport.setNation(order.getNation());
thisReport.setKey(key);
thisReport.setValue(value);
ReportManager.getInstance().add(thisReport);
}
/**
* Add a report entry for this turn.
*
* @param target the target of the report entry.
* @param key the key of the report entry.
* @param value the value of the report entry.
*/
protected final void report(final Nation target, final String key, final String value) {
final Report thisReport = new Report();
thisReport.setGame(game);
thisReport.setTurn(game.getTurn());
thisReport.setNation(target);
thisReport.setKey(key);
thisReport.setValue(value);
ReportManager.getInstance().add(thisReport);
}
/**
* Retrieve a report entry.
*
* @param owner the Owner of the report entry.
* @param turn the Turn of the report entry.
* @param key the key of the report entry.
* @return the value of the report entry.
*/
protected final int retrieveReportAsInt(final Nation owner, final int turn, final String key) {
final String value = retrieveReport(owner, turn, key);
// Check if string is empty
if (value.isEmpty()) {
return 0;
}
return Integer.parseInt(value);
}
/**
* Retrieve a report entry.
*
* @param owner the Owner of the report entry.
* @param turn the Turn of the report entry.
* @param key the key of the report entry.
* @return the value of the report entry.
*/
protected final String retrieveReport(final Nation owner, final int turn, final String key) {
try {
final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner, getParent().getGame(), turn, key);
if (thisReport == null) {
return "";
}
return thisReport.getValue();
} catch (Exception ex) {
return "";
}
}
/**
* Increase/Decrease the VPs of a nation.
*
* @param game the game instance.
* @param owner the Nation to change VPs.
* @param increase the increase or decrease in VPs.
* @param description the description of the VP change.
*/
protected final void changeVP(final Game game,
final Nation owner,
final int increase,
final String description) {
final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner,
game, game.getTurn(), N_VP);
if (thisReport != null) {
final int currentVP = Integer.parseInt(thisReport.getValue());
// Make sure we do not end up with negative VP
if (currentVP + increase > 0) {
thisReport.setValue(Integer.toString(currentVP + increase));
} else {
thisReport.setValue("0");
}
ReportManager.getInstance().update(thisReport);
// Report addition
news(game, owner, owner, NEWS_VP, false, increase, description);
// Modify player's profile
changeProfile(owner, ProfileConstants.VPS, increase);
// Report VP addition in player's achievements list
parent.achievement(game, owner, AchievementConstants.VPS, AchievementConstants.LEVEL_1, description, 0, increase);
}
}
/**
* Increase/Decrease a profile attribute for the player of the nation.
*
* @param owner the Nation to change the profile of the player.
* @param key the profile key of the player.
* @param increase the increase or decrease in the profile entry.
*/
public final void changeProfile(final Nation owner, final String key, final int increase) {
getParent().changeProfile(getParent().getGame(), owner, key, increase);
}
/**
* Check if in this sector there exist foreign+enemy brigades.
*
* @param thisSector the sector to check.
* @return true if enemy brigades are present.
*/
protected final boolean enemyNotPresent(final Sector thisSector) {
boolean notFound = true;
// Trade cities and large and huge fortresses are exempt from this rule.
if (thisSector.getProductionSite() != null
&& thisSector.getProductionSite().getId() >= ProductionSiteConstants.PS_BARRACKS_FL) {
return true;
}
final TradeCity city = TradeCityManager.getInstance().getByPosition(thisSector.getPosition());
if (city != null) {
return true;
}
// Retrieve all brigades at the particular Sector
final List<Brigade> lstBrigades = BrigadeManager.getInstance().listByPosition(thisSector.getPosition());
for (final Brigade thisBrigade : lstBrigades) {
// check owner
if (thisBrigade.getNation().getId() == thisSector.getNation().getId()) {
continue;
}
// Retrieve relations with foreign nation
final NationsRelation relation = RelationsManager.getInstance().getByNations(thisSector.getPosition().getGame(),
thisSector.getNation(),
thisBrigade.getNation());
// Check relations
if (relation.getRelation() == REL_WAR
|| (relation.getRelation() == REL_COLONIAL_WAR && thisSector.getPosition().getRegion().getId() != RegionConstants.EUROPE)) {
return false;
}
}
return notFound;
}
/**
* Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation.
*
* @param sector the sector to examine.
* @param receiver the receiving nation.
* @return 1 if home region, 2 if in sphere of influence, 3 if outside.
*/
protected final int getSphere(final Sector sector, final Nation receiver) {
final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0);
int sphere = 1;
// Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI
if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) {
return 1;
}
// Check if this is not home region
if (thisNationCodeLower != thisSectorCodeLower) {
sphere = 2;
// Check if this is outside sphere of influence
if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) {
sphere = 3;
}
}
return sphere;
}
/**
* Remove commander from army.
*
* @param armyId the army ID.
*/
protected void removeFromArmy(final int armyId, final int commanderId) {
// Retrieve army
final Army thisArmy = ArmyManager.getInstance().getByID(armyId);
if (thisArmy != null) {
//check that the commander in the army is the same (it could be changed previously by an assign order
if (thisArmy.getCommander() != null && thisArmy.getCommander().getId() != commanderId) {
return;
}
// remove commander
thisArmy.setCommander(null);
// update entity
ArmyManager.getInstance().update(thisArmy);
}
}
/**
* Remove commander from corps.
*
* @param corpId the corps id.
*/
protected void removeFromCorp(final int corpId, final int commanderId) {
// Retrieve corp
final Corp thisCorp = CorpManager.getInstance().getByID(corpId);
if (thisCorp != null) {
//check that the commander in the corps is the same (it could be changed previously by an assign order
if (thisCorp.getCommander() != null && thisCorp.getCommander().getId() != commanderId) {
return;
}
// remove commander
thisCorp.setCommander(null);
// update entity
CorpManager.getInstance().update(thisCorp);
}
}
/**
* Remove commander from army or corps.
*
* @param thisComm the commander object.
*/
protected void removeCommander(final Commander thisComm) {
if (thisComm.getArmy() != 0) {
removeFromArmy(thisComm.getArmy(), thisComm.getId());
thisComm.setArmy(0);
}
if (thisComm.getCorp() != 0) {
removeFromCorp(thisComm.getCorp(), thisComm.getId());
thisComm.setCorp(0);
}
//be sure to update commander.
CommanderManager.getInstance().update(thisComm);
}
public void destroyLoadedUnits(final Ship thisShip, final boolean isInLand) {
// Check if a unit is loaded in the ship
final Map<Integer, Integer> storedGoods = thisShip.getStoredGoods();
for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) {
if (entry.getKey() > GoodConstants.GOOD_LAST) {
if (entry.getKey() >= ArmyConstants.SPY * 1000) {
// A spy is loaded
final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
if (isInLand) {
newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when ship '" + thisShip.getName() + "' was scuttled by its crew");
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisSpy.setCarrierInfo(thisCarrying);
SpyManager.getInstance().update(thisSpy);
} else {
newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was drown when the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' was scuttled by its crew");
// Remove spy from game
SpyManager.getInstance().delete(thisSpy);
}
} else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) {
// A commander is loaded
final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue());
// Report capture of commander.
if (isInLand) {
newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisShip.getPosition().toString() + " when ship '" + thisShip.getName() + "' was scuttled by its crew");
} else {
newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was drown when the ship '" + thisShip.getName() + "' sunk");
LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' sunk");
// remove commander from command
removeCommander(thisCommander);
// remove commander from game
thisCommander.setDead(true);
}
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisCommander.setCarrierInfo(thisCarrying);
CommanderManager.getInstance().update(thisCommander);
} else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) {
// A Brigade is loaded
final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
if (isInLand) {
newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew.");
LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew.");
for (final Battalion battalion : thisBrigade.getBattalions()) {
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
battalion.setCarrierInfo(thisCarrying);
BattalionManager.getInstance().update(battalion);
}
BrigadeManager.getInstance().update(thisBrigade);
} else {
newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was disbanded when the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was disbanded when ship '" + thisShip.getName() + "' was scuttled by its crew");
// Remove brigade from game
BrigadeManager.getInstance().delete(thisBrigade);
}
}
}
}
}
public void destroyLoadedUnits(final BaggageTrain thisTrain) {
// Check if a unit is loaded in the ship
final Map<Integer, Integer> storedGoods = thisTrain.getStoredGoods();
for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) {
if (entry.getKey() > GoodConstants.GOOD_LAST) {
if (entry.getKey() >= ArmyConstants.SPY * 1000) {
// A spy is loaded
final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisSpy.setCarrierInfo(thisCarrying);
SpyManager.getInstance().update(thisSpy);
} else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) {
// A commander is loaded
final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue());
// Report capture of commander.
newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisTrain.getPosition().toString() + " when the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisCommander.setCarrierInfo(thisCarrying);
CommanderManager.getInstance().update(thisCommander);
} else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) {
// A Brigade is loaded
final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew.");
LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew.");
for (final Battalion battalion : thisBrigade.getBattalions()) {
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
battalion.setCarrierInfo(thisCarrying);
BattalionManager.getInstance().update(battalion);
}
BrigadeManager.getInstance().update(thisBrigade);
}
}
}
}
public Game getMyGame() {
return game;
}
}
| EaW1805/engine | src/main/java/com/eaw1805/orders/AbstractOrderProcessor.java | 7,583 | // Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI | line_comment | el | package com.eaw1805.orders;
import com.eaw1805.data.constants.AchievementConstants;
import com.eaw1805.data.constants.ArmyConstants;
import com.eaw1805.data.constants.GoodConstants;
import com.eaw1805.data.constants.NewsConstants;
import com.eaw1805.data.constants.OrderConstants;
import com.eaw1805.data.constants.ProductionSiteConstants;
import com.eaw1805.data.constants.ProfileConstants;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.constants.RelationConstants;
import com.eaw1805.data.constants.ReportConstants;
import com.eaw1805.data.constants.VPConstants;
import com.eaw1805.data.managers.NationManager;
import com.eaw1805.data.managers.NewsManager;
import com.eaw1805.data.managers.RelationsManager;
import com.eaw1805.data.managers.ReportManager;
import com.eaw1805.data.managers.army.ArmyManager;
import com.eaw1805.data.managers.army.BattalionManager;
import com.eaw1805.data.managers.army.BrigadeManager;
import com.eaw1805.data.managers.army.CommanderManager;
import com.eaw1805.data.managers.army.CorpManager;
import com.eaw1805.data.managers.army.SpyManager;
import com.eaw1805.data.managers.economy.TradeCityManager;
import com.eaw1805.data.model.Game;
import com.eaw1805.data.model.Nation;
import com.eaw1805.data.model.NationsRelation;
import com.eaw1805.data.model.News;
import com.eaw1805.data.model.PlayerOrder;
import com.eaw1805.data.model.Report;
import com.eaw1805.data.model.army.Army;
import com.eaw1805.data.model.army.Battalion;
import com.eaw1805.data.model.army.Brigade;
import com.eaw1805.data.model.army.Commander;
import com.eaw1805.data.model.army.Corp;
import com.eaw1805.data.model.army.Spy;
import com.eaw1805.data.model.economy.BaggageTrain;
import com.eaw1805.data.model.economy.TradeCity;
import com.eaw1805.data.model.fleet.Ship;
import com.eaw1805.data.model.map.CarrierInfo;
import com.eaw1805.data.model.map.Sector;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract implementation of an order processor.
*/
public abstract class AbstractOrderProcessor
implements OrderInterface, OrderConstants, NewsConstants, ReportConstants, VPConstants,
RelationConstants, RegionConstants {
/**
* a log4j logger to print messages.
*/
private static final Logger LOGGER = LogManager.getLogger(AbstractOrderProcessor.class);
/**
* The object containing the player order.
*/
private PlayerOrder order;
/**
* The parent object.
*/
private final transient OrderProcessor parent;
private final transient Game game;
/**
* nation relations.
*/
private static Map<Nation, Map<Nation, NationsRelation>> relationsMap;
/**
* Default constructor.
*
* @param myParent the parent object that invoked us.
*/
public AbstractOrderProcessor(final OrderProcessor myParent) {
parent = myParent;
game = myParent.getGame();
if (relationsMap == null) {
// Retrieve nation relations
relationsMap = mapNationRelation(getParent().getGame());
}
}
/**
* Default constructor.
*
* @param myGame the parent object that invoked us.
*/
public AbstractOrderProcessor(final Game myGame) {
game = myGame;
parent = null;
if (relationsMap == null) {
// Retrieve nation relations
relationsMap = mapNationRelation(getParent().getGame());
}
}
/**
* Returns the order object.
*
* @return the order object.
*/
public final PlayerOrder getOrder() {
return order;
}
/**
* Sets the particular thisOrder.
*
* @param thisOrder the new PlayerOrder instance.
*/
public final void setOrder(final PlayerOrder thisOrder) {
this.order = thisOrder;
}
/**
* Τhe parent object that invoked us.
*
* @return the parent object that invoked us.
*/
public OrderProcessor getParent() {
return parent;
}
public Game getGame() {
return game;
}
public void reloadRelations() {
relationsMap.clear();
// Retrieve nation relations
relationsMap = mapNationRelation(getParent().getGame());
}
/**
* Get the Relations from the database that corresponds to the input
* parameters.
*
* @param owner the Owner of the Report object.
* @param target the Target of the Report object.
* @return an Entity object.
*/
public NationsRelation getByNations(final Nation owner, final Nation target) {
return relationsMap.get(owner).get(target);
}
private Map<Nation, Map<Nation, NationsRelation>> mapNationRelation(final Game thisGame) {
final Map<Nation, Map<Nation, NationsRelation>> mapRelations = new HashMap<Nation, Map<Nation, NationsRelation>>();
final List<Nation> lstNations = NationManager.getInstance().list();
for (final Nation nation : lstNations) {
final List<NationsRelation> lstRelations = RelationsManager.getInstance().listByGameNation(thisGame, nation);
final Map<Nation, NationsRelation> nationRelations = new HashMap<Nation, NationsRelation>();
for (final NationsRelation relation : lstRelations) {
nationRelations.put(relation.getTarget(), relation);
}
mapRelations.put(nation, nationRelations);
}
return mapRelations;
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param type the type of the news entry.
* @param isGlobal if the news entry will appear to public.
* @param baseNewsId the base news entry.
* @param announcement the value of the news entry.
* @return the ID of the new entry.
*/
protected final int news(final Nation nation,
final Nation subject,
final int type,
final boolean isGlobal,
final int baseNewsId,
final String announcement) {
return news(game, nation, subject, type, isGlobal, baseNewsId, announcement);
}
/**
* Add a news entry for this turn.
*
* @param game the game of the news entry.
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param type the type of the news entry.
* @param isGlobal if the news entry will appear to public.
* @param baseNewsId the base news entry.
* @param announcement the value of the news entry.
* @return the ID of the new entry.
*/
protected final int news(final Game game,
final Nation nation,
final Nation subject,
final int type,
final boolean isGlobal,
final int baseNewsId,
final String announcement) {
final News thisNewsEntry = new News();
thisNewsEntry.setGame(game);
thisNewsEntry.setTurn(game.getTurn());
thisNewsEntry.setNation(nation);
thisNewsEntry.setSubject(subject);
thisNewsEntry.setType(type);
thisNewsEntry.setBaseNewsId(baseNewsId);
thisNewsEntry.setAnnouncement(false);
thisNewsEntry.setGlobal(isGlobal);
thisNewsEntry.setText(announcement);
NewsManager.getInstance().add(thisNewsEntry);
return thisNewsEntry.getNewsId();
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param type the type of the news entry.
* @param isGlobal the entry will appear on the public news.
* @param announcement the value of the news entry to appear for the nation.
* @param announcementAll the value of the news entry to appear for all others.
*/
protected void newsGlobal(final Nation nation,
final int type,
final boolean isGlobal,
final String announcement,
final String announcementAll) {
final int baseNewsId = news(game, nation, nation, type, false, 0, announcement);
final List<Nation> lstNations = getParent().getGameEngine().getAliveNations();
boolean global = isGlobal;
for (final Nation thirdNation : lstNations) {
if (thirdNation.getId() == nation.getId()) {
continue;
}
news(game, thirdNation, nation, type, global, baseNewsId, announcementAll);
global &= false;
}
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
* @param announcementSubject the value of the news entry to appear for the subject.
* @param announcementAll the value of the news entry to appear for all others.
*/
protected void newsGlobal(final Nation nation,
final Nation subject,
final int type,
final String announcementNation,
final String announcementSubject,
final String announcementAll) {
final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation);
news(game, subject, nation, type, false, baseNewsId, announcementSubject);
boolean isGlobal = true;
final List<Nation> lstNations = getParent().getGameEngine().getAliveNations();
for (final Nation thirdNation : lstNations) {
if (thirdNation.getId() == nation.getId()
|| thirdNation.getId() == subject.getId()) {
continue;
}
news(game, thirdNation, nation, type, isGlobal, baseNewsId, announcementAll);
isGlobal &= false;
}
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param subject the subject of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
* @param announcementSubject the value of the news entry to appear for the subject.
*/
protected void newsPair(final Nation nation,
final Nation subject,
final int type,
final String announcementNation,
final String announcementSubject) {
final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation);
news(game, subject, nation, type, false, baseNewsId, announcementSubject);
}
/**
* Add a news entry for this turn.
*
* @param game the game of the news entry.
* @param nation the owner of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
*/
protected void newsSingle(final Game game,
final Nation nation,
final int type,
final String announcementNation) {
news(game, nation, nation, type, false, 0, announcementNation);
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param announcementNation the value of the news entry to appear for the nation.
*/
protected void newsSingle(final Nation nation,
final int type,
final String announcementNation) {
news(game, nation, nation, type, false, 0, announcementNation);
}
/**
* Add a news entry for this turn.
*
* @param nation the owner of the news entry.
* @param additionalId an additional identifier specific to this news entry.
* @param announcementNation the value of the news entry to appear for the nation.
*/
protected void newsSingle(final Nation nation,
final int type,
final int additionalId,
final String announcementNation) {
news(game, nation, nation, type, false, additionalId, announcementNation);
}
/**
* Add a report entry for this turn.
*
* @param key the key of the report entry.
* @param value the value of the report entry.
*/
protected final void report(final String key, final String value) {
final Report thisReport = new Report();
thisReport.setGame(game);
thisReport.setTurn(game.getTurn());
thisReport.setNation(order.getNation());
thisReport.setKey(key);
thisReport.setValue(value);
ReportManager.getInstance().add(thisReport);
}
/**
* Add a report entry for this turn.
*
* @param target the target of the report entry.
* @param key the key of the report entry.
* @param value the value of the report entry.
*/
protected final void report(final Nation target, final String key, final String value) {
final Report thisReport = new Report();
thisReport.setGame(game);
thisReport.setTurn(game.getTurn());
thisReport.setNation(target);
thisReport.setKey(key);
thisReport.setValue(value);
ReportManager.getInstance().add(thisReport);
}
/**
* Retrieve a report entry.
*
* @param owner the Owner of the report entry.
* @param turn the Turn of the report entry.
* @param key the key of the report entry.
* @return the value of the report entry.
*/
protected final int retrieveReportAsInt(final Nation owner, final int turn, final String key) {
final String value = retrieveReport(owner, turn, key);
// Check if string is empty
if (value.isEmpty()) {
return 0;
}
return Integer.parseInt(value);
}
/**
* Retrieve a report entry.
*
* @param owner the Owner of the report entry.
* @param turn the Turn of the report entry.
* @param key the key of the report entry.
* @return the value of the report entry.
*/
protected final String retrieveReport(final Nation owner, final int turn, final String key) {
try {
final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner, getParent().getGame(), turn, key);
if (thisReport == null) {
return "";
}
return thisReport.getValue();
} catch (Exception ex) {
return "";
}
}
/**
* Increase/Decrease the VPs of a nation.
*
* @param game the game instance.
* @param owner the Nation to change VPs.
* @param increase the increase or decrease in VPs.
* @param description the description of the VP change.
*/
protected final void changeVP(final Game game,
final Nation owner,
final int increase,
final String description) {
final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner,
game, game.getTurn(), N_VP);
if (thisReport != null) {
final int currentVP = Integer.parseInt(thisReport.getValue());
// Make sure we do not end up with negative VP
if (currentVP + increase > 0) {
thisReport.setValue(Integer.toString(currentVP + increase));
} else {
thisReport.setValue("0");
}
ReportManager.getInstance().update(thisReport);
// Report addition
news(game, owner, owner, NEWS_VP, false, increase, description);
// Modify player's profile
changeProfile(owner, ProfileConstants.VPS, increase);
// Report VP addition in player's achievements list
parent.achievement(game, owner, AchievementConstants.VPS, AchievementConstants.LEVEL_1, description, 0, increase);
}
}
/**
* Increase/Decrease a profile attribute for the player of the nation.
*
* @param owner the Nation to change the profile of the player.
* @param key the profile key of the player.
* @param increase the increase or decrease in the profile entry.
*/
public final void changeProfile(final Nation owner, final String key, final int increase) {
getParent().changeProfile(getParent().getGame(), owner, key, increase);
}
/**
* Check if in this sector there exist foreign+enemy brigades.
*
* @param thisSector the sector to check.
* @return true if enemy brigades are present.
*/
protected final boolean enemyNotPresent(final Sector thisSector) {
boolean notFound = true;
// Trade cities and large and huge fortresses are exempt from this rule.
if (thisSector.getProductionSite() != null
&& thisSector.getProductionSite().getId() >= ProductionSiteConstants.PS_BARRACKS_FL) {
return true;
}
final TradeCity city = TradeCityManager.getInstance().getByPosition(thisSector.getPosition());
if (city != null) {
return true;
}
// Retrieve all brigades at the particular Sector
final List<Brigade> lstBrigades = BrigadeManager.getInstance().listByPosition(thisSector.getPosition());
for (final Brigade thisBrigade : lstBrigades) {
// check owner
if (thisBrigade.getNation().getId() == thisSector.getNation().getId()) {
continue;
}
// Retrieve relations with foreign nation
final NationsRelation relation = RelationsManager.getInstance().getByNations(thisSector.getPosition().getGame(),
thisSector.getNation(),
thisBrigade.getNation());
// Check relations
if (relation.getRelation() == REL_WAR
|| (relation.getRelation() == REL_COLONIAL_WAR && thisSector.getPosition().getRegion().getId() != RegionConstants.EUROPE)) {
return false;
}
}
return notFound;
}
/**
* Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation.
*
* @param sector the sector to examine.
* @param receiver the receiving nation.
* @return 1 if home region, 2 if in sphere of influence, 3 if outside.
*/
protected final int getSphere(final Sector sector, final Nation receiver) {
final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0);
int sphere = 1;
// Τα<SUF>
if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) {
return 1;
}
// Check if this is not home region
if (thisNationCodeLower != thisSectorCodeLower) {
sphere = 2;
// Check if this is outside sphere of influence
if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) {
sphere = 3;
}
}
return sphere;
}
/**
* Remove commander from army.
*
* @param armyId the army ID.
*/
protected void removeFromArmy(final int armyId, final int commanderId) {
// Retrieve army
final Army thisArmy = ArmyManager.getInstance().getByID(armyId);
if (thisArmy != null) {
//check that the commander in the army is the same (it could be changed previously by an assign order
if (thisArmy.getCommander() != null && thisArmy.getCommander().getId() != commanderId) {
return;
}
// remove commander
thisArmy.setCommander(null);
// update entity
ArmyManager.getInstance().update(thisArmy);
}
}
/**
* Remove commander from corps.
*
* @param corpId the corps id.
*/
protected void removeFromCorp(final int corpId, final int commanderId) {
// Retrieve corp
final Corp thisCorp = CorpManager.getInstance().getByID(corpId);
if (thisCorp != null) {
//check that the commander in the corps is the same (it could be changed previously by an assign order
if (thisCorp.getCommander() != null && thisCorp.getCommander().getId() != commanderId) {
return;
}
// remove commander
thisCorp.setCommander(null);
// update entity
CorpManager.getInstance().update(thisCorp);
}
}
/**
* Remove commander from army or corps.
*
* @param thisComm the commander object.
*/
protected void removeCommander(final Commander thisComm) {
if (thisComm.getArmy() != 0) {
removeFromArmy(thisComm.getArmy(), thisComm.getId());
thisComm.setArmy(0);
}
if (thisComm.getCorp() != 0) {
removeFromCorp(thisComm.getCorp(), thisComm.getId());
thisComm.setCorp(0);
}
//be sure to update commander.
CommanderManager.getInstance().update(thisComm);
}
public void destroyLoadedUnits(final Ship thisShip, final boolean isInLand) {
// Check if a unit is loaded in the ship
final Map<Integer, Integer> storedGoods = thisShip.getStoredGoods();
for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) {
if (entry.getKey() > GoodConstants.GOOD_LAST) {
if (entry.getKey() >= ArmyConstants.SPY * 1000) {
// A spy is loaded
final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
if (isInLand) {
newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when ship '" + thisShip.getName() + "' was scuttled by its crew");
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisSpy.setCarrierInfo(thisCarrying);
SpyManager.getInstance().update(thisSpy);
} else {
newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was drown when the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' was scuttled by its crew");
// Remove spy from game
SpyManager.getInstance().delete(thisSpy);
}
} else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) {
// A commander is loaded
final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue());
// Report capture of commander.
if (isInLand) {
newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisShip.getPosition().toString() + " when ship '" + thisShip.getName() + "' was scuttled by its crew");
} else {
newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was drown when the ship '" + thisShip.getName() + "' sunk");
LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' sunk");
// remove commander from command
removeCommander(thisCommander);
// remove commander from game
thisCommander.setDead(true);
}
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisCommander.setCarrierInfo(thisCarrying);
CommanderManager.getInstance().update(thisCommander);
} else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) {
// A Brigade is loaded
final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
if (isInLand) {
newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew.");
LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew.");
for (final Battalion battalion : thisBrigade.getBattalions()) {
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
battalion.setCarrierInfo(thisCarrying);
BattalionManager.getInstance().update(battalion);
}
BrigadeManager.getInstance().update(thisBrigade);
} else {
newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was disbanded when the ship '" + thisShip.getName() + "' was scuttled by its crew");
LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was disbanded when ship '" + thisShip.getName() + "' was scuttled by its crew");
// Remove brigade from game
BrigadeManager.getInstance().delete(thisBrigade);
}
}
}
}
}
public void destroyLoadedUnits(final BaggageTrain thisTrain) {
// Check if a unit is loaded in the ship
final Map<Integer, Integer> storedGoods = thisTrain.getStoredGoods();
for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) {
if (entry.getKey() > GoodConstants.GOOD_LAST) {
if (entry.getKey() >= ArmyConstants.SPY * 1000) {
// A spy is loaded
final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisSpy.setCarrierInfo(thisCarrying);
SpyManager.getInstance().update(thisSpy);
} else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) {
// A commander is loaded
final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue());
// Report capture of commander.
newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisTrain.getPosition().toString() + " when the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew");
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
thisCommander.setCarrierInfo(thisCarrying);
CommanderManager.getInstance().update(thisCommander);
} else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) {
// A Brigade is loaded
final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue());
// Report capture of spy.
newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew.");
LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew.");
for (final Battalion battalion : thisBrigade.getBattalions()) {
// remove carrier info
final CarrierInfo thisCarrying = new CarrierInfo();
thisCarrying.setCarrierType(0);
thisCarrying.setCarrierId(0);
battalion.setCarrierInfo(thisCarrying);
BattalionManager.getInstance().update(battalion);
}
BrigadeManager.getInstance().update(thisBrigade);
}
}
}
}
public Game getMyGame() {
return game;
}
}
|
9864_8 | package com.eaw1805.www.controllers.remote.hotspot;
import com.eaw1805.data.constants.AdminCommandPoints;
import com.eaw1805.data.constants.ArmyConstants;
import com.eaw1805.data.constants.GoodConstants;
import com.eaw1805.data.constants.NationConstants;
import com.eaw1805.data.constants.OrderConstants;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.dto.collections.DataCollection;
import com.eaw1805.data.dto.common.SectorDTO;
import com.eaw1805.data.dto.converters.SectorConverter;
import com.eaw1805.data.dto.web.ClientOrderDTO;
import com.eaw1805.data.dto.web.OrderCostDTO;
import com.eaw1805.data.dto.web.OrderDTO;
import com.eaw1805.data.dto.web.army.ArmyTypeDTO;
import com.eaw1805.data.dto.web.army.BattalionDTO;
import com.eaw1805.data.dto.web.army.BrigadeDTO;
import com.eaw1805.data.dto.web.economy.BaggageTrainDTO;
import com.eaw1805.data.dto.web.fleet.ShipDTO;
import com.eaw1805.data.dto.web.fleet.ShipTypeDTO;
import com.eaw1805.data.model.Nation;
import com.eaw1805.data.model.army.Brigade;
import com.eaw1805.data.model.map.Sector;
import com.eaw1805.www.controllers.remote.EmpireRpcServiceImpl;
import com.eaw1805.www.shared.stores.GameStore;
import com.eaw1805.www.shared.stores.util.calculators.CostCalculators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@SuppressWarnings("restriction")
public class OrderApplyChangesProcessor
extends AbstractChangesProcessor
implements OrderConstants, GoodConstants {
/**
* The orders and the corresponding costs.
*/
private transient final Map<Integer, List<ClientOrderDTO>> clientOrders;
private transient List<OrderDTO> orders = new ArrayList<OrderDTO>();
private transient final Map<Integer, ArmyTypeDTO> armyTypes = new HashMap<Integer, ArmyTypeDTO>();
private transient final Map<Integer, ShipTypeDTO> shipTypes = new HashMap<Integer, ShipTypeDTO>();
private transient final EmpireRpcServiceImpl service;
private transient final DataCollection prodAndNatSites;
/**
* Default constructor.
*
* @param thisGame the game of the order.
* @param thisNation the owner of the order.
* @param thisTurn the turn of the order.
*/
public OrderApplyChangesProcessor(final int scenarioId,
final int thisGame,
final int thisNation,
final int thisTurn,
final EmpireRpcServiceImpl empireRpcServiceImpl) {
super(scenarioId, thisGame, thisNation, thisTurn);
service = empireRpcServiceImpl;
for (ArmyTypeDTO armyTypeDTO : service.getArmyTypes(getScenarioId(), getNationId())) {
armyTypes.put(armyTypeDTO.getIntId(), armyTypeDTO);
}
for (ShipTypeDTO shipTypeDTO : service.getShipTypes(getScenarioId(), getNationId())) {
shipTypes.put(shipTypeDTO.getIntId(), shipTypeDTO);
}
prodAndNatSites = service.getNaturalResAndProdSites(getScenarioId());
clientOrders = new TreeMap<Integer, List<ClientOrderDTO>>();
}
@SuppressWarnings({"unchecked"})
public void addData(final Collection<?> dbData, final Collection<?> chOrders) {
orders = (List<OrderDTO>) chOrders;
}
public void addData(final Map<?, ?> dbData, final Map<?, ?> chData) {
// do nothing
}
public Map<Integer, List<ClientOrderDTO>> processChanges() {
for (final OrderDTO order : orders) {
OrderCostDTO orderCost = new OrderCostDTO();
int regionId = 1;
String name = "";
String comment = "";
final int[] ids = new int[9];
for (int i = 0; i < 9; i++) {
ids[i] = 0;
}
switch (order.getType()) {
case ORDER_B_BATT: {
// Double costs custom game option
final int doubleCosts = (GameStore.getInstance().isDoubleCostsArmy()) ? 2 : 1;
final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1()));
final int sphere = getSphere(sector, service.nationManager.getByID(getNationId()));
final int multiplier = doubleCosts * sphere;
final BrigadeDTO brig = createBrigadeFromOrder(order);
orderCost = CostCalculators.getBrigadeCost(brig, multiplier, sphere);
name = order.getParameter9();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = brig.getBrigadeId();
regionId = brig.getRegionId();
break;
}
case ORDER_ADDTO_BRIGADE:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
break;
case ORDER_ADDTO_ARMY:
case ORDER_ADDTO_CORP:
case ORDER_ADDTO_FLT:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_HIRE_COM:
orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_ARMY_COM:
name = order.getTemp1() + "-" + order.getParameter2();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_CORP_COM:
name = order.getTemp1() + "-" + order.getParameter2();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_LEAVE_COM:
ids[0] = Integer.parseInt(order.getParameter2());
ids[1] = 0;
break;
case ORDER_DISS_COM:
orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_B_ARMY:
case ORDER_B_FLT:
orderCost = CostCalculators.getFormFederationCost(order.getType());
name = order.getParameter2();
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_B_CORP:
orderCost = CostCalculators.getFormFederationCost(order.getType());
name = order.getParameter3();
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_ADD_BATT: {
final Brigade brigade = service.getBrigadeManager().getByID(Integer.parseInt(order.getParameter1()));
final Sector sector = service.getSectorManager().getByPosition(brigade.getPosition());
final int multiplier = getSphere(sector, service.getNationManager().getByID(getNationId()));
orderCost = CostCalculators.getArmyTypeCost(getArmyTypeById(Integer.parseInt(order.getParameter2())), multiplier);
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
regionId = Integer.parseInt(order.getTemp1());
break;
}
case ORDER_B_BTRAIN:
orderCost = CostCalculators.getBaggageTrainCost();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = Integer.parseInt(order.getTemp1());
break;
case ORDER_R_BTRAIN:
orderCost = CostCalculators.getBaggageTrainRepairCost(100 - Integer.parseInt(order.getParameter3()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = Integer.parseInt(order.getTemp1());
break;
case ORDER_B_PRODS:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
SectorDTO sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
regionId = sectorDTO.getRegionId();
orderCost = CostCalculators.getProductionSiteCost(regionId, prodAndNatSites.getProdSite(Integer.parseInt(order.getParameter2())), false);
break;
case ORDER_D_PRODS:
ids[0] = Integer.parseInt(order.getParameter1());
sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
regionId = sectorDTO.getRegionId();
orderCost = CostCalculators.getProductionSiteCost(regionId, null, true);
break;
case ORDER_B_SHIP:
ShipDTO ship = createShipFromOrder(order);
orderCost = CostCalculators.getShipCost(ship);
name = order.getParameter3();
ids[0] = Integer.parseInt(order.getTemp1());
ids[1] = Integer.parseInt(order.getParameter1());
ids[2] = Integer.parseInt(order.getParameter2());
regionId = ship.getRegionId();
break;
case ORDER_R_FLT:
final String[] costValues = order.getTemp2().split("!");
for (String costValue : costValues) {
final String[] keyVal = costValue.split(":");
orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1]));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
comment = order.getTemp2();
regionId = ids[2];
break;
case ORDER_R_SHP:
ship = service.getShipById(getScenarioId(), Integer.parseInt(order.getParameter1()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
orderCost = CostCalculators.getShipRepairCost(ship.getCondition(), ship);
regionId = Integer.parseInt(order.getTemp1());
break;
case ORDER_D_ARMY:
case ORDER_D_BATT:
case ORDER_D_BRIG:
case ORDER_D_CORP:
case ORDER_D_FLT:
name = order.getTemp1();
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_FM_ARMY:
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_FM_BRIG:
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_FM_CORP:
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_HOVER_SEC:
case ORDER_HOVER_SHIP:
ids[0] = Integer.parseInt(order.getParameter1());
orderCost = CostCalculators.getHandOverCost(order.getType(), Integer.parseInt(order.getTemp1()));
break;
case ORDER_INC_EXP:
case ORDER_INC_EXP_CORPS:
case ORDER_INC_EXP_ARMY:
if (order.getTemp2() != null && !order.getTemp2().isEmpty()) {
final String[] expCostValues = order.getTemp2().split("!");
for (String costValue : expCostValues) {
final String[] keyVal = costValue.split(":");
orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1]));
}
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
regionId = ids[2];
break;
case ORDER_INC_HEADCNT:
case ORDER_INC_HEADCNT_CORPS:
case ORDER_INC_HEADCNT_ARMY:
if (order.getTemp2() != null && !order.getTemp2().isEmpty()) {
final String[] upHeadCostValues = order.getTemp2().split("!");
for (String costValue : upHeadCostValues) {
final String[] keyVal = costValue.split(":");
orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1]));
}
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
regionId = ids[2];
break;
case ORDER_INC_POP: {
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = ids[1];
sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
orderCost = CostCalculators.getIncDecPopCost(sectorDTO, true);
break;
}
case ORDER_DEC_POP: {
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = ids[1];
final SectorDTO sector = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
orderCost = CostCalculators.getIncDecPopCost(sector, false);
break;
}
case ORDER_M_UNIT:
orderCost = CostCalculators.getMovementCost(Integer.parseInt(order.getParameter5()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter5());
break;
case ORDER_MRG_BATT:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_TAXATION:
orderCost = CostCalculators.getTaxationCost(Integer.parseInt(order.getTemp3()),
Integer.parseInt(order.getTemp4()),
Integer.parseInt(order.getTemp1()),
Integer.parseInt(order.getTemp2()));
break;
case ORDER_EXCHF:
case ORDER_EXCHS:
orderCost.setNumericCost(Integer.parseInt(order.getParameter5()), Integer.parseInt(order.getParameter6()));
orderCost.setNumericCost(1, Integer.parseInt(order.getTemp1()));
if (Integer.parseInt(order.getParameter1()) == ArmyConstants.TRADECITY
|| Integer.parseInt(order.getParameter3()) == ArmyConstants.TRADECITY) {
orderCost.setNumericCost(GOOD_AP, AdminCommandPoints.P_ADM.get(order.getType()));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
ids[4] = Integer.parseInt(order.getParameter5());
ids[5] = Integer.parseInt(order.getParameter6());
regionId = Integer.parseInt(order.getParameter9());
break;
case ORDER_LOAD_TROOPSF:
case ORDER_LOAD_TROOPSS:
if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost
orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3()));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
ids[4] = Integer.parseInt(order.getParameter5());
ids[5] = Integer.parseInt(order.getParameter6());
break;
case ORDER_UNLOAD_TROOPSF:
case ORDER_UNLOAD_TROOPSS:
if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost
orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3()));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
ids[4] = Integer.parseInt(order.getParameter5());
ids[5] = Integer.parseInt(order.getTemp1());
ids[6] = Integer.parseInt(order.getTemp2());
break;
case ORDER_REN_SHIP:
case ORDER_REN_BRIG:
case ORDER_REN_COMM:
case ORDER_REN_ARMY:
case ORDER_REN_CORP:
case ORDER_REN_FLT:
case ORDER_REN_BARRACK:
case ORDER_REN_BTRAIN:
ids[0] = Integer.parseInt(order.getParameter1());
name = order.getParameter2();
break;
case ORDER_SCUTTLE_BTRAIN:
ids[0] = Integer.parseInt(order.getParameter1());
final BaggageTrainDTO scuttledTrain = service.getBaggageTrainById(getScenarioId(), ids[0]);
if (scuttledTrain != null) {
orderCost = CostCalculators.getScuttleBaggageTrainCost(scuttledTrain.getCondition());
}
break;
case ORDER_SCUTTLE_SHIP:
ids[0] = Integer.parseInt(order.getParameter1());
final ShipDTO scuttledShip = service.getShipById(getScenarioId(), ids[0]);
if (scuttledShip != null) {
orderCost = CostCalculators.getScuttleShipCost(scuttledShip);
}
break;
case ORDER_POLITICS:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
break;
default:
// do nothing
}
addNewOrder(order.getType(), orderCost, regionId, name, ids, order.getPosition(), comment);
}
return clientOrders;
}
/**
* Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation.
*
* @param sector the sector to examine.
* @param receiver the receiving nation.
* @return 1 if home region, 2 if in sphere of influence, 3 if outside.
*/
protected final int getSphere(final Sector sector, final Nation receiver) {
final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0);
int sphere = 1;
// Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI
if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) {
return 1;
}
// Check if this is not home region
if (thisNationCodeLower != thisSectorCodeLower) {
sphere = 2;
// Check if this is outside sphere of influence
if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) {
sphere = 3;
}
}
return sphere;
}
// /**
// * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation.
// *
// * @param sector the sector to examine.
// * @param receiver the receiving nation.
// * @return 1 if home region, 2 if in sphere of influence, 3 if outside.
// */
// protected int getSphere(final Sector sector, final Nation receiver) {
// final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
// final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0);
// int sphere = 1;
//
// if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) {
// return sphere;
// }
//
// // Check if this is not home region
// if (thisNationCodeLower != thisSectorCodeLower) {
// sphere = 2;
//
// final char thisNationCode = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
//
// // Check if this is outside sphere of influence
// if (sector.getNation().getSphereOfInfluence().indexOf(thisNationCode) < 0) {
// sphere = 3;
// }
// }
//
// return sphere;
// }
/**
* Method that adds a new order to our order Map
*
* @param typeId The type of the order we want to add.
* @param orderCost The calculated cost of the order.
* @param regionId the region of the warehouse.
* @param name the name of the order.
* @param identifiers the id of the order.
* @param position The position of the order.
* @param comment the comment of the order.
* @return 0 if there are no available funds 1 if there are
*/
private int addNewOrder(final int typeId, final OrderCostDTO orderCost,
final int regionId,
final String name,
final int[] identifiers,
final int position,
final String comment) {
int priority = position;
if (clientOrders.get(typeId) == null) {
clientOrders.put(typeId, new ArrayList<ClientOrderDTO>());
} else {
priority = clientOrders.get(typeId).size();
}
if (position == 0) {
priority = clientOrders.get(typeId).size();
}
final ClientOrderDTO order = new ClientOrderDTO();
order.setOrderTypeId(typeId);
order.setPriority(priority);
order.setCosts(orderCost);
order.setName(name);
order.setComment(comment);
for (int index = 0; index < identifiers.length; index++) {
order.setIdentifier(index, identifiers[index]);
}
order.setRegionId(regionId);
clientOrders.get(typeId).add(order);
return 1;
}
/**
* Creates new brigade from the order.
*
* @param order the order to use.
* @return the new brigade object.
*/
private BrigadeDTO createBrigadeFromOrder(final OrderDTO order) {
final BrigadeDTO newBrigade = new BrigadeDTO();
newBrigade.setNationId(getNationId());
newBrigade.setName(order.getParameter9());
try {
newBrigade.setBrigadeId(Integer.parseInt(order.getTemp1()));
} catch (Exception ex) {
if (clientOrders.get(ORDER_ADD_BATT) == null) {
newBrigade.setBrigadeId(0);
} else {
newBrigade.setBrigadeId(clientOrders.get(ORDER_ADD_BATT).size());
}
}
newBrigade.setBattalions(new ArrayList<BattalionDTO>());
final BattalionDTO battalionDto1 = getBattalionByArmyTypeId(order.getParameter2(), 1);
final BattalionDTO battalionDto2 = getBattalionByArmyTypeId(order.getParameter3(), 2);
final BattalionDTO battalionDto3 = getBattalionByArmyTypeId(order.getParameter4(), 3);
final BattalionDTO battalionDto4 = getBattalionByArmyTypeId(order.getParameter5(), 4);
final BattalionDTO battalionDto5 = getBattalionByArmyTypeId(order.getParameter6(), 5);
final BattalionDTO battalionDto6 = getBattalionByArmyTypeId(order.getParameter7(), 6);
final BattalionDTO battalionDto7 = getBattalionByArmyTypeId(order.getParameter8(), 7);
newBrigade.getBattalions().add(battalionDto1);
newBrigade.getBattalions().add(battalionDto2);
newBrigade.getBattalions().add(battalionDto3);
newBrigade.getBattalions().add(battalionDto4);
newBrigade.getBattalions().add(battalionDto5);
newBrigade.getBattalions().add(battalionDto6);
newBrigade.getBattalions().add(battalionDto7);
final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1()));
newBrigade.setRegionId(sector.getPosition().getRegion().getId());
newBrigade.setX(sector.getPosition().getX());
newBrigade.setY(sector.getPosition().getY());
return newBrigade;
}
/**
* Create new battalion.
*
* @param armyTypeID the battalion type.
* @param order the order ID.
* @return the new battalio dto.
*/
private BattalionDTO getBattalionByArmyTypeId(final String armyTypeID, final int order) {
final ArmyTypeDTO armyTypeDto = getArmyTypeById(Integer.parseInt(armyTypeID));
final BattalionDTO newBattalion = new BattalionDTO();
newBattalion.setEmpireArmyType(armyTypeDto);
int headcount = 800;
if (newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_MOROCCO
|| newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_OTTOMAN
|| newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_EGYPT) {
headcount = 1000;
}
newBattalion.setExperience(1);
newBattalion.setHeadcount(headcount);
newBattalion.setId(-1);
newBattalion.setOrder(order);
return newBattalion;
}
/**
* Creates new ship from the order.
*
* @param order the order describing the new ship.
* @return the new ship dto.
*/
public ShipDTO createShipFromOrder(final OrderDTO order) {
final ShipDTO newShip = new ShipDTO();
newShip.setNationId(getNationId());
newShip.setName(order.getParameter3());
newShip.setId(Integer.parseInt(order.getTemp1()));
final ShipTypeDTO shipTypeDTO = getShipTypeId(Integer.parseInt(order.getParameter2()));
newShip.setTypeId(shipTypeDTO.getIndPt());
newShip.setType(shipTypeDTO);
final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1()));
newShip.setRegionId(sector.getPosition().getRegion().getId());
newShip.setX(sector.getPosition().getX());
newShip.setY(sector.getPosition().getY());
return newShip;
}
/**
* @param shipTypeID the type of the ship.
* @return the new ship type dto.
*/
private ShipTypeDTO getShipTypeId(final int shipTypeID) {
final ShipTypeDTO shipTypeDto = new ShipTypeDTO();
if (shipTypes.containsKey(shipTypeID)) {
return shipTypes.get(shipTypeID);
}
return shipTypeDto;
}
public ArmyTypeDTO getArmyTypeById(final int armyTypeId) {
final ArmyTypeDTO armyTypeDto = new ArmyTypeDTO();
if (armyTypes.containsKey(armyTypeId)) {
return armyTypes.get(armyTypeId);
}
return armyTypeDto;
}
}
| EaW1805/www | src/main/java/com/eaw1805/www/controllers/remote/hotspot/OrderApplyChangesProcessor.java | 7,072 | // Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI | line_comment | el | package com.eaw1805.www.controllers.remote.hotspot;
import com.eaw1805.data.constants.AdminCommandPoints;
import com.eaw1805.data.constants.ArmyConstants;
import com.eaw1805.data.constants.GoodConstants;
import com.eaw1805.data.constants.NationConstants;
import com.eaw1805.data.constants.OrderConstants;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.dto.collections.DataCollection;
import com.eaw1805.data.dto.common.SectorDTO;
import com.eaw1805.data.dto.converters.SectorConverter;
import com.eaw1805.data.dto.web.ClientOrderDTO;
import com.eaw1805.data.dto.web.OrderCostDTO;
import com.eaw1805.data.dto.web.OrderDTO;
import com.eaw1805.data.dto.web.army.ArmyTypeDTO;
import com.eaw1805.data.dto.web.army.BattalionDTO;
import com.eaw1805.data.dto.web.army.BrigadeDTO;
import com.eaw1805.data.dto.web.economy.BaggageTrainDTO;
import com.eaw1805.data.dto.web.fleet.ShipDTO;
import com.eaw1805.data.dto.web.fleet.ShipTypeDTO;
import com.eaw1805.data.model.Nation;
import com.eaw1805.data.model.army.Brigade;
import com.eaw1805.data.model.map.Sector;
import com.eaw1805.www.controllers.remote.EmpireRpcServiceImpl;
import com.eaw1805.www.shared.stores.GameStore;
import com.eaw1805.www.shared.stores.util.calculators.CostCalculators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@SuppressWarnings("restriction")
public class OrderApplyChangesProcessor
extends AbstractChangesProcessor
implements OrderConstants, GoodConstants {
/**
* The orders and the corresponding costs.
*/
private transient final Map<Integer, List<ClientOrderDTO>> clientOrders;
private transient List<OrderDTO> orders = new ArrayList<OrderDTO>();
private transient final Map<Integer, ArmyTypeDTO> armyTypes = new HashMap<Integer, ArmyTypeDTO>();
private transient final Map<Integer, ShipTypeDTO> shipTypes = new HashMap<Integer, ShipTypeDTO>();
private transient final EmpireRpcServiceImpl service;
private transient final DataCollection prodAndNatSites;
/**
* Default constructor.
*
* @param thisGame the game of the order.
* @param thisNation the owner of the order.
* @param thisTurn the turn of the order.
*/
public OrderApplyChangesProcessor(final int scenarioId,
final int thisGame,
final int thisNation,
final int thisTurn,
final EmpireRpcServiceImpl empireRpcServiceImpl) {
super(scenarioId, thisGame, thisNation, thisTurn);
service = empireRpcServiceImpl;
for (ArmyTypeDTO armyTypeDTO : service.getArmyTypes(getScenarioId(), getNationId())) {
armyTypes.put(armyTypeDTO.getIntId(), armyTypeDTO);
}
for (ShipTypeDTO shipTypeDTO : service.getShipTypes(getScenarioId(), getNationId())) {
shipTypes.put(shipTypeDTO.getIntId(), shipTypeDTO);
}
prodAndNatSites = service.getNaturalResAndProdSites(getScenarioId());
clientOrders = new TreeMap<Integer, List<ClientOrderDTO>>();
}
@SuppressWarnings({"unchecked"})
public void addData(final Collection<?> dbData, final Collection<?> chOrders) {
orders = (List<OrderDTO>) chOrders;
}
public void addData(final Map<?, ?> dbData, final Map<?, ?> chData) {
// do nothing
}
public Map<Integer, List<ClientOrderDTO>> processChanges() {
for (final OrderDTO order : orders) {
OrderCostDTO orderCost = new OrderCostDTO();
int regionId = 1;
String name = "";
String comment = "";
final int[] ids = new int[9];
for (int i = 0; i < 9; i++) {
ids[i] = 0;
}
switch (order.getType()) {
case ORDER_B_BATT: {
// Double costs custom game option
final int doubleCosts = (GameStore.getInstance().isDoubleCostsArmy()) ? 2 : 1;
final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1()));
final int sphere = getSphere(sector, service.nationManager.getByID(getNationId()));
final int multiplier = doubleCosts * sphere;
final BrigadeDTO brig = createBrigadeFromOrder(order);
orderCost = CostCalculators.getBrigadeCost(brig, multiplier, sphere);
name = order.getParameter9();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = brig.getBrigadeId();
regionId = brig.getRegionId();
break;
}
case ORDER_ADDTO_BRIGADE:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
break;
case ORDER_ADDTO_ARMY:
case ORDER_ADDTO_CORP:
case ORDER_ADDTO_FLT:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_HIRE_COM:
orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_ARMY_COM:
name = order.getTemp1() + "-" + order.getParameter2();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_CORP_COM:
name = order.getTemp1() + "-" + order.getParameter2();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_LEAVE_COM:
ids[0] = Integer.parseInt(order.getParameter2());
ids[1] = 0;
break;
case ORDER_DISS_COM:
orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_B_ARMY:
case ORDER_B_FLT:
orderCost = CostCalculators.getFormFederationCost(order.getType());
name = order.getParameter2();
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_B_CORP:
orderCost = CostCalculators.getFormFederationCost(order.getType());
name = order.getParameter3();
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_ADD_BATT: {
final Brigade brigade = service.getBrigadeManager().getByID(Integer.parseInt(order.getParameter1()));
final Sector sector = service.getSectorManager().getByPosition(brigade.getPosition());
final int multiplier = getSphere(sector, service.getNationManager().getByID(getNationId()));
orderCost = CostCalculators.getArmyTypeCost(getArmyTypeById(Integer.parseInt(order.getParameter2())), multiplier);
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
regionId = Integer.parseInt(order.getTemp1());
break;
}
case ORDER_B_BTRAIN:
orderCost = CostCalculators.getBaggageTrainCost();
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = Integer.parseInt(order.getTemp1());
break;
case ORDER_R_BTRAIN:
orderCost = CostCalculators.getBaggageTrainRepairCost(100 - Integer.parseInt(order.getParameter3()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = Integer.parseInt(order.getTemp1());
break;
case ORDER_B_PRODS:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
SectorDTO sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
regionId = sectorDTO.getRegionId();
orderCost = CostCalculators.getProductionSiteCost(regionId, prodAndNatSites.getProdSite(Integer.parseInt(order.getParameter2())), false);
break;
case ORDER_D_PRODS:
ids[0] = Integer.parseInt(order.getParameter1());
sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
regionId = sectorDTO.getRegionId();
orderCost = CostCalculators.getProductionSiteCost(regionId, null, true);
break;
case ORDER_B_SHIP:
ShipDTO ship = createShipFromOrder(order);
orderCost = CostCalculators.getShipCost(ship);
name = order.getParameter3();
ids[0] = Integer.parseInt(order.getTemp1());
ids[1] = Integer.parseInt(order.getParameter1());
ids[2] = Integer.parseInt(order.getParameter2());
regionId = ship.getRegionId();
break;
case ORDER_R_FLT:
final String[] costValues = order.getTemp2().split("!");
for (String costValue : costValues) {
final String[] keyVal = costValue.split(":");
orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1]));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
comment = order.getTemp2();
regionId = ids[2];
break;
case ORDER_R_SHP:
ship = service.getShipById(getScenarioId(), Integer.parseInt(order.getParameter1()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
orderCost = CostCalculators.getShipRepairCost(ship.getCondition(), ship);
regionId = Integer.parseInt(order.getTemp1());
break;
case ORDER_D_ARMY:
case ORDER_D_BATT:
case ORDER_D_BRIG:
case ORDER_D_CORP:
case ORDER_D_FLT:
name = order.getTemp1();
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_FM_ARMY:
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_FM_BRIG:
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_FM_CORP:
ids[0] = Integer.parseInt(order.getParameter1());
break;
case ORDER_HOVER_SEC:
case ORDER_HOVER_SHIP:
ids[0] = Integer.parseInt(order.getParameter1());
orderCost = CostCalculators.getHandOverCost(order.getType(), Integer.parseInt(order.getTemp1()));
break;
case ORDER_INC_EXP:
case ORDER_INC_EXP_CORPS:
case ORDER_INC_EXP_ARMY:
if (order.getTemp2() != null && !order.getTemp2().isEmpty()) {
final String[] expCostValues = order.getTemp2().split("!");
for (String costValue : expCostValues) {
final String[] keyVal = costValue.split(":");
orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1]));
}
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
regionId = ids[2];
break;
case ORDER_INC_HEADCNT:
case ORDER_INC_HEADCNT_CORPS:
case ORDER_INC_HEADCNT_ARMY:
if (order.getTemp2() != null && !order.getTemp2().isEmpty()) {
final String[] upHeadCostValues = order.getTemp2().split("!");
for (String costValue : upHeadCostValues) {
final String[] keyVal = costValue.split(":");
orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1]));
}
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
regionId = ids[2];
break;
case ORDER_INC_POP: {
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = ids[1];
sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
orderCost = CostCalculators.getIncDecPopCost(sectorDTO, true);
break;
}
case ORDER_DEC_POP: {
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
regionId = ids[1];
final SectorDTO sector = SectorConverter.convert(service.getSectorManager().getByID(ids[0]));
orderCost = CostCalculators.getIncDecPopCost(sector, false);
break;
}
case ORDER_M_UNIT:
orderCost = CostCalculators.getMovementCost(Integer.parseInt(order.getParameter5()));
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter5());
break;
case ORDER_MRG_BATT:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
break;
case ORDER_TAXATION:
orderCost = CostCalculators.getTaxationCost(Integer.parseInt(order.getTemp3()),
Integer.parseInt(order.getTemp4()),
Integer.parseInt(order.getTemp1()),
Integer.parseInt(order.getTemp2()));
break;
case ORDER_EXCHF:
case ORDER_EXCHS:
orderCost.setNumericCost(Integer.parseInt(order.getParameter5()), Integer.parseInt(order.getParameter6()));
orderCost.setNumericCost(1, Integer.parseInt(order.getTemp1()));
if (Integer.parseInt(order.getParameter1()) == ArmyConstants.TRADECITY
|| Integer.parseInt(order.getParameter3()) == ArmyConstants.TRADECITY) {
orderCost.setNumericCost(GOOD_AP, AdminCommandPoints.P_ADM.get(order.getType()));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
ids[4] = Integer.parseInt(order.getParameter5());
ids[5] = Integer.parseInt(order.getParameter6());
regionId = Integer.parseInt(order.getParameter9());
break;
case ORDER_LOAD_TROOPSF:
case ORDER_LOAD_TROOPSS:
if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost
orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3()));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
ids[4] = Integer.parseInt(order.getParameter5());
ids[5] = Integer.parseInt(order.getParameter6());
break;
case ORDER_UNLOAD_TROOPSF:
case ORDER_UNLOAD_TROOPSS:
if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost
orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3()));
}
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
ids[3] = Integer.parseInt(order.getParameter4());
ids[4] = Integer.parseInt(order.getParameter5());
ids[5] = Integer.parseInt(order.getTemp1());
ids[6] = Integer.parseInt(order.getTemp2());
break;
case ORDER_REN_SHIP:
case ORDER_REN_BRIG:
case ORDER_REN_COMM:
case ORDER_REN_ARMY:
case ORDER_REN_CORP:
case ORDER_REN_FLT:
case ORDER_REN_BARRACK:
case ORDER_REN_BTRAIN:
ids[0] = Integer.parseInt(order.getParameter1());
name = order.getParameter2();
break;
case ORDER_SCUTTLE_BTRAIN:
ids[0] = Integer.parseInt(order.getParameter1());
final BaggageTrainDTO scuttledTrain = service.getBaggageTrainById(getScenarioId(), ids[0]);
if (scuttledTrain != null) {
orderCost = CostCalculators.getScuttleBaggageTrainCost(scuttledTrain.getCondition());
}
break;
case ORDER_SCUTTLE_SHIP:
ids[0] = Integer.parseInt(order.getParameter1());
final ShipDTO scuttledShip = service.getShipById(getScenarioId(), ids[0]);
if (scuttledShip != null) {
orderCost = CostCalculators.getScuttleShipCost(scuttledShip);
}
break;
case ORDER_POLITICS:
ids[0] = Integer.parseInt(order.getParameter1());
ids[1] = Integer.parseInt(order.getParameter2());
ids[2] = Integer.parseInt(order.getParameter3());
break;
default:
// do nothing
}
addNewOrder(order.getType(), orderCost, regionId, name, ids, order.getPosition(), comment);
}
return clientOrders;
}
/**
* Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation.
*
* @param sector the sector to examine.
* @param receiver the receiving nation.
* @return 1 if home region, 2 if in sphere of influence, 3 if outside.
*/
protected final int getSphere(final Sector sector, final Nation receiver) {
final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0);
int sphere = 1;
// Τα<SUF>
if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) {
return 1;
}
// Check if this is not home region
if (thisNationCodeLower != thisSectorCodeLower) {
sphere = 2;
// Check if this is outside sphere of influence
if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) {
sphere = 3;
}
}
return sphere;
}
// /**
// * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation.
// *
// * @param sector the sector to examine.
// * @param receiver the receiving nation.
// * @return 1 if home region, 2 if in sphere of influence, 3 if outside.
// */
// protected int getSphere(final Sector sector, final Nation receiver) {
// final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
// final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0);
// int sphere = 1;
//
// if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) {
// return sphere;
// }
//
// // Check if this is not home region
// if (thisNationCodeLower != thisSectorCodeLower) {
// sphere = 2;
//
// final char thisNationCode = String.valueOf(receiver.getCode()).toLowerCase().charAt(0);
//
// // Check if this is outside sphere of influence
// if (sector.getNation().getSphereOfInfluence().indexOf(thisNationCode) < 0) {
// sphere = 3;
// }
// }
//
// return sphere;
// }
/**
* Method that adds a new order to our order Map
*
* @param typeId The type of the order we want to add.
* @param orderCost The calculated cost of the order.
* @param regionId the region of the warehouse.
* @param name the name of the order.
* @param identifiers the id of the order.
* @param position The position of the order.
* @param comment the comment of the order.
* @return 0 if there are no available funds 1 if there are
*/
private int addNewOrder(final int typeId, final OrderCostDTO orderCost,
final int regionId,
final String name,
final int[] identifiers,
final int position,
final String comment) {
int priority = position;
if (clientOrders.get(typeId) == null) {
clientOrders.put(typeId, new ArrayList<ClientOrderDTO>());
} else {
priority = clientOrders.get(typeId).size();
}
if (position == 0) {
priority = clientOrders.get(typeId).size();
}
final ClientOrderDTO order = new ClientOrderDTO();
order.setOrderTypeId(typeId);
order.setPriority(priority);
order.setCosts(orderCost);
order.setName(name);
order.setComment(comment);
for (int index = 0; index < identifiers.length; index++) {
order.setIdentifier(index, identifiers[index]);
}
order.setRegionId(regionId);
clientOrders.get(typeId).add(order);
return 1;
}
/**
* Creates new brigade from the order.
*
* @param order the order to use.
* @return the new brigade object.
*/
private BrigadeDTO createBrigadeFromOrder(final OrderDTO order) {
final BrigadeDTO newBrigade = new BrigadeDTO();
newBrigade.setNationId(getNationId());
newBrigade.setName(order.getParameter9());
try {
newBrigade.setBrigadeId(Integer.parseInt(order.getTemp1()));
} catch (Exception ex) {
if (clientOrders.get(ORDER_ADD_BATT) == null) {
newBrigade.setBrigadeId(0);
} else {
newBrigade.setBrigadeId(clientOrders.get(ORDER_ADD_BATT).size());
}
}
newBrigade.setBattalions(new ArrayList<BattalionDTO>());
final BattalionDTO battalionDto1 = getBattalionByArmyTypeId(order.getParameter2(), 1);
final BattalionDTO battalionDto2 = getBattalionByArmyTypeId(order.getParameter3(), 2);
final BattalionDTO battalionDto3 = getBattalionByArmyTypeId(order.getParameter4(), 3);
final BattalionDTO battalionDto4 = getBattalionByArmyTypeId(order.getParameter5(), 4);
final BattalionDTO battalionDto5 = getBattalionByArmyTypeId(order.getParameter6(), 5);
final BattalionDTO battalionDto6 = getBattalionByArmyTypeId(order.getParameter7(), 6);
final BattalionDTO battalionDto7 = getBattalionByArmyTypeId(order.getParameter8(), 7);
newBrigade.getBattalions().add(battalionDto1);
newBrigade.getBattalions().add(battalionDto2);
newBrigade.getBattalions().add(battalionDto3);
newBrigade.getBattalions().add(battalionDto4);
newBrigade.getBattalions().add(battalionDto5);
newBrigade.getBattalions().add(battalionDto6);
newBrigade.getBattalions().add(battalionDto7);
final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1()));
newBrigade.setRegionId(sector.getPosition().getRegion().getId());
newBrigade.setX(sector.getPosition().getX());
newBrigade.setY(sector.getPosition().getY());
return newBrigade;
}
/**
* Create new battalion.
*
* @param armyTypeID the battalion type.
* @param order the order ID.
* @return the new battalio dto.
*/
private BattalionDTO getBattalionByArmyTypeId(final String armyTypeID, final int order) {
final ArmyTypeDTO armyTypeDto = getArmyTypeById(Integer.parseInt(armyTypeID));
final BattalionDTO newBattalion = new BattalionDTO();
newBattalion.setEmpireArmyType(armyTypeDto);
int headcount = 800;
if (newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_MOROCCO
|| newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_OTTOMAN
|| newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_EGYPT) {
headcount = 1000;
}
newBattalion.setExperience(1);
newBattalion.setHeadcount(headcount);
newBattalion.setId(-1);
newBattalion.setOrder(order);
return newBattalion;
}
/**
* Creates new ship from the order.
*
* @param order the order describing the new ship.
* @return the new ship dto.
*/
public ShipDTO createShipFromOrder(final OrderDTO order) {
final ShipDTO newShip = new ShipDTO();
newShip.setNationId(getNationId());
newShip.setName(order.getParameter3());
newShip.setId(Integer.parseInt(order.getTemp1()));
final ShipTypeDTO shipTypeDTO = getShipTypeId(Integer.parseInt(order.getParameter2()));
newShip.setTypeId(shipTypeDTO.getIndPt());
newShip.setType(shipTypeDTO);
final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1()));
newShip.setRegionId(sector.getPosition().getRegion().getId());
newShip.setX(sector.getPosition().getX());
newShip.setY(sector.getPosition().getY());
return newShip;
}
/**
* @param shipTypeID the type of the ship.
* @return the new ship type dto.
*/
private ShipTypeDTO getShipTypeId(final int shipTypeID) {
final ShipTypeDTO shipTypeDto = new ShipTypeDTO();
if (shipTypes.containsKey(shipTypeID)) {
return shipTypes.get(shipTypeID);
}
return shipTypeDto;
}
public ArmyTypeDTO getArmyTypeById(final int armyTypeId) {
final ArmyTypeDTO armyTypeDto = new ArmyTypeDTO();
if (armyTypes.containsKey(armyTypeId)) {
return armyTypes.get(armyTypeId);
}
return armyTypeDto;
}
}
|
865_5 | package com.example.eshop3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
//κάνω implements View.OnclickListener ένας άλλος τρόπος αντί να κάνω setOncliCkListener(new View.OnclickListner) σε εάν κουμπί
public class menu_proionta extends Fragment implements View.OnClickListener{
//δημιουργώ 3 μεταβλητές τύπου Button
Button B_insertPr, B_deletePr, B_editPr;
public menu_proionta() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//δημιορυγώ το view κάνοντας inflate το αντίστοιχο fragment
View view = inflater.inflate(R.layout.fragment_menu_proionta, container, false);
//κάνω αντιστόιχηση τις μεταβλητές μου με τα ανάλογα button
//χρησιμοποιόντας την findViewById
//και ορίζω σε κάθε κουμπί την ιδιότητα setOnClickListener(this)
///δηλαδή τι θα γίνεται κάθε φορα που κάποιος πατάει κάποιο κουμπί
B_insertPr = view.findViewById(R.id.insertButtonPr);
B_insertPr.setOnClickListener(this);
B_deletePr =view.findViewById(R.id.deleteButtonPr);
B_deletePr.setOnClickListener(this);
B_editPr =view.findViewById(R.id.editButtonPr);
B_editPr.setOnClickListener(this);
return view;
}
//η onClick παίρνει σα παράμετρο τη View που έχω δημιουργήσει και ανάλογα τα id των κουμπιών
// που έχει η view πάει στο ανόλογο case. Μέσα στο case ανάλογα ποιο κουμπί έχει πατηθεί
//ξεκινάει μια συναλλαγή και δημιουργεί το αντίστοιχο fragment και με addToBackStack μπορεί
//κανείς να πηγαίνει πίσω και φυσικά στο τέλος commit.
public void onClick(View v) {
switch (v.getId()) {
case R.id.insertButtonPr:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new InsertProion()).addToBackStack(null).commit();
break;
case R.id.deleteButtonPr:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new DeleteProionta()).addToBackStack(null).commit();
break;
case R.id.editButtonPr:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new UpdateProionta()).addToBackStack(null).commit();
break;
}
}}
| EfthimisKele/E_Shop | app/src/main/java/com/example/eshop3/menu_proionta.java | 928 | //χρησιμοποιόντας την findViewById | line_comment | el | package com.example.eshop3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
//κάνω implements View.OnclickListener ένας άλλος τρόπος αντί να κάνω setOncliCkListener(new View.OnclickListner) σε εάν κουμπί
public class menu_proionta extends Fragment implements View.OnClickListener{
//δημιουργώ 3 μεταβλητές τύπου Button
Button B_insertPr, B_deletePr, B_editPr;
public menu_proionta() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//δημιορυγώ το view κάνοντας inflate το αντίστοιχο fragment
View view = inflater.inflate(R.layout.fragment_menu_proionta, container, false);
//κάνω αντιστόιχηση τις μεταβλητές μου με τα ανάλογα button
//χρ<SUF>
//και ορίζω σε κάθε κουμπί την ιδιότητα setOnClickListener(this)
///δηλαδή τι θα γίνεται κάθε φορα που κάποιος πατάει κάποιο κουμπί
B_insertPr = view.findViewById(R.id.insertButtonPr);
B_insertPr.setOnClickListener(this);
B_deletePr =view.findViewById(R.id.deleteButtonPr);
B_deletePr.setOnClickListener(this);
B_editPr =view.findViewById(R.id.editButtonPr);
B_editPr.setOnClickListener(this);
return view;
}
//η onClick παίρνει σα παράμετρο τη View που έχω δημιουργήσει και ανάλογα τα id των κουμπιών
// που έχει η view πάει στο ανόλογο case. Μέσα στο case ανάλογα ποιο κουμπί έχει πατηθεί
//ξεκινάει μια συναλλαγή και δημιουργεί το αντίστοιχο fragment και με addToBackStack μπορεί
//κανείς να πηγαίνει πίσω και φυσικά στο τέλος commit.
public void onClick(View v) {
switch (v.getId()) {
case R.id.insertButtonPr:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new InsertProion()).addToBackStack(null).commit();
break;
case R.id.deleteButtonPr:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new DeleteProionta()).addToBackStack(null).commit();
break;
case R.id.editButtonPr:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new UpdateProionta()).addToBackStack(null).commit();
break;
}
}}
|
16735_0 | package gr.dit.hua.divorce.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
DataSource dataSource;
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager() throws Exception {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
jdbcUserDetailsManager.setDataSource(dataSource);
return jdbcUserDetailsManager;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.requestMatchers("/").permitAll()
.requestMatchers("/register").permitAll()
.requestMatchers("/contact").permitAll()
.requestMatchers("/more_information").permitAll()
.requestMatchers("/help").permitAll()
.requestMatchers("/member/**").hasRole("ADMIN")
.requestMatchers("/my_divorces" ).hasAnyRole("LAWYER", "SPOUSE", "NOTARY")
.requestMatchers("/divorce/deleteDivorce").hasRole("LAWYER")
.requestMatchers("/divorce/getDivorces").hasRole("ADMIN")
.requestMatchers("/divorce/saveDivorce").hasRole("LAWYER")
.requestMatchers("/divorce/approveDivorce").hasRole("NOTARY")
.requestMatchers("/cdp").hasRole("LAWYER")
.requestMatchers("/member_names").hasRole("LAWYER")
.requestMatchers("/document_details").hasRole("LAWYER")
.requestMatchers("/confirmation_of_divorce").hasAnyRole("SPOUSE", "LAWYER")
.requestMatchers("/divorce_cancellation").hasRole("LAWYER")
.requestMatchers("/account_details").hasRole("NOTARY")
.requestMatchers("/notarialActionId/**").hasRole("NOTARY")
.requestMatchers("/cu").hasRole("ADMIN")
//μόλις φτιαχτεί να το αλλάξω
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").defaultSuccessUrl("/my_divorces", true).permitAll()
.and().logout();
http.headers().frameOptions().sameOrigin();
return http.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) ->
web.ignoring().requestMatchers(
"/css/**", "/js/**", "/images/**");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
| EliteOneTube/divorce_app_dev_ops | src/main/java/gr/dit/hua/divorce/config/SecurityConfig.java | 759 | //μόλις φτιαχτεί να το αλλάξω
| line_comment | el | package gr.dit.hua.divorce.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
DataSource dataSource;
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager() throws Exception {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
jdbcUserDetailsManager.setDataSource(dataSource);
return jdbcUserDetailsManager;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.requestMatchers("/").permitAll()
.requestMatchers("/register").permitAll()
.requestMatchers("/contact").permitAll()
.requestMatchers("/more_information").permitAll()
.requestMatchers("/help").permitAll()
.requestMatchers("/member/**").hasRole("ADMIN")
.requestMatchers("/my_divorces" ).hasAnyRole("LAWYER", "SPOUSE", "NOTARY")
.requestMatchers("/divorce/deleteDivorce").hasRole("LAWYER")
.requestMatchers("/divorce/getDivorces").hasRole("ADMIN")
.requestMatchers("/divorce/saveDivorce").hasRole("LAWYER")
.requestMatchers("/divorce/approveDivorce").hasRole("NOTARY")
.requestMatchers("/cdp").hasRole("LAWYER")
.requestMatchers("/member_names").hasRole("LAWYER")
.requestMatchers("/document_details").hasRole("LAWYER")
.requestMatchers("/confirmation_of_divorce").hasAnyRole("SPOUSE", "LAWYER")
.requestMatchers("/divorce_cancellation").hasRole("LAWYER")
.requestMatchers("/account_details").hasRole("NOTARY")
.requestMatchers("/notarialActionId/**").hasRole("NOTARY")
.requestMatchers("/cu").hasRole("ADMIN")
//μό<SUF>
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").defaultSuccessUrl("/my_divorces", true).permitAll()
.and().logout();
http.headers().frameOptions().sameOrigin();
return http.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) ->
web.ignoring().requestMatchers(
"/css/**", "/js/**", "/images/**");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
6544_1 |
import java.math.BigDecimal;
/**
* @author EvanCoh
* se: ConvertMoneyToString.getVerbal(412444.87)
*/
public class ConvertMoneyToString {
private ConvertMoneyToString() {
}
private static String[] m = {"", "ΕΝΑ ", "ΔΥΟ ", "ΤΡΙΑ ",
"ΤΕΣΣΕΡΑ ", "ΠΕΝΤΕ ", "ΕΞΙ ",
"ΕΠΤΑ ", "ΟΚΤΩ ", "ΕΝΝΕΑ "};
private static String[] mF = {"", "ΜΙΑ ", "", "ΤΡΕΙΣ ",
"ΤΕΣΣΕΡΙΣ "};
private static String[] d1 = { //Διαφοροποίησεις των 11,12 ...
"ΔΕΚΑ ", "ΕΝΤΕΚΑ ",
"ΔΩΔΕΚΑ "};
private static String[] d = {"", "ΔΕΚΑ", "ΕΙΚΟΣΙ ",
"ΤΡΙΑΝΤΑ ", "ΣΑΡΑΝΤΑ ",
"ΠΕΝΗΝΤΑ ", "ΕΞΗΝΤΑ ",
"ΕΒΔΟΜΗΝΤΑ ", "ΟΓΔΟΝΤΑ ",
"ΕΝΕΝΗΝΤΑ "};
private static String[] e = {"", "ΕΚΑΤΟ", "ΔΙΑΚΟΣΙ",
"ΤΡΙΑΚΟΣΙ", "ΤΕΤΡΑΚΟΣΙ",
"ΠΕΝΤΑΚΟΣΙ", "ΕΞΑΚΟΣΙ",
"ΕΠΤΑΚΟΣΙ", "ΟΚΤΑΚΟΣΙ",
"ΕΝΝΙΑΚΟΣΙ"};
private static String[] idx = {"ΛΕΠΤΑ", "ΕΥΡΩ ", "ΧΙΛΙΑΔΕΣ ",
"ΕΚΑΤΟΜΜΥΡΙ", "ΔΙΣ", "ΤΡΙΣ",
"ΤΕΤΡΑΚΙΣ ", "ΠΕΝΤΑΚΙΣ "};
public static Integer Round(Double value) {
Double doubl = Round(value, 0);
Long lng = Math.round(doubl);
return lng.intValue();
}
public static Double Round(Double value, Integer precision) {
return new BigDecimal(String.valueOf(value)).setScale(precision, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static String GetVerbal(Double money) {
return GetVerbal(money, true);
}
public static String GetVerbal(Double money, Boolean showZero) {
return GetVerbal(money, showZero, true);
}
public static String GetVerbal(Double money, Boolean showZero,
Boolean showCurrency) {
String str;
Short index = 0;
Boolean isZero = true;
Boolean isNegative = false;
str = "";
if (money < 0) {
money = -money;
isNegative = true;
}
if (money != Math.floor(money)) {
Integer value = Round(100 * money - 100 * Math.floor(money));
if (value >= 100) {
value -= 100;
money += 1.0;
}
//money = (Long)money;
Long moneyLong = money.longValue();
if (value > 0) {
isZero = false;
if (moneyLong >= 1 && value > 0) {
str += "ΚΑΙ ";
}
str += GetValue(value, index, showCurrency);
}
}
while (money >= 1) {
isZero = false;
Double kati = money % 1000;
Integer value = kati.intValue();
money /= 1000;
Integer indexValue = index.intValue();
indexValue += 1;
index = indexValue.shortValue();
str = GetValue(value, index, showCurrency) + str;
//money = (Long)money;
Long moneyLong = money.longValue();
money = moneyLong.doubleValue();
}
if (isZero) {
if (showZero) {
str = "ΜΗΔΕΝ ";
if (showCurrency) {
str += idx[1];
}
}
} else {
if (isNegative) {
str = "MEION " + str;
}
}
return str;
}
public static String GetValue(Integer money, Short index,
Boolean showCurrency) {
if (index == 2 && money == 1) {
return "ΧΙΛΙΑ ";
}
String str = "";
Integer dekmon = money % 100;
Integer monades = dekmon % 10;
Integer ekatontades = (Integer) (money / 100);
Integer dekades = (Integer) (dekmon / 10);
//EKATONTADES
if (ekatontades == 1) {
if (dekmon == 0) {
str = e[1] + " ";
} else {
str = e[1] + "Ν ";
}
} else if (ekatontades > 1) {
if (index == 2) {
str = e[ekatontades] + "ΕΣ ";
} else {
str = e[ekatontades] + "Α ";
}
}
//DEKADES
switch (dekmon) {
case 10:
str += d1[monades]; //"ΔΕΚΑ " με κενό στο τέλος
break;
case 11:
str += d1[monades];
monades = 0;
break;
case 12:
str += d1[monades];
monades = 0;
break;
default:
str += d[dekades];
break;
}
//MONADES
if ((index == 2)
&& (monades == 1 || monades == 3 || monades == 4)) {
str += mF[monades];
} else {
if (dekmon < 10 || dekmon > 12) {
str += m[monades];
}
}
if (str.length() > 0 || index == 1) {
if (index == 0 && money == 1) {
if (showCurrency) {
str += "ΛΕΠΤΟ";
}
} else {
if (index > 1 || showCurrency) {
str += idx[index];
if (index > 2) {
if (index > 3) {
str += idx[3];
}
if (money > 1) {
str += "Α ";
} else {
str += "Ο ";
}
}
}
}
}
return str;
}
}
| EvanCoh/monetaryAmountToGreek | ConvertMoneyToString.java | 1,860 | //Διαφοροποίησεις των 11,12 ... | line_comment | el |
import java.math.BigDecimal;
/**
* @author EvanCoh
* se: ConvertMoneyToString.getVerbal(412444.87)
*/
public class ConvertMoneyToString {
private ConvertMoneyToString() {
}
private static String[] m = {"", "ΕΝΑ ", "ΔΥΟ ", "ΤΡΙΑ ",
"ΤΕΣΣΕΡΑ ", "ΠΕΝΤΕ ", "ΕΞΙ ",
"ΕΠΤΑ ", "ΟΚΤΩ ", "ΕΝΝΕΑ "};
private static String[] mF = {"", "ΜΙΑ ", "", "ΤΡΕΙΣ ",
"ΤΕΣΣΕΡΙΣ "};
private static String[] d1 = { //Δι<SUF>
"ΔΕΚΑ ", "ΕΝΤΕΚΑ ",
"ΔΩΔΕΚΑ "};
private static String[] d = {"", "ΔΕΚΑ", "ΕΙΚΟΣΙ ",
"ΤΡΙΑΝΤΑ ", "ΣΑΡΑΝΤΑ ",
"ΠΕΝΗΝΤΑ ", "ΕΞΗΝΤΑ ",
"ΕΒΔΟΜΗΝΤΑ ", "ΟΓΔΟΝΤΑ ",
"ΕΝΕΝΗΝΤΑ "};
private static String[] e = {"", "ΕΚΑΤΟ", "ΔΙΑΚΟΣΙ",
"ΤΡΙΑΚΟΣΙ", "ΤΕΤΡΑΚΟΣΙ",
"ΠΕΝΤΑΚΟΣΙ", "ΕΞΑΚΟΣΙ",
"ΕΠΤΑΚΟΣΙ", "ΟΚΤΑΚΟΣΙ",
"ΕΝΝΙΑΚΟΣΙ"};
private static String[] idx = {"ΛΕΠΤΑ", "ΕΥΡΩ ", "ΧΙΛΙΑΔΕΣ ",
"ΕΚΑΤΟΜΜΥΡΙ", "ΔΙΣ", "ΤΡΙΣ",
"ΤΕΤΡΑΚΙΣ ", "ΠΕΝΤΑΚΙΣ "};
public static Integer Round(Double value) {
Double doubl = Round(value, 0);
Long lng = Math.round(doubl);
return lng.intValue();
}
public static Double Round(Double value, Integer precision) {
return new BigDecimal(String.valueOf(value)).setScale(precision, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static String GetVerbal(Double money) {
return GetVerbal(money, true);
}
public static String GetVerbal(Double money, Boolean showZero) {
return GetVerbal(money, showZero, true);
}
public static String GetVerbal(Double money, Boolean showZero,
Boolean showCurrency) {
String str;
Short index = 0;
Boolean isZero = true;
Boolean isNegative = false;
str = "";
if (money < 0) {
money = -money;
isNegative = true;
}
if (money != Math.floor(money)) {
Integer value = Round(100 * money - 100 * Math.floor(money));
if (value >= 100) {
value -= 100;
money += 1.0;
}
//money = (Long)money;
Long moneyLong = money.longValue();
if (value > 0) {
isZero = false;
if (moneyLong >= 1 && value > 0) {
str += "ΚΑΙ ";
}
str += GetValue(value, index, showCurrency);
}
}
while (money >= 1) {
isZero = false;
Double kati = money % 1000;
Integer value = kati.intValue();
money /= 1000;
Integer indexValue = index.intValue();
indexValue += 1;
index = indexValue.shortValue();
str = GetValue(value, index, showCurrency) + str;
//money = (Long)money;
Long moneyLong = money.longValue();
money = moneyLong.doubleValue();
}
if (isZero) {
if (showZero) {
str = "ΜΗΔΕΝ ";
if (showCurrency) {
str += idx[1];
}
}
} else {
if (isNegative) {
str = "MEION " + str;
}
}
return str;
}
public static String GetValue(Integer money, Short index,
Boolean showCurrency) {
if (index == 2 && money == 1) {
return "ΧΙΛΙΑ ";
}
String str = "";
Integer dekmon = money % 100;
Integer monades = dekmon % 10;
Integer ekatontades = (Integer) (money / 100);
Integer dekades = (Integer) (dekmon / 10);
//EKATONTADES
if (ekatontades == 1) {
if (dekmon == 0) {
str = e[1] + " ";
} else {
str = e[1] + "Ν ";
}
} else if (ekatontades > 1) {
if (index == 2) {
str = e[ekatontades] + "ΕΣ ";
} else {
str = e[ekatontades] + "Α ";
}
}
//DEKADES
switch (dekmon) {
case 10:
str += d1[monades]; //"ΔΕΚΑ " με κενό στο τέλος
break;
case 11:
str += d1[monades];
monades = 0;
break;
case 12:
str += d1[monades];
monades = 0;
break;
default:
str += d[dekades];
break;
}
//MONADES
if ((index == 2)
&& (monades == 1 || monades == 3 || monades == 4)) {
str += mF[monades];
} else {
if (dekmon < 10 || dekmon > 12) {
str += m[monades];
}
}
if (str.length() > 0 || index == 1) {
if (index == 0 && money == 1) {
if (showCurrency) {
str += "ΛΕΠΤΟ";
}
} else {
if (index > 1 || showCurrency) {
str += idx[index];
if (index > 2) {
if (index > 3) {
str += idx[3];
}
if (money > 1) {
str += "Α ";
} else {
str += "Ο ";
}
}
}
}
}
return str;
}
}
|
2063_27 | package mvc.com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import mvc.com.bean.CategoryInfo;
import mvc.com.bean.EvaluationlInfo;
import mvc.com.util.DBConnection;
public class EvaluationDao {
public boolean evaluateEmployee(int amika, HttpServletRequest request) {
//retrieve parameters
int total = 0;
double totald = 0.0;
String type = request.getParameter("typeTF");
System.out.println("Type: " + type);
String evaluationDate = request.getParameter("dateTF");
System.out.println("Uformatted date: " + evaluationDate);
Date date = null;
if (evaluationDate!=null){
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(evaluationDate);
} catch (ParseException e1) {
System.out.println("Cannot parse date");
e1.printStackTrace();
}
}
String comments = request.getParameter("commentsTF");
String nextEvaluationDate = request.getParameter("nextEvaluationDateTF");
System.out.println("Uformatted nextEvaluationDate: " + nextEvaluationDate);
Date next_evaluation_date = null;
if (nextEvaluationDate!=null){
try {
next_evaluation_date = new SimpleDateFormat("yyyy-MM-dd").parse(nextEvaluationDate);
} catch (ParseException e1) {
System.out.println("Cannot parse nextEvaluationDate");
e1.printStackTrace();
}
}
totald = Double.parseDouble(request.getParameter("totalTF"));
System.out.println("Total before: " + totald);
total = roundUp(totald);
System.out.println("Total after: " + total);
Connection currentCon = null;
PreparedStatement prepStatement = null;
int rowsUpdated = 0;
try
{
currentCon = DBConnection.getConnection();
String query = "INSERT INTO employee_evaluation (type, date, comments, next_evaluation_date, total_rating, employee_am_ika) VALUES (?, ?, ?, ?, ?, ?)";
//6 values to insert
prepStatement = currentCon.prepareStatement(query);
prepStatement.setString(1, type);
prepStatement.setDate(2, new java.sql.Date(date.getTime()));
prepStatement.setString(3, comments);
prepStatement.setDate(4, new java.sql.Date(next_evaluation_date.getTime()));
prepStatement.setInt(5, total);
prepStatement.setInt(6, amika);
rowsUpdated = prepStatement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Evaluation Inserted!");
return true;
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
private static int roundUp(double d) {
return (d > (int) d) ? (int) d + 1 : (int) d;
}
public boolean ratingPerCategory(HttpServletRequest request) {
//retrieve parameters
String[] titles = request.getParameterValues("title");
String[] ratings = request.getParameterValues("rating");
int[] categoryIds = new int[titles.length];
int[] ratingsInt = new int[ratings.length];
for(int i=0; i<ratingsInt.length; i++){
ratingsInt[i] = Integer.parseInt(ratings[i]);
}
for (int i = 0; i < titles.length; i++) {
categoryIds[i] = i + 1;
}
// for (int i = 0; i < titles.length; i++) {
// if(titles[i].trim().equalsIgnoreCase("Διαθεσιμότητα")){
// categoryIds[i] = 1;
// }
// else if(titles[i].trim().equalsIgnoreCase("Ανεξαρτησία")){
// categoryIds[i] = 2;
// }
// else if(titles[i].trim().equalsIgnoreCase("Πρωτοβουλία")){
// categoryIds[i] = 3;
// }
// else if(titles[i].trim().equalsIgnoreCase("Γνώση Εργασίας")){
// categoryIds[i] = 4;
// }
// else if(titles[i].trim().equalsIgnoreCase("Κρίση")){
// categoryIds[i] = 5;
// }
// else if(titles[i].trim().equalsIgnoreCase("Παραγωγικότητα")){
// categoryIds[i] = 6;
// }
// else if(titles[i].trim().equalsIgnoreCase("Ποιότητα")){
// categoryIds[i] = 7;
// }
// else if(titles[i].trim().equalsIgnoreCase("Αξιοπιστία")){
// categoryIds[i] = 8;
// }
// else if(titles[i].trim().equalsIgnoreCase("Εργασιακές Σχέσεις")){
// categoryIds[i] = 9;
// }
// else if(titles[i].trim().equalsIgnoreCase("Δημιουργικότητα")){
// categoryIds[i] = 10;
// }
// else if(titles[i].trim().equalsIgnoreCase("Διαχείριση Στόχων")){
// categoryIds[i] = 11;
// }
// else if(titles[i].trim().equalsIgnoreCase("Ανάληψη πολύπλοκων στόχων")){
// categoryIds[i] = 12;
// }
Connection currentCon = null;
PreparedStatement prepStatement = null;
ResultSet resultSet = null;
int[] rowsUpdated = new int[0];
int id = -1;
try
{
currentCon = DBConnection.getConnection();
String last_insert_query = "SELECT max(id) FROM employee_evaluation ";
prepStatement = currentCon.prepareStatement(last_insert_query);
resultSet = prepStatement.executeQuery(last_insert_query);
while (resultSet.next()) {
id = resultSet.getInt(1);
System.out.println("ID = " + id);
}
String insert_query = "INSERT INTO evaluation_has_category (evaluation_id, category_id, rating) VALUES (?, ?, ?)";
prepStatement = currentCon.prepareStatement(insert_query);
//3 values to insert
for (int j = 0; j < ratingsInt.length; j++) {
System.out.println("id: " + categoryIds[j] + "title" + titles[j] + ": " + ratings[j]);
prepStatement.setInt(1, id);
prepStatement.setInt(2, categoryIds[j]);
prepStatement.setInt(3, ratingsInt[j]);
prepStatement.addBatch();
}
System.out.println("_____________________________");
rowsUpdated = prepStatement.executeBatch();
if (rowsUpdated.length > 0) {
System.out.println("Evaluation Inserted!");
return true;
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
public List<EvaluationlInfo> myEvaluationsList(int employee_am_ika) throws SQLException {
List<EvaluationlInfo> myEvaluations = new ArrayList<EvaluationlInfo>();
Connection currentCon = null;
Statement statement = null;
ResultSet resultSet = null;
try{
currentCon = DBConnection.getConnection();
statement = currentCon.createStatement();
resultSet = statement.executeQuery("SELECT * FROM trackingdb.employee_evaluation AS e WHERE employee_am_ika='" + employee_am_ika + "' ORDER BY e.id");
while (resultSet.next()) {
EvaluationlInfo myEvaluation = new EvaluationlInfo();
myEvaluation.setId(resultSet.getInt("id"));
myEvaluation.setType(resultSet.getString("type"));
myEvaluation.setDate(resultSet.getDate("date"));
myEvaluation.setComments(resultSet.getString("comments"));
myEvaluation.setNext_evaluation_date(resultSet.getDate("next_evaluation_date"));
myEvaluation.setTotal_rating(resultSet.getInt("total_rating"));
myEvaluation.setEmployee_am_ika(resultSet.getInt("employee_am_ika"));
myEvaluations.add(myEvaluation);
}
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return myEvaluations; //returning the list of completed goals
}
public List<CategoryInfo> ratingsList(int employee_am_ika, int id) throws SQLException {
List<CategoryInfo> ratings = new ArrayList<CategoryInfo>();
Connection currentCon = null;
Statement statement = null;
ResultSet resultSet = null;
try{
currentCon = DBConnection.getConnection();
statement = currentCon.createStatement();
resultSet = statement.executeQuery("SELECT title, rating FROM trackingdb.employee_evaluation AS e" +
" INNER JOIN trackingdb.evaluation_has_category AS h" +
" ON e.id ='"+ id +"' AND h.evaluation_id ='"+ id +"' AND employee_am_ika='" + employee_am_ika + "'" +
" INNER JOIN trackingdb.category AS c ON c.id=h.category_id;");
while (resultSet.next()) {
CategoryInfo categoryPerRating = new CategoryInfo();
categoryPerRating.setCategory_title(resultSet.getString(1));
categoryPerRating.setRating(resultSet.getInt(2));
ratings.add(categoryPerRating);
}
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return ratings; //returning the list of completed goals
}
}
| Evrydiki/TrackingEvaluationBonusSystem | src/mvc/com/dao/EvaluationDao.java | 2,802 | // else if(titles[i].trim().equalsIgnoreCase("Ανάληψη πολύπλοκων στόχων")){
| line_comment | el | package mvc.com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import mvc.com.bean.CategoryInfo;
import mvc.com.bean.EvaluationlInfo;
import mvc.com.util.DBConnection;
public class EvaluationDao {
public boolean evaluateEmployee(int amika, HttpServletRequest request) {
//retrieve parameters
int total = 0;
double totald = 0.0;
String type = request.getParameter("typeTF");
System.out.println("Type: " + type);
String evaluationDate = request.getParameter("dateTF");
System.out.println("Uformatted date: " + evaluationDate);
Date date = null;
if (evaluationDate!=null){
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(evaluationDate);
} catch (ParseException e1) {
System.out.println("Cannot parse date");
e1.printStackTrace();
}
}
String comments = request.getParameter("commentsTF");
String nextEvaluationDate = request.getParameter("nextEvaluationDateTF");
System.out.println("Uformatted nextEvaluationDate: " + nextEvaluationDate);
Date next_evaluation_date = null;
if (nextEvaluationDate!=null){
try {
next_evaluation_date = new SimpleDateFormat("yyyy-MM-dd").parse(nextEvaluationDate);
} catch (ParseException e1) {
System.out.println("Cannot parse nextEvaluationDate");
e1.printStackTrace();
}
}
totald = Double.parseDouble(request.getParameter("totalTF"));
System.out.println("Total before: " + totald);
total = roundUp(totald);
System.out.println("Total after: " + total);
Connection currentCon = null;
PreparedStatement prepStatement = null;
int rowsUpdated = 0;
try
{
currentCon = DBConnection.getConnection();
String query = "INSERT INTO employee_evaluation (type, date, comments, next_evaluation_date, total_rating, employee_am_ika) VALUES (?, ?, ?, ?, ?, ?)";
//6 values to insert
prepStatement = currentCon.prepareStatement(query);
prepStatement.setString(1, type);
prepStatement.setDate(2, new java.sql.Date(date.getTime()));
prepStatement.setString(3, comments);
prepStatement.setDate(4, new java.sql.Date(next_evaluation_date.getTime()));
prepStatement.setInt(5, total);
prepStatement.setInt(6, amika);
rowsUpdated = prepStatement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Evaluation Inserted!");
return true;
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
private static int roundUp(double d) {
return (d > (int) d) ? (int) d + 1 : (int) d;
}
public boolean ratingPerCategory(HttpServletRequest request) {
//retrieve parameters
String[] titles = request.getParameterValues("title");
String[] ratings = request.getParameterValues("rating");
int[] categoryIds = new int[titles.length];
int[] ratingsInt = new int[ratings.length];
for(int i=0; i<ratingsInt.length; i++){
ratingsInt[i] = Integer.parseInt(ratings[i]);
}
for (int i = 0; i < titles.length; i++) {
categoryIds[i] = i + 1;
}
// for (int i = 0; i < titles.length; i++) {
// if(titles[i].trim().equalsIgnoreCase("Διαθεσιμότητα")){
// categoryIds[i] = 1;
// }
// else if(titles[i].trim().equalsIgnoreCase("Ανεξαρτησία")){
// categoryIds[i] = 2;
// }
// else if(titles[i].trim().equalsIgnoreCase("Πρωτοβουλία")){
// categoryIds[i] = 3;
// }
// else if(titles[i].trim().equalsIgnoreCase("Γνώση Εργασίας")){
// categoryIds[i] = 4;
// }
// else if(titles[i].trim().equalsIgnoreCase("Κρίση")){
// categoryIds[i] = 5;
// }
// else if(titles[i].trim().equalsIgnoreCase("Παραγωγικότητα")){
// categoryIds[i] = 6;
// }
// else if(titles[i].trim().equalsIgnoreCase("Ποιότητα")){
// categoryIds[i] = 7;
// }
// else if(titles[i].trim().equalsIgnoreCase("Αξιοπιστία")){
// categoryIds[i] = 8;
// }
// else if(titles[i].trim().equalsIgnoreCase("Εργασιακές Σχέσεις")){
// categoryIds[i] = 9;
// }
// else if(titles[i].trim().equalsIgnoreCase("Δημιουργικότητα")){
// categoryIds[i] = 10;
// }
// else if(titles[i].trim().equalsIgnoreCase("Διαχείριση Στόχων")){
// categoryIds[i] = 11;
// }
// el<SUF>
// categoryIds[i] = 12;
// }
Connection currentCon = null;
PreparedStatement prepStatement = null;
ResultSet resultSet = null;
int[] rowsUpdated = new int[0];
int id = -1;
try
{
currentCon = DBConnection.getConnection();
String last_insert_query = "SELECT max(id) FROM employee_evaluation ";
prepStatement = currentCon.prepareStatement(last_insert_query);
resultSet = prepStatement.executeQuery(last_insert_query);
while (resultSet.next()) {
id = resultSet.getInt(1);
System.out.println("ID = " + id);
}
String insert_query = "INSERT INTO evaluation_has_category (evaluation_id, category_id, rating) VALUES (?, ?, ?)";
prepStatement = currentCon.prepareStatement(insert_query);
//3 values to insert
for (int j = 0; j < ratingsInt.length; j++) {
System.out.println("id: " + categoryIds[j] + "title" + titles[j] + ": " + ratings[j]);
prepStatement.setInt(1, id);
prepStatement.setInt(2, categoryIds[j]);
prepStatement.setInt(3, ratingsInt[j]);
prepStatement.addBatch();
}
System.out.println("_____________________________");
rowsUpdated = prepStatement.executeBatch();
if (rowsUpdated.length > 0) {
System.out.println("Evaluation Inserted!");
return true;
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
public List<EvaluationlInfo> myEvaluationsList(int employee_am_ika) throws SQLException {
List<EvaluationlInfo> myEvaluations = new ArrayList<EvaluationlInfo>();
Connection currentCon = null;
Statement statement = null;
ResultSet resultSet = null;
try{
currentCon = DBConnection.getConnection();
statement = currentCon.createStatement();
resultSet = statement.executeQuery("SELECT * FROM trackingdb.employee_evaluation AS e WHERE employee_am_ika='" + employee_am_ika + "' ORDER BY e.id");
while (resultSet.next()) {
EvaluationlInfo myEvaluation = new EvaluationlInfo();
myEvaluation.setId(resultSet.getInt("id"));
myEvaluation.setType(resultSet.getString("type"));
myEvaluation.setDate(resultSet.getDate("date"));
myEvaluation.setComments(resultSet.getString("comments"));
myEvaluation.setNext_evaluation_date(resultSet.getDate("next_evaluation_date"));
myEvaluation.setTotal_rating(resultSet.getInt("total_rating"));
myEvaluation.setEmployee_am_ika(resultSet.getInt("employee_am_ika"));
myEvaluations.add(myEvaluation);
}
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return myEvaluations; //returning the list of completed goals
}
public List<CategoryInfo> ratingsList(int employee_am_ika, int id) throws SQLException {
List<CategoryInfo> ratings = new ArrayList<CategoryInfo>();
Connection currentCon = null;
Statement statement = null;
ResultSet resultSet = null;
try{
currentCon = DBConnection.getConnection();
statement = currentCon.createStatement();
resultSet = statement.executeQuery("SELECT title, rating FROM trackingdb.employee_evaluation AS e" +
" INNER JOIN trackingdb.evaluation_has_category AS h" +
" ON e.id ='"+ id +"' AND h.evaluation_id ='"+ id +"' AND employee_am_ika='" + employee_am_ika + "'" +
" INNER JOIN trackingdb.category AS c ON c.id=h.category_id;");
while (resultSet.next()) {
CategoryInfo categoryPerRating = new CategoryInfo();
categoryPerRating.setCategory_title(resultSet.getString(1));
categoryPerRating.setRating(resultSet.getInt(2));
ratings.add(categoryPerRating);
}
}
finally {
if (currentCon != null) {
// closes the database connection
try {
currentCon.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return ratings; //returning the list of completed goals
}
}
|
23225_1 | import java.util.Scanner;
public class DNAPalindrome {
public static StringDoubleEndedQueueImpl CreateQ(String DNAseq){
StringDoubleEndedQueueImpl s = new StringDoubleEndedQueueImpl();
char[] charArray = DNAseq.toCharArray();
for (int i = 0; i < charArray.length; i++) {
s.addLast(String.valueOf(charArray[i]));
}
return s;
}
public static boolean isValidDNASequence(String sequence) {
// Ελέγχουμε αν το String είναι null.
if (sequence == null) {
return false;
}
// Ελέγχουμε αν το String είναι κενό.
if (sequence.isEmpty()) {
return true;
}
// Ελέγχουμε κάθε χαρακτήρα του String για εγκυρότητα.
for (char nucleotide : sequence.toCharArray()) {
if (!isValidNucleotide(nucleotide)) {
return false;
}
}
return true;
}
private static boolean isValidNucleotide(char nucleotide) {
// Ελέγχουμε αν ο χαρακτήρας είναι ένα από τα έγκυρα A, T, C, G (πεζά γράμματα).
return (nucleotide == 'A' || nucleotide == 'T' || nucleotide == 'C' || nucleotide == 'G');
}
public static boolean isWatson( StringDoubleEndedQueueImpl q1){
while(!q1.isEmpty()){
if((q1.getFirst().equals("A") && q1.getLast().equals("T")) ||
(q1.getFirst().equals("T") && q1.getLast().equals("A")) ||
(q1.getFirst().equals("C") && q1.getLast().equals("G")) ||
(q1.getFirst().equals("G") &&q1.getLast().equals("C"))){
q1.removeFirst();
q1.removeLast();
q1.printQueue(System.out);
System.out.println("this is queue");
}else{
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Give me a Dna sequence");
String DNAseq=in.nextLine();
while(!isValidDNASequence(DNAseq)){
System.out.println("Give me a Dna sequence");
DNAseq=in.nextLine();
}
StringDoubleEndedQueueImpl q1=CreateQ(DNAseq);
if (isWatson(q1)) {
System.out.println(DNAseq+" is watson");
}else{
System.out.println(DNAseq+" is not watson");
}
}
}
} | FANISPAP123/Data-Structure | DS23-project1/DNAPalindrome.java | 715 | // Ελέγχουμε αν το String είναι κενό.
| line_comment | el | import java.util.Scanner;
public class DNAPalindrome {
public static StringDoubleEndedQueueImpl CreateQ(String DNAseq){
StringDoubleEndedQueueImpl s = new StringDoubleEndedQueueImpl();
char[] charArray = DNAseq.toCharArray();
for (int i = 0; i < charArray.length; i++) {
s.addLast(String.valueOf(charArray[i]));
}
return s;
}
public static boolean isValidDNASequence(String sequence) {
// Ελέγχουμε αν το String είναι null.
if (sequence == null) {
return false;
}
// Ελ<SUF>
if (sequence.isEmpty()) {
return true;
}
// Ελέγχουμε κάθε χαρακτήρα του String για εγκυρότητα.
for (char nucleotide : sequence.toCharArray()) {
if (!isValidNucleotide(nucleotide)) {
return false;
}
}
return true;
}
private static boolean isValidNucleotide(char nucleotide) {
// Ελέγχουμε αν ο χαρακτήρας είναι ένα από τα έγκυρα A, T, C, G (πεζά γράμματα).
return (nucleotide == 'A' || nucleotide == 'T' || nucleotide == 'C' || nucleotide == 'G');
}
public static boolean isWatson( StringDoubleEndedQueueImpl q1){
while(!q1.isEmpty()){
if((q1.getFirst().equals("A") && q1.getLast().equals("T")) ||
(q1.getFirst().equals("T") && q1.getLast().equals("A")) ||
(q1.getFirst().equals("C") && q1.getLast().equals("G")) ||
(q1.getFirst().equals("G") &&q1.getLast().equals("C"))){
q1.removeFirst();
q1.removeLast();
q1.printQueue(System.out);
System.out.println("this is queue");
}else{
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Give me a Dna sequence");
String DNAseq=in.nextLine();
while(!isValidDNASequence(DNAseq)){
System.out.println("Give me a Dna sequence");
DNAseq=in.nextLine();
}
StringDoubleEndedQueueImpl q1=CreateQ(DNAseq);
if (isWatson(q1)) {
System.out.println(DNAseq+" is watson");
}else{
System.out.println(DNAseq+" is not watson");
}
}
}
} |
11705_0 | // Στο αρχείο Main.java
package bankapp;
import bankapp.model.OverdraftAccount;
import bankapp.model.JointAccount;
/**
* Κύρια κλάση για τον έλεγχο της λειτουργίας των λογαριασμών.
*/
public class Main {
public static void main(String[] args) {
// Δημιουργία λογαριασμών
OverdraftAccount overdraftAccount = new OverdraftAccount(1, 1000.0, 500.0);
JointAccount jointAccount = new JointAccount(2, 2000.0, "John", "Mike");
// Εκτύπωση ιδιοτήτων λογαριασμών
System.out.println("Overdraft Account Balance: " + overdraftAccount.getBalance());
System.out.println("Joint Account Holders: " + String.join(", ", jointAccount.getHolders()));
}
}
| Filippostsak/java-oo-projects | src/bankapp/Main.java | 284 | // Στο αρχείο Main.java | line_comment | el | // Στ<SUF>
package bankapp;
import bankapp.model.OverdraftAccount;
import bankapp.model.JointAccount;
/**
* Κύρια κλάση για τον έλεγχο της λειτουργίας των λογαριασμών.
*/
public class Main {
public static void main(String[] args) {
// Δημιουργία λογαριασμών
OverdraftAccount overdraftAccount = new OverdraftAccount(1, 1000.0, 500.0);
JointAccount jointAccount = new JointAccount(2, 2000.0, "John", "Mike");
// Εκτύπωση ιδιοτήτων λογαριασμών
System.out.println("Overdraft Account Balance: " + overdraftAccount.getBalance());
System.out.println("Joint Account Holders: " + String.join(", ", jointAccount.getHolders()));
}
}
|
22457_1 | package JavaClasses.class1;
public class X {
private int i;
private int j;
public int getI() {return i;}
public int getJ() {return j;}
public void setI(int i1) {
i = i1;
};
public void setJ(int j) {
this.j = j;
};
// constructors
public X (int i, int j) {
this.i = i;
setJ(j);
}
// αντίγραφο
public X (X x) {
this(x.i, x.j);
// or
//this.i = x.getI();
//this.j = x.getJ();
}
public X () {}
}
| Firewolf05/JavaClasses | src/JavaClasses/class1/X.java | 176 | // αντίγραφο | line_comment | el | package JavaClasses.class1;
public class X {
private int i;
private int j;
public int getI() {return i;}
public int getJ() {return j;}
public void setI(int i1) {
i = i1;
};
public void setJ(int j) {
this.j = j;
};
// constructors
public X (int i, int j) {
this.i = i;
setJ(j);
}
// αν<SUF>
public X (X x) {
this(x.i, x.j);
// or
//this.i = x.getI();
//this.j = x.getJ();
}
public X () {}
}
|
19290_16 | package org.example;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
//Create arraylist of doctors
ArrayList<Doctor> doctors = new ArrayList<>();
Doctor doc1 = new Doctor("maria", "k", "8754");
Doctor doc2 = new Doctor("kwstas", "k", "8753");
Doctor doc3 = new Doctor("dimitra", "k", "98674");
Doctor doc4 = new Doctor("giwrgos", "k", "8764");
//create arraylist of timeslots for VacCenter1
ArrayList<Timeslot> timeslots1 = new ArrayList<>();
timeslots1.add(new Timeslot(10, 4, 2024, 9, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 10, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 11, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 12, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 13, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 14, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 15, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 16, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 17, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 18, 0,
10, 30, doc2));
//create arraylist of timeslots for VacCenter2
ArrayList<Timeslot> timeslots2 = new ArrayList<>();
timeslots2.add(new Timeslot(10, 4, 2024, 9, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 10, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 11, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 12, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 13, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 14, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 15, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 16, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 17, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 18, 0,
10, 30, doc4));
//create arraylist of VacCenters
ArrayList<VaccinationCenter> vaccinationCenters = new ArrayList<>();
vaccinationCenters.add(new VaccinationCenter("123", "casterly rock", timeslots1));
vaccinationCenters.add(new VaccinationCenter("456", "storm's end", timeslots2));
//Set vaccination center to doctors
doc1.setVaccinationCenter(vaccinationCenters.get(0));
doc2.setVaccinationCenter(vaccinationCenters.get(0));
doc3.setVaccinationCenter(vaccinationCenters.get(1));
doc4.setVaccinationCenter(vaccinationCenters.get(1));
//add timeslots to doctors
for(int i=0;i<10;i++){
if(i<5){
doc1.addTimeslot(timeslots1.get(i));
doc3.addTimeslot(timeslots2.get(i));
}
else{
doc2.addTimeslot(timeslots2.get(i));
doc4.addTimeslot(timeslots2.get(i));
}
}
//create arraylist of insures people
ArrayList<Insured> insuredpeople = new ArrayList<>();
insuredpeople.add(new Insured("Petyr", "Baelish", "128975439", "[email protected]",
"673537", "11/03/1935"));
insuredpeople.add(new Insured("Lord", "Varys", "373598", "[email protected]",
"846338", "17/03/1972"));
insuredpeople.add(new Insured("Theon", "Greyjoy", "83635", "[email protected]",
"83625", "7/08/1945"));
insuredpeople.add(new Insured("Sandor", "Clegane", "823627", "[email protected]",
"927156", "5/12/1988"));
insuredpeople.add(new Insured("Brienne", "of Tarth", "987534", "[email protected]",
"82615", "15/12/1999"));
insuredpeople.add(new Insured("Arya", "Stark", "765439", "[email protected]",
"76754", "10/1/2010"));
insuredpeople.add(new Insured("Sansa", "Stark", "6535978", "[email protected]",
"787530", "8/11/2011"));
insuredpeople.add(new Insured("Jon", "Snow", "898674", "[email protected]",
"876430", "18/4/1980"));
insuredpeople.add(new Insured("Daenerys", "Targaryen", "875643", "[email protected]",
"998764", "1/5/1989"));
insuredpeople.add(new Insured("Tyrion", "Lannister", "7635234", "[email protected]",
"926254", "10/7/1970"));
insuredpeople.add(new Insured("Cersei", "Lannister", "87632", "[email protected]",
"9864309", "1/4/1943"));
insuredpeople.add(new Insured("Ned", "Stark", "875318", "[email protected]",
"986752", "19/9/1969"));
// Shuffle the list to get random ordering
Collections.shuffle(insuredpeople);
//make reservation for 8 insured people
//prepei na ftiaxtei o elegxos gia to an apo randoms select vaccCenter na min dialegete panta 1.
for (int i = 0; i < 8; i++){
Reservation reservation = insuredpeople.get(i).makeReservation(vaccinationCenters);
VaccinationCenter VacCenter = reservation.getVaccinationCenter();
VacCenter.addReservation(reservation);
Doctor doctor = reservation.findDoctor(doctors);
doctor.addReservation(reservation);
}
int count = 0;
//Make vaccination
//Na min 3exaso avrio na valo oti emvoliazontai oi 6 apo tous 8
for (Doctor doctor:doctors){
for (Reservation res:doctor.getReservations()){
//den xreiazetai mallon na epistrefei
Vaccination VaccObj =res.getInsured().getVaccinated(res,doctor);
doctor.addVaccination(VaccObj);
count=count+1;
if (count >=6) {
break; // Breaks out of the inner loop
}
}
if (count >= 6) {
break; // Breaks out of the outer loop
}
}
//Επικείμενα ραντεβου για κάθε εμβολιαστικό
for(VaccinationCenter vacCenter:vaccinationCenters){
vacCenter.printUpcomingReservations();
}
//Ελέυθερες χρονικές θυρίδες κάθε εμβολιαστικού
vaccinationCenters.get(0).printFreeTimeslot(timeslots1);
vaccinationCenters.get(1).printFreeTimeslot(timeslots2);
//Εμβολιασμούς κάθε γιατρός για όλους τους γιατρούς
for (Doctor doctor:doctors){
doctor.printVaccinations();
}
/*//Ασφαλισμένοι >60 που δεν έχουν κλείσει ραντεβού
for(VaccinationCenter vaccCenter:vaccinationCenters){
vaccCenter.printInsuredWithoutReservation(insuredpeople);
}*/
/*//create second Arraylist of appointments na to sizitisoume
ArrayList<Reservation> reservations = new ArrayList<>();
reservations.add(new Reservation(insuredpeople.get(0), timeslots1.get(1)));
reservations.add(new Reservation(insuredpeople.get(3), timeslots2.get(4)));
reservations.add(new Reservation(insuredpeople.get(4), timeslots1.get(7)));
reservations.add(new Reservation(insuredpeople.get(6), timeslots2.get(8)));
reservations.add(new Reservation(insuredpeople.get(7), timeslots1.get(2)));
reservations.add(new Reservation(insuredpeople.get(10), timeslots2.get(3)));
reservations.add(new Reservation(insuredpeople.get(11), timeslots1.get(9)));
reservations.add(new Reservation(insuredpeople.get(9), timeslots2.get(1)));
printToFile(reservations);*/
}
private static void printToFile(List<Reservation> reservations) {
File file = new File("vaccination-results.txt");
try (PrintWriter pw = new PrintWriter(file)) {
pw.println("The first center has the appointments: ");
for (var elem : reservations) {
if (elem.getVaccinationCenter().getCode().equals("123")) {
pw.println(elem.getTimeslot());
}
}
pw.println("The second center has the appointments: ");
for (var elem : reservations) {
if (elem.getVaccinationCenter().getCode().equals("456")) {
pw.println(elem.getTimeslot());
}
}
} catch (IOException e) {
System.out.println(e);
}
}
}
| GTGH-accenture-uom-2/Team4-part1 | src/main/java/org/example/Main.java | 3,081 | //Ελέυθερες χρονικές θυρίδες κάθε εμβολιαστικού | line_comment | el | package org.example;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
//Create arraylist of doctors
ArrayList<Doctor> doctors = new ArrayList<>();
Doctor doc1 = new Doctor("maria", "k", "8754");
Doctor doc2 = new Doctor("kwstas", "k", "8753");
Doctor doc3 = new Doctor("dimitra", "k", "98674");
Doctor doc4 = new Doctor("giwrgos", "k", "8764");
//create arraylist of timeslots for VacCenter1
ArrayList<Timeslot> timeslots1 = new ArrayList<>();
timeslots1.add(new Timeslot(10, 4, 2024, 9, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 10, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 11, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 12, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 13, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 14, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 15, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 16, 0,
10, 30, doc2));
timeslots1.add(new Timeslot(10, 4, 2024, 17, 0,
9, 30, doc1));
timeslots1.add(new Timeslot(10, 4, 2024, 18, 0,
10, 30, doc2));
//create arraylist of timeslots for VacCenter2
ArrayList<Timeslot> timeslots2 = new ArrayList<>();
timeslots2.add(new Timeslot(10, 4, 2024, 9, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 10, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 11, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 12, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 13, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 14, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 15, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 16, 0,
10, 30, doc4));
timeslots2.add(new Timeslot(10, 4, 2024, 17, 0,
9, 30, doc3));
timeslots2.add(new Timeslot(10, 4, 2024, 18, 0,
10, 30, doc4));
//create arraylist of VacCenters
ArrayList<VaccinationCenter> vaccinationCenters = new ArrayList<>();
vaccinationCenters.add(new VaccinationCenter("123", "casterly rock", timeslots1));
vaccinationCenters.add(new VaccinationCenter("456", "storm's end", timeslots2));
//Set vaccination center to doctors
doc1.setVaccinationCenter(vaccinationCenters.get(0));
doc2.setVaccinationCenter(vaccinationCenters.get(0));
doc3.setVaccinationCenter(vaccinationCenters.get(1));
doc4.setVaccinationCenter(vaccinationCenters.get(1));
//add timeslots to doctors
for(int i=0;i<10;i++){
if(i<5){
doc1.addTimeslot(timeslots1.get(i));
doc3.addTimeslot(timeslots2.get(i));
}
else{
doc2.addTimeslot(timeslots2.get(i));
doc4.addTimeslot(timeslots2.get(i));
}
}
//create arraylist of insures people
ArrayList<Insured> insuredpeople = new ArrayList<>();
insuredpeople.add(new Insured("Petyr", "Baelish", "128975439", "[email protected]",
"673537", "11/03/1935"));
insuredpeople.add(new Insured("Lord", "Varys", "373598", "[email protected]",
"846338", "17/03/1972"));
insuredpeople.add(new Insured("Theon", "Greyjoy", "83635", "[email protected]",
"83625", "7/08/1945"));
insuredpeople.add(new Insured("Sandor", "Clegane", "823627", "[email protected]",
"927156", "5/12/1988"));
insuredpeople.add(new Insured("Brienne", "of Tarth", "987534", "[email protected]",
"82615", "15/12/1999"));
insuredpeople.add(new Insured("Arya", "Stark", "765439", "[email protected]",
"76754", "10/1/2010"));
insuredpeople.add(new Insured("Sansa", "Stark", "6535978", "[email protected]",
"787530", "8/11/2011"));
insuredpeople.add(new Insured("Jon", "Snow", "898674", "[email protected]",
"876430", "18/4/1980"));
insuredpeople.add(new Insured("Daenerys", "Targaryen", "875643", "[email protected]",
"998764", "1/5/1989"));
insuredpeople.add(new Insured("Tyrion", "Lannister", "7635234", "[email protected]",
"926254", "10/7/1970"));
insuredpeople.add(new Insured("Cersei", "Lannister", "87632", "[email protected]",
"9864309", "1/4/1943"));
insuredpeople.add(new Insured("Ned", "Stark", "875318", "[email protected]",
"986752", "19/9/1969"));
// Shuffle the list to get random ordering
Collections.shuffle(insuredpeople);
//make reservation for 8 insured people
//prepei na ftiaxtei o elegxos gia to an apo randoms select vaccCenter na min dialegete panta 1.
for (int i = 0; i < 8; i++){
Reservation reservation = insuredpeople.get(i).makeReservation(vaccinationCenters);
VaccinationCenter VacCenter = reservation.getVaccinationCenter();
VacCenter.addReservation(reservation);
Doctor doctor = reservation.findDoctor(doctors);
doctor.addReservation(reservation);
}
int count = 0;
//Make vaccination
//Na min 3exaso avrio na valo oti emvoliazontai oi 6 apo tous 8
for (Doctor doctor:doctors){
for (Reservation res:doctor.getReservations()){
//den xreiazetai mallon na epistrefei
Vaccination VaccObj =res.getInsured().getVaccinated(res,doctor);
doctor.addVaccination(VaccObj);
count=count+1;
if (count >=6) {
break; // Breaks out of the inner loop
}
}
if (count >= 6) {
break; // Breaks out of the outer loop
}
}
//Επικείμενα ραντεβου για κάθε εμβολιαστικό
for(VaccinationCenter vacCenter:vaccinationCenters){
vacCenter.printUpcomingReservations();
}
//Ελ<SUF>
vaccinationCenters.get(0).printFreeTimeslot(timeslots1);
vaccinationCenters.get(1).printFreeTimeslot(timeslots2);
//Εμβολιασμούς κάθε γιατρός για όλους τους γιατρούς
for (Doctor doctor:doctors){
doctor.printVaccinations();
}
/*//Ασφαλισμένοι >60 που δεν έχουν κλείσει ραντεβού
for(VaccinationCenter vaccCenter:vaccinationCenters){
vaccCenter.printInsuredWithoutReservation(insuredpeople);
}*/
/*//create second Arraylist of appointments na to sizitisoume
ArrayList<Reservation> reservations = new ArrayList<>();
reservations.add(new Reservation(insuredpeople.get(0), timeslots1.get(1)));
reservations.add(new Reservation(insuredpeople.get(3), timeslots2.get(4)));
reservations.add(new Reservation(insuredpeople.get(4), timeslots1.get(7)));
reservations.add(new Reservation(insuredpeople.get(6), timeslots2.get(8)));
reservations.add(new Reservation(insuredpeople.get(7), timeslots1.get(2)));
reservations.add(new Reservation(insuredpeople.get(10), timeslots2.get(3)));
reservations.add(new Reservation(insuredpeople.get(11), timeslots1.get(9)));
reservations.add(new Reservation(insuredpeople.get(9), timeslots2.get(1)));
printToFile(reservations);*/
}
private static void printToFile(List<Reservation> reservations) {
File file = new File("vaccination-results.txt");
try (PrintWriter pw = new PrintWriter(file)) {
pw.println("The first center has the appointments: ");
for (var elem : reservations) {
if (elem.getVaccinationCenter().getCode().equals("123")) {
pw.println(elem.getTimeslot());
}
}
pw.println("The second center has the appointments: ");
for (var elem : reservations) {
if (elem.getVaccinationCenter().getCode().equals("456")) {
pw.println(elem.getTimeslot());
}
}
} catch (IOException e) {
System.out.println(e);
}
}
}
|
22866_1 | import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import jxl.Workbook;
import jxl.write.Border;
import jxl.write.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class XlsWriter {
private ArrayList<Course> FCourses = new ArrayList<Course>();
private ArrayList<Label> labels = new ArrayList<Label>();
public XlsWriter(ArrayList<Course> array)
{
FCourses.addAll(array);
}
public void writeToExcel()
{
WritableWorkbook workbook = null;
try {
workbook = Workbook.createWorkbook(new File("MyUOMSchedule.xls"));
//δημιουργια νεου excel
WritableSheet excelSheet = workbook.createSheet("MySchedule", 0);
//δημιουργια φυλλου excel
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setWrap(true);
cellFormat.setBackground(cellFormat.getBackgroundColour().GRAY_25);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
Label label = new Label(0, 0, "ΩΡΑ/ΜΕΡΑ",cellFormat);
excelSheet.addCell(label);
excelSheet.setColumnView(0, 12);
for(int j=1;j<6;j++)
{
excelSheet.setColumnView(j, 50);
}
for(int i=1;i<14;i++)
{
excelSheet.setRowView(i, 500);
}
int i=8;
int inext=i+1;
Label hour = new Label(0, 1,""+ i +":00 -"+inext+":00",cellFormat);
excelSheet.addCell(hour);
for(int k=2;k<14;k++)
{
i++;
inext++;
hour = new Label(0, k,""+ i +":00-"+inext+":00",cellFormat);
excelSheet.addCell(hour);
}
Label day = new Label(1, 0, "ΔΕΥΤΕΡΑ",cellFormat);
excelSheet.addCell(day);
day = new Label(2, 0, "ΤΡΙΤΗ",cellFormat);
excelSheet.addCell(day);
day = new Label(3, 0, "ΤΕΤΑΡΤΗ",cellFormat);
excelSheet.addCell(day);
day = new Label(4, 0, "ΠΕΜΠΤΗ",cellFormat);
excelSheet.addCell(day);
day = new Label(5, 0, "ΠΑΡΑΣΚΕΥΗ",cellFormat);
excelSheet.addCell(day);//προσθηκη μερων και ωρων με την μεθοδο addCell
if(!FCourses.isEmpty())
{
labels.add(new Label(FCourses.get(0).getDay(),FCourses.get(0).getHour()-7,FCourses.get(0).getName()
+"\n"+FCourses.get(0).getClassr(),cellFormat));
for(i=1;i<FCourses.size();i++)
{
labels.add(new Label(FCourses.get(i).getDay(),FCourses.get(i).getHour()-7,
FCourses.get(i).getName() +"\n"+FCourses.get(i).getClassr(),cellFormat));
}
}
for(i=0;i<labels.size();i++)
{
excelSheet.addCell(labels.get(i));
}//προσθηκη μαθηματων και δραστηριοτητων στο mySchedule
workbook.write();//γραψιμο στο excel
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
}
}
| GeorgeMichos13/MyUom | src/XlsWriter.java | 1,130 | //δημιουργια φυλλου excel | line_comment | el | import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import jxl.Workbook;
import jxl.write.Border;
import jxl.write.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class XlsWriter {
private ArrayList<Course> FCourses = new ArrayList<Course>();
private ArrayList<Label> labels = new ArrayList<Label>();
public XlsWriter(ArrayList<Course> array)
{
FCourses.addAll(array);
}
public void writeToExcel()
{
WritableWorkbook workbook = null;
try {
workbook = Workbook.createWorkbook(new File("MyUOMSchedule.xls"));
//δημιουργια νεου excel
WritableSheet excelSheet = workbook.createSheet("MySchedule", 0);
//δη<SUF>
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setWrap(true);
cellFormat.setBackground(cellFormat.getBackgroundColour().GRAY_25);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
Label label = new Label(0, 0, "ΩΡΑ/ΜΕΡΑ",cellFormat);
excelSheet.addCell(label);
excelSheet.setColumnView(0, 12);
for(int j=1;j<6;j++)
{
excelSheet.setColumnView(j, 50);
}
for(int i=1;i<14;i++)
{
excelSheet.setRowView(i, 500);
}
int i=8;
int inext=i+1;
Label hour = new Label(0, 1,""+ i +":00 -"+inext+":00",cellFormat);
excelSheet.addCell(hour);
for(int k=2;k<14;k++)
{
i++;
inext++;
hour = new Label(0, k,""+ i +":00-"+inext+":00",cellFormat);
excelSheet.addCell(hour);
}
Label day = new Label(1, 0, "ΔΕΥΤΕΡΑ",cellFormat);
excelSheet.addCell(day);
day = new Label(2, 0, "ΤΡΙΤΗ",cellFormat);
excelSheet.addCell(day);
day = new Label(3, 0, "ΤΕΤΑΡΤΗ",cellFormat);
excelSheet.addCell(day);
day = new Label(4, 0, "ΠΕΜΠΤΗ",cellFormat);
excelSheet.addCell(day);
day = new Label(5, 0, "ΠΑΡΑΣΚΕΥΗ",cellFormat);
excelSheet.addCell(day);//προσθηκη μερων και ωρων με την μεθοδο addCell
if(!FCourses.isEmpty())
{
labels.add(new Label(FCourses.get(0).getDay(),FCourses.get(0).getHour()-7,FCourses.get(0).getName()
+"\n"+FCourses.get(0).getClassr(),cellFormat));
for(i=1;i<FCourses.size();i++)
{
labels.add(new Label(FCourses.get(i).getDay(),FCourses.get(i).getHour()-7,
FCourses.get(i).getName() +"\n"+FCourses.get(i).getClassr(),cellFormat));
}
}
for(i=0;i<labels.size();i++)
{
excelSheet.addCell(labels.get(i));
}//προσθηκη μαθηματων και δραστηριοτητων στο mySchedule
workbook.write();//γραψιμο στο excel
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
}
}
|
6291_0 | package gr.conference.menus;
import java.util.Scanner;
public class StartingScreen {
public String user;
public StartingScreen()
{
loadMenu();
}
private void loadMenu()
{
Scanner scanner = new Scanner(System.in);
int flag = 0;
LoginPage lp = new LoginPage();
System.out.println("------------------------------------------");
System.out.println("WELCOME TO THE CONFERENCE SYSTEM USER PAGE");
while(flag == 0)
{
System.out.println("1. LOGIN");
System.out.println("2. REGISTER");
System.out.println("3. CONTINUE AS GUEST");
System.out.println("4. ADMIN LOGIN");
System.out.println("5. EXIT");
System.out.print("Your input >");
int input = scanner.nextInt();
switch(input)
{
case 1:
flag = 1;
lp.loadPageUser();
break;
case 2:
flag = 1;
RegisterPage rp = new RegisterPage();
break;
case 3:
flag = 1;
//TODO Φτιάξε τι θα γίνεται σε περίπτωση visitor.
break;
case 4:
flag =1;
lp.loadPageAdmin();
break;
case 5:
flag = 1;
System.exit(0);
break;
default:
flag = 0;
break;
}
}
}
public String getUser() {
return user;
}
}
| Georgezach24/Project-soft | OneDrive/Desktop/5th Semester/Soft. Eng/final/sys/src/main/java/gr/conference/menus/StartingScreen.java | 424 | //TODO Φτιάξε τι θα γίνεται σε περίπτωση visitor. | line_comment | el | package gr.conference.menus;
import java.util.Scanner;
public class StartingScreen {
public String user;
public StartingScreen()
{
loadMenu();
}
private void loadMenu()
{
Scanner scanner = new Scanner(System.in);
int flag = 0;
LoginPage lp = new LoginPage();
System.out.println("------------------------------------------");
System.out.println("WELCOME TO THE CONFERENCE SYSTEM USER PAGE");
while(flag == 0)
{
System.out.println("1. LOGIN");
System.out.println("2. REGISTER");
System.out.println("3. CONTINUE AS GUEST");
System.out.println("4. ADMIN LOGIN");
System.out.println("5. EXIT");
System.out.print("Your input >");
int input = scanner.nextInt();
switch(input)
{
case 1:
flag = 1;
lp.loadPageUser();
break;
case 2:
flag = 1;
RegisterPage rp = new RegisterPage();
break;
case 3:
flag = 1;
//TO<SUF>
break;
case 4:
flag =1;
lp.loadPageAdmin();
break;
case 5:
flag = 1;
System.exit(0);
break;
default:
flag = 0;
break;
}
}
}
public String getUser() {
return user;
}
}
|
8394_8 | package com.example.brick_breaker_game;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Bounds;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Sphere;
import javafx.scene.text.Font;
import javafx.util.Duration;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private Rectangle rod;
@FXML
private Sphere ball;
@FXML
protected int deltaX = 10, deltaY = -5, scoreCounter = 0, rodSpeed = 65, minX = 10, maxX = 12, minY = 8, maxY = 10,
maxA = 360, minA = 180;
@FXML
private final ArrayList<Rectangle> bricks = new ArrayList<>();
@FXML
private AnchorPane scene;
@FXML
private Label score;
@FXML
Random rand = new Random();
@FXML
private Canvas canvas;
@FXML
PhongMaterial material = new PhongMaterial();
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(50), new EventHandler<>() {
@Override
public void handle(ActionEvent event) {
Bounds bounds = scene.getBoundsInLocal();
//Δίνει κίνηση στην μπάλα
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
ball.setTranslateX(ball.getTranslateX() + deltaX );
ball.setTranslateY(ball.getTranslateY() + deltaY );
//Όταν πάει να βγει από τα όρια της οθόνης η μπάλα αναπηδάει
if(ball.getTranslateX() >= (bounds.getMaxX()/2) - ball.getRadius()) {
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaX = -1 * (rand.nextInt(maxX + 1 - minX) + minX);
ball.setTranslateX(ball.getTranslateX() + deltaX);
scoreCounter += 2;
score.setText("Score: " + scoreCounter);
}else if( ball.getTranslateX() <= (-bounds.getMaxX()/2) + ball.getRadius()){
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaX = (rand.nextInt(maxX + 1 - minX) + minX);
ball.setTranslateX(ball.getTranslateX() + deltaX);
scoreCounter += 2;
score.setText("Score: " + scoreCounter);
}
if (ball.getTranslateY() <= (-bounds.getMaxY()/2) + ball.getRadius()){
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaY = (rand.nextInt(maxY + 1 - minY) + minY);
ball.setTranslateY(ball.getTranslateY() + deltaY);
scoreCounter += 2;
score.setText("Score: " + scoreCounter);
}
//Αναγνωρίζει αν η μπάλα ακούμπησε την μπάρα αναπηδάει
if(ball.getBoundsInParent().intersects(rod.getBoundsInParent())){
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaY = -1 * (rand.nextInt(maxY + 1 - minY) + minY);
ball.setRotate(rand.nextInt(360));
ball.setTranslateY(ball.getTranslateY() + deltaY);
//Ανεβάζει το σκορ
scoreCounter += 5;
score.setText("Score: " + scoreCounter);
}
//Αν η μπάλα πάει στο κάτω μέρος της οθόνης ο παίκτης χάνει και τελειώνει το παιχνίδι
if (ball.getTranslateY() >= (bounds.getMaxY()/2) - ball.getRadius()) {
timeline.stop();
//Εμφανίζει το μήνυμα στην οθόνη
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.setFont(new Font("", 40));
gc.fillText("GAME OVER!! Your score is: " + scoreCounter, 50, 300);
}
//Αν υπάρχουν ακόμη τουβλάκια στη λίστα το παιχνίδι συνεχίζεται αφαιρώντας το τουβλάκι που ακούμπησε η μπάλα
if(!bricks.isEmpty()){
bricks.removeIf(brick -> checkCollisionBricks(brick));
//Διαφορετικά ο παίκτης κερδίζει το παιχνίδι
} else {
timeline.stop();
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.setFont(new Font("", 40));
gc.fillText("YOU WON!! Your score is: " + scoreCounter, 50, 300);
}
}
}));
//Ρυθμίζει την πορεία της μπάλας όταν χτυπάει στα τουβλάκια. Αν αφαιρεθεί τουβλάκι η συνάρτηση επιστρέφει true
public boolean checkCollisionBricks(Rectangle brick){
if(ball.getBoundsInParent().intersects(brick.getBoundsInParent())){
boolean rightBorder = ball.getLayoutX() >= ((brick.getX() + brick.getWidth()) - ball.getRadius());
boolean leftBorder = ball.getLayoutX() <= (brick.getX() + ball.getRadius());
boolean bottomBorder = ball.getLayoutY() >= ((brick.getY() + brick.getHeight()) - ball.getRadius());
boolean topBorder = ball.getLayoutY() <= (brick.getY() + ball.getRadius());
if (rightBorder || leftBorder) {
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaX *= -1;
}
if (bottomBorder || topBorder) {
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaY *= -1;
}
scene.getChildren().remove(brick);//Αφαιρεί το τουβλάκι από την οθόνη όταν το ακουμπήσει η μπάλα
scoreCounter += 10;
score.setText("Score: " + scoreCounter);
return true;
}
return false;
}
//Για να κινείται η μπάρα προς τα δεξιά
public void moveRight(){
Bounds bounds = scene.getBoundsInLocal();
//Ρυθμίζει την ταχύτητα κίνησης
//Αλλάζει τη θέση του
rod.setTranslateX(rod.getTranslateX() + rodSpeed);
//Άμα φτάσει στο όριο της οθόνης εμφανίζεται από την άλλη μεριά
if(rod.getTranslateX() >= (bounds.getMaxX()/2)){
rod.setTranslateX(rod.getTranslateX() - rodSpeed);
}
}
public void moveLeft() {
Bounds bounds = scene.getBoundsInLocal();
rod.setTranslateX(rod.getTranslateX() - rodSpeed);
if(rod.getTranslateX() <= (-(bounds.getMaxX()/2))){
rod.setTranslateX(rod.getTranslateX() + rodSpeed);
}
}
@FXML //Εμφανίζει τα τουβλάκια στην οθόνη
private void createBricks(){
double width = 640;
double height = 200;
int spaceCheck = 1;
for (double i = height; i > 0 ; i = i - 40) {
for (double j = width; j > 0 ; j = j - 15) {
if(spaceCheck % 3 == 0){
Rectangle brick = new Rectangle(j,i,40,15);
brick.setFill(Color.FIREBRICK);
scene.getChildren().add(brick);
bricks.add(brick);
}
spaceCheck++;
}
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
material.setDiffuseColor(Color.YELLOW);
material.setSpecularColor(Color.BLACK);
ball.setMaterial(material);
score.setText("Score: " + scoreCounter);
createBricks();
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
} | Giannis1273646/Brick-Breaker-Game | src/main/java/com/example/brick_breaker_game/Controller.java | 2,486 | //Ρυθμίζει την πορεία της μπάλας όταν χτυπάει στα τουβλάκια. Αν αφαιρεθεί τουβλάκι η συνάρτηση επιστρέφει true | line_comment | el | package com.example.brick_breaker_game;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Bounds;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Sphere;
import javafx.scene.text.Font;
import javafx.util.Duration;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private Rectangle rod;
@FXML
private Sphere ball;
@FXML
protected int deltaX = 10, deltaY = -5, scoreCounter = 0, rodSpeed = 65, minX = 10, maxX = 12, minY = 8, maxY = 10,
maxA = 360, minA = 180;
@FXML
private final ArrayList<Rectangle> bricks = new ArrayList<>();
@FXML
private AnchorPane scene;
@FXML
private Label score;
@FXML
Random rand = new Random();
@FXML
private Canvas canvas;
@FXML
PhongMaterial material = new PhongMaterial();
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(50), new EventHandler<>() {
@Override
public void handle(ActionEvent event) {
Bounds bounds = scene.getBoundsInLocal();
//Δίνει κίνηση στην μπάλα
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
ball.setTranslateX(ball.getTranslateX() + deltaX );
ball.setTranslateY(ball.getTranslateY() + deltaY );
//Όταν πάει να βγει από τα όρια της οθόνης η μπάλα αναπηδάει
if(ball.getTranslateX() >= (bounds.getMaxX()/2) - ball.getRadius()) {
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaX = -1 * (rand.nextInt(maxX + 1 - minX) + minX);
ball.setTranslateX(ball.getTranslateX() + deltaX);
scoreCounter += 2;
score.setText("Score: " + scoreCounter);
}else if( ball.getTranslateX() <= (-bounds.getMaxX()/2) + ball.getRadius()){
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaX = (rand.nextInt(maxX + 1 - minX) + minX);
ball.setTranslateX(ball.getTranslateX() + deltaX);
scoreCounter += 2;
score.setText("Score: " + scoreCounter);
}
if (ball.getTranslateY() <= (-bounds.getMaxY()/2) + ball.getRadius()){
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaY = (rand.nextInt(maxY + 1 - minY) + minY);
ball.setTranslateY(ball.getTranslateY() + deltaY);
scoreCounter += 2;
score.setText("Score: " + scoreCounter);
}
//Αναγνωρίζει αν η μπάλα ακούμπησε την μπάρα αναπηδάει
if(ball.getBoundsInParent().intersects(rod.getBoundsInParent())){
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaY = -1 * (rand.nextInt(maxY + 1 - minY) + minY);
ball.setRotate(rand.nextInt(360));
ball.setTranslateY(ball.getTranslateY() + deltaY);
//Ανεβάζει το σκορ
scoreCounter += 5;
score.setText("Score: " + scoreCounter);
}
//Αν η μπάλα πάει στο κάτω μέρος της οθόνης ο παίκτης χάνει και τελειώνει το παιχνίδι
if (ball.getTranslateY() >= (bounds.getMaxY()/2) - ball.getRadius()) {
timeline.stop();
//Εμφανίζει το μήνυμα στην οθόνη
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.setFont(new Font("", 40));
gc.fillText("GAME OVER!! Your score is: " + scoreCounter, 50, 300);
}
//Αν υπάρχουν ακόμη τουβλάκια στη λίστα το παιχνίδι συνεχίζεται αφαιρώντας το τουβλάκι που ακούμπησε η μπάλα
if(!bricks.isEmpty()){
bricks.removeIf(brick -> checkCollisionBricks(brick));
//Διαφορετικά ο παίκτης κερδίζει το παιχνίδι
} else {
timeline.stop();
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.setFont(new Font("", 40));
gc.fillText("YOU WON!! Your score is: " + scoreCounter, 50, 300);
}
}
}));
//Ρυ<SUF>
public boolean checkCollisionBricks(Rectangle brick){
if(ball.getBoundsInParent().intersects(brick.getBoundsInParent())){
boolean rightBorder = ball.getLayoutX() >= ((brick.getX() + brick.getWidth()) - ball.getRadius());
boolean leftBorder = ball.getLayoutX() <= (brick.getX() + ball.getRadius());
boolean bottomBorder = ball.getLayoutY() >= ((brick.getY() + brick.getHeight()) - ball.getRadius());
boolean topBorder = ball.getLayoutY() <= (brick.getY() + ball.getRadius());
if (rightBorder || leftBorder) {
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaX *= -1;
}
if (bottomBorder || topBorder) {
ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA);
deltaY *= -1;
}
scene.getChildren().remove(brick);//Αφαιρεί το τουβλάκι από την οθόνη όταν το ακουμπήσει η μπάλα
scoreCounter += 10;
score.setText("Score: " + scoreCounter);
return true;
}
return false;
}
//Για να κινείται η μπάρα προς τα δεξιά
public void moveRight(){
Bounds bounds = scene.getBoundsInLocal();
//Ρυθμίζει την ταχύτητα κίνησης
//Αλλάζει τη θέση του
rod.setTranslateX(rod.getTranslateX() + rodSpeed);
//Άμα φτάσει στο όριο της οθόνης εμφανίζεται από την άλλη μεριά
if(rod.getTranslateX() >= (bounds.getMaxX()/2)){
rod.setTranslateX(rod.getTranslateX() - rodSpeed);
}
}
public void moveLeft() {
Bounds bounds = scene.getBoundsInLocal();
rod.setTranslateX(rod.getTranslateX() - rodSpeed);
if(rod.getTranslateX() <= (-(bounds.getMaxX()/2))){
rod.setTranslateX(rod.getTranslateX() + rodSpeed);
}
}
@FXML //Εμφανίζει τα τουβλάκια στην οθόνη
private void createBricks(){
double width = 640;
double height = 200;
int spaceCheck = 1;
for (double i = height; i > 0 ; i = i - 40) {
for (double j = width; j > 0 ; j = j - 15) {
if(spaceCheck % 3 == 0){
Rectangle brick = new Rectangle(j,i,40,15);
brick.setFill(Color.FIREBRICK);
scene.getChildren().add(brick);
bricks.add(brick);
}
spaceCheck++;
}
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
material.setDiffuseColor(Color.YELLOW);
material.setSpecularColor(Color.BLACK);
ball.setMaterial(material);
score.setText("Score: " + scoreCounter);
createBricks();
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
} |
3410_39 | package sample;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ResourceBundle;
public class SinglePlayerController implements Initializable {
@FXML
private ComboBox<String> menu;
@FXML
String s = ".";
@FXML
private Label label, label1, label2;
@FXML
private TextField textField;
@FXML
private char[] wordsLetters;
@FXML
ArrayList<String> word = new ArrayList<>();
@FXML
public int counter, tries = 7;
@FXML
private ImageView img;
@FXML
private Button button, playAgainB, menuB;
@FXML
private void menu(ActionEvent event) throws IOException {
//Παίρνει την επιλογή του χρήστη
String choice = menu.getValue();
//Επιστρέφει στο αρχικό μενού
if(choice.equals("Επιστροφή στο κύριο μενού")){
Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene singlePlayerScene = new Scene(singlePlayerParent);
//This line gets the stage information
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(singlePlayerScene);
window.setTitle("Menu");
window.show();
}else{
Platform.exit();
}
}
@FXML
private void getLetters(ActionEvent event){
boolean found = false;
//Παίρνει από το textField το γράμμα που δίνει ο χρήστης
String letter = textField.getText();
textField.clear();
switch (letter){
case "α":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ά".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ε":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "έ".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ι":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ί".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "η":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ή".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "υ":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ύ".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ο":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ό".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ω":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ώ".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
default:
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i]))) {
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,letter);
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
}
//Άμα δεν έχει βρεθεί το γράμμα το εμφανίζει στα γράμματα που έχουν χρησιμοποιηθεί και αφαιρεί μία ζωή
if (!found){
label1.setText(label1.getText() + letter +" ,");
tries--;
}
//Εμφανίζει τα γράμματα στο label από το ArrayList word
label.setText("");
for (int i = 0; i< wordsLetters.length; i++){
label.setText(label.getText() + word.get(i));
}
//Εμφανίζει το ανθρωπάκι μέσω εικόνων
switch (tries){
case 6:
img.setImage(new Image("resources/try2.png"));
break;
case 5:
img.setImage(new Image("resources/try3.png"));
break;
case 4:
img.setImage(new Image("resources/try4.png"));
break;
case 3:
img.setImage(new Image("resources/try5.png"));
break;
case 2:
img.setImage(new Image("resources/try6.png"));
break;
case 1:
img.setImage(new Image("resources/try7.png"));
break;
case 0:
//Αν τελειώσουν οι προσπάθειες το πρόγραμμα τερματίζει
label.setText("");
//Για να εμφανίζεται η λέξη όταν χάσει ο παίκτης
for (int i=0; i<wordsLetters.length; i++){
if(s.equals(String.valueOf(wordsLetters[i]))){
label.setText(label.getText() + word.get(i));
}else {
label.setText(label.getText() + wordsLetters[i]);
}
}
//Εμφανίζονται κάποιες επιπλέον επιλογές αφού έχει τελειώσει το πρόγραμμα
label2.setVisible(true);
textField.setEditable(false);
button.setVisible(false);
playAgainB.setVisible(true);
menuB.setVisible(true);
break;
}
//Αφορά την στιγμή που ο χρήστης βρίσκει την λέξη
if (counter==1){
label2.setText("You Won");
label2.setVisible(true);
textField.setEditable(false);
button.setVisible(false);
playAgainB.setVisible(true);
menuB.setVisible(true);
}
}
@FXML //Ξεκινάει το πρόγραμμα από την αρχή
private void playAgain(ActionEvent event) throws IOException {
Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("SinglePlayer.fxml"));
Scene singlePlayerScene = new Scene(singlePlayerParent,683, 373.6);
//This line gets the stage information
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(singlePlayerScene);
window.setTitle("Single Player");
window.show();
}
@FXML //Επιστρέφει στο μενού
private void returnMenu(ActionEvent event) throws IOException {
Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene singlePlayerScene = new Scene(singlePlayerParent);
//This line gets the stage information
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(singlePlayerScene);
window.setTitle("Menu");
window.show();
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
menu.getItems().addAll("Επιστροφή στο κύριο μενού", "Έξοδος");
label2.setVisible(false);
playAgainB.setVisible(false);
menuB.setVisible(false);
//Για να δέχεται γράμματα Ελληνικά με τόνους και Αγγλικά
textField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\sα-ωΑ-Ωά-ώ*")) {
textField.setText(newValue.replaceAll("[^\\sA-Zά-ώ]", ""));
}
});
//Για να δέχεται μόνο ένα γράμμα
textField.setTextFormatter(new TextFormatter<String>((TextFormatter.Change change) -> {
String newText = change.getControlNewText();
if (newText.length() > 1) {
return null;
} else {
return change;
}
}));
//Ορισμός του πίνακα με τις λέξεις του παιχνιδιού και αντιγραφή σε ένα ArrayList , για την εύκολη ανακάτεψή τους
String[] EnglishWords = {"αγαλλίαση", "Αλόννησος", "αναστήλωση", "ανέγγιχτος", "ανδρεία", "αστοιχείωτος",
"βδελυρός","βερίκοκο", "βυσσοδομώ","γάγγραινα", "γιατρειά", "γλαφυρός", "γλιτώνω ",
"δεισιδαιμονία", "διαπρύσιοι ", "διευκρίνιση", "δοκησίσοφος", "δωσίλογος",
"εγκάθειρκτος", "εκεχειρία", "έκπαγλος", "ελλιπής", "εμπεριστατωμένος","εξαπίνης",
"καταμεσής", "κλαυθμυρίζω", "κνώδαλο", "κομπορρημοσύνη", "κρησφύγετο", "κωδίκελος",
"λέκιθος", "λήκυθος", "λογύδριο", "λυθρίνι", "μεγαλεπήβολος", "μυδράλιο", "μυκτηρίζω",
"νηπενθής", "ξένοιαστος", "φερέγγυος", "χρεοκοπία", "τετριμμένος", "συνονθύλευμα"};
ArrayList<String> Words = new ArrayList<>();
Collections.addAll(Words, EnglishWords);
//Ανακατεύει το ArrayList
Collections.shuffle(Words);
//Αποθήκευση της πρώτης λέξης του σε μία μεταβλητή τύπου String και αφαίρεση από την λίστα
String magicWord = Words.get(0);
Words.remove(0);
// Copy character by character into array
wordsLetters = magicWord.toCharArray();
//Αρχικοποίηση της μεταβλητής για να ξέρουμε πότε ο χρήστης θα βρει την λέξη
counter = wordsLetters.length;
//Για να εμφανίζεται το πρώτο γράμμα της λέξης
word.add(0, String.valueOf(wordsLetters[0]));
wordsLetters[0] = '.';
//Για να εμφανίζονται οι παύλες των γραμμάτων που δεν έχει βρει ο χρήστης
for (int i = 1; i <= wordsLetters.length; i++) {
word.add(" _");
label.setText(label.getText() + word.get(i - 1));
}
}
} | Giannis1273646/Hangman-Game | src/sample/SinglePlayerController.java | 4,870 | //Για να εμφανίζονται οι παύλες των γραμμάτων που δεν έχει βρει ο χρήστης | line_comment | el | package sample;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ResourceBundle;
public class SinglePlayerController implements Initializable {
@FXML
private ComboBox<String> menu;
@FXML
String s = ".";
@FXML
private Label label, label1, label2;
@FXML
private TextField textField;
@FXML
private char[] wordsLetters;
@FXML
ArrayList<String> word = new ArrayList<>();
@FXML
public int counter, tries = 7;
@FXML
private ImageView img;
@FXML
private Button button, playAgainB, menuB;
@FXML
private void menu(ActionEvent event) throws IOException {
//Παίρνει την επιλογή του χρήστη
String choice = menu.getValue();
//Επιστρέφει στο αρχικό μενού
if(choice.equals("Επιστροφή στο κύριο μενού")){
Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene singlePlayerScene = new Scene(singlePlayerParent);
//This line gets the stage information
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(singlePlayerScene);
window.setTitle("Menu");
window.show();
}else{
Platform.exit();
}
}
@FXML
private void getLetters(ActionEvent event){
boolean found = false;
//Παίρνει από το textField το γράμμα που δίνει ο χρήστης
String letter = textField.getText();
textField.clear();
switch (letter){
case "α":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ά".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ε":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "έ".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ι":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ί".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "η":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ή".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "υ":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ύ".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ο":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ό".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
case "ω":
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i])) || "ώ".equals(String.valueOf(wordsLetters[i]))){
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,String.valueOf(wordsLetters[i]));
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
break;
default:
for(int i = 0; i< wordsLetters.length; i++) {
if (letter.equals(String.valueOf(wordsLetters[i]))) {
//Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης
word.set(i,letter);
//‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση
wordsLetters[i] ='.';
counter--;
found = true;
}
}
}
//Άμα δεν έχει βρεθεί το γράμμα το εμφανίζει στα γράμματα που έχουν χρησιμοποιηθεί και αφαιρεί μία ζωή
if (!found){
label1.setText(label1.getText() + letter +" ,");
tries--;
}
//Εμφανίζει τα γράμματα στο label από το ArrayList word
label.setText("");
for (int i = 0; i< wordsLetters.length; i++){
label.setText(label.getText() + word.get(i));
}
//Εμφανίζει το ανθρωπάκι μέσω εικόνων
switch (tries){
case 6:
img.setImage(new Image("resources/try2.png"));
break;
case 5:
img.setImage(new Image("resources/try3.png"));
break;
case 4:
img.setImage(new Image("resources/try4.png"));
break;
case 3:
img.setImage(new Image("resources/try5.png"));
break;
case 2:
img.setImage(new Image("resources/try6.png"));
break;
case 1:
img.setImage(new Image("resources/try7.png"));
break;
case 0:
//Αν τελειώσουν οι προσπάθειες το πρόγραμμα τερματίζει
label.setText("");
//Για να εμφανίζεται η λέξη όταν χάσει ο παίκτης
for (int i=0; i<wordsLetters.length; i++){
if(s.equals(String.valueOf(wordsLetters[i]))){
label.setText(label.getText() + word.get(i));
}else {
label.setText(label.getText() + wordsLetters[i]);
}
}
//Εμφανίζονται κάποιες επιπλέον επιλογές αφού έχει τελειώσει το πρόγραμμα
label2.setVisible(true);
textField.setEditable(false);
button.setVisible(false);
playAgainB.setVisible(true);
menuB.setVisible(true);
break;
}
//Αφορά την στιγμή που ο χρήστης βρίσκει την λέξη
if (counter==1){
label2.setText("You Won");
label2.setVisible(true);
textField.setEditable(false);
button.setVisible(false);
playAgainB.setVisible(true);
menuB.setVisible(true);
}
}
@FXML //Ξεκινάει το πρόγραμμα από την αρχή
private void playAgain(ActionEvent event) throws IOException {
Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("SinglePlayer.fxml"));
Scene singlePlayerScene = new Scene(singlePlayerParent,683, 373.6);
//This line gets the stage information
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(singlePlayerScene);
window.setTitle("Single Player");
window.show();
}
@FXML //Επιστρέφει στο μενού
private void returnMenu(ActionEvent event) throws IOException {
Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene singlePlayerScene = new Scene(singlePlayerParent);
//This line gets the stage information
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(singlePlayerScene);
window.setTitle("Menu");
window.show();
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
menu.getItems().addAll("Επιστροφή στο κύριο μενού", "Έξοδος");
label2.setVisible(false);
playAgainB.setVisible(false);
menuB.setVisible(false);
//Για να δέχεται γράμματα Ελληνικά με τόνους και Αγγλικά
textField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\sα-ωΑ-Ωά-ώ*")) {
textField.setText(newValue.replaceAll("[^\\sA-Zά-ώ]", ""));
}
});
//Για να δέχεται μόνο ένα γράμμα
textField.setTextFormatter(new TextFormatter<String>((TextFormatter.Change change) -> {
String newText = change.getControlNewText();
if (newText.length() > 1) {
return null;
} else {
return change;
}
}));
//Ορισμός του πίνακα με τις λέξεις του παιχνιδιού και αντιγραφή σε ένα ArrayList , για την εύκολη ανακάτεψή τους
String[] EnglishWords = {"αγαλλίαση", "Αλόννησος", "αναστήλωση", "ανέγγιχτος", "ανδρεία", "αστοιχείωτος",
"βδελυρός","βερίκοκο", "βυσσοδομώ","γάγγραινα", "γιατρειά", "γλαφυρός", "γλιτώνω ",
"δεισιδαιμονία", "διαπρύσιοι ", "διευκρίνιση", "δοκησίσοφος", "δωσίλογος",
"εγκάθειρκτος", "εκεχειρία", "έκπαγλος", "ελλιπής", "εμπεριστατωμένος","εξαπίνης",
"καταμεσής", "κλαυθμυρίζω", "κνώδαλο", "κομπορρημοσύνη", "κρησφύγετο", "κωδίκελος",
"λέκιθος", "λήκυθος", "λογύδριο", "λυθρίνι", "μεγαλεπήβολος", "μυδράλιο", "μυκτηρίζω",
"νηπενθής", "ξένοιαστος", "φερέγγυος", "χρεοκοπία", "τετριμμένος", "συνονθύλευμα"};
ArrayList<String> Words = new ArrayList<>();
Collections.addAll(Words, EnglishWords);
//Ανακατεύει το ArrayList
Collections.shuffle(Words);
//Αποθήκευση της πρώτης λέξης του σε μία μεταβλητή τύπου String και αφαίρεση από την λίστα
String magicWord = Words.get(0);
Words.remove(0);
// Copy character by character into array
wordsLetters = magicWord.toCharArray();
//Αρχικοποίηση της μεταβλητής για να ξέρουμε πότε ο χρήστης θα βρει την λέξη
counter = wordsLetters.length;
//Για να εμφανίζεται το πρώτο γράμμα της λέξης
word.add(0, String.valueOf(wordsLetters[0]));
wordsLetters[0] = '.';
//Γι<SUF>
for (int i = 1; i <= wordsLetters.length; i++) {
word.add(" _");
label.setText(label.getText() + word.get(i - 1));
}
}
} |
2923_1 | package sample;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Optional;
public class Controller{
@FXML
private Button button1, button2, button3, button4, button5, button6, button7, button8, button9;
@FXML
int playerTurn = 0, counter = 0;
@FXML//Καθορίζει πότε θα τυπώνετε το χ και πότε ο
private void setText(Button button){
if(playerTurn % 2 == 0){
//Ορίζει το χρώμα από το χ
button.setStyle("-fx-text-fill: #2229EE");
//τυπώνει το χ πάνω στο κουμπί
button.setText("X");
playerTurn = 1;
}else {
button.setStyle("-fx-text-fill: #EA1B1B");
button.setText("O");
playerTurn = 0;
}
}
@FXML
private void game(ActionEvent event) throws IOException{
//Αναγνωρίζει πιο κουμπί πατήθηκε και ορίζει το κατάλληλο γράμμα
if(event.getSource() == button1){
setText(button1);
button1.setDisable(true);
}else if(event.getSource() == button2){
setText(button2);
button2.setDisable(true);
}else if(event.getSource()== button3){
setText(button3);
button3.setDisable(true);
}else if(event.getSource()== button4){
setText(button4);
button4.setDisable(true);
}else if(event.getSource()== button5){
setText(button5);
button5.setDisable(true);
}else if(event.getSource()== button6){
setText(button6);
button6.setDisable(true);
}else if(event.getSource()== button7){
setText(button7);
button7.setDisable(true);
}else if(event.getSource()== button8){
setText(button8);
button8.setDisable(true);
}else if(event.getSource()== button9) {
setText(button9);
button9.setDisable(true);
}
//Κάνει ελέγχους για το αν έχει δημιουργηθεί τρίλιζα. Εαν ναι εμφανίζει τον νικητή με ανάλογο μήνυμα
if((button1.getText() + button2.getText() + button3.getText()).equals("XXX") ||
(button1.getText() + button2.getText() + button3.getText()).equals("OOO")){
showMessage(event, button1);
}else if ((button4.getText() + button5.getText() + button6.getText()).equals("XXX") ||
(button4.getText() + button5.getText() + button6.getText()).equals("OOO")){
showMessage(event, button4);
}else if ((button7.getText() + button8.getText() + button9.getText()).equals("XXX") ||
(button7.getText() + button8.getText() + button9.getText()).equals("OOO")){
showMessage(event, button7);
}else if ((button1.getText() + button4.getText() + button7.getText()).equals("XXX") ||
(button1.getText() + button4.getText() + button7.getText()).equals("OOO")){
showMessage(event, button1);
}else if ((button2.getText() + button5.getText() + button8.getText()).equals("XXX") ||
(button2.getText() + button5.getText() + button8.getText()).equals("OOO")){
showMessage(event, button2);
}else if ((button3.getText() + button6.getText() + button9.getText()).equals("XXX") ||
(button3.getText() + button6.getText() + button9.getText()).equals("OOO")){
showMessage(event, button3);
}else if ((button1.getText() + button5.getText() + button9.getText()).equals("XXX") ||
(button1.getText() + button5.getText() + button9.getText()).equals("OOO")){
showMessage(event, button1);
}else if ((button3.getText() + button5.getText() + button7.getText()).equals("XXX") ||
(button3.getText() + button5.getText() + button7.getText()).equals("OOO")){
showMessage(event, button3);
}
//Για να ξέρουμε πότε το παιχνίδι βγαίνει ισοπαλία
counter++;
if(counter == 9){
Button draw = new Button();
draw.setText("draw");
showMessage(event, draw);
}
}
@FXML
private void showMessage(ActionEvent event, Button button) throws IOException{
//Δημιουργεί τα κουμπιά στο Alert
ButtonType playAgain = new ButtonType("Play again");
ButtonType exit = new ButtonType("Exit");
//Δημιουργεί το Alert
Alert a = new Alert(Alert.AlertType.INFORMATION, "", playAgain, exit);
a.setTitle("Game over!");
//Για να εμφανίζει το κατάλληλο μήνυμα
if (button.getText().equals("draw")){
a.setHeaderText("Draw!!!");
}else {
a.setHeaderText(button.getText() + " wins!!!");
}
//Δίνει λειτουργικότητα στα κουμπιά του Alert
Optional<ButtonType> result = a.showAndWait();
if(!result.isPresent()) {
Platform.exit();
}else if(result.get() == playAgain) {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Stage primaryStage = (Stage)((Node)event.getSource()).getScene().getWindow();
primaryStage.setTitle("Τρίλιζα");
primaryStage.setScene(new Scene(root, 500, 500));
primaryStage.show();
}else if(result.get() == exit) {
Platform.exit();
}
}
}
| Giannis1273646/tic-tac-toe | src/sample/Controller.java | 1,709 | //Ορίζει το χρώμα από το χ | line_comment | el | package sample;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Optional;
public class Controller{
@FXML
private Button button1, button2, button3, button4, button5, button6, button7, button8, button9;
@FXML
int playerTurn = 0, counter = 0;
@FXML//Καθορίζει πότε θα τυπώνετε το χ και πότε ο
private void setText(Button button){
if(playerTurn % 2 == 0){
//Ορ<SUF>
button.setStyle("-fx-text-fill: #2229EE");
//τυπώνει το χ πάνω στο κουμπί
button.setText("X");
playerTurn = 1;
}else {
button.setStyle("-fx-text-fill: #EA1B1B");
button.setText("O");
playerTurn = 0;
}
}
@FXML
private void game(ActionEvent event) throws IOException{
//Αναγνωρίζει πιο κουμπί πατήθηκε και ορίζει το κατάλληλο γράμμα
if(event.getSource() == button1){
setText(button1);
button1.setDisable(true);
}else if(event.getSource() == button2){
setText(button2);
button2.setDisable(true);
}else if(event.getSource()== button3){
setText(button3);
button3.setDisable(true);
}else if(event.getSource()== button4){
setText(button4);
button4.setDisable(true);
}else if(event.getSource()== button5){
setText(button5);
button5.setDisable(true);
}else if(event.getSource()== button6){
setText(button6);
button6.setDisable(true);
}else if(event.getSource()== button7){
setText(button7);
button7.setDisable(true);
}else if(event.getSource()== button8){
setText(button8);
button8.setDisable(true);
}else if(event.getSource()== button9) {
setText(button9);
button9.setDisable(true);
}
//Κάνει ελέγχους για το αν έχει δημιουργηθεί τρίλιζα. Εαν ναι εμφανίζει τον νικητή με ανάλογο μήνυμα
if((button1.getText() + button2.getText() + button3.getText()).equals("XXX") ||
(button1.getText() + button2.getText() + button3.getText()).equals("OOO")){
showMessage(event, button1);
}else if ((button4.getText() + button5.getText() + button6.getText()).equals("XXX") ||
(button4.getText() + button5.getText() + button6.getText()).equals("OOO")){
showMessage(event, button4);
}else if ((button7.getText() + button8.getText() + button9.getText()).equals("XXX") ||
(button7.getText() + button8.getText() + button9.getText()).equals("OOO")){
showMessage(event, button7);
}else if ((button1.getText() + button4.getText() + button7.getText()).equals("XXX") ||
(button1.getText() + button4.getText() + button7.getText()).equals("OOO")){
showMessage(event, button1);
}else if ((button2.getText() + button5.getText() + button8.getText()).equals("XXX") ||
(button2.getText() + button5.getText() + button8.getText()).equals("OOO")){
showMessage(event, button2);
}else if ((button3.getText() + button6.getText() + button9.getText()).equals("XXX") ||
(button3.getText() + button6.getText() + button9.getText()).equals("OOO")){
showMessage(event, button3);
}else if ((button1.getText() + button5.getText() + button9.getText()).equals("XXX") ||
(button1.getText() + button5.getText() + button9.getText()).equals("OOO")){
showMessage(event, button1);
}else if ((button3.getText() + button5.getText() + button7.getText()).equals("XXX") ||
(button3.getText() + button5.getText() + button7.getText()).equals("OOO")){
showMessage(event, button3);
}
//Για να ξέρουμε πότε το παιχνίδι βγαίνει ισοπαλία
counter++;
if(counter == 9){
Button draw = new Button();
draw.setText("draw");
showMessage(event, draw);
}
}
@FXML
private void showMessage(ActionEvent event, Button button) throws IOException{
//Δημιουργεί τα κουμπιά στο Alert
ButtonType playAgain = new ButtonType("Play again");
ButtonType exit = new ButtonType("Exit");
//Δημιουργεί το Alert
Alert a = new Alert(Alert.AlertType.INFORMATION, "", playAgain, exit);
a.setTitle("Game over!");
//Για να εμφανίζει το κατάλληλο μήνυμα
if (button.getText().equals("draw")){
a.setHeaderText("Draw!!!");
}else {
a.setHeaderText(button.getText() + " wins!!!");
}
//Δίνει λειτουργικότητα στα κουμπιά του Alert
Optional<ButtonType> result = a.showAndWait();
if(!result.isPresent()) {
Platform.exit();
}else if(result.get() == playAgain) {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Stage primaryStage = (Stage)((Node)event.getSource()).getScene().getWindow();
primaryStage.setTitle("Τρίλιζα");
primaryStage.setScene(new Scene(root, 500, 500));
primaryStage.show();
}else if(result.get() == exit) {
Platform.exit();
}
}
}
|
2767_2 | //CompensationRepository.java
// Το πακετο JpaRepository βοηθαει την διαχειριση του compensation στην βαση δεδομενων, δεν χρειαζεται κατι περαιτερω
package com.example.demo.repository;
import com.example.demo.model.Compensation;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CompensationRepository extends JpaRepository<Compensation, Long> {
}
// ΠΕΡΙΜΕΝΕ, ΜΗΝ ΞΕΚΙΝΗΣΕΙΣ ΤΗΝ ΑΝΑΠΤΥΞΗ ΑΚΟΜΑ. ΕΧΕΙ ΚΙΑΛΛΑ ΚΟΜΜΑΤΙΑ ΚΩΔΙΚΑ. | GiannisNtz01/farmers | demo/src/main/java/com/example/demo/repository/CompensationRepository.java | 279 | // ΠΕΡΙΜΕΝΕ, ΜΗΝ ΞΕΚΙΝΗΣΕΙΣ ΤΗΝ ΑΝΑΠΤΥΞΗ ΑΚΟΜΑ. ΕΧΕΙ ΚΙΑΛΛΑ ΚΟΜΜΑΤΙΑ ΚΩΔΙΚΑ. | line_comment | el | //CompensationRepository.java
// Το πακετο JpaRepository βοηθαει την διαχειριση του compensation στην βαση δεδομενων, δεν χρειαζεται κατι περαιτερω
package com.example.demo.repository;
import com.example.demo.model.Compensation;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CompensationRepository extends JpaRepository<Compensation, Long> {
}
// ΠΕ<SUF> |
20353_2 | /*
* 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 SoftwareEngineering;
import java.time.LocalDateTime;
import java.util.ArrayList;
/**
*
* @author DeRed
*/
public class Schedule {
private ArrayList<Appointment> appointment_list;
public Schedule(){
this.appointment_list = new ArrayList<Appointment>();
}
public boolean AddAppointment(int doctorID, Patient p, LocalDateTime d){
// ΔΗΜΙΟΥΡΓΙΑ ΕΝΟΣ TMP APPOINTMENT
Appointment tmp = new Appointment(p,d,doctorID);
// ΕΛΕΓΧΟΣ ΕΑΝ ΜΠΟΡΕΙ ΝΑ ΜΠΕΙ ΣΤΟ ΠΡΟΓΡΑΜΜΑ
for ( Appointment booking : this.appointment_list ){
if (booking.getDate() == tmp.getDate())
return false; //ΥΠΑΡΧΕΙ ΗΔΗ ΚΑΠΟΙΟ ΡΑΝΤΕΒΟΥ
}
// ΕΙΣΑΓΩΓΗ ΤΟΥ ΡΑΝΤΕΒΟΥ ΕΦΟΣΟΝ ΓΙΝΕΤΕ
this.appointment_list.add(tmp);
return true;
}
}
| GiannisP97/Medical_office_2018 | Medical_office/src/SoftwareEngineering/Schedule.java | 411 | // ΔΗΜΙΟΥΡΓΙΑ ΕΝΟΣ TMP APPOINTMENT
| line_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 SoftwareEngineering;
import java.time.LocalDateTime;
import java.util.ArrayList;
/**
*
* @author DeRed
*/
public class Schedule {
private ArrayList<Appointment> appointment_list;
public Schedule(){
this.appointment_list = new ArrayList<Appointment>();
}
public boolean AddAppointment(int doctorID, Patient p, LocalDateTime d){
// ΔΗ<SUF>
Appointment tmp = new Appointment(p,d,doctorID);
// ΕΛΕΓΧΟΣ ΕΑΝ ΜΠΟΡΕΙ ΝΑ ΜΠΕΙ ΣΤΟ ΠΡΟΓΡΑΜΜΑ
for ( Appointment booking : this.appointment_list ){
if (booking.getDate() == tmp.getDate())
return false; //ΥΠΑΡΧΕΙ ΗΔΗ ΚΑΠΟΙΟ ΡΑΝΤΕΒΟΥ
}
// ΕΙΣΑΓΩΓΗ ΤΟΥ ΡΑΝΤΕΒΟΥ ΕΦΟΣΟΝ ΓΙΝΕΤΕ
this.appointment_list.add(tmp);
return true;
}
}
|
16379_4 | /*
*Copyright.....
*/
package gr.aueb.elearn.ch1;
/**
* υπολογιζει και εμφανιζει το αθροισμα 2 αριθμων του 12 και του 5
*/
public class DataDemo {
public static void main(String[] args) {
//Δηλωση αρχικοποιηση μεταβλητων
int num1 = 12;
int num2 = 5;
int sum;
//Εντολες
sum = num1 + num2;
//Εκτυπωση αποτελεσματων
System.out.println("Το αθροισμα ειναι" + sum);
}
}
| GioNik7/java-jr-to-mid-level | chapter1/DataDemo.java | 227 | //Εκτυπωση αποτελεσματων
| line_comment | el | /*
*Copyright.....
*/
package gr.aueb.elearn.ch1;
/**
* υπολογιζει και εμφανιζει το αθροισμα 2 αριθμων του 12 και του 5
*/
public class DataDemo {
public static void main(String[] args) {
//Δηλωση αρχικοποιηση μεταβλητων
int num1 = 12;
int num2 = 5;
int sum;
//Εντολες
sum = num1 + num2;
//Εκ<SUF>
System.out.println("Το αθροισμα ειναι" + sum);
}
}
|
7697_5 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package project_test;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.Serializable;
/**
*
* @author Giorgos Giannopoulos
* @author Ioannis Giannopoulos
*/
public class Game {
// private Refugee _player;
private List<Refugee> players;
// private GiverEntity ngo_bank = new GiverEntity("NGO Bank", 10000);
private GiverEntity ngo_bank;
// private MoneyReceiver ngo_bank;
private ReceiverEntity mafia_bank;
private ReceiverEntity nobody;
private Board gameBoard;
private Square square;
List<Integer> paySquares = Arrays.asList(1, 3, 6, 9, 13, 16, 21, 26, 37);
List<Integer> rollSquares = Arrays.asList(2, 9, 12, 16, 17, 22, 28, 31, 33);
List<Integer> staySquares = Arrays.asList(8, 11, 14, 19, 24, 27, 32, 34);
List<Integer> goToSquares = Arrays.asList(4, 5, 15, 18, 23, 25, 29, 30, 33, 35, 38);
List<Integer> receiveSquares = Arrays.asList(20);
List<Integer> winSquares = Arrays.asList(36,39);
List<Integer> deadSquares = Arrays.asList(10);
public void setNgoBank() {
ngo_bank = new GiverEntity("NGO Bank", 10000);
}
public String getNgoBank() {
return (ngo_bank.toString());
}
public void setMafiaBank() {
mafia_bank = new ReceiverEntity("Mafia Bank", 0);
}
public String getMafiaBank() {
return (mafia_bank.toString());
}
public void setNobodyReceives(){
nobody = new ReceiverEntity("Nobody", 0);
}
public void setBoard() {
gameBoard = new Board();
try {
File file = new File("src\\project_test\\refugeoly-squares.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int number = Integer.parseInt(scanner.nextLine().trim());
String text = scanner.nextLine().trim();
String description = scanner.nextLine().trim();
// Προσθέστε το τετράγωνο στο ταμπλό
square = new Square(number, text, description, gameBoard);
// switch based on square number add the actions to be performed by the player
gameBoard.addSquare(square);
/*
if (square.getNumber() == 7) {
System.out.println("DEBUG: Square number is 7");
ExtraLiveAction extraLiveAction = new ExtraLiveAction();
square.addAction(extraLiveAction);
//IsDeadAction dead = new IsDeadAction();
//square.addAction(dead);
}
*/
// Διαβάστε την κενή γραμμή μεταξύ των τετραγώνων
if (scanner.hasNextLine()) {
scanner.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void setPlayers(int numberOfPlayers) {
if (numberOfPlayers < 1 || numberOfPlayers > 4) {
System.out.println("Invalid number of players. Please choose a number between 1 and 4.");
return;
}
players = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < numberOfPlayers; i++) {
System.out.print("Enter name for player " + (i + 1) + ": ");
String playerName = scanner.nextLine();
Refugee player = new Refugee(playerName, 10000, 0, 0, false, false, false, false);
players.add(player);
}
}
public void playGame() {
setNgoBank();
System.out.println(getNgoBank());
setMafiaBank();
System.out.println(getMafiaBank());
setNobodyReceives();
setBoard();
int numberOfPlayers;
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter the number of players (1 - 4): ");
numberOfPlayers = scanner.nextInt();
if (numberOfPlayers < 1 || numberOfPlayers > 4) {
System.out.println("Invalid number of players. Please choose a number between 1 and 4.");
}
} while (numberOfPlayers < 1 || numberOfPlayers > 4);
scanner.nextLine(); //read the next line
// Set up players
setPlayers(numberOfPlayers);
ExtraLiveAction extraLiveAction = new ExtraLiveAction();
StayAction stay = new StayAction();
int current_square = 0;
int i = 0;
int round;
boolean play_again = true;
// for square 26 where the user choose option B and stays in the same square for two rounds instead of 1 round that's the normal
int doubleStay = 0;
String userInput;
while (!isGameOver(numberOfPlayers)) {
round = i + 1;
System.out.println("\t\tRound " + round);
for (Refugee player : players) {
if (!player.isDead() && !player.getHasWon()) {
System.out.println("\n" + player.getName() + "'s turn: ");
if (!player.isStayed()) {
System.out.println("Press r to roll the dice");
System.out.println("Press s to save the game");
System.out.println("Press l to load a game");
System.out.println("Enter your input: ");
//Scanner scanner = new Scanner(System.in);
userInput = scanner.nextLine();
//System.out.println(userInput);
if (userInput.equalsIgnoreCase("s")) {
saveGame(); // Call the saveGame method
System.out.println("Game saved successfully!");
userInput = "r";
//continue; // Skip the rest of the player's turn
}
if (userInput.equalsIgnoreCase("l")) {
loadGame(); // Call the loadGame method
// Continue the game from the loaded state
continue;
}
if(userInput.equalsIgnoreCase("r")){
// standard dice for the player turn
RollDiceAction diceAction = new RollDiceAction();
// go to square
// valid move, player is moving to the new square
diceAction.act(player);
if(!diceAction.isLegal()){
// the move is not legal, player exceed's square 39 so stay on the same square and break so he doesn't perform any other actions
break;
}
else{
//player move is legal
GoToAction goToAction = new GoToAction(diceAction.diceval);
goToAction.act(player);
play_again = true;
while(play_again){
gameBoard.getSquare(player.getCurrentSquare()); // get text of the square and number
square.clearActions();
play_again = false; //set play_again false and set it true if player get's to roll the dice again
current_square = player.getCurrentSquare();
if (paySquares.contains(current_square)) {
//handle the square 26 actions that have two options after paying the amount
if(current_square == 26){
PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, 1000);
square.addAction(payMoney);
System.out.println("Choose between\nOption A: Pay $1500 to Mafia Bank and roll dice");
System.out.println("Option B: Don’t pay and stay 2 turns");
System.out.println("Enter A or B: ");
//userInput = scanner.nextLine();
boolean validInput = false;
do {
userInput = scanner.nextLine();
if (userInput.equalsIgnoreCase("A")) {
// User chose option A
PayMoneyAction payMoney2 = new PayMoneyAction(player, mafia_bank, 1500);
square.addAction(payMoney2);
square.addAction(diceAction);
square.addAction(goToAction);
play_again = true; // So the player gets the new actions of the box
validInput = true; // Valid input, exit the loop
} else if (userInput.equalsIgnoreCase("B")) {
// User chose option B
square.addAction(stay);
doubleStay = 1; //stay for 2 rounds
validInput = true; // Valid input, exit the loop
} else {
// User entered something other than A or B
System.out.println("Invalid input. Please enter either A or B.\n");
}
} while (!validInput);
}
// handle square 21 where you have lost 1500$ due to theft
else if (current_square == 21) {
PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 1500);
square.addAction(payMoney);
}
else if(current_square == 1){
//the money goes to nobody, not in the Mafia Bank
PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 100);
square.addAction(payMoney);
}
else{
String textForPay = gameBoard.getText(current_square);
// Finding the positions of "Pay" and "$" in the message
int payIndex = textForPay.indexOf("Pay");
int dollarIndex = textForPay.indexOf("$");
//System.out.println("Pay index = " + payIndex);
//System.out.println("Dollar index = " + dollarIndex);
if (payIndex != -1 && dollarIndex != -1) {
String amountStr = "0";
// Check if the dollar sign appears after amount
if (dollarIndex - payIndex > 4) {
// Extracting the amount substring
amountStr = textForPay.substring(payIndex + "Pay".length(),
dollarIndex).trim();
} else {
int endIndex = dollarIndex + 4; // Assuming the maximum amount length is 4 digits
endIndex = Math.min(endIndex, textForPay.length()); // Ensure not to go beyond the
// string length
// Extracting the amount substring when the dollar sign comes before amount
amountStr = textForPay.substring(dollarIndex + 1, endIndex).trim();
}
// Parsing the amount to an integer
try {
int amount = Integer.parseInt(amountStr);
// Creating PayMoneyAction with the extracted amount
//System.out.println("Text for pay is " + textForPay);
PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, amount);
square.addAction(payMoney);
} catch (NumberFormatException e) {
// Handle the case where the amount is not a valid integer
System.out.println("Error: Unable to parse amount from the text");
}
} else {
// Handle the case where "Pay" or "$" is not found in the expected positions
System.out.println("Error: Amount not found in the text");
}
}
}
if (rollSquares.contains(current_square)) {
square.addAction(diceAction);
square.addAction(goToAction);
play_again = true; //so the player get's the new actions of the box
}
if (staySquares.contains(current_square)) {
square.addAction(stay);
}
if (goToSquares.contains(current_square)) {
//manual go to square 5 if player is on square 15
//Text in the refugeoly-squares.txt is : Border Control 2. Back to Border Control 1
//It's missing the square number
if (current_square == 15){
player.setCurrentSquare(5);
square.addAction(goToAction);
}
else{ //other squares with Go to square have in the text the destination square
String textForGoTo = gameBoard.getText(current_square);
// Finding the positions of the opening and closing parentheses
int openParenthesisIndex = textForGoTo.indexOf("(");
int closeParenthesisIndex = textForGoTo.indexOf(")");
// System.out.println("Text for go to is: " + textForGoTo);
if (openParenthesisIndex != -1 && closeParenthesisIndex != -1) {
//System.out.println("openParenthesisIndex: " + openParenthesisIndex);
//System.out.println("closeParenthesisIndex: " + closeParenthesisIndex);
// Parsing the content to check if it's a number or a box number
try {
if(closeParenthesisIndex - openParenthesisIndex < 4){
// Extracting the content inside the parentheses
String contentInsideParentheses = textForGoTo
.substring(openParenthesisIndex + 1, closeParenthesisIndex).trim();
//System.out.println("Content inside parentheses: " +
// contentInsideParentheses);
int destination = Integer.parseInt(contentInsideParentheses);
// Setting the new position for the player
player.setCurrentSquare(destination);
square.addAction(goToAction);
}
else{
// the text inside the parenthesis is (box number)
// so we get rid off box string (3) + 1 for the space
int startIndex = openParenthesisIndex + 4;
// Extracting the content inside the parentheses
String contentInsideParentheses = textForGoTo
.substring(startIndex, closeParenthesisIndex).trim();
//System.out.println("Content inside parentheses: " +
// contentInsideParentheses);
int destination = Integer.parseInt(contentInsideParentheses);
player.setCurrentSquare(destination);
square.addAction(goToAction);
}
} catch (NumberFormatException e) {
// If parsing as an integer fails, treat it as a box number
System.out.println("Error parsing the integer in the parenthesis");
}
} else {
// Handle the case where "(" or ")" is not found in the expected positions
System.out.println("Error: Destination number not found in the text");
}
}
}
if (receiveSquares.contains(current_square)) {
ReceiveMoneyAction receiveMoney = new ReceiveMoneyAction(ngo_bank, player, 1000);
square.addAction(receiveMoney);
}
if (current_square == 7) {
square.addAction(extraLiveAction);
}
if (winSquares.contains(current_square)){
System.out.println("You did it!!!\nYou won the game!!!");
player.setHasWon(true);
}
if (deadSquares.contains(current_square)){
if(player.hasExtraLife()){
System.out.println(player.getName()+ " is saved because he has an extra life");
player.setExtraLife(false);
}
else{
IsDeadAction dead = new IsDeadAction();
square.addAction(dead);
}
}
square.act(player);
}
}
}
System.out.println(player.getCurrentSquare());
System.out.println(player.toString());
System.out.println(getNgoBank());
System.out.println(getMafiaBank());
System.out.println("---------------------------------------------------------------");
}
else if (player.isStayed()) {
System.out.println("Player " + player.getName()
+ " has lost his turn in the previous round and so he is not playing right now");
// handle the square 26 option B when user stays for 2 turns in the same square
if(doubleStay <= 0){
player.setStayed(false); // set the player to play next round
doubleStay = 0;
}
else{
doubleStay -= 1;
}
}
}
}
++i;
}
System.out.println("\n\n---------------------Game Finished---------------------");
// Print the player status if he won or not
for(Refugee player : players){
if(player.getHasWon()){
System.out.println("Player: " + player.getName() + " managed to survive and found a new home and spend " + player.getExpenses() + "$ in his journey");
}
else{
System.out.println("Player: " + player.getName() + " didn't managed to survive");
}
}
System.out.println("\nThank you for playing Refugeoly!!!");
scanner.close();
}
public boolean isGameOver(int numberOfPlayers) {
int i = 0;
for(Refugee player : players){
if(player.isDead() || player.getHasWon()){
++i;
}
}
if(i == numberOfPlayers){
return true;
}
else{
return false;
}
}
public void saveGame() {
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("savedGame.ser"))) {
// Serialize the game state
GameData gameData = new GameData(players, ngo_bank.getMoney(), mafia_bank.getMoney(), gameBoard);
outputStream.writeObject(gameData);
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadGame() {
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("savedGame.ser"))) {
// Deserialize the game state
GameData loadedGameData = (GameData) inputStream.readObject();
// Update the game state based on the loaded data
players = loadedGameData.getPlayers();
ngo_bank.setMoney(loadedGameData.getNgoBank());
mafia_bank.setMoney(loadedGameData.getMafiaBank());
System.out.println("Game loaded successfully!");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| GiorgosG1an/Refugeoly | src/project_test/Game.java | 4,385 | // Προσθέστε το τετράγωνο στο ταμπλό | line_comment | el | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package project_test;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.Serializable;
/**
*
* @author Giorgos Giannopoulos
* @author Ioannis Giannopoulos
*/
public class Game {
// private Refugee _player;
private List<Refugee> players;
// private GiverEntity ngo_bank = new GiverEntity("NGO Bank", 10000);
private GiverEntity ngo_bank;
// private MoneyReceiver ngo_bank;
private ReceiverEntity mafia_bank;
private ReceiverEntity nobody;
private Board gameBoard;
private Square square;
List<Integer> paySquares = Arrays.asList(1, 3, 6, 9, 13, 16, 21, 26, 37);
List<Integer> rollSquares = Arrays.asList(2, 9, 12, 16, 17, 22, 28, 31, 33);
List<Integer> staySquares = Arrays.asList(8, 11, 14, 19, 24, 27, 32, 34);
List<Integer> goToSquares = Arrays.asList(4, 5, 15, 18, 23, 25, 29, 30, 33, 35, 38);
List<Integer> receiveSquares = Arrays.asList(20);
List<Integer> winSquares = Arrays.asList(36,39);
List<Integer> deadSquares = Arrays.asList(10);
public void setNgoBank() {
ngo_bank = new GiverEntity("NGO Bank", 10000);
}
public String getNgoBank() {
return (ngo_bank.toString());
}
public void setMafiaBank() {
mafia_bank = new ReceiverEntity("Mafia Bank", 0);
}
public String getMafiaBank() {
return (mafia_bank.toString());
}
public void setNobodyReceives(){
nobody = new ReceiverEntity("Nobody", 0);
}
public void setBoard() {
gameBoard = new Board();
try {
File file = new File("src\\project_test\\refugeoly-squares.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int number = Integer.parseInt(scanner.nextLine().trim());
String text = scanner.nextLine().trim();
String description = scanner.nextLine().trim();
// Πρ<SUF>
square = new Square(number, text, description, gameBoard);
// switch based on square number add the actions to be performed by the player
gameBoard.addSquare(square);
/*
if (square.getNumber() == 7) {
System.out.println("DEBUG: Square number is 7");
ExtraLiveAction extraLiveAction = new ExtraLiveAction();
square.addAction(extraLiveAction);
//IsDeadAction dead = new IsDeadAction();
//square.addAction(dead);
}
*/
// Διαβάστε την κενή γραμμή μεταξύ των τετραγώνων
if (scanner.hasNextLine()) {
scanner.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void setPlayers(int numberOfPlayers) {
if (numberOfPlayers < 1 || numberOfPlayers > 4) {
System.out.println("Invalid number of players. Please choose a number between 1 and 4.");
return;
}
players = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < numberOfPlayers; i++) {
System.out.print("Enter name for player " + (i + 1) + ": ");
String playerName = scanner.nextLine();
Refugee player = new Refugee(playerName, 10000, 0, 0, false, false, false, false);
players.add(player);
}
}
public void playGame() {
setNgoBank();
System.out.println(getNgoBank());
setMafiaBank();
System.out.println(getMafiaBank());
setNobodyReceives();
setBoard();
int numberOfPlayers;
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter the number of players (1 - 4): ");
numberOfPlayers = scanner.nextInt();
if (numberOfPlayers < 1 || numberOfPlayers > 4) {
System.out.println("Invalid number of players. Please choose a number between 1 and 4.");
}
} while (numberOfPlayers < 1 || numberOfPlayers > 4);
scanner.nextLine(); //read the next line
// Set up players
setPlayers(numberOfPlayers);
ExtraLiveAction extraLiveAction = new ExtraLiveAction();
StayAction stay = new StayAction();
int current_square = 0;
int i = 0;
int round;
boolean play_again = true;
// for square 26 where the user choose option B and stays in the same square for two rounds instead of 1 round that's the normal
int doubleStay = 0;
String userInput;
while (!isGameOver(numberOfPlayers)) {
round = i + 1;
System.out.println("\t\tRound " + round);
for (Refugee player : players) {
if (!player.isDead() && !player.getHasWon()) {
System.out.println("\n" + player.getName() + "'s turn: ");
if (!player.isStayed()) {
System.out.println("Press r to roll the dice");
System.out.println("Press s to save the game");
System.out.println("Press l to load a game");
System.out.println("Enter your input: ");
//Scanner scanner = new Scanner(System.in);
userInput = scanner.nextLine();
//System.out.println(userInput);
if (userInput.equalsIgnoreCase("s")) {
saveGame(); // Call the saveGame method
System.out.println("Game saved successfully!");
userInput = "r";
//continue; // Skip the rest of the player's turn
}
if (userInput.equalsIgnoreCase("l")) {
loadGame(); // Call the loadGame method
// Continue the game from the loaded state
continue;
}
if(userInput.equalsIgnoreCase("r")){
// standard dice for the player turn
RollDiceAction diceAction = new RollDiceAction();
// go to square
// valid move, player is moving to the new square
diceAction.act(player);
if(!diceAction.isLegal()){
// the move is not legal, player exceed's square 39 so stay on the same square and break so he doesn't perform any other actions
break;
}
else{
//player move is legal
GoToAction goToAction = new GoToAction(diceAction.diceval);
goToAction.act(player);
play_again = true;
while(play_again){
gameBoard.getSquare(player.getCurrentSquare()); // get text of the square and number
square.clearActions();
play_again = false; //set play_again false and set it true if player get's to roll the dice again
current_square = player.getCurrentSquare();
if (paySquares.contains(current_square)) {
//handle the square 26 actions that have two options after paying the amount
if(current_square == 26){
PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, 1000);
square.addAction(payMoney);
System.out.println("Choose between\nOption A: Pay $1500 to Mafia Bank and roll dice");
System.out.println("Option B: Don’t pay and stay 2 turns");
System.out.println("Enter A or B: ");
//userInput = scanner.nextLine();
boolean validInput = false;
do {
userInput = scanner.nextLine();
if (userInput.equalsIgnoreCase("A")) {
// User chose option A
PayMoneyAction payMoney2 = new PayMoneyAction(player, mafia_bank, 1500);
square.addAction(payMoney2);
square.addAction(diceAction);
square.addAction(goToAction);
play_again = true; // So the player gets the new actions of the box
validInput = true; // Valid input, exit the loop
} else if (userInput.equalsIgnoreCase("B")) {
// User chose option B
square.addAction(stay);
doubleStay = 1; //stay for 2 rounds
validInput = true; // Valid input, exit the loop
} else {
// User entered something other than A or B
System.out.println("Invalid input. Please enter either A or B.\n");
}
} while (!validInput);
}
// handle square 21 where you have lost 1500$ due to theft
else if (current_square == 21) {
PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 1500);
square.addAction(payMoney);
}
else if(current_square == 1){
//the money goes to nobody, not in the Mafia Bank
PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 100);
square.addAction(payMoney);
}
else{
String textForPay = gameBoard.getText(current_square);
// Finding the positions of "Pay" and "$" in the message
int payIndex = textForPay.indexOf("Pay");
int dollarIndex = textForPay.indexOf("$");
//System.out.println("Pay index = " + payIndex);
//System.out.println("Dollar index = " + dollarIndex);
if (payIndex != -1 && dollarIndex != -1) {
String amountStr = "0";
// Check if the dollar sign appears after amount
if (dollarIndex - payIndex > 4) {
// Extracting the amount substring
amountStr = textForPay.substring(payIndex + "Pay".length(),
dollarIndex).trim();
} else {
int endIndex = dollarIndex + 4; // Assuming the maximum amount length is 4 digits
endIndex = Math.min(endIndex, textForPay.length()); // Ensure not to go beyond the
// string length
// Extracting the amount substring when the dollar sign comes before amount
amountStr = textForPay.substring(dollarIndex + 1, endIndex).trim();
}
// Parsing the amount to an integer
try {
int amount = Integer.parseInt(amountStr);
// Creating PayMoneyAction with the extracted amount
//System.out.println("Text for pay is " + textForPay);
PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, amount);
square.addAction(payMoney);
} catch (NumberFormatException e) {
// Handle the case where the amount is not a valid integer
System.out.println("Error: Unable to parse amount from the text");
}
} else {
// Handle the case where "Pay" or "$" is not found in the expected positions
System.out.println("Error: Amount not found in the text");
}
}
}
if (rollSquares.contains(current_square)) {
square.addAction(diceAction);
square.addAction(goToAction);
play_again = true; //so the player get's the new actions of the box
}
if (staySquares.contains(current_square)) {
square.addAction(stay);
}
if (goToSquares.contains(current_square)) {
//manual go to square 5 if player is on square 15
//Text in the refugeoly-squares.txt is : Border Control 2. Back to Border Control 1
//It's missing the square number
if (current_square == 15){
player.setCurrentSquare(5);
square.addAction(goToAction);
}
else{ //other squares with Go to square have in the text the destination square
String textForGoTo = gameBoard.getText(current_square);
// Finding the positions of the opening and closing parentheses
int openParenthesisIndex = textForGoTo.indexOf("(");
int closeParenthesisIndex = textForGoTo.indexOf(")");
// System.out.println("Text for go to is: " + textForGoTo);
if (openParenthesisIndex != -1 && closeParenthesisIndex != -1) {
//System.out.println("openParenthesisIndex: " + openParenthesisIndex);
//System.out.println("closeParenthesisIndex: " + closeParenthesisIndex);
// Parsing the content to check if it's a number or a box number
try {
if(closeParenthesisIndex - openParenthesisIndex < 4){
// Extracting the content inside the parentheses
String contentInsideParentheses = textForGoTo
.substring(openParenthesisIndex + 1, closeParenthesisIndex).trim();
//System.out.println("Content inside parentheses: " +
// contentInsideParentheses);
int destination = Integer.parseInt(contentInsideParentheses);
// Setting the new position for the player
player.setCurrentSquare(destination);
square.addAction(goToAction);
}
else{
// the text inside the parenthesis is (box number)
// so we get rid off box string (3) + 1 for the space
int startIndex = openParenthesisIndex + 4;
// Extracting the content inside the parentheses
String contentInsideParentheses = textForGoTo
.substring(startIndex, closeParenthesisIndex).trim();
//System.out.println("Content inside parentheses: " +
// contentInsideParentheses);
int destination = Integer.parseInt(contentInsideParentheses);
player.setCurrentSquare(destination);
square.addAction(goToAction);
}
} catch (NumberFormatException e) {
// If parsing as an integer fails, treat it as a box number
System.out.println("Error parsing the integer in the parenthesis");
}
} else {
// Handle the case where "(" or ")" is not found in the expected positions
System.out.println("Error: Destination number not found in the text");
}
}
}
if (receiveSquares.contains(current_square)) {
ReceiveMoneyAction receiveMoney = new ReceiveMoneyAction(ngo_bank, player, 1000);
square.addAction(receiveMoney);
}
if (current_square == 7) {
square.addAction(extraLiveAction);
}
if (winSquares.contains(current_square)){
System.out.println("You did it!!!\nYou won the game!!!");
player.setHasWon(true);
}
if (deadSquares.contains(current_square)){
if(player.hasExtraLife()){
System.out.println(player.getName()+ " is saved because he has an extra life");
player.setExtraLife(false);
}
else{
IsDeadAction dead = new IsDeadAction();
square.addAction(dead);
}
}
square.act(player);
}
}
}
System.out.println(player.getCurrentSquare());
System.out.println(player.toString());
System.out.println(getNgoBank());
System.out.println(getMafiaBank());
System.out.println("---------------------------------------------------------------");
}
else if (player.isStayed()) {
System.out.println("Player " + player.getName()
+ " has lost his turn in the previous round and so he is not playing right now");
// handle the square 26 option B when user stays for 2 turns in the same square
if(doubleStay <= 0){
player.setStayed(false); // set the player to play next round
doubleStay = 0;
}
else{
doubleStay -= 1;
}
}
}
}
++i;
}
System.out.println("\n\n---------------------Game Finished---------------------");
// Print the player status if he won or not
for(Refugee player : players){
if(player.getHasWon()){
System.out.println("Player: " + player.getName() + " managed to survive and found a new home and spend " + player.getExpenses() + "$ in his journey");
}
else{
System.out.println("Player: " + player.getName() + " didn't managed to survive");
}
}
System.out.println("\nThank you for playing Refugeoly!!!");
scanner.close();
}
public boolean isGameOver(int numberOfPlayers) {
int i = 0;
for(Refugee player : players){
if(player.isDead() || player.getHasWon()){
++i;
}
}
if(i == numberOfPlayers){
return true;
}
else{
return false;
}
}
public void saveGame() {
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("savedGame.ser"))) {
// Serialize the game state
GameData gameData = new GameData(players, ngo_bank.getMoney(), mafia_bank.getMoney(), gameBoard);
outputStream.writeObject(gameData);
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadGame() {
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("savedGame.ser"))) {
// Deserialize the game state
GameData loadedGameData = (GameData) inputStream.readObject();
// Update the game state based on the loaded data
players = loadedGameData.getPlayers();
ngo_bank.setMoney(loadedGameData.getNgoBank());
mafia_bank.setMoney(loadedGameData.getMafiaBank());
System.out.println("Game loaded successfully!");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
13392_21 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package medlars_collection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.LockObtainFailedException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.store.FSDirectory;
/**
*
* @author Giorgos
*/
public class KnowledgeBase {
public static void main(String args[]) throws CorruptIndexException, IOException, ParseException, LockObtainFailedException, Exception {
try {
System.out.println(parseTerms("Knowledge_Base.xml"));
} catch (Exception ex) {
Logger.getLogger(KnowledgeBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void indexing() throws Exception {
// 0. Specify the analyzer for tokenizing text.
// The same analyzer should be used for indexing and searching
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
String indexLocation = "knowledge";
// 1. create the index
Directory index = FSDirectory.open(new File(indexLocation));
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
IndexWriter writer = new IndexWriter(index, config);
List<Term> terms = parseTerms("Knowledge_Base.xml");
for (Term term : terms) {
addDoc(writer, term.getDef(), term.getIs_a(), term.getSynonym());
}
writer.close();
}
public static ArrayList<String> findSynonyms(String query, int k) throws Exception {
// 0. create the index
//indexing();
// The same analyzer should be used for indexing and searching
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
String indexLocation = "knowledge";
// 1. open the index
Directory index = FSDirectory.open(new File(indexLocation));
// 2. query
Query q = new QueryParser(Version.LUCENE_35, "name", analyzer).parse(query);
// 3. search
IndexReader reader = IndexReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(k, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// 4. display results
//System.out.println("Found: "+ hits.length + "hits");
ArrayList<String> synonyms = new ArrayList<String>();
for (int j = 0; j < hits.length; ++j) {
int docId = hits[j].doc;
org.apache.lucene.document.Document d = searcher.doc(docId);
String syn = d.get("synonym").replace("(", "").replace(")", "").replace(":", "");
synonyms.add(syn.split("#")[0]);
}
searcher.close();
reader.close();
return synonyms;
}
private static void addDoc(IndexWriter writer, String name, String is_a, ArrayList<String> synonyms) throws IOException {
org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document();
Field namefield = new Field("name", name, Field.Store.YES, Field.Index.ANALYZED);
Field is_afield = new Field("is_a", is_a, Field.Store.YES, Field.Index.ANALYZED);
String syn = "";
for (String synonym : synonyms) {
syn += synonym + "#";
}
//remove last #
if (syn.length() > 0) {
syn = syn.substring(0, syn.length() - 1);
}
Field synonymfield = new Field("synonym", syn, Field.Store.YES, Field.Index.ANALYZED);
doc.add(namefield);
doc.add(is_afield);
doc.add(synonymfield);
writer.addDocument(doc);
}
private static List<Term> parseTerms(String fl) throws Exception {
List<Term> terms = new ArrayList<Term>();
//Δημιουργία του DOM XML parser
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Parse fil to DOM Tree
Document doc = dBuilder.parse(fl);
//Διαβάσμα του root κόμβου
Element rootElement = doc.getDocumentElement();
System.out.println("Root element :" + rootElement.getNodeName());
//Παίρνουμε όλα τα elements <user>
NodeList nList = doc.getElementsByTagName("term");
for (int n = 0; n < nList.getLength(); n++) {
Node nNode = nList.item(n);
Element eElement = (Element) nNode;
//Διαβάζουμε τα στοιχεία που βρίσκονται στα tags κάτω από κάθε user
//element
ArrayList<String> namelist = getTagValue("name", eElement);
ArrayList<String> deflist = getTagValue("def", eElement);
ArrayList<String> is_alist = getTagValue("is_a", eElement);
ArrayList<String> synonyms = getTagValue("synonym", eElement);
String name = listToString(namelist);
String def = listToString(deflist);
name += def;
String is_a = listToString(is_alist);
//Δημιουργούμε ένα object Temr με τα στοιχεία που διαβάσαμε
Term term = new Term(name, synonyms, is_a);
terms.add(term);
}
return terms;
}
/***
* Επιστρέφει το κείμενο που βρίσκεται ανάμεσα στo <stag></stag>
*
* @param sTag
* @param eElement το parent node (tag element)
* @return
*/
private static ArrayList<String> getTagValue(String sTag, Element eElement) {
ArrayList<String> output = new ArrayList<String>();
if (eElement.getElementsByTagName(sTag).item(0) != null) {
NodeList nlList;
if (eElement.getElementsByTagName(sTag).getLength() > 1) {
for (int j = 0; j < eElement.getElementsByTagName(sTag).getLength(); j++) {
nlList = eElement.getElementsByTagName(sTag).item(j).getChildNodes();
Node nValue = nlList.item(0);
if (nValue != null) {
output.add(nValue.getNodeValue());
}
}
return output;
} else {
nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = nlList.item(0);
output.add(nValue.getNodeValue());
return output;
}
} else {
return output;
}
}
private static String listToString(List<String> list) {
String output = "";
for (String item : list) {
output = output + " " + item;
}
return output;
}
}
| GiorgosPa/Medlars | java code/KnowledgeBase.java | 2,005 | /***
* Επιστρέφει το κείμενο που βρίσκεται ανάμεσα στo <stag></stag>
*
* @param sTag
* @param eElement το parent node (tag element)
* @return
*/ | block_comment | el | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package medlars_collection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.LockObtainFailedException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.store.FSDirectory;
/**
*
* @author Giorgos
*/
public class KnowledgeBase {
public static void main(String args[]) throws CorruptIndexException, IOException, ParseException, LockObtainFailedException, Exception {
try {
System.out.println(parseTerms("Knowledge_Base.xml"));
} catch (Exception ex) {
Logger.getLogger(KnowledgeBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void indexing() throws Exception {
// 0. Specify the analyzer for tokenizing text.
// The same analyzer should be used for indexing and searching
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
String indexLocation = "knowledge";
// 1. create the index
Directory index = FSDirectory.open(new File(indexLocation));
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
IndexWriter writer = new IndexWriter(index, config);
List<Term> terms = parseTerms("Knowledge_Base.xml");
for (Term term : terms) {
addDoc(writer, term.getDef(), term.getIs_a(), term.getSynonym());
}
writer.close();
}
public static ArrayList<String> findSynonyms(String query, int k) throws Exception {
// 0. create the index
//indexing();
// The same analyzer should be used for indexing and searching
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
String indexLocation = "knowledge";
// 1. open the index
Directory index = FSDirectory.open(new File(indexLocation));
// 2. query
Query q = new QueryParser(Version.LUCENE_35, "name", analyzer).parse(query);
// 3. search
IndexReader reader = IndexReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(k, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// 4. display results
//System.out.println("Found: "+ hits.length + "hits");
ArrayList<String> synonyms = new ArrayList<String>();
for (int j = 0; j < hits.length; ++j) {
int docId = hits[j].doc;
org.apache.lucene.document.Document d = searcher.doc(docId);
String syn = d.get("synonym").replace("(", "").replace(")", "").replace(":", "");
synonyms.add(syn.split("#")[0]);
}
searcher.close();
reader.close();
return synonyms;
}
private static void addDoc(IndexWriter writer, String name, String is_a, ArrayList<String> synonyms) throws IOException {
org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document();
Field namefield = new Field("name", name, Field.Store.YES, Field.Index.ANALYZED);
Field is_afield = new Field("is_a", is_a, Field.Store.YES, Field.Index.ANALYZED);
String syn = "";
for (String synonym : synonyms) {
syn += synonym + "#";
}
//remove last #
if (syn.length() > 0) {
syn = syn.substring(0, syn.length() - 1);
}
Field synonymfield = new Field("synonym", syn, Field.Store.YES, Field.Index.ANALYZED);
doc.add(namefield);
doc.add(is_afield);
doc.add(synonymfield);
writer.addDocument(doc);
}
private static List<Term> parseTerms(String fl) throws Exception {
List<Term> terms = new ArrayList<Term>();
//Δημιουργία του DOM XML parser
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Parse fil to DOM Tree
Document doc = dBuilder.parse(fl);
//Διαβάσμα του root κόμβου
Element rootElement = doc.getDocumentElement();
System.out.println("Root element :" + rootElement.getNodeName());
//Παίρνουμε όλα τα elements <user>
NodeList nList = doc.getElementsByTagName("term");
for (int n = 0; n < nList.getLength(); n++) {
Node nNode = nList.item(n);
Element eElement = (Element) nNode;
//Διαβάζουμε τα στοιχεία που βρίσκονται στα tags κάτω από κάθε user
//element
ArrayList<String> namelist = getTagValue("name", eElement);
ArrayList<String> deflist = getTagValue("def", eElement);
ArrayList<String> is_alist = getTagValue("is_a", eElement);
ArrayList<String> synonyms = getTagValue("synonym", eElement);
String name = listToString(namelist);
String def = listToString(deflist);
name += def;
String is_a = listToString(is_alist);
//Δημιουργούμε ένα object Temr με τα στοιχεία που διαβάσαμε
Term term = new Term(name, synonyms, is_a);
terms.add(term);
}
return terms;
}
/***
* Επι<SUF>*/
private static ArrayList<String> getTagValue(String sTag, Element eElement) {
ArrayList<String> output = new ArrayList<String>();
if (eElement.getElementsByTagName(sTag).item(0) != null) {
NodeList nlList;
if (eElement.getElementsByTagName(sTag).getLength() > 1) {
for (int j = 0; j < eElement.getElementsByTagName(sTag).getLength(); j++) {
nlList = eElement.getElementsByTagName(sTag).item(j).getChildNodes();
Node nValue = nlList.item(0);
if (nValue != null) {
output.add(nValue.getNodeValue());
}
}
return output;
} else {
nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = nlList.item(0);
output.add(nValue.getNodeValue());
return output;
}
} else {
return output;
}
}
private static String listToString(List<String> list) {
String output = "";
for (String item : list) {
output = output + " " + item;
}
return output;
}
}
|
174_13 | package thesis;
import java.awt.Component;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.JPanel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.gmele.general.sheets.XlsxSheet;
/**
* @author Nektarios Gkouvousis
* @author ice18390193
*
* Η κλάση Utilities
*/
public class Utilities {
public Utilities(){
}
/**
* Η συνάρτηση δέχεται ένα string ως παράμετρο και επιστρέφει το string χωρίς
* τόνους στους ελληνικούς χαρακτήρες.
* @param s Το string που θα υποστεί επεξεργασία (String).
* @return Το τροποποιημένο string (String).
*/
public String removeAccents(String s) {
return s.replaceAll("ά", "α")
.replaceAll("έ", "ε")
.replaceAll("ή", "η")
.replaceAll("ί", "ι")
.replaceAll("ό", "ο")
.replaceAll("ύ", "υ")
.replaceAll("ώ", "ω")
.replaceAll("Ά", "Α")
.replaceAll("Έ", "Ε")
.replaceAll("Ή", "Η")
.replaceAll("Ί", "Ι")
.replaceAll("Ό", "Ο")
.replaceAll("Ύ", "Υ")
.replaceAll("Ώ", "Ω");
}
/**
* Συνάρτηση που αλλάζει αυτόματα το μέγεθος των στηλών του φύλλου excel.
* @param sheet Το sheet του οποίου οι στήλες θα αλλάξουν μέγεθος (XSSFSheet).
* @param columns Ο αριθμός των στηλών προς αλλαγή (integer).
*/
public void autoSizeColumns(XSSFSheet sheet, int columns){
for (int i = 0; i <= columns; i++){
sheet.autoSizeColumn(i);
}
}
public boolean checkDate(List<String> dates, String dt){
if(dates.contains(dt))
return true;
return false;
}
public boolean checkTimeslot(List<String> timeslots, String ts){
if(timeslots.contains(ts))
return true;
return false;
}
/**
* Η συνάρτηση εφαρμόζει template στυλ κελιών σε συγκεκριμένες θέσεις
* για να αποτυπώσει το τελικό excel προγράμματος εξετάσεων.
* @param workbook Το αρχείο προς επεξεργασία (XSSFWorkbook).
* @param sheet Το φύλλο προς επεξεργασία (XSSFSheet).
*/
public void applyCellStyles(XSSFWorkbook workbook, XSSFSheet sheet){
int curRow, curCol = 0;
CellStyles cs = new CellStyles();
for (Row row : sheet) {
for (Cell cell : row) {
curRow = cell.getRowIndex();
curCol = cell.getColumnIndex();
if (curRow > 0 && curCol >= 2){
cell.setCellStyle(cs.getFinalScheduleBasicStyle(workbook));
}else if (curRow == 0 && curCol <= 1){
cell.setCellStyle(cs.getDateHeadersStyle(workbook));
}else if (curRow > 0 && curCol < 2){
cell.setCellStyle(cs.getDateValuesStyle(workbook));
}else if (curRow == 0 && curCol > 1){
cell.setCellStyle(cs.getTimeslotsHeadersStyle(workbook));
}
}
}
}
/**
* Συνάρτηση που εντοπίζει εάν υπάρχει ένα string στην λίστα με τα μαθήματα
*
* @param cellValue Το λεκτικό με το όνομα του μαθήματος ή την συντομογραφία
* του (String).
*
* @return Επιστρέφει είτε το αντικείμενο του μαθήματος εάν βρέθηκε (Course), είτε null
* εάν δεν υπάρχει.
*/
public Course getCourse(List<Course> courses, String cellValue){
for (Course tmp : courses){
if (tmp.getCourseName().equals(cellValue) ||
tmp.getCourseShort().equals(cellValue)){
return tmp;
}
}
return null;
}
public ScheduledCourse getScheduledCourse(List<ScheduledCourse> scheduledCourses, Course course){
for(ScheduledCourse crs : scheduledCourses){
if(crs.getCourse().getCourseName().equals(course.getCourseName())){
return crs;
}
}
return null;
}
public String getSafeCellString(XlsxSheet sheet, int rowIndex, int colIndex) {
try {
return sheet.GetCellString(rowIndex, colIndex);
} catch (Exception e) { // Σε περίπτωση που το κελί είναι κενό (null), επιστρέφω ένα κενό string.
return "";
}
}
public String getDateWithGreekFormat(String[] weekdays, String dateStr) {
try {
Locale greekLocale = new Locale("el", "GR");
SimpleDateFormat inputFormatter = new SimpleDateFormat("dd/MM/yyyy EEEE", greekLocale);
// Create a custom DateFormatSymbols with weekdays without accents
DateFormatSymbols customSymbols = new DateFormatSymbols(greekLocale);
customSymbols.setWeekdays(weekdays);
inputFormatter.setDateFormatSymbols(customSymbols);
Date date = inputFormatter.parse(dateStr);
SimpleDateFormat outputFormatter = new SimpleDateFormat("dd/MM/yyyy");
return outputFormatter.format(date);
} catch (ParseException e) {
return null;
}
}
public static String getGreekDayName(String dateStr) {
try {
// Parse the input date string
SimpleDateFormat inputFormatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date date = inputFormatter.parse(dateStr);
// Get the Greek day name without accents and in capital letters
SimpleDateFormat outputFormatter = new SimpleDateFormat("EEEE", new Locale("el", "GR"));
String greekDayName = outputFormatter.format(date).toUpperCase();
return greekDayName;
} catch (ParseException e) {
// Handle parsing exception
e.printStackTrace();
return null;
}
}
public String modifyDate(String inputDate, int daysToModify, char operation) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
LocalDate date = LocalDate.parse(inputDate, formatter);
// Modify the date based on the operation
if (operation == '+') {
date = date.plusDays(daysToModify);
} else if (operation == '-') {
date = date.minusDays(daysToModify);
} else {
return null;
}
return date.format(formatter);
} catch (DateTimeParseException e) {
return null;
}
}
/**
* Η συνάρτηση γεμίζει το τελικό πρόγραμμα εξεταστικής με τα headers
* από τις ημερομηνίες και τα timeslots.
* @param workbook Το αρχείο προς επεξεργασία (XSSFWorkbook).
* @param sheet Το φύλλο προς επεξεργασία (XSSFSheet).
* @param timeslots Η λίστα με τα χρονικά διαστήματα (List<String>).
* @param dates Η λίστα με τις ημερομηνίες εξέτασης (List<String>).
*/
public void fillHeaders(XSSFWorkbook workbook, XSSFSheet sheet, List<String> timeslots, List<String> dates){
CellStyles cs = new CellStyles();
// Προσθήκη των χρονικών διαστημάτων (timeslots) ως headers στις στήλες
Row timeslotRow = sheet.createRow(0);
Cell cell1 = timeslotRow.createCell(0);
Cell cell2 = timeslotRow.createCell(1);
cell1.setCellValue("ΗΜ/ΝΙΑ");
cell2.setCellValue("ΗΜΕΡΑ");
for (int i = 0; i < timeslots.size(); i++) {
Cell cell = timeslotRow.createCell(i + 2);
cell.setCellValue(timeslots.get(i));
cell.setCellStyle(cs.getDateValuesStyle(workbook));
}
// Προσθήκη των ημερομηνιών στις γραμμές της 1ης στήλης
int rowIndex = 1;
for (String tmp : dates) {
Row row = sheet.createRow(rowIndex++);
Cell dayCell = row.createCell(0);
String greekDayName = this.getGreekDayName(tmp);
greekDayName = this.removeAccents(greekDayName);
dayCell.setCellValue(greekDayName.toUpperCase());
Cell dateCell = row.createCell(1);
dateCell.setCellValue(tmp);
}
}
//method to filter out not needed courses.
public List<Course> getValidCourses(List<Course> courses){
List<Course> validCoursesList = new ArrayList<>();
for(Course crs : courses){
if (crs.getApproxStudents() > 0 && crs.getIsExamined() == true){
validCoursesList.add(crs);
}
}
return validCoursesList;
}
public CourseClassroomsPanel findPanelForCourse(Course course, JPanel coursesClassroomsPanelContainer) {
for (Component comp : coursesClassroomsPanelContainer.getComponents()) {
if (comp instanceof CourseClassroomsPanel) {
CourseClassroomsPanel panel = (CourseClassroomsPanel) comp;
if (panel.getScheduledCourse().getCourse().equals(course)) {
return panel;
}
}
}
return null;
}
}
| Gouvo7/Exam-Schedule-Creator | src/thesis/Utilities.java | 2,919 | // Προσθήκη των ημερομηνιών στις γραμμές της 1ης στήλης | line_comment | el | package thesis;
import java.awt.Component;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.JPanel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.gmele.general.sheets.XlsxSheet;
/**
* @author Nektarios Gkouvousis
* @author ice18390193
*
* Η κλάση Utilities
*/
public class Utilities {
public Utilities(){
}
/**
* Η συνάρτηση δέχεται ένα string ως παράμετρο και επιστρέφει το string χωρίς
* τόνους στους ελληνικούς χαρακτήρες.
* @param s Το string που θα υποστεί επεξεργασία (String).
* @return Το τροποποιημένο string (String).
*/
public String removeAccents(String s) {
return s.replaceAll("ά", "α")
.replaceAll("έ", "ε")
.replaceAll("ή", "η")
.replaceAll("ί", "ι")
.replaceAll("ό", "ο")
.replaceAll("ύ", "υ")
.replaceAll("ώ", "ω")
.replaceAll("Ά", "Α")
.replaceAll("Έ", "Ε")
.replaceAll("Ή", "Η")
.replaceAll("Ί", "Ι")
.replaceAll("Ό", "Ο")
.replaceAll("Ύ", "Υ")
.replaceAll("Ώ", "Ω");
}
/**
* Συνάρτηση που αλλάζει αυτόματα το μέγεθος των στηλών του φύλλου excel.
* @param sheet Το sheet του οποίου οι στήλες θα αλλάξουν μέγεθος (XSSFSheet).
* @param columns Ο αριθμός των στηλών προς αλλαγή (integer).
*/
public void autoSizeColumns(XSSFSheet sheet, int columns){
for (int i = 0; i <= columns; i++){
sheet.autoSizeColumn(i);
}
}
public boolean checkDate(List<String> dates, String dt){
if(dates.contains(dt))
return true;
return false;
}
public boolean checkTimeslot(List<String> timeslots, String ts){
if(timeslots.contains(ts))
return true;
return false;
}
/**
* Η συνάρτηση εφαρμόζει template στυλ κελιών σε συγκεκριμένες θέσεις
* για να αποτυπώσει το τελικό excel προγράμματος εξετάσεων.
* @param workbook Το αρχείο προς επεξεργασία (XSSFWorkbook).
* @param sheet Το φύλλο προς επεξεργασία (XSSFSheet).
*/
public void applyCellStyles(XSSFWorkbook workbook, XSSFSheet sheet){
int curRow, curCol = 0;
CellStyles cs = new CellStyles();
for (Row row : sheet) {
for (Cell cell : row) {
curRow = cell.getRowIndex();
curCol = cell.getColumnIndex();
if (curRow > 0 && curCol >= 2){
cell.setCellStyle(cs.getFinalScheduleBasicStyle(workbook));
}else if (curRow == 0 && curCol <= 1){
cell.setCellStyle(cs.getDateHeadersStyle(workbook));
}else if (curRow > 0 && curCol < 2){
cell.setCellStyle(cs.getDateValuesStyle(workbook));
}else if (curRow == 0 && curCol > 1){
cell.setCellStyle(cs.getTimeslotsHeadersStyle(workbook));
}
}
}
}
/**
* Συνάρτηση που εντοπίζει εάν υπάρχει ένα string στην λίστα με τα μαθήματα
*
* @param cellValue Το λεκτικό με το όνομα του μαθήματος ή την συντομογραφία
* του (String).
*
* @return Επιστρέφει είτε το αντικείμενο του μαθήματος εάν βρέθηκε (Course), είτε null
* εάν δεν υπάρχει.
*/
public Course getCourse(List<Course> courses, String cellValue){
for (Course tmp : courses){
if (tmp.getCourseName().equals(cellValue) ||
tmp.getCourseShort().equals(cellValue)){
return tmp;
}
}
return null;
}
public ScheduledCourse getScheduledCourse(List<ScheduledCourse> scheduledCourses, Course course){
for(ScheduledCourse crs : scheduledCourses){
if(crs.getCourse().getCourseName().equals(course.getCourseName())){
return crs;
}
}
return null;
}
public String getSafeCellString(XlsxSheet sheet, int rowIndex, int colIndex) {
try {
return sheet.GetCellString(rowIndex, colIndex);
} catch (Exception e) { // Σε περίπτωση που το κελί είναι κενό (null), επιστρέφω ένα κενό string.
return "";
}
}
public String getDateWithGreekFormat(String[] weekdays, String dateStr) {
try {
Locale greekLocale = new Locale("el", "GR");
SimpleDateFormat inputFormatter = new SimpleDateFormat("dd/MM/yyyy EEEE", greekLocale);
// Create a custom DateFormatSymbols with weekdays without accents
DateFormatSymbols customSymbols = new DateFormatSymbols(greekLocale);
customSymbols.setWeekdays(weekdays);
inputFormatter.setDateFormatSymbols(customSymbols);
Date date = inputFormatter.parse(dateStr);
SimpleDateFormat outputFormatter = new SimpleDateFormat("dd/MM/yyyy");
return outputFormatter.format(date);
} catch (ParseException e) {
return null;
}
}
public static String getGreekDayName(String dateStr) {
try {
// Parse the input date string
SimpleDateFormat inputFormatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date date = inputFormatter.parse(dateStr);
// Get the Greek day name without accents and in capital letters
SimpleDateFormat outputFormatter = new SimpleDateFormat("EEEE", new Locale("el", "GR"));
String greekDayName = outputFormatter.format(date).toUpperCase();
return greekDayName;
} catch (ParseException e) {
// Handle parsing exception
e.printStackTrace();
return null;
}
}
public String modifyDate(String inputDate, int daysToModify, char operation) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
LocalDate date = LocalDate.parse(inputDate, formatter);
// Modify the date based on the operation
if (operation == '+') {
date = date.plusDays(daysToModify);
} else if (operation == '-') {
date = date.minusDays(daysToModify);
} else {
return null;
}
return date.format(formatter);
} catch (DateTimeParseException e) {
return null;
}
}
/**
* Η συνάρτηση γεμίζει το τελικό πρόγραμμα εξεταστικής με τα headers
* από τις ημερομηνίες και τα timeslots.
* @param workbook Το αρχείο προς επεξεργασία (XSSFWorkbook).
* @param sheet Το φύλλο προς επεξεργασία (XSSFSheet).
* @param timeslots Η λίστα με τα χρονικά διαστήματα (List<String>).
* @param dates Η λίστα με τις ημερομηνίες εξέτασης (List<String>).
*/
public void fillHeaders(XSSFWorkbook workbook, XSSFSheet sheet, List<String> timeslots, List<String> dates){
CellStyles cs = new CellStyles();
// Προσθήκη των χρονικών διαστημάτων (timeslots) ως headers στις στήλες
Row timeslotRow = sheet.createRow(0);
Cell cell1 = timeslotRow.createCell(0);
Cell cell2 = timeslotRow.createCell(1);
cell1.setCellValue("ΗΜ/ΝΙΑ");
cell2.setCellValue("ΗΜΕΡΑ");
for (int i = 0; i < timeslots.size(); i++) {
Cell cell = timeslotRow.createCell(i + 2);
cell.setCellValue(timeslots.get(i));
cell.setCellStyle(cs.getDateValuesStyle(workbook));
}
// Πρ<SUF>
int rowIndex = 1;
for (String tmp : dates) {
Row row = sheet.createRow(rowIndex++);
Cell dayCell = row.createCell(0);
String greekDayName = this.getGreekDayName(tmp);
greekDayName = this.removeAccents(greekDayName);
dayCell.setCellValue(greekDayName.toUpperCase());
Cell dateCell = row.createCell(1);
dateCell.setCellValue(tmp);
}
}
//method to filter out not needed courses.
public List<Course> getValidCourses(List<Course> courses){
List<Course> validCoursesList = new ArrayList<>();
for(Course crs : courses){
if (crs.getApproxStudents() > 0 && crs.getIsExamined() == true){
validCoursesList.add(crs);
}
}
return validCoursesList;
}
public CourseClassroomsPanel findPanelForCourse(Course course, JPanel coursesClassroomsPanelContainer) {
for (Component comp : coursesClassroomsPanelContainer.getComponents()) {
if (comp instanceof CourseClassroomsPanel) {
CourseClassroomsPanel panel = (CourseClassroomsPanel) comp;
if (panel.getScheduledCourse().getCourse().equals(course)) {
return panel;
}
}
}
return null;
}
}
|
16406_0 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Αποφασιζει αν θα αναψει τα φωτα ή οχι
* με βαση αν βρεχει , αν ειναι σκωτεινα
* και αν η ταχυτητα ειναι > 100 χιλ
* Τις τιμες τισ δεινει ο χρητσης
*/
public class LightsOnApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isRaining = false;
boolean isDark = false;
int speed = 0;
final int MAX_SPEED = 100;
boolean isRunning = false;
boolean lightsOn = false;
System.out.println("please insert if is raining (true/false)");
isRaining = scanner.nextBoolean();
System.out.println("please insert if is Dark (true/false)");
isDark = scanner.nextBoolean();
System.out.println("please insert car speed ");
speed = scanner.nextInt();
lightsOn = isRaining && (isDark || (speed > MAX_SPEED));
System.out.println("Lights on: " + lightsOn);
}
}
| GregoryPerifanos/Coding-Factory-5-Class-Projects | src/gr/aueb/cf/ch3/LightsOnApp.java | 348 | /**
* Αποφασιζει αν θα αναψει τα φωτα ή οχι
* με βαση αν βρεχει , αν ειναι σκωτεινα
* και αν η ταχυτητα ειναι > 100 χιλ
* Τις τιμες τισ δεινει ο χρητσης
*/ | block_comment | el | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Απο<SUF>*/
public class LightsOnApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isRaining = false;
boolean isDark = false;
int speed = 0;
final int MAX_SPEED = 100;
boolean isRunning = false;
boolean lightsOn = false;
System.out.println("please insert if is raining (true/false)");
isRaining = scanner.nextBoolean();
System.out.println("please insert if is Dark (true/false)");
isDark = scanner.nextBoolean();
System.out.println("please insert car speed ");
speed = scanner.nextInt();
lightsOn = isRaining && (isDark || (speed > MAX_SPEED));
System.out.println("Lights on: " + lightsOn);
}
}
|
6661_1 | package gr.aueb.cf.exercise.preliminary;
public class SumApp {
public static void main(String[] args) {
// Δήλωση ακεραίων
int num1 = 19;
int num2 = 30;
int sum = 0;
// Εντολές
sum = num1 + num2;
//Εκτύπωση αποτελέσματος
System.out.println("Το αποτέλεσμα της πρόσθεσης είναι ίσο με: " + sum);
}
}
| GregoryPerifanos/java-oo-projects | exercise/preliminary/SumApp.java | 170 | // Εντολές | line_comment | el | package gr.aueb.cf.exercise.preliminary;
public class SumApp {
public static void main(String[] args) {
// Δήλωση ακεραίων
int num1 = 19;
int num2 = 30;
int sum = 0;
// Εν<SUF>
sum = num1 + num2;
//Εκτύπωση αποτελέσματος
System.out.println("Το αποτέλεσμα της πρόσθεσης είναι ίσο με: " + sum);
}
}
|
5831_100 | package org.oxford.comlab.perfectref.rewriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import edu.ntua.image.datastructures.Tree;
import edu.ntua.image.datastructures.TreeNode;
public class Saturator_Tree {
private TermFactory m_termFactory;
protected ArrayList<TreeNode<Clause>> m_nodesAddedToTree;
protected ArrayList<Clause> m_unprocessedClauses;
private ArrayList<TreeNode<Clause>> m_unprocessedNodes;
private Map<String,TreeNode<Clause>> m_canonicalsToDAGNodes;
// private Variable lostVariable;
// public Variable getLostVariable() {
// return lostVariable;
// }
private int skolemIndex = 0;;
public Saturator_Tree(TermFactory termFactory) {
m_termFactory = termFactory;
m_unprocessedClauses = new ArrayList<Clause>();
m_nodesAddedToTree = new ArrayList<TreeNode<Clause>>();
m_canonicalsToDAGNodes = new HashMap<String,TreeNode<Clause>>();
}
public Clause getNewQuery(PI pi, int atomIndex, Clause clause){
Term newAtom = null;
Term g = clause.getBody()[atomIndex];
// lostVariable = null;
if(g.getArity() == 1){
Variable var1 = (Variable)g.getArguments()[0];
if(pi.m_right.equals(g.getName()))
switch(pi.m_type){
case 1:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 4:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 7:
// if (clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
return null;
}
// Binary atom
else{
Variable var1 = (Variable)g.getArguments()[0];
Variable var2 = (Variable)g.getArguments()[1];
if(pi.m_right.equals(g.getName())){
if(!clause.isBound(var2))
switch(pi.m_type){
case 2:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
// lostVariable = var2;
break;
case 5:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 8:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else if(!clause.isBound(var1))
switch(pi.m_type){
case 3:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index));
// lostVariable = var1;
break;
case 6:
// if ( clauseContainsVarLargerThan( clause, 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)});
break;
case 9:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var2.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
switch (pi.m_type) {
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
} else
return null;
}
Set<Term> newBody = new LinkedHashSet<Term>();
newBody.add(newAtom);
// Copy the other atoms from the clause
for (int index=0; index < clause.getBody().length; index++)
if (index != atomIndex)
newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory));
// New body and head
Term[] body = new Term[newBody.size()];
newBody.toArray(body);
Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory);
Clause newQuery = new Clause(body, head);
// // Rename variables in resolvent
// ArrayList<Variable> variablesNewQuery = newQuery.getVariables();
//
// HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>();
// for(int i=0; i < variablesNewQuery.size(); i++)
// variableMapping.put(variablesNewQuery.get(i),i);
//
// Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping);
return newQuery;
}
public Clause getNewQueryForIncremental(PI pi, int atomIndex, Clause clause, int localSkolem){
Term newAtom = null;
Term g = clause.getBody()[atomIndex];
// lostVariable = null;
if(g.getArity() == 1){
Variable var1 = (Variable)g.getArguments()[0];
if(pi.m_right.equals(g.getName()))
switch(pi.m_type){
case 1:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 4:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 7:
// if (clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
return null;
}
// Binary atom
else{
Variable var1 = (Variable)g.getArguments()[0];
Variable var2 = (Variable)g.getArguments()[1];
if(pi.m_right.equals(g.getName())){
if(!clause.isBound(var2))
switch(pi.m_type){
case 2:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
// lostVariable = var2;
break;
case 5:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 8:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else if(!clause.isBound(var1))
switch(pi.m_type){
case 3:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index));
// lostVariable = var1;
break;
case 6:
// if ( clauseContainsVarLargerThan( clause, 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(localSkolem))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)});
break;
case 9:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var2.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
switch (pi.m_type) {
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
} else
return null;
}
Set<Term> newBody = new LinkedHashSet<Term>();
newBody.add(newAtom);
// Copy the other atoms from the clause
for (int index=0; index < clause.getBody().length; index++)
if (index != atomIndex)
newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory));
// New body and head
Term[] body = new Term[newBody.size()];
newBody.toArray(body);
Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory);
Clause newQuery = new Clause(body, head);
// // Rename variables in resolvent
// ArrayList<Variable> variablesNewQuery = newQuery.getVariables();
//
// HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>();
// for(int i=0; i < variablesNewQuery.size(); i++)
// variableMapping.put(variablesNewQuery.get(i),i);
//
// Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping);
return newQuery;
}
private boolean clauseContainsVarLargerThan(Clause clause , int max) {
for ( Variable var : clause.getVariables() )
if ( Integer.parseInt( var.toString().substring( 1 , var.toString().length() ) ) >= max )
return true;
return false;
}
/**
* Creates a new query by applying the mgu of two atoms to a given query
*/
private Clause getNewQuery(Substitution mgu, Clause clause){
Set<Term> newBody = new LinkedHashSet<Term>();
//Copy the atoms from the main premise
/*
* CHECK HERE
*
* I arxiki de douleuei swsta me to paradeigma TestABC
*/
for (int index=0; index < clause.getBody().length; index++)
// boolean exists = false;
// for (Iterator<Term> iter = newBody.iterator() ; iter.hasNext() ;)
// if ( iter.next().toString().equals(clause.getBody()[index].apply(mgu, this.m_termFactory).toString()) )
// exists = true;
// if (!exists)
newBody.add(clause.getBody()[index].apply(mgu, this.m_termFactory));
//New body and head
Term[] body = new Term[newBody.size()];
newBody.toArray(body);
Term head = clause.getHead().apply(mgu, this.m_termFactory);
Clause newQuery = new Clause(body, head);
return newQuery;
// Substitution sub = new Substitution();
// //Rename variables in new query
// boolean rename = true;
// ArrayList<Variable> variablesNewQuery = newQuery.getVariables();
// HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>();
// for(int i=0; i < variablesNewQuery.size(); i++) {
// variableMapping.put(variablesNewQuery.get(i), i);
// if ( ( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) ) {
// rename = false;
// return newQuery;
// }
//// if ( !( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) )
//// sub.put(variablesNewQuery.get(i), new Variable( i ) );
// }
//
// Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping);
//
// if ( newQueryRenamed.m_canonicalRepresentation.contains("degreeFrom(X1,X2) ^ headOf(X0,X2)") )
// System.out.println( newQuery + "\t\t" + variableMapping );
//
// //avenet
//// newQueryRenamed.addUnification( sub );
//
// return newQueryRenamed;
}
/**
* Checks if a given clause is contained in m_clausesCanonicals based on its naive canonical representation
*/
public TreeNode<Clause> getEquivalentNodeAlreadyInDAG(TreeNode<Clause> newNode) {
/**
* Option 1
*/
// Node<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation);
// if( nodeInTree !=null )
// return nodeInTree;
/**
* Option 2
*/
TreeNode<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation);
if( nodeInTree !=null )
return nodeInTree;
for (TreeNode<Clause> nodeInRewritingTree : m_nodesAddedToTree)
if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel()))
return nodeInRewritingTree;
/**
* Option 3
*/
// for (Node<Clause> nodeInRewritingTree : m_nodesAddedToTree)
// if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel()))
// return nodeInRewritingTree;
return null;
}
/**
* Η συνάρτηση αυτή δεν περιέχει όλους τους κανόνες που υπάρχουν στην getNewQuery επειδή όταν μας δίνεται ένα άτομο R(x,y) σαν extraAtom τότε μας ενδιαφέρουν να υπάρχουν και οι 2 μεταβλητές.
* Η συνάρτηση αυτή στην refine χρησιμοποιείται σε συνδυασμό με τον έλγχο για το εάν το clause στο οποίο πάμε να κάνουμε refine περιέχει κάποια από τις μεταβλητές που έχει το άτομο (clause)
* που παράγεται από αυτή τη συνάρτηση.
* @param pi
* @param clause
* @return
*/
public Clause getSubsumees(PI pi , Clause clause ){
Term newAtom = null;
Term g = clause.getBody()[0];
int gArity = g.getArity();
String name = g.getName();
if(gArity == 1){
Variable var1 = (Variable)g.getArguments()[0];
if(pi.m_right.equals( name ))
switch(pi.m_type){
case 1:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 4:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)});
break;
case 7:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
return null;
}
else{
Variable var1 = (Variable)g.getArguments()[0];
Variable var2 = (Variable)g.getArguments()[1];
if(pi.m_right.equals( name ))
// if(!clause.isBound(var2)){
switch(pi.m_type){
case 2:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 3:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index));
break;
case 5:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)});
break;
case 6:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(50000)});
break;
case 8:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)});
break;
case 9:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var2.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
// }
}
else
return null;
}
Term [] body = new Term[1];
body[0] = newAtom;
return new Clause ( body, clause.getHead() );
}
public Tree<Clause> saturate(ArrayList<PI> pis, Clause query) {
m_unprocessedNodes = new ArrayList<TreeNode<Clause>>();
TreeNode<Clause> givenNode;
TreeNode<Clause> rootElement = new TreeNode<Clause>( query );
Tree<Clause> rewritingDAG = new Tree<Clause>(rootElement) ;
m_unprocessedNodes.add(rootElement);
while (!m_unprocessedNodes.isEmpty()) {
givenNode = m_unprocessedNodes.remove( 0 );
Clause givenClause = givenNode.getNodeLabel();
// System.out.println( "m_nodesAddedToTree contains " + givenNode.getNodeLabel() + " is " + m_nodesAddedToTree.contains( givenNode ) );
m_nodesAddedToTree.add(givenNode);
for (int i = 0; i < givenClause.getBody().length; i++)
for (PI pi: pis) {
Clause newQuery = getNewQuery(pi, i, givenClause);
if (newQuery!=null) {
TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery );
TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode);
if (nodeInRewritingDAG==null) {
for ( Substitution s : givenNode.getNodeLabel().getUnifications() )
newNode.getNodeLabel().addUnification( s );
givenNode.addChild(newNode);
m_unprocessedNodes.add(newNode);
m_nodesAddedToTree.add(newNode);
m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode);
}
//if commented on june 8th
else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode))
givenNode.addChild( nodeInRewritingDAG );
}
}
for (int i = 0; i < givenClause.getBody().length - 1; i++)
for (int j = i+1; j < givenClause.getBody().length; j++) {
Substitution unifier = Substitution.mostGeneralUnifier(givenClause.getBody()[i], givenClause.getBody()[j], this.m_termFactory);
// System.out.println( "GivenClause = " + givenClause + "\t\tUnifier = " + unifier + "\t\t" + givenClause.getBody()[i] + "\t\t" + givenClause.getBody()[j]);
if (unifier!=null) {
Clause newQuery = getNewQuery(unifier, givenClause);
TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery );
TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode);
if(nodeInRewritingDAG==null) {
for ( Substitution s : givenNode.getNodeLabel().getUnifications() )
newNode.getNodeLabel().addUnification( s );
for ( Entry<Variable,Term> s : unifier.entrySet() ) {
// if ( ! ( Integer.parseInt( s.getKey().toString().substring( 1 , s.getKey().toString().length() ) ) >= 500 || Integer.parseInt( s.getValue().toString().substring( 1 , s.getValue().toString().length() ) ) >= 500 ) ) {
Substitution ns = new Substitution();
ns.put( s.getKey(), s.getValue() );
newNode.getNodeLabel().addUnification( ns );
}
givenNode.addChild( newNode );
m_unprocessedNodes.add( newNode );
m_nodesAddedToTree.add( newNode );
m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode);
}
//if commented on june 8th
else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode))
givenNode.addChild( nodeInRewritingDAG );
}
}
}
return rewritingDAG;
}
} | HBPMedical/MIPMapRew | src/org/oxford/comlab/perfectref/rewriter/Saturator_Tree.java | 7,789 | /**
* Η συνάρτηση αυτή δεν περιέχει όλους τους κανόνες που υπάρχουν στην getNewQuery επειδή όταν μας δίνεται ένα άτομο R(x,y) σαν extraAtom τότε μας ενδιαφέρουν να υπάρχουν και οι 2 μεταβλητές.
* Η συνάρτηση αυτή στην refine χρησιμοποιείται σε συνδυασμό με τον έλγχο για το εάν το clause στο οποίο πάμε να κάνουμε refine περιέχει κάποια από τις μεταβλητές που έχει το άτομο (clause)
* που παράγεται από αυτή τη συνάρτηση.
* @param pi
* @param clause
* @return
*/ | block_comment | el | package org.oxford.comlab.perfectref.rewriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import edu.ntua.image.datastructures.Tree;
import edu.ntua.image.datastructures.TreeNode;
public class Saturator_Tree {
private TermFactory m_termFactory;
protected ArrayList<TreeNode<Clause>> m_nodesAddedToTree;
protected ArrayList<Clause> m_unprocessedClauses;
private ArrayList<TreeNode<Clause>> m_unprocessedNodes;
private Map<String,TreeNode<Clause>> m_canonicalsToDAGNodes;
// private Variable lostVariable;
// public Variable getLostVariable() {
// return lostVariable;
// }
private int skolemIndex = 0;;
public Saturator_Tree(TermFactory termFactory) {
m_termFactory = termFactory;
m_unprocessedClauses = new ArrayList<Clause>();
m_nodesAddedToTree = new ArrayList<TreeNode<Clause>>();
m_canonicalsToDAGNodes = new HashMap<String,TreeNode<Clause>>();
}
public Clause getNewQuery(PI pi, int atomIndex, Clause clause){
Term newAtom = null;
Term g = clause.getBody()[atomIndex];
// lostVariable = null;
if(g.getArity() == 1){
Variable var1 = (Variable)g.getArguments()[0];
if(pi.m_right.equals(g.getName()))
switch(pi.m_type){
case 1:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 4:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 7:
// if (clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
return null;
}
// Binary atom
else{
Variable var1 = (Variable)g.getArguments()[0];
Variable var2 = (Variable)g.getArguments()[1];
if(pi.m_right.equals(g.getName())){
if(!clause.isBound(var2))
switch(pi.m_type){
case 2:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
// lostVariable = var2;
break;
case 5:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 8:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else if(!clause.isBound(var1))
switch(pi.m_type){
case 3:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index));
// lostVariable = var1;
break;
case 6:
// if ( clauseContainsVarLargerThan( clause, 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)});
break;
case 9:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var2.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
switch (pi.m_type) {
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
} else
return null;
}
Set<Term> newBody = new LinkedHashSet<Term>();
newBody.add(newAtom);
// Copy the other atoms from the clause
for (int index=0; index < clause.getBody().length; index++)
if (index != atomIndex)
newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory));
// New body and head
Term[] body = new Term[newBody.size()];
newBody.toArray(body);
Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory);
Clause newQuery = new Clause(body, head);
// // Rename variables in resolvent
// ArrayList<Variable> variablesNewQuery = newQuery.getVariables();
//
// HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>();
// for(int i=0; i < variablesNewQuery.size(); i++)
// variableMapping.put(variablesNewQuery.get(i),i);
//
// Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping);
return newQuery;
}
public Clause getNewQueryForIncremental(PI pi, int atomIndex, Clause clause, int localSkolem){
Term newAtom = null;
Term g = clause.getBody()[atomIndex];
// lostVariable = null;
if(g.getArity() == 1){
Variable var1 = (Variable)g.getArguments()[0];
if(pi.m_right.equals(g.getName()))
switch(pi.m_type){
case 1:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 4:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 7:
// if (clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
return null;
}
// Binary atom
else{
Variable var1 = (Variable)g.getArguments()[0];
Variable var2 = (Variable)g.getArguments()[1];
if(pi.m_right.equals(g.getName())){
if(!clause.isBound(var2))
switch(pi.m_type){
case 2:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
// lostVariable = var2;
break;
case 5:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)});
break;
case 8:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else if(!clause.isBound(var1))
switch(pi.m_type){
case 3:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index));
// lostVariable = var1;
break;
case 6:
// if ( clauseContainsVarLargerThan( clause, 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(localSkolem))});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)});
break;
case 9:
// if ( clauseContainsVarLargerThan( clause , 500 ) )
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var2.m_index)});
// else
// newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
switch (pi.m_type) {
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
} else
return null;
}
Set<Term> newBody = new LinkedHashSet<Term>();
newBody.add(newAtom);
// Copy the other atoms from the clause
for (int index=0; index < clause.getBody().length; index++)
if (index != atomIndex)
newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory));
// New body and head
Term[] body = new Term[newBody.size()];
newBody.toArray(body);
Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory);
Clause newQuery = new Clause(body, head);
// // Rename variables in resolvent
// ArrayList<Variable> variablesNewQuery = newQuery.getVariables();
//
// HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>();
// for(int i=0; i < variablesNewQuery.size(); i++)
// variableMapping.put(variablesNewQuery.get(i),i);
//
// Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping);
return newQuery;
}
private boolean clauseContainsVarLargerThan(Clause clause , int max) {
for ( Variable var : clause.getVariables() )
if ( Integer.parseInt( var.toString().substring( 1 , var.toString().length() ) ) >= max )
return true;
return false;
}
/**
* Creates a new query by applying the mgu of two atoms to a given query
*/
private Clause getNewQuery(Substitution mgu, Clause clause){
Set<Term> newBody = new LinkedHashSet<Term>();
//Copy the atoms from the main premise
/*
* CHECK HERE
*
* I arxiki de douleuei swsta me to paradeigma TestABC
*/
for (int index=0; index < clause.getBody().length; index++)
// boolean exists = false;
// for (Iterator<Term> iter = newBody.iterator() ; iter.hasNext() ;)
// if ( iter.next().toString().equals(clause.getBody()[index].apply(mgu, this.m_termFactory).toString()) )
// exists = true;
// if (!exists)
newBody.add(clause.getBody()[index].apply(mgu, this.m_termFactory));
//New body and head
Term[] body = new Term[newBody.size()];
newBody.toArray(body);
Term head = clause.getHead().apply(mgu, this.m_termFactory);
Clause newQuery = new Clause(body, head);
return newQuery;
// Substitution sub = new Substitution();
// //Rename variables in new query
// boolean rename = true;
// ArrayList<Variable> variablesNewQuery = newQuery.getVariables();
// HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>();
// for(int i=0; i < variablesNewQuery.size(); i++) {
// variableMapping.put(variablesNewQuery.get(i), i);
// if ( ( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) ) {
// rename = false;
// return newQuery;
// }
//// if ( !( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) )
//// sub.put(variablesNewQuery.get(i), new Variable( i ) );
// }
//
// Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping);
//
// if ( newQueryRenamed.m_canonicalRepresentation.contains("degreeFrom(X1,X2) ^ headOf(X0,X2)") )
// System.out.println( newQuery + "\t\t" + variableMapping );
//
// //avenet
//// newQueryRenamed.addUnification( sub );
//
// return newQueryRenamed;
}
/**
* Checks if a given clause is contained in m_clausesCanonicals based on its naive canonical representation
*/
public TreeNode<Clause> getEquivalentNodeAlreadyInDAG(TreeNode<Clause> newNode) {
/**
* Option 1
*/
// Node<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation);
// if( nodeInTree !=null )
// return nodeInTree;
/**
* Option 2
*/
TreeNode<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation);
if( nodeInTree !=null )
return nodeInTree;
for (TreeNode<Clause> nodeInRewritingTree : m_nodesAddedToTree)
if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel()))
return nodeInRewritingTree;
/**
* Option 3
*/
// for (Node<Clause> nodeInRewritingTree : m_nodesAddedToTree)
// if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel()))
// return nodeInRewritingTree;
return null;
}
/**
* Η σ<SUF>*/
public Clause getSubsumees(PI pi , Clause clause ){
Term newAtom = null;
Term g = clause.getBody()[0];
int gArity = g.getArity();
String name = g.getName();
if(gArity == 1){
Variable var1 = (Variable)g.getArguments()[0];
if(pi.m_right.equals( name ))
switch(pi.m_type){
case 1:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 4:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)});
break;
case 7:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
}
else
return null;
}
else{
Variable var1 = (Variable)g.getArguments()[0];
Variable var2 = (Variable)g.getArguments()[1];
if(pi.m_right.equals( name ))
// if(!clause.isBound(var2)){
switch(pi.m_type){
case 2:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index));
break;
case 3:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index));
break;
case 5:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)});
break;
case 6:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(50000)});
break;
case 8:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)});
break;
case 9:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var2.m_index)});
break;
case 10:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)});
break;
case 11:
newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)});
break;
default:
return null;
// }
}
else
return null;
}
Term [] body = new Term[1];
body[0] = newAtom;
return new Clause ( body, clause.getHead() );
}
public Tree<Clause> saturate(ArrayList<PI> pis, Clause query) {
m_unprocessedNodes = new ArrayList<TreeNode<Clause>>();
TreeNode<Clause> givenNode;
TreeNode<Clause> rootElement = new TreeNode<Clause>( query );
Tree<Clause> rewritingDAG = new Tree<Clause>(rootElement) ;
m_unprocessedNodes.add(rootElement);
while (!m_unprocessedNodes.isEmpty()) {
givenNode = m_unprocessedNodes.remove( 0 );
Clause givenClause = givenNode.getNodeLabel();
// System.out.println( "m_nodesAddedToTree contains " + givenNode.getNodeLabel() + " is " + m_nodesAddedToTree.contains( givenNode ) );
m_nodesAddedToTree.add(givenNode);
for (int i = 0; i < givenClause.getBody().length; i++)
for (PI pi: pis) {
Clause newQuery = getNewQuery(pi, i, givenClause);
if (newQuery!=null) {
TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery );
TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode);
if (nodeInRewritingDAG==null) {
for ( Substitution s : givenNode.getNodeLabel().getUnifications() )
newNode.getNodeLabel().addUnification( s );
givenNode.addChild(newNode);
m_unprocessedNodes.add(newNode);
m_nodesAddedToTree.add(newNode);
m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode);
}
//if commented on june 8th
else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode))
givenNode.addChild( nodeInRewritingDAG );
}
}
for (int i = 0; i < givenClause.getBody().length - 1; i++)
for (int j = i+1; j < givenClause.getBody().length; j++) {
Substitution unifier = Substitution.mostGeneralUnifier(givenClause.getBody()[i], givenClause.getBody()[j], this.m_termFactory);
// System.out.println( "GivenClause = " + givenClause + "\t\tUnifier = " + unifier + "\t\t" + givenClause.getBody()[i] + "\t\t" + givenClause.getBody()[j]);
if (unifier!=null) {
Clause newQuery = getNewQuery(unifier, givenClause);
TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery );
TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode);
if(nodeInRewritingDAG==null) {
for ( Substitution s : givenNode.getNodeLabel().getUnifications() )
newNode.getNodeLabel().addUnification( s );
for ( Entry<Variable,Term> s : unifier.entrySet() ) {
// if ( ! ( Integer.parseInt( s.getKey().toString().substring( 1 , s.getKey().toString().length() ) ) >= 500 || Integer.parseInt( s.getValue().toString().substring( 1 , s.getValue().toString().length() ) ) >= 500 ) ) {
Substitution ns = new Substitution();
ns.put( s.getKey(), s.getValue() );
newNode.getNodeLabel().addUnification( ns );
}
givenNode.addChild( newNode );
m_unprocessedNodes.add( newNode );
m_nodesAddedToTree.add( newNode );
m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode);
}
//if commented on june 8th
else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode))
givenNode.addChild( nodeInRewritingDAG );
}
}
}
return rewritingDAG;
}
} |
28838_29 | package com.example.smartalert;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Incident {
private String userEmail;
private String type;
private String comment;
private String timestamp;
private String image;
private String location;
private String status;
// for sorted incidents
// 1. keep incident type
// 2. comments list
// 3. locations lit
// 4. keep timestamp
// 5. photos list
// 6. (new) submission number
private List<String> locations = new ArrayList<>();
private List<String> comments = new ArrayList<>();
private List<String> timestamps = new ArrayList<>();
private List<String> photos = new ArrayList<>();
private List<String> keys = new ArrayList<>();
private List<String> usersEmails = new ArrayList<>();
private int subNumber;
public Incident() {}
public Incident(List<String> keys, List<String> comments, List<String> locations, List<String> timestamps,
List<String> photos, int subNumber, String status){
this.keys = keys;
this.comments = comments;
this.locations = locations;
this.timestamps = timestamps;
this.photos = photos;
this.subNumber = subNumber;
this.status = status;
}
public Incident(String userEmail, String type, String comment, String timestamp,String image,String location) {
this.userEmail = userEmail;
this.type = type;
this.comment = comment;
this.timestamp = timestamp;
this.image=image;
this.location=location;
}
public Incident(List<String> usersEmails, /*String type,*/ String timestamp){
this.usersEmails = usersEmails;
//this.type = type;
this.timestamp = timestamp;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getUserEmail() {return userEmail;}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public List<String> getLocations() {
return locations;
}
public void setLocations(List<String> locations) {
this.locations = locations;
}
public List<String> getComments() {
return comments;
}
public void setComments(List<String> comments) {
this.comments = comments;
}
public List<String> getTimestamps() {
return timestamps;
}
public void setTimestamps(List<String> timestamps) {
this.timestamps = timestamps;
}
public List<String> getPhotos() {
return photos;
}
public void setPhotos(List<String> photos) {
this.photos = photos;
}
public int getSubNumber() {
return subNumber;
}
public void setSubNumber(int subNumber) {
this.subNumber = subNumber;
}
public List<String> getKeys() {return keys;}
public void setKeys(List<String> keys) {this.keys = keys;}
public String getStatus() {return status;}
public void setStatus(String status) {this.status = status;}
public List<String> getUsersEmails() {return usersEmails;}
public void setUsersEmails(List<String> usersEmails) {this.usersEmails = usersEmails;}
static boolean isWithinTimeframe(String prevTimestamp, String timestamp, int hours, int minutes) {
try {
// Define the timestamp format
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss", Locale.getDefault());
// Parse the timestamps into Date objects
Date incidentDate1 = dateFormat.parse(prevTimestamp);
Date incidentDate2 = dateFormat.parse(timestamp);
// Check if the incidents are on different dates
if (!isSameDate(incidentDate1, incidentDate2)) {
return false;
}
// Calculate the difference in minutes
long diffInMinutes = Math.abs(incidentDate1.getTime() - incidentDate2.getTime()) / (60 * 1000);
// Check if the difference is less than the specified number of hours and minutes
return diffInMinutes < (hours * 60 + minutes);
} catch (ParseException e) {
e.printStackTrace();
return false; // Return false in case of an error
}
}
// Helper method to check if two Dates are on the same date
private static boolean isSameDate(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
}
static boolean isWithinDistance(String prevLocation, String location, double distanceKm, double distanceMeters) {
double distance = calculateDistance(prevLocation, location);
return distance <= distanceKm || (distance <= (distanceMeters / 1000.0));
}
private static double calculateDistance(String location1, String location2) {
// Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings
double lat1 = extractCoordinate(location1, "Lat");
//System.out.println("lat1: " + lat1);
double lon1 = extractCoordinate(location1, "Long");
//System.out.println("lon1: " + lon1);
double lat2 = extractCoordinate(location2, "Lat");
double lon2 = extractCoordinate(location2, "Long");
// Υπολογισμός της απόστασης με τον τύπο Haversine
return haversine(lat1, lon1, lat2, lon2);
}
// Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings
private static double extractCoordinate(String location, String coordinateType) {
//String[] parts = location.split(": ")[1].split(", Long: ");
//[1].split(",");
/*double[] parts1 = Arrays.stream(location.replaceAll("[^\\d.,-]", "").split(", "))
.mapToDouble(Double::parseDouble)
.toArray();*/
String[] parts = location.replaceAll("[^\\d.-]+", " ").trim().split("\\s+");
double lat = 0, lon = 0;
// Ensure we have at least two parts
if (parts.length >= 2) {
lat = Double.parseDouble(parts[0]);
lon = Double.parseDouble(parts[1]);
}
//System.out.println("parts: " + Arrays.toString(parts));
//System.out.println("paers[0]: " + parts[1].split(",")[0]);
return coordinateType.equals("Lat") ? lat : lon;
}
// Υπολογισμός της απόστασης με τον τύπο Haversine
private static double haversine(double lat1, double lon1, double lat2, double lon2) {
final int R = 6371; // Ακτίνα της Γης σε χιλιόμετρα
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // Επιστροφή της απόστασης σε χιλιόμετρα
}
}
| HelenPolychroni/SmartAlert | app/src/main/java/com/example/smartalert/Incident.java | 2,106 | // Επιστροφή της απόστασης σε χιλιόμετρα | line_comment | el | package com.example.smartalert;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Incident {
private String userEmail;
private String type;
private String comment;
private String timestamp;
private String image;
private String location;
private String status;
// for sorted incidents
// 1. keep incident type
// 2. comments list
// 3. locations lit
// 4. keep timestamp
// 5. photos list
// 6. (new) submission number
private List<String> locations = new ArrayList<>();
private List<String> comments = new ArrayList<>();
private List<String> timestamps = new ArrayList<>();
private List<String> photos = new ArrayList<>();
private List<String> keys = new ArrayList<>();
private List<String> usersEmails = new ArrayList<>();
private int subNumber;
public Incident() {}
public Incident(List<String> keys, List<String> comments, List<String> locations, List<String> timestamps,
List<String> photos, int subNumber, String status){
this.keys = keys;
this.comments = comments;
this.locations = locations;
this.timestamps = timestamps;
this.photos = photos;
this.subNumber = subNumber;
this.status = status;
}
public Incident(String userEmail, String type, String comment, String timestamp,String image,String location) {
this.userEmail = userEmail;
this.type = type;
this.comment = comment;
this.timestamp = timestamp;
this.image=image;
this.location=location;
}
public Incident(List<String> usersEmails, /*String type,*/ String timestamp){
this.usersEmails = usersEmails;
//this.type = type;
this.timestamp = timestamp;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getUserEmail() {return userEmail;}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public List<String> getLocations() {
return locations;
}
public void setLocations(List<String> locations) {
this.locations = locations;
}
public List<String> getComments() {
return comments;
}
public void setComments(List<String> comments) {
this.comments = comments;
}
public List<String> getTimestamps() {
return timestamps;
}
public void setTimestamps(List<String> timestamps) {
this.timestamps = timestamps;
}
public List<String> getPhotos() {
return photos;
}
public void setPhotos(List<String> photos) {
this.photos = photos;
}
public int getSubNumber() {
return subNumber;
}
public void setSubNumber(int subNumber) {
this.subNumber = subNumber;
}
public List<String> getKeys() {return keys;}
public void setKeys(List<String> keys) {this.keys = keys;}
public String getStatus() {return status;}
public void setStatus(String status) {this.status = status;}
public List<String> getUsersEmails() {return usersEmails;}
public void setUsersEmails(List<String> usersEmails) {this.usersEmails = usersEmails;}
static boolean isWithinTimeframe(String prevTimestamp, String timestamp, int hours, int minutes) {
try {
// Define the timestamp format
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss", Locale.getDefault());
// Parse the timestamps into Date objects
Date incidentDate1 = dateFormat.parse(prevTimestamp);
Date incidentDate2 = dateFormat.parse(timestamp);
// Check if the incidents are on different dates
if (!isSameDate(incidentDate1, incidentDate2)) {
return false;
}
// Calculate the difference in minutes
long diffInMinutes = Math.abs(incidentDate1.getTime() - incidentDate2.getTime()) / (60 * 1000);
// Check if the difference is less than the specified number of hours and minutes
return diffInMinutes < (hours * 60 + minutes);
} catch (ParseException e) {
e.printStackTrace();
return false; // Return false in case of an error
}
}
// Helper method to check if two Dates are on the same date
private static boolean isSameDate(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
}
static boolean isWithinDistance(String prevLocation, String location, double distanceKm, double distanceMeters) {
double distance = calculateDistance(prevLocation, location);
return distance <= distanceKm || (distance <= (distanceMeters / 1000.0));
}
private static double calculateDistance(String location1, String location2) {
// Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings
double lat1 = extractCoordinate(location1, "Lat");
//System.out.println("lat1: " + lat1);
double lon1 = extractCoordinate(location1, "Long");
//System.out.println("lon1: " + lon1);
double lat2 = extractCoordinate(location2, "Lat");
double lon2 = extractCoordinate(location2, "Long");
// Υπολογισμός της απόστασης με τον τύπο Haversine
return haversine(lat1, lon1, lat2, lon2);
}
// Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings
private static double extractCoordinate(String location, String coordinateType) {
//String[] parts = location.split(": ")[1].split(", Long: ");
//[1].split(",");
/*double[] parts1 = Arrays.stream(location.replaceAll("[^\\d.,-]", "").split(", "))
.mapToDouble(Double::parseDouble)
.toArray();*/
String[] parts = location.replaceAll("[^\\d.-]+", " ").trim().split("\\s+");
double lat = 0, lon = 0;
// Ensure we have at least two parts
if (parts.length >= 2) {
lat = Double.parseDouble(parts[0]);
lon = Double.parseDouble(parts[1]);
}
//System.out.println("parts: " + Arrays.toString(parts));
//System.out.println("paers[0]: " + parts[1].split(",")[0]);
return coordinateType.equals("Lat") ? lat : lon;
}
// Υπολογισμός της απόστασης με τον τύπο Haversine
private static double haversine(double lat1, double lon1, double lat2, double lon2) {
final int R = 6371; // Ακτίνα της Γης σε χιλιόμετρα
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // Επ<SUF>
}
}
|
44562_1 | package Asteras;
/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.lucene.queryparser.classic.ParseException;
/**
*
* @author Ηλίας
*/
public class Results extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ArrayList<Author> results = new ArrayList<>();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String query = request.getParameter("query");
String k = request.getParameter("k");
System.out.println("K: " + k);
LuceneTester tester = new LuceneTester();
tester.run(query, k);
for (String i : tester.matches.keySet()) {
results.add(tester.matches.get(i));
}
Collections.sort(results);
out.println("<!DOCTYPE html>\n"
+ "<html lang=\"en\">\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <!-- This file has been downloaded from bootdey.com @bootdey on twitter -->\n"
+ " <!-- All snippets are MIT license http://bootdey.com/license -->\n"
+ " <title>Search Results</title>\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
+ " <script src=\"https://code.jquery.com/jquery-1.10.2.min.js\"></script>\n"
+ " <link href=\"https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n"
+ " <script src=\"https://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js\"></script>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"container bootstrap snippets bootdey\">\n"
+ " <div class=\"row\">\n"
+ " <div class=\"col-lg-12\">\n"
+ " <div class=\"ibox float-e-margins\">\n"
+ " <div class=\"ibox-content\">\n"
+ " <a href=\"http://localhost:8080/Asteras/\" class=\"btn btn-primary\">Home</a><br><br>\n"
+ " <label for=\"k_results\">Top k results: </label>\n"
+ " <input type=\"text\" id=\"k_results\" name=\"k_results\" required><br>\n"
+ " <input name =\"submit_btn\" id = \"submit_btn\" type=\"submit\" value=\"Submit\">\n");
out.println("<h2>\n"
+ results.size() + " results found for: <span class=\"text-navy\">" + query + "</span>\n"
+ " </h2>\n"
+ " <small>Request time ( " + tester.time / 10.0 + " Seconds)</small>");
for (Author i : results) {
out.println(" <div class=\"hr-line-dashed\"></div>\n"
+ " <div class=\"search-result\">\n"
+ " <h3><a href=\"#\">" + i.getName() + " score: " + i.getScore() + "</a></h3>\n"
+ " <a href=\"https://dblp.org/search?q=" + i.getName() + "\"" + "class=\"search-link\">https://dblp.org/search?q=" + i.getName() + "</a>\n"
+ " <p>\n"
+ i.getField() + "\n"
+ " </p>\n"
+ " </div>\n"
+ " <div class=\"hr-line-dashed\"></div>");
}
out.println("</div>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>\n"
+ "\n"
+ "\n"
+ " <style type=\"text/css\">\n"
+ " body{\n"
+ " background:#eee;\n"
+ " }\n"
+ " .ibox-content {\n"
+ " background-color: #FFFFFF;\n"
+ " color: inherit;\n"
+ " padding: 15px 20px 20px 20px;\n"
+ " border-color: #E7EAEC;\n"
+ " border-image: none;\n"
+ " border-style: solid solid none;\n"
+ " border-width: 1px 0px;\n"
+ " }\n"
+ "\n"
+ " .search-form {\n"
+ " margin-top: 10px;\n"
+ " }\n"
+ "\n"
+ " .search-result h3 {\n"
+ " margin-bottom: 0;\n"
+ " color: #1E0FBE;\n"
+ " }\n"
+ "\n"
+ " .search-result .search-link {\n"
+ " color: #006621;\n"
+ " }\n"
+ "\n"
+ " .search-result p {\n"
+ " font-size: 12px;\n"
+ " margin-top: 5px;\n"
+ " }\n"
+ "\n"
+ " .hr-line-dashed {\n"
+ " border-top: 1px dashed #E7EAEC;\n"
+ " color: #ffffff;\n"
+ " background-color: #ffffff;\n"
+ " height: 1px;\n"
+ " margin: 20px 0;\n"
+ " }\n"
+ "\n"
+ " h2 {\n"
+ " font-size: 24px;\n"
+ " font-weight: 100;\n"
+ " }\n"
+ "\n"
+ "\n"
+ " </style>\n"
+ "\n"
+ " <script type=\"text/javascript\">\n"
+ "\n"
+ "\n"
+ " </script>\n"
+ " </body>\n"
+ "</html>");
out.println("<script>\n"
+ " function refreshK() {\n"
+ " window.location.href = 'http://localhost:8080/Asteras/Results?query=" + query + "'"+ " +' &k=' + document.getElementById(\"k_results\").value;\n"
+ " }\n"
+ "\n"
+ " document.getElementById(\"submit_btn\").addEventListener(\"click\", refreshK);\n"
+ "\n"
+ "</script> ");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException ex) {
Logger.getLogger(Results.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| IliasAlex/Asteras | src/java/Asteras/Results.java | 2,135 | /**
*
* @author Ηλίας
*/ | block_comment | el | package Asteras;
/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.lucene.queryparser.classic.ParseException;
/**
*
* @au<SUF>*/
public class Results extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ArrayList<Author> results = new ArrayList<>();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String query = request.getParameter("query");
String k = request.getParameter("k");
System.out.println("K: " + k);
LuceneTester tester = new LuceneTester();
tester.run(query, k);
for (String i : tester.matches.keySet()) {
results.add(tester.matches.get(i));
}
Collections.sort(results);
out.println("<!DOCTYPE html>\n"
+ "<html lang=\"en\">\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <!-- This file has been downloaded from bootdey.com @bootdey on twitter -->\n"
+ " <!-- All snippets are MIT license http://bootdey.com/license -->\n"
+ " <title>Search Results</title>\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
+ " <script src=\"https://code.jquery.com/jquery-1.10.2.min.js\"></script>\n"
+ " <link href=\"https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n"
+ " <script src=\"https://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js\"></script>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"container bootstrap snippets bootdey\">\n"
+ " <div class=\"row\">\n"
+ " <div class=\"col-lg-12\">\n"
+ " <div class=\"ibox float-e-margins\">\n"
+ " <div class=\"ibox-content\">\n"
+ " <a href=\"http://localhost:8080/Asteras/\" class=\"btn btn-primary\">Home</a><br><br>\n"
+ " <label for=\"k_results\">Top k results: </label>\n"
+ " <input type=\"text\" id=\"k_results\" name=\"k_results\" required><br>\n"
+ " <input name =\"submit_btn\" id = \"submit_btn\" type=\"submit\" value=\"Submit\">\n");
out.println("<h2>\n"
+ results.size() + " results found for: <span class=\"text-navy\">" + query + "</span>\n"
+ " </h2>\n"
+ " <small>Request time ( " + tester.time / 10.0 + " Seconds)</small>");
for (Author i : results) {
out.println(" <div class=\"hr-line-dashed\"></div>\n"
+ " <div class=\"search-result\">\n"
+ " <h3><a href=\"#\">" + i.getName() + " score: " + i.getScore() + "</a></h3>\n"
+ " <a href=\"https://dblp.org/search?q=" + i.getName() + "\"" + "class=\"search-link\">https://dblp.org/search?q=" + i.getName() + "</a>\n"
+ " <p>\n"
+ i.getField() + "\n"
+ " </p>\n"
+ " </div>\n"
+ " <div class=\"hr-line-dashed\"></div>");
}
out.println("</div>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>\n"
+ "\n"
+ "\n"
+ " <style type=\"text/css\">\n"
+ " body{\n"
+ " background:#eee;\n"
+ " }\n"
+ " .ibox-content {\n"
+ " background-color: #FFFFFF;\n"
+ " color: inherit;\n"
+ " padding: 15px 20px 20px 20px;\n"
+ " border-color: #E7EAEC;\n"
+ " border-image: none;\n"
+ " border-style: solid solid none;\n"
+ " border-width: 1px 0px;\n"
+ " }\n"
+ "\n"
+ " .search-form {\n"
+ " margin-top: 10px;\n"
+ " }\n"
+ "\n"
+ " .search-result h3 {\n"
+ " margin-bottom: 0;\n"
+ " color: #1E0FBE;\n"
+ " }\n"
+ "\n"
+ " .search-result .search-link {\n"
+ " color: #006621;\n"
+ " }\n"
+ "\n"
+ " .search-result p {\n"
+ " font-size: 12px;\n"
+ " margin-top: 5px;\n"
+ " }\n"
+ "\n"
+ " .hr-line-dashed {\n"
+ " border-top: 1px dashed #E7EAEC;\n"
+ " color: #ffffff;\n"
+ " background-color: #ffffff;\n"
+ " height: 1px;\n"
+ " margin: 20px 0;\n"
+ " }\n"
+ "\n"
+ " h2 {\n"
+ " font-size: 24px;\n"
+ " font-weight: 100;\n"
+ " }\n"
+ "\n"
+ "\n"
+ " </style>\n"
+ "\n"
+ " <script type=\"text/javascript\">\n"
+ "\n"
+ "\n"
+ " </script>\n"
+ " </body>\n"
+ "</html>");
out.println("<script>\n"
+ " function refreshK() {\n"
+ " window.location.href = 'http://localhost:8080/Asteras/Results?query=" + query + "'"+ " +' &k=' + document.getElementById(\"k_results\").value;\n"
+ " }\n"
+ "\n"
+ " document.getElementById(\"submit_btn\").addEventListener(\"click\", refreshK);\n"
+ "\n"
+ "</script> ");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException ex) {
Logger.getLogger(Results.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
9202_0 | /*
ΠΡΟΗΓΜΕΝΑ ΘΕΜΑΤΑ ΑΝΤΙΚΕΙΜΕΝΟΣΤΕΦΟΥΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΥ
ΠΜΣ «Προηγμένα Συστήματα Πληροφορικής - Ανάπτυξη Λογισμικού και Τεχνητής Νοημοσύνης»
ΠΑΝΕΠΙΣΤΗΜΙΟ ΠΕΙΡΑΙΩΣ
Τίτλος Εργασίας: «Precedence Graph Threading using Blockchains»
Φοιτητές:
Παπανικολάου Ηλίας ΜΠΣΠ20039
Δαβλιάνη Ιωάννα ΜΠΣΠ20010
14/3/2021
*/
package com.unipi.precedence_graph;
import java.io.IOException;
import java.sql.Connection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
*
* Main thread calls functions to read p_precedence.txt, p_timings.txt
* and create process instances which are saved in List<Process> processes.
*
* When processes are defined, globalTimerStart is set and thread execution
* starts. The main thread goes into a waiting state until all processes
* are completed.
*
* After completion the main thread checks if there are already stored blocks
* in the repository.
* - If there are already saved blocks in the repository a new emulation name is
* created and the blockChain continues from the last block that already exists in DB
* - If there is not blockChain in DB a new one is created with GenesisBlock
*
* After blockchain creation blocks are stored in database.
*
* Lastly, the consistency of the entire BlockChain is checked by calling
* repository.verifyBlockChain() ,method.
*
*/
public class PrecedenceGraph {
public static Instant globalTimerStart;
public static volatile List<Process> blockOrder = new ArrayList<>();
public static List<Block> blockChainList = new ArrayList<>();
public static void main(String[] args){
List<Process> processes = new ArrayList<>(new Parser().readPrecedenceFiles());
System.out.println("================== Precedence ====================");
int countGenesis = 0;
int countSecondary = 0;
for (Process p : processes){
if (p.isGenesisProcess()) countGenesis++;
else countSecondary++;
}
System.out.println("Number of genesis processes: " +countGenesis);
System.out.println("Number of secondary processes: " +countSecondary);
for (Process p: processes){
if (p.getWaitTime() != 0) System.out.println(p.getProcessName() +" has to work for " +p.getWaitTime() +"ms");
if (!p.getDependencies().isEmpty()){
System.out.print(p.getProcessName() +" has to wait for ");
for (Process proc : p.getDependencies()){
System.out.print(proc.getProcessName() +" ");
}
System.out.println();
}
}
System.out.println("=============== Starting Threads =================");
globalTimerStart = Instant.now();
for (Process p: processes){
p.start();
}
//Wait for processes to finish before continue
processes.forEach(process -> {
try {
process.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("============= Creating BlockChain ================");
BlockChain blockChain = new BlockChain();
//DB Connection
Repository repository = new Repository();
// repository.createNewDatabase();
// repository.createNewTable();
Connection conn = repository.connect();
//If exists, retrieve the last Block from DB
Block lastBlock = repository.retrieveLastBlock(conn);
if (lastBlock != null) {
blockChain.setIsGenesisBlock(false);
//retrieve previous Emulation Name
int count = Integer.parseInt(lastBlock.getEmulationName().substring(10));
//Create new Emulation Name - Auto Increment
String emulationName = String.format("emulation_%d", ++count);
//Continue the BlockChain from the last Block that already exists in DB
blockChain.createBlock(blockOrder.get(0), emulationName, lastBlock.getPreviousHash());
for (int i=1; i < blockOrder.size(); i++){
blockChain.createBlock(blockOrder.get(i), emulationName);
}
}
//Else if there is not BlockChain in DB, create a new one with GenesisBlock
else {
for (Process p: blockOrder){
blockChain.createBlock(p, "emulation_1");
}
}
//print BlockChain
blockChainList.forEach(System.out::println);
//Save Block Chain to DB
System.out.println("============= Saving to DataBase ================");
for (Block b : blockChainList){
repository.insert(conn, b.getEmulationName(), b.getHash(), b.getPreviousHash(),
b.getProcessName(), b.getExecutionTime(), b.getDependencies(),
b.getTimeStamp(), b.getNonce());
}
System.out.println("BlockChain saved Successfully");
System.out.println("============= Validate BlockChain ================");
Boolean isValid = repository.verifyBlockChain(conn, blockChain.getPrefix());
System.out.println("BlockChain Valid: " +isValid);
repository.close(conn);
System.out.println("\nPress any key to exit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| IliasPapanikolaou/PrecedenceGraph | src/main/java/com/unipi/precedence_graph/PrecedenceGraph.java | 1,475 | /*
ΠΡΟΗΓΜΕΝΑ ΘΕΜΑΤΑ ΑΝΤΙΚΕΙΜΕΝΟΣΤΕΦΟΥΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΥ
ΠΜΣ «Προηγμένα Συστήματα Πληροφορικής - Ανάπτυξη Λογισμικού και Τεχνητής Νοημοσύνης»
ΠΑΝΕΠΙΣΤΗΜΙΟ ΠΕΙΡΑΙΩΣ
Τίτλος Εργασίας: «Precedence Graph Threading using Blockchains»
Φοιτητές:
Παπανικολάου Ηλίας ΜΠΣΠ20039
Δαβλιάνη Ιωάννα ΜΠΣΠ20010
14/3/2021
*/ | block_comment | el | /*
ΠΡΟ<SUF>*/
package com.unipi.precedence_graph;
import java.io.IOException;
import java.sql.Connection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
*
* Main thread calls functions to read p_precedence.txt, p_timings.txt
* and create process instances which are saved in List<Process> processes.
*
* When processes are defined, globalTimerStart is set and thread execution
* starts. The main thread goes into a waiting state until all processes
* are completed.
*
* After completion the main thread checks if there are already stored blocks
* in the repository.
* - If there are already saved blocks in the repository a new emulation name is
* created and the blockChain continues from the last block that already exists in DB
* - If there is not blockChain in DB a new one is created with GenesisBlock
*
* After blockchain creation blocks are stored in database.
*
* Lastly, the consistency of the entire BlockChain is checked by calling
* repository.verifyBlockChain() ,method.
*
*/
public class PrecedenceGraph {
public static Instant globalTimerStart;
public static volatile List<Process> blockOrder = new ArrayList<>();
public static List<Block> blockChainList = new ArrayList<>();
public static void main(String[] args){
List<Process> processes = new ArrayList<>(new Parser().readPrecedenceFiles());
System.out.println("================== Precedence ====================");
int countGenesis = 0;
int countSecondary = 0;
for (Process p : processes){
if (p.isGenesisProcess()) countGenesis++;
else countSecondary++;
}
System.out.println("Number of genesis processes: " +countGenesis);
System.out.println("Number of secondary processes: " +countSecondary);
for (Process p: processes){
if (p.getWaitTime() != 0) System.out.println(p.getProcessName() +" has to work for " +p.getWaitTime() +"ms");
if (!p.getDependencies().isEmpty()){
System.out.print(p.getProcessName() +" has to wait for ");
for (Process proc : p.getDependencies()){
System.out.print(proc.getProcessName() +" ");
}
System.out.println();
}
}
System.out.println("=============== Starting Threads =================");
globalTimerStart = Instant.now();
for (Process p: processes){
p.start();
}
//Wait for processes to finish before continue
processes.forEach(process -> {
try {
process.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("============= Creating BlockChain ================");
BlockChain blockChain = new BlockChain();
//DB Connection
Repository repository = new Repository();
// repository.createNewDatabase();
// repository.createNewTable();
Connection conn = repository.connect();
//If exists, retrieve the last Block from DB
Block lastBlock = repository.retrieveLastBlock(conn);
if (lastBlock != null) {
blockChain.setIsGenesisBlock(false);
//retrieve previous Emulation Name
int count = Integer.parseInt(lastBlock.getEmulationName().substring(10));
//Create new Emulation Name - Auto Increment
String emulationName = String.format("emulation_%d", ++count);
//Continue the BlockChain from the last Block that already exists in DB
blockChain.createBlock(blockOrder.get(0), emulationName, lastBlock.getPreviousHash());
for (int i=1; i < blockOrder.size(); i++){
blockChain.createBlock(blockOrder.get(i), emulationName);
}
}
//Else if there is not BlockChain in DB, create a new one with GenesisBlock
else {
for (Process p: blockOrder){
blockChain.createBlock(p, "emulation_1");
}
}
//print BlockChain
blockChainList.forEach(System.out::println);
//Save Block Chain to DB
System.out.println("============= Saving to DataBase ================");
for (Block b : blockChainList){
repository.insert(conn, b.getEmulationName(), b.getHash(), b.getPreviousHash(),
b.getProcessName(), b.getExecutionTime(), b.getDependencies(),
b.getTimeStamp(), b.getNonce());
}
System.out.println("BlockChain saved Successfully");
System.out.println("============= Validate BlockChain ================");
Boolean isValid = repository.verifyBlockChain(conn, blockChain.getPrefix());
System.out.println("BlockChain Valid: " +isValid);
repository.close(conn);
System.out.println("\nPress any key to exit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
10412_1 | package com.ipap;
public abstract class Shape {
protected double centerX; // X στο καρτεσιανό επίπεδο
protected double centerY; // Y στο καρτεσιανό επίπεδο
// Constructor
public Shape(double centerX, double centerY) {
this.centerX = centerX;
this.centerY = centerY;
}
// Getters
public double getCenterX() {
return this.centerX;
}
public double getCenterY() {
return this.centerY;
}
// Setters
public void setCenterX(double centerX) {
this.centerX = centerX;
}
public void setCenterY(double centerY) {
this.centerY = centerY;
}
public void printInfo() {
System.out.println("Center = (" + this.centerX + "," + this.centerY + ")");
}
public abstract double calcArea();
}
| IliasPapanikolaou/java-oop-inheritance | src/main/java/com/ipap/Shape.java | 236 | // Y στο καρτεσιανό επίπεδο | line_comment | el | package com.ipap;
public abstract class Shape {
protected double centerX; // X στο καρτεσιανό επίπεδο
protected double centerY; // Y <SUF>
// Constructor
public Shape(double centerX, double centerY) {
this.centerX = centerX;
this.centerY = centerY;
}
// Getters
public double getCenterX() {
return this.centerX;
}
public double getCenterY() {
return this.centerY;
}
// Setters
public void setCenterX(double centerX) {
this.centerX = centerX;
}
public void setCenterY(double centerY) {
this.centerY = centerY;
}
public void printInfo() {
System.out.println("Center = (" + this.centerX + "," + this.centerY + ")");
}
public abstract double calcArea();
}
|
20877_7 | package org.example;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Scanner;
public class DummyApplication {
private static ObjectOutputStream out;
private static ObjectInputStream in;
private static Socket requestSocket;
public static void main(String[] args) {
try {
// Connect to the Master server
requestSocket = new Socket("localhost", 4321); // Use the correct IP and port
out = new ObjectOutputStream(requestSocket.getOutputStream());
in = new ObjectInputStream(requestSocket.getInputStream());
Scanner scanner = new Scanner(System.in);
int userType;
// Επιλογή τύπου χρήστη
System.out.println("Select user type:");
System.out.println("1. Manager");
System.out.println("2. Customer");
System.out.print("Enter your choice: ");
userType = scanner.nextInt();
// Εμφάνιση μενού ανάλογα με τον τύπο χρήστη
switch (userType) {
case 1:
displayManagerMenu(scanner);
break;
case 2:
displayCustomerMenu(scanner);
break;
default:
System.out.println("Invalid user type.");
}
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// Close connections
try {
in.close();
out.close();
requestSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
public static void displayManagerMenu(Scanner scanner) throws IOException {
int choice;
do {
// Εμφάνιση μενού για τον διαχειριστή του καταλύματος
System.out.println("\nManager Menu:");
System.out.println("1. Add accomodation");
System.out.println("2. Add available dates for rental");
System.out.println("3. Display reservations");
System.out.println("4. Logout");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
// Εκτέλεση επιλογής χρήστη
switch (choice) {
case 1:
System.out.println("Adding accomodation...");
System.out.print("Enter the path of the JSON file for the accommodation: ");
String jsonFilePath = scanner.next();
File jsonFile = new File(jsonFilePath);
String jsonString = new String(Files.readAllBytes(jsonFile.toPath()), StandardCharsets.UTF_8);
out.writeObject("add_accommodation");
out.writeObject(jsonString);
out.flush();
break;
case 2:
System.out.println("Adding available dates for rental...");
break;
case 3:
System.out.println("Displaying reservations...");
break;
case 4:
System.out.println("Loging out");
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4);
}
public static void displayCustomerMenu(Scanner scanner) {
int choice;
do {
// Εμφάνιση μενού για τον πελάτη
System.out.println("\nCustomer Menu:");
System.out.println("1. Filter accomodations");
System.out.println("2. Book accomodation");
System.out.println("3. Rank accomodation");
System.out.println("4. Logout");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
// Εκτέλεση επιλογής διαχειριστή
switch (choice) {
case 1:
System.out.println("Filtering accomodations...");
break;
case 2:
System.out.println("Booking accomodation...");
break;
case 3:
System.out.println("Ranking accomodation...");
break;
case 4:
System.out.println("Loging out");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4);
// make display menu and customer menu methods check gpt4
}
}
| Ioanna-jpg/GetaRoom-App | backend/src/DummyApplication.java | 1,152 | // Εμφάνιση μενού για τον πελάτη
| line_comment | el | package org.example;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Scanner;
public class DummyApplication {
private static ObjectOutputStream out;
private static ObjectInputStream in;
private static Socket requestSocket;
public static void main(String[] args) {
try {
// Connect to the Master server
requestSocket = new Socket("localhost", 4321); // Use the correct IP and port
out = new ObjectOutputStream(requestSocket.getOutputStream());
in = new ObjectInputStream(requestSocket.getInputStream());
Scanner scanner = new Scanner(System.in);
int userType;
// Επιλογή τύπου χρήστη
System.out.println("Select user type:");
System.out.println("1. Manager");
System.out.println("2. Customer");
System.out.print("Enter your choice: ");
userType = scanner.nextInt();
// Εμφάνιση μενού ανάλογα με τον τύπο χρήστη
switch (userType) {
case 1:
displayManagerMenu(scanner);
break;
case 2:
displayCustomerMenu(scanner);
break;
default:
System.out.println("Invalid user type.");
}
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// Close connections
try {
in.close();
out.close();
requestSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
public static void displayManagerMenu(Scanner scanner) throws IOException {
int choice;
do {
// Εμφάνιση μενού για τον διαχειριστή του καταλύματος
System.out.println("\nManager Menu:");
System.out.println("1. Add accomodation");
System.out.println("2. Add available dates for rental");
System.out.println("3. Display reservations");
System.out.println("4. Logout");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
// Εκτέλεση επιλογής χρήστη
switch (choice) {
case 1:
System.out.println("Adding accomodation...");
System.out.print("Enter the path of the JSON file for the accommodation: ");
String jsonFilePath = scanner.next();
File jsonFile = new File(jsonFilePath);
String jsonString = new String(Files.readAllBytes(jsonFile.toPath()), StandardCharsets.UTF_8);
out.writeObject("add_accommodation");
out.writeObject(jsonString);
out.flush();
break;
case 2:
System.out.println("Adding available dates for rental...");
break;
case 3:
System.out.println("Displaying reservations...");
break;
case 4:
System.out.println("Loging out");
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4);
}
public static void displayCustomerMenu(Scanner scanner) {
int choice;
do {
// Εμ<SUF>
System.out.println("\nCustomer Menu:");
System.out.println("1. Filter accomodations");
System.out.println("2. Book accomodation");
System.out.println("3. Rank accomodation");
System.out.println("4. Logout");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
// Εκτέλεση επιλογής διαχειριστή
switch (choice) {
case 1:
System.out.println("Filtering accomodations...");
break;
case 2:
System.out.println("Booking accomodation...");
break;
case 3:
System.out.println("Ranking accomodation...");
break;
case 4:
System.out.println("Loging out");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4);
// make display menu and customer menu methods check gpt4
}
}
|
4388_4 | package payroll;
import java.util.ArrayList;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
*
* @author Alexandros Dimitrakopoulos
*/
public class Company
{
//Λίστα με τoυς τύπους των υπαλλήλων
final ArrayList<EmployeeType> types = new ArrayList<>();
//Λίστα υπαλλήλων της εταιρείας
private ArrayList<Employee> employees = new ArrayList<>();
//Ανάθεση νέου project σε υπάλληλο
public void addProjectToEmployee(String empl, Project project)
{
//Java functional operations (Πρόταση του JDK αντι για την χρήση for)
//Αν ο υπάλληλος υπάρχει στη λίστα υπαλλήλων
employees.stream().filter((employeeee) -> (empl.equals(employeeee.getName()))).map((employeeee) ->
{
employeeee.addProject(project); //Ανάθεσέ του project
return employeeee;
}).forEachOrdered((employeeee) ->
{
employeeee.getType().setMoney(employeeee.getType().getMoney() + 80); //Προσθήκη Bonus
});
}
//Αποθήκευση σε αρχείο TXT των επιμέρους αποδοχών καθώς και τη συνολική της εταιρείας
public void save() throws IOException
{
BufferedWriter output;
output = new BufferedWriter(new FileWriter("Payroll.txt"));
try
{
output.write(calcPayroll());
}
catch (IOException e)
{
System.out.println(e);
}
finally
{
output.close();
}
}
//Προσθήκη νέου υπαλλήλου στην εταιρεία
public void addEmployee(Employee employee)
{
employees.add(employee);
}
//Υπολογισμός μισθοδοσίας της εταιρείας για έναν συγκεκριμένο μήνα
public String calcPayroll()
{
String payroll = "";
int total = 0; //Αρχικοποίηση της μισθοδοσίας
for (Employee employee : employees) //Για κάθε υπάλληλο (διαπέραση της λίστας των υπαλλήλων)
{
//θα χρησιμοποιήσουμε το instanceof για τον ελεγχο της σχέσης υπερκλάσης π.χ (EmployeeType) και υποκλάσης (Salary)
//Επίσης, για να υπολογίσουμε τις αποδοχές θα διαβάσουμε πρώτα (μέσω της μεθόδου getType()),
//Υπολογισμός μηνιαίων αποδοχών
if (employee.getType() instanceof Salary) //Έλεγχος σχέσης υπερκλάσης (EmployeeType) και υποκλάσης (Salary)
{
//Αν ο υπάλληλος είναι Manager
if (employee instanceof Manager)
{
employee.getType().setMoney(employee.getType().getMoney() + 2000);
}
//Αν ο υπάλληλος είναι Developer
if (employee instanceof Developer)
{
employee.getType().setMoney(employee.getType().getMoney() + 1200);
}
//Αν ο υπάλληλος είναι Analyst
if (employee instanceof Analyst)
{
employee.getType().setMoney(employee.getType().getMoney() + 1500);
}
//Αν ο υπάλληλος είναι Technical
if (employee instanceof Technical)
{
employee.getType().setMoney(employee.getType().getMoney() + 800);
}
}
//Υπολογισμός αποδοχών με την ώρα
if (employee.getType() instanceof PerHour)
{
//Αν ο υπάλληλος είναι Analyst
if (employee instanceof Analyst)
{
employee.getType().setMoney(employee.getType().getMoney() + (15 * employee.getType().getHour()));
}
//Αν ο υπάλληλος είναι Developer
if (employee instanceof Developer)
{
employee.getType().setMoney(employee.getType().getMoney() + (12 * employee.getType().getHour()));
}
//Αν ο υπάλληλος είναι Technical
if (employee instanceof Technical)
{
employee.getType().setMoney(employee.getType().getMoney() + (8 * employee.getType().getHour()));
}
//Αν ο υπάλληλος είναι Manager
if (employee instanceof Manager)
{
employee.getType().setMoney(employee.getType().getMoney() + (20 * employee.getType().getHour()));
}
}
//Επιμέρους μισθοδοσίες των υπαλλήλων για έναν μήνα
payroll = payroll + "\nΥπάλληλος: " + employee.getName() + "\nΑποδοχές: " + employee.getType().getMoney() + " Ευρώ\n";
total = total + employee.getType().getMoney();
}
//Υπολογισμός συνολικής μισθοδοσίας της εταιρείας για έναν μήνα
payroll = payroll + "----------------------------------------" + "\nΣυνολική Μισθοδοσία Εταιρείας: " + total + " Ευρώ\n";
return payroll;
}
} | JaskJohin/Payroll | src/payroll/Company.java | 1,759 | //Java functional operations (Πρόταση του JDK αντι για την χρήση for) | line_comment | el | package payroll;
import java.util.ArrayList;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
*
* @author Alexandros Dimitrakopoulos
*/
public class Company
{
//Λίστα με τoυς τύπους των υπαλλήλων
final ArrayList<EmployeeType> types = new ArrayList<>();
//Λίστα υπαλλήλων της εταιρείας
private ArrayList<Employee> employees = new ArrayList<>();
//Ανάθεση νέου project σε υπάλληλο
public void addProjectToEmployee(String empl, Project project)
{
//Ja<SUF>
//Αν ο υπάλληλος υπάρχει στη λίστα υπαλλήλων
employees.stream().filter((employeeee) -> (empl.equals(employeeee.getName()))).map((employeeee) ->
{
employeeee.addProject(project); //Ανάθεσέ του project
return employeeee;
}).forEachOrdered((employeeee) ->
{
employeeee.getType().setMoney(employeeee.getType().getMoney() + 80); //Προσθήκη Bonus
});
}
//Αποθήκευση σε αρχείο TXT των επιμέρους αποδοχών καθώς και τη συνολική της εταιρείας
public void save() throws IOException
{
BufferedWriter output;
output = new BufferedWriter(new FileWriter("Payroll.txt"));
try
{
output.write(calcPayroll());
}
catch (IOException e)
{
System.out.println(e);
}
finally
{
output.close();
}
}
//Προσθήκη νέου υπαλλήλου στην εταιρεία
public void addEmployee(Employee employee)
{
employees.add(employee);
}
//Υπολογισμός μισθοδοσίας της εταιρείας για έναν συγκεκριμένο μήνα
public String calcPayroll()
{
String payroll = "";
int total = 0; //Αρχικοποίηση της μισθοδοσίας
for (Employee employee : employees) //Για κάθε υπάλληλο (διαπέραση της λίστας των υπαλλήλων)
{
//θα χρησιμοποιήσουμε το instanceof για τον ελεγχο της σχέσης υπερκλάσης π.χ (EmployeeType) και υποκλάσης (Salary)
//Επίσης, για να υπολογίσουμε τις αποδοχές θα διαβάσουμε πρώτα (μέσω της μεθόδου getType()),
//Υπολογισμός μηνιαίων αποδοχών
if (employee.getType() instanceof Salary) //Έλεγχος σχέσης υπερκλάσης (EmployeeType) και υποκλάσης (Salary)
{
//Αν ο υπάλληλος είναι Manager
if (employee instanceof Manager)
{
employee.getType().setMoney(employee.getType().getMoney() + 2000);
}
//Αν ο υπάλληλος είναι Developer
if (employee instanceof Developer)
{
employee.getType().setMoney(employee.getType().getMoney() + 1200);
}
//Αν ο υπάλληλος είναι Analyst
if (employee instanceof Analyst)
{
employee.getType().setMoney(employee.getType().getMoney() + 1500);
}
//Αν ο υπάλληλος είναι Technical
if (employee instanceof Technical)
{
employee.getType().setMoney(employee.getType().getMoney() + 800);
}
}
//Υπολογισμός αποδοχών με την ώρα
if (employee.getType() instanceof PerHour)
{
//Αν ο υπάλληλος είναι Analyst
if (employee instanceof Analyst)
{
employee.getType().setMoney(employee.getType().getMoney() + (15 * employee.getType().getHour()));
}
//Αν ο υπάλληλος είναι Developer
if (employee instanceof Developer)
{
employee.getType().setMoney(employee.getType().getMoney() + (12 * employee.getType().getHour()));
}
//Αν ο υπάλληλος είναι Technical
if (employee instanceof Technical)
{
employee.getType().setMoney(employee.getType().getMoney() + (8 * employee.getType().getHour()));
}
//Αν ο υπάλληλος είναι Manager
if (employee instanceof Manager)
{
employee.getType().setMoney(employee.getType().getMoney() + (20 * employee.getType().getHour()));
}
}
//Επιμέρους μισθοδοσίες των υπαλλήλων για έναν μήνα
payroll = payroll + "\nΥπάλληλος: " + employee.getName() + "\nΑποδοχές: " + employee.getType().getMoney() + " Ευρώ\n";
total = total + employee.getType().getMoney();
}
//Υπολογισμός συνολικής μισθοδοσίας της εταιρείας για έναν μήνα
payroll = payroll + "----------------------------------------" + "\nΣυνολική Μισθοδοσία Εταιρείας: " + total + " Ευρώ\n";
return payroll;
}
} |
6842_2 | package basics;
import java.io.Serializable;
/*αναπαριστά τη διαθέσιμη ώρα λειτουργίας για κάθε επιχείρηση*/
/*η κάθε επιχείρηση περιλαμβάνει ένα ArrayList απο πολλά αντικείμενα τύπου OpenHour*/
public class OpenHour implements Serializable{
private Long day; //ημερα λειτουργίας
private String start; //ώρα ανοίγματος
private String end; //ώρα κλεισίματος
private Boolean isOvernight; //boolean τιμή για το αν είναι ολονύχτια η επιχείρηση
//Constructor
public OpenHour(Long day, String from, String to) {
this.day = day;
this.start = from;
this.end = to;
}
public OpenHour() {
}
//Methods
public Long getDay() {
return day;
}
public void setDay(Long day) {
this.day = day;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public Boolean getIsOvernight() {
return isOvernight;
}
public void setIsOvernight(Boolean isOvernight) {
this.isOvernight = isOvernight;
}
@Override
public String toString() {
return "OpenHour{" +
"day='" + day + '\'' +
", start=" + start +
", end=" + end +
", isOvernight='" + isOvernight + '\'' +
'}';
}
}
| JohnChantz/JavaII-YelpAPI-Project | YelpBasics/src/basics/OpenHour.java | 500 | //ημερα λειτουργίας | line_comment | el | package basics;
import java.io.Serializable;
/*αναπαριστά τη διαθέσιμη ώρα λειτουργίας για κάθε επιχείρηση*/
/*η κάθε επιχείρηση περιλαμβάνει ένα ArrayList απο πολλά αντικείμενα τύπου OpenHour*/
public class OpenHour implements Serializable{
private Long day; //ημ<SUF>
private String start; //ώρα ανοίγματος
private String end; //ώρα κλεισίματος
private Boolean isOvernight; //boolean τιμή για το αν είναι ολονύχτια η επιχείρηση
//Constructor
public OpenHour(Long day, String from, String to) {
this.day = day;
this.start = from;
this.end = to;
}
public OpenHour() {
}
//Methods
public Long getDay() {
return day;
}
public void setDay(Long day) {
this.day = day;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public Boolean getIsOvernight() {
return isOvernight;
}
public void setIsOvernight(Boolean isOvernight) {
this.isOvernight = isOvernight;
}
@Override
public String toString() {
return "OpenHour{" +
"day='" + day + '\'' +
", start=" + start +
", end=" + end +
", isOvernight='" + isOvernight + '\'' +
'}';
}
}
|
3992_3 |
public class SRTF extends Scheduler {
public SRTF() {
/* TODO: you _may_ need to add some code here */
}
public void addProcess(Process p) {
/* TODO: you need to add some code here */
p.getPCB().setState(ProcessState.READY,CPU.clock); // Βαζουμε την διεργασια απο την σε κατασταση NEW σε READY
processes.add(p); // Προσθετουμε μια νεα διεργασια στην λιστα διεργασιων προς εκτελεση
}
public Process getNextProcess() {
/* TODO: you need to add some code here
* and change the return value */
// If there are no scheduled processes return null.
if (processes.size() == 0) {
return null;
}
Process nextProcess = processes.get(0);
for (int i = 0 ; i < processes.size(); i++) {
if (processes.get(i).getPCB().getState() == ProcessState.RUNNING) {
processes.get(i).getPCB().setState(ProcessState.READY, CPU.clock);
}
if (processes.get(i).getBurstTime() - getRunTime(processes.get(i)) < nextProcess.getBurstTime() - getRunTime(nextProcess)) {
nextProcess = processes.get(i);
}
}
return nextProcess;
}
// Μέθοδος για να βρούμε το run time της διεργασίας μέχρι το τωρινό CPU clock
private int getRunTime(Process p) {
int runTime = 0;
for (int i = 0 ; i < p.getPCB().getStartTimes().size() ; i++) {
if (i >= p.getPCB().getStopTimes().size()) {
runTime += CPU.clock - p.getPCB().getStartTimes().get(i);
}
else {
runTime += p.getPCB().getStopTimes().get(i) - p.getPCB().getStartTimes().get(i);
}
}
return runTime;
}
} | JohnOiko/operating-system-scheduler | src/SRTF.java | 572 | // Προσθετουμε μια νεα διεργασια στην λιστα διεργασιων προς εκτελεση | line_comment | el |
public class SRTF extends Scheduler {
public SRTF() {
/* TODO: you _may_ need to add some code here */
}
public void addProcess(Process p) {
/* TODO: you need to add some code here */
p.getPCB().setState(ProcessState.READY,CPU.clock); // Βαζουμε την διεργασια απο την σε κατασταση NEW σε READY
processes.add(p); // Πρ<SUF>
}
public Process getNextProcess() {
/* TODO: you need to add some code here
* and change the return value */
// If there are no scheduled processes return null.
if (processes.size() == 0) {
return null;
}
Process nextProcess = processes.get(0);
for (int i = 0 ; i < processes.size(); i++) {
if (processes.get(i).getPCB().getState() == ProcessState.RUNNING) {
processes.get(i).getPCB().setState(ProcessState.READY, CPU.clock);
}
if (processes.get(i).getBurstTime() - getRunTime(processes.get(i)) < nextProcess.getBurstTime() - getRunTime(nextProcess)) {
nextProcess = processes.get(i);
}
}
return nextProcess;
}
// Μέθοδος για να βρούμε το run time της διεργασίας μέχρι το τωρινό CPU clock
private int getRunTime(Process p) {
int runTime = 0;
for (int i = 0 ; i < p.getPCB().getStartTimes().size() ; i++) {
if (i >= p.getPCB().getStopTimes().size()) {
runTime += CPU.clock - p.getPCB().getStartTimes().get(i);
}
else {
runTime += p.getPCB().getStopTimes().get(i) - p.getPCB().getStartTimes().get(i);
}
}
return runTime;
}
} |
3851_21 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package it2021091;
import static it2021091.It2021091.personsList;
import static it2021091.It2021091.showsList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author John skoul
*/
public class Admin extends Account {
public Admin(String username, String password) {
super(username, password);
}
//καταχωρηση θεαματος η σειρας
public void addShow(){
Scanner input=new Scanner(System.in);
/*εισάγω τίτλο θεάματος*/
System.out.print("Title: ");
String title = input.nextLine();
//αν είναι ήδη καταχωρημενο
if(super.ShowExists(title)){
System.out.println("This Show already exists");
return;
}
/*εισάγω έτος 1ης προβολής*/
System.out.print("Year: ");
int year=input.nextInt();
input.nextLine();
/*εισάγω χώρα παραγωγής*/
System.out.print("Country: ");
String country=input.nextLine();
/*εισάγω τύπο θεάματος*/
System.out.print("type or types: ");
String types=input.nextLine();
String[] arraytypes = types.split(" ");
ArrayList<String> typelist = new ArrayList<>();
for (String str : arraytypes) {
typelist.add(str.trim());
}
System.out.println("types:" + typelist);
/*εισάγω σκηνοθέτη*/
System.out.println("Director details:");
System.out.print("Director fullname:");
String directorName=input.nextLine();
Person director;
if( super.personExists(directorName) ){
System.out.println("this Director already exists in the system");
director= super.returnPerson(directorName);
System.out.println(director.toString());
} else {
//εισαγωγη ημερομηνια γεννησης σκηνοθέτη
System.out.print("Director birthdate(enter day/month/year with space between them):");
String directorBirthdate=input.nextLine();
String addslashBirthdate = directorBirthdate.replaceAll("\\s+", "/");
System.out.println("Formatted birthdate: " + addslashBirthdate);
//εισαγωγη χωρα καταγωγής σκηνοθέτη
System.out.print("Director country:");
String directorCountry=input.nextLine();
//εισαγωγη ιστοσελιδα σκηνοθέτη
System.out.print("Director website:");
String directorWebsite=input.nextLine();
director= new Person(directorName,addslashBirthdate,directorCountry,directorWebsite);
System.out.print(director.toString());
personsList.add(director);
}
//εισαγωγη ηθοποιών
System.out.print("enter number of actors you want to add:");
int numberOfactors=input.nextInt();
input.nextLine();
ArrayList<Person> actors=new ArrayList<>();
for(int i=0; i<numberOfactors; i++){
Person actor;
//εισαγωγη ονόματος
System.out.print("enter actor fullName:");
String actorName=input.nextLine();
if( super.personExists(actorName) ){
System.out.println("this Actor already exists in the system");
actor= super.returnPerson(actorName);
System.out.println( actor.toString() );
actors.add(actor);
}else{
//εισαγωγη ημερομηνιας γεννησης ηθοποιού
System.out.print("enter actor birthdate(enter day/month/year with space between them):");
String actorBirthdate=input.nextLine();
String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/");
System.out.println("Formatted birthdate: " + addslashBirthdate);
//εισαγωγη χώρας ηθοποιού
System.out.print("enter actor country:");
String actorCountry=input.nextLine();
//εισαγωγη ιστοσελιδας ηθοποιου
System.out.print("enter actor website:");
String actorWebsite=input.nextLine();
//δημιουργω τον ηθοποιό
actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite);
System.out.println(actor.toString());
actors.add(actor);
personsList.add(actor);
}
}
System.out.println("is the show a series?(y/n)");
char answer=input.nextLine().charAt(0);
if( (answer=='Y') || (answer=='y') ){
System.out.println("enter the number of seasons:");
int seasons=input.nextInt();
//εισαγωγή επεισόδια ανα σεασόν
int[] episodesPerSeason= new int[seasons];
for(int i=0; i<seasons; i++){
System.out.print("episodes of season " + (i+1) + ":" );
episodesPerSeason[i]=input.nextInt();
}
input.nextLine();
//εισαγωγή έτους τελευταίας προβολής
System.out.println("enter series last year(leave it blank if the series is still running):");
String lastYear=input.nextLine();
Series series= new Series(seasons,episodesPerSeason,lastYear,title,year,typelist,country,director,actors);
System.out.println(series.toString());
showsList.add(series);
System.out.println("series added Successfully!!!");
}else {
Show show=new Show(title,year,country,director,typelist,actors);
System.out.println(show.toString());
showsList.add(show);
System.out.println("Show added Successfully!!!");
}
}
public void updateSeries(){
System.out.print("provide the serie's id or title that you are searching:");
Scanner input= new Scanner(System.in);
String search=input.nextLine();
if(!super.ShowExists(search)){
System.out.println("This Show doesnt exist");
}else if(super.returnShow(search) instanceof Series){
Series series = (Series) super.returnShow(search);
System.out.println("Series title:" + series.getTitle());
System.out.println("""
Choose what you want to change:
1. number of seasons
2. number of episodes of a season
3. last year
4. add actor to the series
""");
int choice=input.nextInt();
switch(choice){
case 1:
int previousSeasons=series.getSeasons();
int[]previousEpisodesPerSeason=series.getEpisodesPerSeason();
System.out.print("enter new number of seasons:");
int updatedSeasons=input.nextInt();
int[]updatedEpisodesPerSeason=Arrays.copyOf(previousEpisodesPerSeason, updatedSeasons);
series.setSeasons(updatedSeasons);
series.setEpisodesPerSeason(updatedEpisodesPerSeason);
if(updatedSeasons > previousSeasons){
System.out.println("enter the episodes for the new seasons.");
for(int i=1; i<=(updatedSeasons - previousSeasons); i++){
System.out.print("enter the episodes for season " + (previousSeasons + i) +":");
int episodes=input.nextInt();
series.setEpisodesForSeason(previousSeasons + i, episodes);
}
}
System.out.println( "New number of seasons is:"+series.getSeasons() );
System.out.println(Arrays.toString(series.getEpisodesPerSeason()) );
for(int i=1; i<=series.getSeasons(); i++){
System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) );
}
break;
case 2:
System.out.print("enter a season out of " + series.getSeasons() +":");
int season=input.nextInt();
if( season<=0 || season>series.getSeasons() ){
System.out.println("wrong input");
}else{
System.out.println("enter number of episodes for season " + season +":");
int episodes=input.nextInt();
if(episodes<=0){
System.out.println("wrong input");
}else{
series.setEpisodesForSeason(season, episodes);
}
for(int i=1; i<=series.getSeasons(); i++){
System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) );
}
}
break;
case 3:
System.out.print("enter last year:");
input.nextLine();
String lastYear=input.nextLine();
try{
if(lastYear.equalsIgnoreCase("-")){
series.setLastYear("-");
}else if(Integer.parseInt(lastYear)<=0){
System.out.println("wrong input");
}else{
series.setLastYear(lastYear);
}
}catch(NumberFormatException e){
System.out.println("wrong input");
}
break;
case 4:
System.out.print("enter actor fullname:");
input.nextLine();
String actorName=input.nextLine();
for( Person p:series.getActors() ){
if(p.getFullName().equalsIgnoreCase(actorName)){
System.out.println("this Actor is already added to this series!");
return;
}
}
Person actor;
if( super.personExists(actorName) ){
System.out.println("this Actor already exists in the system");
actor= super.returnPerson(actorName);
System.out.println( actor.toString() );
series.addActor(actor);
System.out.println(actor.getFullName() + " was added to the actors of this series!");
System.out.println(series.getActors());
}else{
//εισαγωγη ημερομηνιας γεννησης ηθοποιού
System.out.print("enter actor birthdate(enter day/month/year with space between them):");
String actorBirthdate=input.nextLine();
String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/");
System.out.println("Formatted birthdate: " + addslashBirthdate);
//εισαγωγη χώρας ηθοποιού
System.out.print("enter actor country:");
String actorCountry=input.nextLine();
//εισαγωγη ιστοσελιδας ηθοποιου
System.out.print("enter actor website:");
String actorWebsite=input.nextLine();
//δημιουργω τον ηθοποιό
actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite);
System.out.println( actor.toString() );
series.addActor(actor);
System.out.println(actor.getFullName() + " was added to the actors of this series and to the system!");
System.out.println(series.getActors());
personsList.add(actor);
}
break;
default:
System.out.println("This option was not found.");
break;
}
}else{
System.out.println("This is a show not a series");
}
}
}
| JohnSkouloudis/JavaMovieManagement | src/it2021091/Admin.java | 3,044 | //εισαγωγη χώρας ηθοποιού | line_comment | el | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package it2021091;
import static it2021091.It2021091.personsList;
import static it2021091.It2021091.showsList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author John skoul
*/
public class Admin extends Account {
public Admin(String username, String password) {
super(username, password);
}
//καταχωρηση θεαματος η σειρας
public void addShow(){
Scanner input=new Scanner(System.in);
/*εισάγω τίτλο θεάματος*/
System.out.print("Title: ");
String title = input.nextLine();
//αν είναι ήδη καταχωρημενο
if(super.ShowExists(title)){
System.out.println("This Show already exists");
return;
}
/*εισάγω έτος 1ης προβολής*/
System.out.print("Year: ");
int year=input.nextInt();
input.nextLine();
/*εισάγω χώρα παραγωγής*/
System.out.print("Country: ");
String country=input.nextLine();
/*εισάγω τύπο θεάματος*/
System.out.print("type or types: ");
String types=input.nextLine();
String[] arraytypes = types.split(" ");
ArrayList<String> typelist = new ArrayList<>();
for (String str : arraytypes) {
typelist.add(str.trim());
}
System.out.println("types:" + typelist);
/*εισάγω σκηνοθέτη*/
System.out.println("Director details:");
System.out.print("Director fullname:");
String directorName=input.nextLine();
Person director;
if( super.personExists(directorName) ){
System.out.println("this Director already exists in the system");
director= super.returnPerson(directorName);
System.out.println(director.toString());
} else {
//εισαγωγη ημερομηνια γεννησης σκηνοθέτη
System.out.print("Director birthdate(enter day/month/year with space between them):");
String directorBirthdate=input.nextLine();
String addslashBirthdate = directorBirthdate.replaceAll("\\s+", "/");
System.out.println("Formatted birthdate: " + addslashBirthdate);
//εισαγωγη χωρα καταγωγής σκηνοθέτη
System.out.print("Director country:");
String directorCountry=input.nextLine();
//εισαγωγη ιστοσελιδα σκηνοθέτη
System.out.print("Director website:");
String directorWebsite=input.nextLine();
director= new Person(directorName,addslashBirthdate,directorCountry,directorWebsite);
System.out.print(director.toString());
personsList.add(director);
}
//εισαγωγη ηθοποιών
System.out.print("enter number of actors you want to add:");
int numberOfactors=input.nextInt();
input.nextLine();
ArrayList<Person> actors=new ArrayList<>();
for(int i=0; i<numberOfactors; i++){
Person actor;
//εισαγωγη ονόματος
System.out.print("enter actor fullName:");
String actorName=input.nextLine();
if( super.personExists(actorName) ){
System.out.println("this Actor already exists in the system");
actor= super.returnPerson(actorName);
System.out.println( actor.toString() );
actors.add(actor);
}else{
//εισαγωγη ημερομηνιας γεννησης ηθοποιού
System.out.print("enter actor birthdate(enter day/month/year with space between them):");
String actorBirthdate=input.nextLine();
String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/");
System.out.println("Formatted birthdate: " + addslashBirthdate);
//εισαγωγη χώρας ηθοποιού
System.out.print("enter actor country:");
String actorCountry=input.nextLine();
//εισαγωγη ιστοσελιδας ηθοποιου
System.out.print("enter actor website:");
String actorWebsite=input.nextLine();
//δημιουργω τον ηθοποιό
actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite);
System.out.println(actor.toString());
actors.add(actor);
personsList.add(actor);
}
}
System.out.println("is the show a series?(y/n)");
char answer=input.nextLine().charAt(0);
if( (answer=='Y') || (answer=='y') ){
System.out.println("enter the number of seasons:");
int seasons=input.nextInt();
//εισαγωγή επεισόδια ανα σεασόν
int[] episodesPerSeason= new int[seasons];
for(int i=0; i<seasons; i++){
System.out.print("episodes of season " + (i+1) + ":" );
episodesPerSeason[i]=input.nextInt();
}
input.nextLine();
//εισαγωγή έτους τελευταίας προβολής
System.out.println("enter series last year(leave it blank if the series is still running):");
String lastYear=input.nextLine();
Series series= new Series(seasons,episodesPerSeason,lastYear,title,year,typelist,country,director,actors);
System.out.println(series.toString());
showsList.add(series);
System.out.println("series added Successfully!!!");
}else {
Show show=new Show(title,year,country,director,typelist,actors);
System.out.println(show.toString());
showsList.add(show);
System.out.println("Show added Successfully!!!");
}
}
public void updateSeries(){
System.out.print("provide the serie's id or title that you are searching:");
Scanner input= new Scanner(System.in);
String search=input.nextLine();
if(!super.ShowExists(search)){
System.out.println("This Show doesnt exist");
}else if(super.returnShow(search) instanceof Series){
Series series = (Series) super.returnShow(search);
System.out.println("Series title:" + series.getTitle());
System.out.println("""
Choose what you want to change:
1. number of seasons
2. number of episodes of a season
3. last year
4. add actor to the series
""");
int choice=input.nextInt();
switch(choice){
case 1:
int previousSeasons=series.getSeasons();
int[]previousEpisodesPerSeason=series.getEpisodesPerSeason();
System.out.print("enter new number of seasons:");
int updatedSeasons=input.nextInt();
int[]updatedEpisodesPerSeason=Arrays.copyOf(previousEpisodesPerSeason, updatedSeasons);
series.setSeasons(updatedSeasons);
series.setEpisodesPerSeason(updatedEpisodesPerSeason);
if(updatedSeasons > previousSeasons){
System.out.println("enter the episodes for the new seasons.");
for(int i=1; i<=(updatedSeasons - previousSeasons); i++){
System.out.print("enter the episodes for season " + (previousSeasons + i) +":");
int episodes=input.nextInt();
series.setEpisodesForSeason(previousSeasons + i, episodes);
}
}
System.out.println( "New number of seasons is:"+series.getSeasons() );
System.out.println(Arrays.toString(series.getEpisodesPerSeason()) );
for(int i=1; i<=series.getSeasons(); i++){
System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) );
}
break;
case 2:
System.out.print("enter a season out of " + series.getSeasons() +":");
int season=input.nextInt();
if( season<=0 || season>series.getSeasons() ){
System.out.println("wrong input");
}else{
System.out.println("enter number of episodes for season " + season +":");
int episodes=input.nextInt();
if(episodes<=0){
System.out.println("wrong input");
}else{
series.setEpisodesForSeason(season, episodes);
}
for(int i=1; i<=series.getSeasons(); i++){
System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) );
}
}
break;
case 3:
System.out.print("enter last year:");
input.nextLine();
String lastYear=input.nextLine();
try{
if(lastYear.equalsIgnoreCase("-")){
series.setLastYear("-");
}else if(Integer.parseInt(lastYear)<=0){
System.out.println("wrong input");
}else{
series.setLastYear(lastYear);
}
}catch(NumberFormatException e){
System.out.println("wrong input");
}
break;
case 4:
System.out.print("enter actor fullname:");
input.nextLine();
String actorName=input.nextLine();
for( Person p:series.getActors() ){
if(p.getFullName().equalsIgnoreCase(actorName)){
System.out.println("this Actor is already added to this series!");
return;
}
}
Person actor;
if( super.personExists(actorName) ){
System.out.println("this Actor already exists in the system");
actor= super.returnPerson(actorName);
System.out.println( actor.toString() );
series.addActor(actor);
System.out.println(actor.getFullName() + " was added to the actors of this series!");
System.out.println(series.getActors());
}else{
//εισαγωγη ημερομηνιας γεννησης ηθοποιού
System.out.print("enter actor birthdate(enter day/month/year with space between them):");
String actorBirthdate=input.nextLine();
String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/");
System.out.println("Formatted birthdate: " + addslashBirthdate);
//ει<SUF>
System.out.print("enter actor country:");
String actorCountry=input.nextLine();
//εισαγωγη ιστοσελιδας ηθοποιου
System.out.print("enter actor website:");
String actorWebsite=input.nextLine();
//δημιουργω τον ηθοποιό
actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite);
System.out.println( actor.toString() );
series.addActor(actor);
System.out.println(actor.getFullName() + " was added to the actors of this series and to the system!");
System.out.println(series.getActors());
personsList.add(actor);
}
break;
default:
System.out.println("This option was not found.");
break;
}
}else{
System.out.println("This is a show not a series");
}
}
}
|
8806_10 | package com.example.myevents;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.HeaderMap;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
public interface FetchData {
//5e83622f862c46101ac164c8
//5e9230c2cc62be4369c30aba/1
@GET("events") //Λήψη events
Call<List<Events>> getData(@Header("x-access-token") String token);
@GET("events/type/{Category}") //Λήψη events βάσει Category
Call<List<Events>> getSelectedData(@Header("x-access-token") String token,@Path("Category") String cat);
@GET("events/date/{Prev}/{Next}") //Λήψη events βάσει Date
Call<List<Events>> getSelectedDataDate(@Header("x-access-token") String token,@Path("Prev") String prev,@Path("Next") String next);
@GET("my_events") //Λήψη events
Call<List<Events>> getMyEvent(@Header("x-access-token") String token);
@Headers("Content-Type: application/json")
@POST("users") //Εγγραφή user
Call<List<User>> UploadUser(@Body User newUser);
@DELETE("events/{id}") //Διαγραφή event
Call<List<Events>> DeleteData(@Path("id") int Id, @Header("x-access-token") String token);
@Headers("Content-Type: application/json")
@POST("events/{id}") //Επεξεργασία Event
Call<List<Events>> UpdateEvent(@Path("id") int Id,@Header("x-access-token") String token,@Body Events newEvent);
@Headers("Content-Type: application/json")
@POST("events") // Δημιουργία Event
Call<List<Events>> UploadEvent(@Header("x-access-token") String token,@Body Events newEvent);
@GET("login") // Για login και λήψη token
Call<List<String>> GetToken(@Header("Authorization") String header);
@Headers("Content-Type: application/json")
@POST("events/{id}/rating") //Για Post Rate Event
Call<List<Events>> RateEvent(@Path("id") int Id,@Header("x-access-token") String token,@Body Events newEvent);
@Headers("Content-Type: application/json")
@POST("backend_ai/photo") //Για Post Image
Call<List<Events>> Uploadimage(@Header("x-access-token") String token,@Body Events Event);
@GET("events/{id}/rating") //Για Rate event
Call<List<Events>> GetEventComments(@Path("id") int Id,@Header("x-access-token") String token);
} | Johnylil/E-Events | app/src/main/java/com/example/myevents/FetchData.java | 796 | // Για login και λήψη token | line_comment | el | package com.example.myevents;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.HeaderMap;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
public interface FetchData {
//5e83622f862c46101ac164c8
//5e9230c2cc62be4369c30aba/1
@GET("events") //Λήψη events
Call<List<Events>> getData(@Header("x-access-token") String token);
@GET("events/type/{Category}") //Λήψη events βάσει Category
Call<List<Events>> getSelectedData(@Header("x-access-token") String token,@Path("Category") String cat);
@GET("events/date/{Prev}/{Next}") //Λήψη events βάσει Date
Call<List<Events>> getSelectedDataDate(@Header("x-access-token") String token,@Path("Prev") String prev,@Path("Next") String next);
@GET("my_events") //Λήψη events
Call<List<Events>> getMyEvent(@Header("x-access-token") String token);
@Headers("Content-Type: application/json")
@POST("users") //Εγγραφή user
Call<List<User>> UploadUser(@Body User newUser);
@DELETE("events/{id}") //Διαγραφή event
Call<List<Events>> DeleteData(@Path("id") int Id, @Header("x-access-token") String token);
@Headers("Content-Type: application/json")
@POST("events/{id}") //Επεξεργασία Event
Call<List<Events>> UpdateEvent(@Path("id") int Id,@Header("x-access-token") String token,@Body Events newEvent);
@Headers("Content-Type: application/json")
@POST("events") // Δημιουργία Event
Call<List<Events>> UploadEvent(@Header("x-access-token") String token,@Body Events newEvent);
@GET("login") // Γι<SUF>
Call<List<String>> GetToken(@Header("Authorization") String header);
@Headers("Content-Type: application/json")
@POST("events/{id}/rating") //Για Post Rate Event
Call<List<Events>> RateEvent(@Path("id") int Id,@Header("x-access-token") String token,@Body Events newEvent);
@Headers("Content-Type: application/json")
@POST("backend_ai/photo") //Για Post Image
Call<List<Events>> Uploadimage(@Header("x-access-token") String token,@Body Events Event);
@GET("events/{id}/rating") //Για Rate event
Call<List<Events>> GetEventComments(@Path("id") int Id,@Header("x-access-token") String token);
} |
37010_0 | import java.awt.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Logger;
import ithakimodem.*;
/*
*
* Δίκτυα Υπολογιστών I
*
* Experimental Virtual Lab
*
* Παπαδόπουλος Κωνσταντίνος, Α.Ε.Μ. 8677
*
*/
public class virtualModem {
/////////////////////////////////////////// initializing values
String echo="E7281\r"; // Echo request code
String imgfree="M4464\r"; // Image request code (Tx/Rx error free)
String imgerror="G5996\r"; // Image request code (Tx/Rx with errors)
String gps="P2812R=1000099\r"; // GPS request code
String gps2="P2812R=1011099\r"; // GPS request code 2
String gps_plain="P2812";
String ack="Q9734\r"; // ACK result code
String nack="R9531\r"; // NACK result code
///////////////////////////////////////////
public static void main(String[] param) {
//(new virtualModem()).nechopackets(5);
//(new virtualModem()).imagepackets("error");
//(new virtualModem()).chronoechopackets(480000);
//(new virtualModem()).gpspackets();
//(new virtualModem()).acknackpackets(480000);
}
////////////////////////////////////////////////// // creates and initializes modem
public Modem setmodem(int speed, int timeout){
Modem modem;
modem=new Modem();
modem.setSpeed(speed); // set new speed at 8000 (old speed was at 1000)
modem.setTimeout(timeout);
return modem;
}
//////////////////////////////////////////////////
/////////////////////////////////////////////////// creates files for input data
public FileOutputStream makefile(String filename, String extension){
FileOutputStream fout = null;
try {
fout = new FileOutputStream(filename
+ ""
+ extension);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fout;
}
public FileOutputStream makefileappend(String filename, String extension){ // creates appended files for input data
FileOutputStream fout = null;
try {
fout = new FileOutputStream(filename
+ ""
+ extension, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fout;
}
///////////////////////////////////////////////////
public void nechopackets(int number) { // for requesting n number of echo packets
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("necho", ".txt"); // opening file to store input data
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
for (int i = 0; i<number; i++){
modem.write(echo.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
if (k==-1){fout.write("\r\n".getBytes()); break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
}// end of nechopackets
/////////////////////////////////////////////////////////////////////////////////
public void imagepackets(String quality) { // error or free
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("image", ".jpeg"); // opening file to store input data
String img;
if (quality == "error")
img = imgerror;
else img = imgfree;
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
for (int i = 0; i<1; i++){
modem.write(img.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
if (k==-1){fout.write("\r\n".getBytes()); break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
}// end of imagepackets
public void acknackpackets(long acktime) {
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("ack", ".txt"); // opening file to store input data
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
String[] fcs; // it is the FCS string in the packet
int[] fcsint = new int[1000]; // it is the FCS string in the packet converted to int
int[] fcsxor = new int[1000]; // it is the FCS in decimal that comes from the XOR between the characters
byte[][] fcsxorbyte = new byte[1000][1000]; // it turns every sequence into bytes
byte[] fcsxorbinary = new byte[1000]; // the outcome of every packet that is XORed that needs to become from binary to decimal
int whilecounter = 0; // how many times in the while loop
int kmscounter = 0; // how many times k==-1
int[] nackpackets = new int[1000]; // for every ack requests how many nack there are
for(int i = 0; i <1000; i++){
nackpackets[i] = 0;
}
int requests = 0; //number of ack requests
long[] responsetime = new long[1000]; // measures response time
responsetime[0] = 0;
long[] tmp = new long[1000]; // counts from ack to ack
long tmp2 = 0; // counts inside nack
String[] sequence = new String[1000]; // the string sequence of every packet
int ackresponseflag = 0; // flag to measure time between two ack packets
long[][] tmpn = new long[1000][1000]; //--new
long[] responsetimen = new long[1000]; // measures response time //--new
responsetimen[0] = 0; //--new
long[] responsetimetotal = new long[1000]; //--new
long start= System.currentTimeMillis();
long end = start + acktime;
while (System.currentTimeMillis() < end){
if ( fcsxor[kmscounter] != fcsint[kmscounter] ){ // result -> ack or nack
tmpn[requests][nackpackets[requests]] = System.currentTimeMillis(); //--new counts nack time to receive as well
modem.write(nack.getBytes());
ackresponseflag = 0;
nackpackets[requests]++;
}
else{
tmp[requests] = System.currentTimeMillis();
modem.write(ack.getBytes());
ackresponseflag = 1;
requests++;
}
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
System.out.print((char)k);
if (k==-1){
fout.write("\r\n".getBytes());
if (ackresponseflag == 0) //--new counts nack time to receive as well
responsetimen[requests] += System.currentTimeMillis() - tmpn[requests][nackpackets[requests]-1]; //--new
if (ackresponseflag == 1)
responsetime[requests] = System.currentTimeMillis() - tmp[requests-1];
responsetimetotal[requests] = responsetimen[requests] + responsetime[requests]; //--new
////////////////////////////////////////////////////////////////////////
kmscounter++;
break;
} // end of if k==-1
fout.write(k);
} catch (Exception x) {
break;
}
} // end of infinite for loop
BufferedReader in = null; // opens reader for the file to be scanned
try {
in = new BufferedReader(new FileReader("ack.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str;
ArrayList list = new ArrayList(); // puts every line of the file into list
try {
while((str = in.readLine()) != null){
list.add(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] stockArr = new String[list.size()]; // converts list into String array
String[] stringArr = (String[]) list.toArray(stockArr);
String temp = "";
for(int y = 49; y <=51 ; y++){
temp += Character.toString(stringArr[kmscounter-1].charAt(y));
}
//System.out.print("---fcsint---" + temp + "\n");
fcsint[kmscounter] = Integer.parseInt(temp); // gets integer value of fcs
temp ="";
for(int y = 31; y <=46 ; y++){
temp += Character.toString(stringArr[kmscounter-1].charAt(y));
}
sequence[kmscounter] = temp;
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fcsxorbyte[kmscounter] = sequence[kmscounter].getBytes(); // turns every sequence into bytes
byte tmpbyte = fcsxorbyte[kmscounter][0]; // initializes tmpbyte
for(int y = 0; y<15 ; y++){ // do xor to all characters
tmpbyte = (byte)(tmpbyte^fcsxorbyte[kmscounter][y+1]);
fcsxorbinary[kmscounter] = tmpbyte;
//System.out.print("--sequence--" + kmscounter + " is " + (int)fcsxorbinary[kmscounter] + "\n");
}
fcsxor[kmscounter] = (int) fcsxorbinary[kmscounter];
//System.out.print("--THE fcsxor[kmscounter]-- " + fcsxor[kmscounter] + "\n");
//System.out.print("--fcsxorbyte[kmscounter][0]--" + fcsxorbyte[kmscounter][0] + "\n");
//System.out.print("--fcsxorbyte[kmscounter][1]--" + fcsxorbyte[kmscounter][1] + "\n");
//byte test = (byte)(fcsxorbyte[kmscounter][2]^((byte) (fcsxorbyte[kmscounter][0]^fcsxorbyte[kmscounter][0+1])));
//System.out.print("--test--" + test + "\n");
//System.out.print("--final--" + fcsxor[kmscounter] + "\n");
whilecounter++;
} // end of while
modem.close();
String[] str = new String[requests];
for (int y=1;y<requests;y++){ // write input data of response times into file, start from 1 (0+1)
// because if you send n ack packets there are n-1 response times
//str[y] = Long.toString(responsetime[y]); //--new bring back
str[y] = Long.toString(responsetimetotal[y]); //--new
try (FileWriter out = new FileWriter("response_ack_nack.txt",true))
{
out.write(str[y]);
out.write("\r\n");
}
catch (IOException exc)
{
System.out.println("Exception ");
}
}
System.out.print("\n"+"--NUMBER OF REQUESTS (ACK PACKETS)--" + requests + "\n");
for(int i=0; i<requests; i++)
System.out.print("--NUMBER OF NACK (NACK PACKETS)--" + (i+1) + " " + nackpackets[i] + "\n");
} // end of acknackpackets2
public void chronoechopackets(long echotime) {
int k;
String[] str = new String[200]; // to save response times as strings
long[] responsetime = new long[200]; // to save response times
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("chronoecho", ".txt"); // opening file to store input data
int t = 0;
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
long start= System.currentTimeMillis();
long end = start + echotime;
long timesent;
while (System.currentTimeMillis() < end){
timesent = System.currentTimeMillis(); // start of measuring response time
modem.write(echo.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read(); // while k!=0
if (k==-1){
responsetime[t] = System.currentTimeMillis() - timesent; // end of measuring response time
fout.write("\r\n".getBytes());
t++;
break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
for (int y=0;y<t;y++){ // write input data of response times into file
str[y] = Long.toString(responsetime[y]);
try (FileWriter out = new FileWriter("echoresponse.txt",true))
{
out.write(str[y]);
out.write("\r\n");
}
catch (IOException exc)
{
System.out.println("Exception ");
}
}
}// end of chronoechopackets2
public void gpspackets() {
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("gps", ".txt"); // opening file to store input data
int l = 0; // lines of N,E arrays, increases every time we find a packet with the correct format
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
for (int i = 0; i<1; i++){
modem.write(gps.getBytes());
modem.write(gps2.getBytes()); // two different gps routes for the data files
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
if (k==-1){fout.write("\r\n".getBytes()); break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
//blankremover("gpstest.txt");
///////////////////////////////////////////////////////////////this part scans for the coordinates
BufferedReader in = null; // opens reader for the file to be scanned
try {
in = new BufferedReader(new FileReader("gps.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str;
ArrayList list = new ArrayList(); // puts every line of the file into list
try {
while((str = in.readLine()) != null){
list.add(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] stockArr = new String[list.size()]; // converts list into String array
String[] stringArr = (String[]) list.toArray(stockArr);
int numtraces=0; // traces that have 4" difference
String[] North = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
North[i] = "";
}
String[] East = new String[1000];
for(int i = 0; i < 1000; i++){
East[i] = "";
}
String[] Northconvert = new String[198]; //initialize Strings for North and South coordinates to be converted
for(int i = 0; i < 198; i++){
Northconvert[i] = "";
}
String[] Eastconvert = new String[198]; // 198 because that's the lines of the gps file
for(int i = 0; i < 198; i++){
Eastconvert[i] = "";
}
/////////////////////////////////////////////////////// initialize Strings for Hours, Minutes, Seconds
String[] Hours = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
Hours[i] = "0";
}
String[] Minutes = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
Minutes[i] = "0";
}
String[] Seconds = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
Seconds[i] = "0";
}
int[] conversioneast= new int[1000]; // converts to " of degrees
int[] conversionnorth= new int[1000]; // converts to " of degrees
///////////////////////////////////////////////////////
String[] trace = new String[6]; // the final traces
for (int i = 1; i<(stringArr.length-2); i++){
if (stringArr[i].charAt(4) == 'G' ){ // checking for correct gps format
for(int y = 18; y<=21 ; y++){
North[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 23; y<=24 ; y++){
Northconvert[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 31; y<=34 ; y++ ){
East[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 36; y<=37; y++){
Eastconvert[l] += Character.toString(stringArr[i].charAt(y));
}
////////////////////////////////////////get time
for(int y = 7; y<=8 ; y++){ // hours
Hours[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 9; y<=10 ; y++){ // minutes
Minutes[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 10; y<=11 ; y++){ // seconds
Seconds[l] += Character.toString(stringArr[i].charAt(y));
}
l++;
}
}
/////////////////////////////////////////////////////////// conversions
for (int y = 0; y < Northconvert.length; y++){
conversionnorth[y] = (int) (0.6 * Integer.valueOf(Northconvert[y])); // converts to "
Northconvert[y] = String.valueOf(conversionnorth[y]); // converts to String again
North[y] += Northconvert[y]; // re-attaches to String
conversioneast[y] = (int) (0.6 * Integer.valueOf(Eastconvert[y]));
Eastconvert[y] = String.valueOf(conversioneast[y]);
East[y] += Eastconvert[y];
}
//////////////////////////////////////////// making arrays for reading time
int[] hoursint = new int[Hours.length];
int[] minutesint = new int[Minutes.length];
int[] secondsint = new int[Seconds.length];
int[] timeint = new int[Hours.length];
for (int y = 0; y < Hours.length; y++){
hoursint[y] = 3600 * Integer.valueOf(Hours[y]);
minutesint[y] = 60 * Integer.valueOf(Minutes[y]);
secondsint[y] = 1 * Integer.valueOf(Seconds[y]);
timeint[y] = hoursint[y] + minutesint[y] + secondsint[y];
}
////////////////////////////////////////////////////////
int z; // trying to find traces that are 4" away, the numbers of z and y are random
for (z = 20; z < l; z++){
for(int y= z + 100; y<l;y=y+30, z += 50){
if ((Math.abs(timeint[z] - timeint[y])) >= 50
&& numtraces!=4){
trace[numtraces] = East[z] + North[z];
trace[numtraces+1] = East[y] + North[y];
numtraces=numtraces+2;
System.out.print(z + "\n");
}
}
}
/*
trace[0] = East[0] + North[0]; // since the time in the data is increasing by 1 sec in every packet
trace[1] = East[50] + North[50]; // the traces are definitely 4" away (50 secs to be exact)
trace[2] = East[100] + North[100];
trace[3] = East[150] + North[150];
*/
/////////////////////////////////////////////////////////////////////////new image
String newgpscode = new String();
newgpscode = gps_plain + "T=" + trace[0] +
"T=" + trace[1] +
"T=" + trace[2] +
"T=" + trace[3] + "\r";
System.out.print("THIS IS THE NEW GPS CODE " + newgpscode +"\n");
int k2;
Modem modem2 = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout2 = makefile("gps", ".jpeg"); // opening file to store input data
modem2.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k2=modem2.read();
if (k2==-1){ break;}
System.out.print((char)k2);
} catch (Exception x) {
break;
}
}
for (int i = 0; i<1; i++){
modem2.write(newgpscode.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k2=modem2.read();
if (k2==-1){fout2.write("\r\n".getBytes()); break;}
System.out.print((char)k2);
fout2.write(k2);
} catch (Exception x) {
break;
}
}
}
modem2.close();
}// end of gpspackets
//////////////////removes empty lines from files (it isn't used eventually)
public void blankremover(String args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File(args));
writer = new PrintWriter("gpstest100.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
//Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
} // end of blankremover
} // end of class | KAUTH/University-Projects | Computer Networks (Java)/Course 1/userApplication.java | 6,673 | /*
*
* Δίκτυα Υπολογιστών I
*
* Experimental Virtual Lab
*
* Παπαδόπουλος Κωνσταντίνος, Α.Ε.Μ. 8677
*
*/ | block_comment | el | import java.awt.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Logger;
import ithakimodem.*;
/*
*
* Δίκ<SUF>*/
public class virtualModem {
/////////////////////////////////////////// initializing values
String echo="E7281\r"; // Echo request code
String imgfree="M4464\r"; // Image request code (Tx/Rx error free)
String imgerror="G5996\r"; // Image request code (Tx/Rx with errors)
String gps="P2812R=1000099\r"; // GPS request code
String gps2="P2812R=1011099\r"; // GPS request code 2
String gps_plain="P2812";
String ack="Q9734\r"; // ACK result code
String nack="R9531\r"; // NACK result code
///////////////////////////////////////////
public static void main(String[] param) {
//(new virtualModem()).nechopackets(5);
//(new virtualModem()).imagepackets("error");
//(new virtualModem()).chronoechopackets(480000);
//(new virtualModem()).gpspackets();
//(new virtualModem()).acknackpackets(480000);
}
////////////////////////////////////////////////// // creates and initializes modem
public Modem setmodem(int speed, int timeout){
Modem modem;
modem=new Modem();
modem.setSpeed(speed); // set new speed at 8000 (old speed was at 1000)
modem.setTimeout(timeout);
return modem;
}
//////////////////////////////////////////////////
/////////////////////////////////////////////////// creates files for input data
public FileOutputStream makefile(String filename, String extension){
FileOutputStream fout = null;
try {
fout = new FileOutputStream(filename
+ ""
+ extension);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fout;
}
public FileOutputStream makefileappend(String filename, String extension){ // creates appended files for input data
FileOutputStream fout = null;
try {
fout = new FileOutputStream(filename
+ ""
+ extension, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fout;
}
///////////////////////////////////////////////////
public void nechopackets(int number) { // for requesting n number of echo packets
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("necho", ".txt"); // opening file to store input data
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
for (int i = 0; i<number; i++){
modem.write(echo.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
if (k==-1){fout.write("\r\n".getBytes()); break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
}// end of nechopackets
/////////////////////////////////////////////////////////////////////////////////
public void imagepackets(String quality) { // error or free
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("image", ".jpeg"); // opening file to store input data
String img;
if (quality == "error")
img = imgerror;
else img = imgfree;
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
for (int i = 0; i<1; i++){
modem.write(img.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
if (k==-1){fout.write("\r\n".getBytes()); break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
}// end of imagepackets
public void acknackpackets(long acktime) {
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("ack", ".txt"); // opening file to store input data
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
String[] fcs; // it is the FCS string in the packet
int[] fcsint = new int[1000]; // it is the FCS string in the packet converted to int
int[] fcsxor = new int[1000]; // it is the FCS in decimal that comes from the XOR between the characters
byte[][] fcsxorbyte = new byte[1000][1000]; // it turns every sequence into bytes
byte[] fcsxorbinary = new byte[1000]; // the outcome of every packet that is XORed that needs to become from binary to decimal
int whilecounter = 0; // how many times in the while loop
int kmscounter = 0; // how many times k==-1
int[] nackpackets = new int[1000]; // for every ack requests how many nack there are
for(int i = 0; i <1000; i++){
nackpackets[i] = 0;
}
int requests = 0; //number of ack requests
long[] responsetime = new long[1000]; // measures response time
responsetime[0] = 0;
long[] tmp = new long[1000]; // counts from ack to ack
long tmp2 = 0; // counts inside nack
String[] sequence = new String[1000]; // the string sequence of every packet
int ackresponseflag = 0; // flag to measure time between two ack packets
long[][] tmpn = new long[1000][1000]; //--new
long[] responsetimen = new long[1000]; // measures response time //--new
responsetimen[0] = 0; //--new
long[] responsetimetotal = new long[1000]; //--new
long start= System.currentTimeMillis();
long end = start + acktime;
while (System.currentTimeMillis() < end){
if ( fcsxor[kmscounter] != fcsint[kmscounter] ){ // result -> ack or nack
tmpn[requests][nackpackets[requests]] = System.currentTimeMillis(); //--new counts nack time to receive as well
modem.write(nack.getBytes());
ackresponseflag = 0;
nackpackets[requests]++;
}
else{
tmp[requests] = System.currentTimeMillis();
modem.write(ack.getBytes());
ackresponseflag = 1;
requests++;
}
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
System.out.print((char)k);
if (k==-1){
fout.write("\r\n".getBytes());
if (ackresponseflag == 0) //--new counts nack time to receive as well
responsetimen[requests] += System.currentTimeMillis() - tmpn[requests][nackpackets[requests]-1]; //--new
if (ackresponseflag == 1)
responsetime[requests] = System.currentTimeMillis() - tmp[requests-1];
responsetimetotal[requests] = responsetimen[requests] + responsetime[requests]; //--new
////////////////////////////////////////////////////////////////////////
kmscounter++;
break;
} // end of if k==-1
fout.write(k);
} catch (Exception x) {
break;
}
} // end of infinite for loop
BufferedReader in = null; // opens reader for the file to be scanned
try {
in = new BufferedReader(new FileReader("ack.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str;
ArrayList list = new ArrayList(); // puts every line of the file into list
try {
while((str = in.readLine()) != null){
list.add(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] stockArr = new String[list.size()]; // converts list into String array
String[] stringArr = (String[]) list.toArray(stockArr);
String temp = "";
for(int y = 49; y <=51 ; y++){
temp += Character.toString(stringArr[kmscounter-1].charAt(y));
}
//System.out.print("---fcsint---" + temp + "\n");
fcsint[kmscounter] = Integer.parseInt(temp); // gets integer value of fcs
temp ="";
for(int y = 31; y <=46 ; y++){
temp += Character.toString(stringArr[kmscounter-1].charAt(y));
}
sequence[kmscounter] = temp;
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fcsxorbyte[kmscounter] = sequence[kmscounter].getBytes(); // turns every sequence into bytes
byte tmpbyte = fcsxorbyte[kmscounter][0]; // initializes tmpbyte
for(int y = 0; y<15 ; y++){ // do xor to all characters
tmpbyte = (byte)(tmpbyte^fcsxorbyte[kmscounter][y+1]);
fcsxorbinary[kmscounter] = tmpbyte;
//System.out.print("--sequence--" + kmscounter + " is " + (int)fcsxorbinary[kmscounter] + "\n");
}
fcsxor[kmscounter] = (int) fcsxorbinary[kmscounter];
//System.out.print("--THE fcsxor[kmscounter]-- " + fcsxor[kmscounter] + "\n");
//System.out.print("--fcsxorbyte[kmscounter][0]--" + fcsxorbyte[kmscounter][0] + "\n");
//System.out.print("--fcsxorbyte[kmscounter][1]--" + fcsxorbyte[kmscounter][1] + "\n");
//byte test = (byte)(fcsxorbyte[kmscounter][2]^((byte) (fcsxorbyte[kmscounter][0]^fcsxorbyte[kmscounter][0+1])));
//System.out.print("--test--" + test + "\n");
//System.out.print("--final--" + fcsxor[kmscounter] + "\n");
whilecounter++;
} // end of while
modem.close();
String[] str = new String[requests];
for (int y=1;y<requests;y++){ // write input data of response times into file, start from 1 (0+1)
// because if you send n ack packets there are n-1 response times
//str[y] = Long.toString(responsetime[y]); //--new bring back
str[y] = Long.toString(responsetimetotal[y]); //--new
try (FileWriter out = new FileWriter("response_ack_nack.txt",true))
{
out.write(str[y]);
out.write("\r\n");
}
catch (IOException exc)
{
System.out.println("Exception ");
}
}
System.out.print("\n"+"--NUMBER OF REQUESTS (ACK PACKETS)--" + requests + "\n");
for(int i=0; i<requests; i++)
System.out.print("--NUMBER OF NACK (NACK PACKETS)--" + (i+1) + " " + nackpackets[i] + "\n");
} // end of acknackpackets2
public void chronoechopackets(long echotime) {
int k;
String[] str = new String[200]; // to save response times as strings
long[] responsetime = new long[200]; // to save response times
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("chronoecho", ".txt"); // opening file to store input data
int t = 0;
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
long start= System.currentTimeMillis();
long end = start + echotime;
long timesent;
while (System.currentTimeMillis() < end){
timesent = System.currentTimeMillis(); // start of measuring response time
modem.write(echo.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read(); // while k!=0
if (k==-1){
responsetime[t] = System.currentTimeMillis() - timesent; // end of measuring response time
fout.write("\r\n".getBytes());
t++;
break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
for (int y=0;y<t;y++){ // write input data of response times into file
str[y] = Long.toString(responsetime[y]);
try (FileWriter out = new FileWriter("echoresponse.txt",true))
{
out.write(str[y]);
out.write("\r\n");
}
catch (IOException exc)
{
System.out.println("Exception ");
}
}
}// end of chronoechopackets2
public void gpspackets() {
int k;
Modem modem = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout = makefile("gps", ".txt"); // opening file to store input data
int l = 0; // lines of N,E arrays, increases every time we find a packet with the correct format
modem.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k=modem.read();
if (k==-1){ break;}
System.out.print((char)k);
} catch (Exception x) {
break;
}
}
//////////////////////////////////
for (int i = 0; i<1; i++){
modem.write(gps.getBytes());
modem.write(gps2.getBytes()); // two different gps routes for the data files
for ( ; ; ) { //// it's for reading the characters
try {
k=modem.read();
if (k==-1){fout.write("\r\n".getBytes()); break;}
System.out.print((char)k);
fout.write(k);
} catch (Exception x) {
break;
}
}
}
modem.close();
//blankremover("gpstest.txt");
///////////////////////////////////////////////////////////////this part scans for the coordinates
BufferedReader in = null; // opens reader for the file to be scanned
try {
in = new BufferedReader(new FileReader("gps.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str;
ArrayList list = new ArrayList(); // puts every line of the file into list
try {
while((str = in.readLine()) != null){
list.add(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] stockArr = new String[list.size()]; // converts list into String array
String[] stringArr = (String[]) list.toArray(stockArr);
int numtraces=0; // traces that have 4" difference
String[] North = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
North[i] = "";
}
String[] East = new String[1000];
for(int i = 0; i < 1000; i++){
East[i] = "";
}
String[] Northconvert = new String[198]; //initialize Strings for North and South coordinates to be converted
for(int i = 0; i < 198; i++){
Northconvert[i] = "";
}
String[] Eastconvert = new String[198]; // 198 because that's the lines of the gps file
for(int i = 0; i < 198; i++){
Eastconvert[i] = "";
}
/////////////////////////////////////////////////////// initialize Strings for Hours, Minutes, Seconds
String[] Hours = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
Hours[i] = "0";
}
String[] Minutes = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
Minutes[i] = "0";
}
String[] Seconds = new String[1000]; //initialize Strings for North and South coordinates
for(int i = 0; i < 1000; i++){
Seconds[i] = "0";
}
int[] conversioneast= new int[1000]; // converts to " of degrees
int[] conversionnorth= new int[1000]; // converts to " of degrees
///////////////////////////////////////////////////////
String[] trace = new String[6]; // the final traces
for (int i = 1; i<(stringArr.length-2); i++){
if (stringArr[i].charAt(4) == 'G' ){ // checking for correct gps format
for(int y = 18; y<=21 ; y++){
North[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 23; y<=24 ; y++){
Northconvert[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 31; y<=34 ; y++ ){
East[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 36; y<=37; y++){
Eastconvert[l] += Character.toString(stringArr[i].charAt(y));
}
////////////////////////////////////////get time
for(int y = 7; y<=8 ; y++){ // hours
Hours[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 9; y<=10 ; y++){ // minutes
Minutes[l] += Character.toString(stringArr[i].charAt(y));
}
for(int y = 10; y<=11 ; y++){ // seconds
Seconds[l] += Character.toString(stringArr[i].charAt(y));
}
l++;
}
}
/////////////////////////////////////////////////////////// conversions
for (int y = 0; y < Northconvert.length; y++){
conversionnorth[y] = (int) (0.6 * Integer.valueOf(Northconvert[y])); // converts to "
Northconvert[y] = String.valueOf(conversionnorth[y]); // converts to String again
North[y] += Northconvert[y]; // re-attaches to String
conversioneast[y] = (int) (0.6 * Integer.valueOf(Eastconvert[y]));
Eastconvert[y] = String.valueOf(conversioneast[y]);
East[y] += Eastconvert[y];
}
//////////////////////////////////////////// making arrays for reading time
int[] hoursint = new int[Hours.length];
int[] minutesint = new int[Minutes.length];
int[] secondsint = new int[Seconds.length];
int[] timeint = new int[Hours.length];
for (int y = 0; y < Hours.length; y++){
hoursint[y] = 3600 * Integer.valueOf(Hours[y]);
minutesint[y] = 60 * Integer.valueOf(Minutes[y]);
secondsint[y] = 1 * Integer.valueOf(Seconds[y]);
timeint[y] = hoursint[y] + minutesint[y] + secondsint[y];
}
////////////////////////////////////////////////////////
int z; // trying to find traces that are 4" away, the numbers of z and y are random
for (z = 20; z < l; z++){
for(int y= z + 100; y<l;y=y+30, z += 50){
if ((Math.abs(timeint[z] - timeint[y])) >= 50
&& numtraces!=4){
trace[numtraces] = East[z] + North[z];
trace[numtraces+1] = East[y] + North[y];
numtraces=numtraces+2;
System.out.print(z + "\n");
}
}
}
/*
trace[0] = East[0] + North[0]; // since the time in the data is increasing by 1 sec in every packet
trace[1] = East[50] + North[50]; // the traces are definitely 4" away (50 secs to be exact)
trace[2] = East[100] + North[100];
trace[3] = East[150] + North[150];
*/
/////////////////////////////////////////////////////////////////////////new image
String newgpscode = new String();
newgpscode = gps_plain + "T=" + trace[0] +
"T=" + trace[1] +
"T=" + trace[2] +
"T=" + trace[3] + "\r";
System.out.print("THIS IS THE NEW GPS CODE " + newgpscode +"\n");
int k2;
Modem modem2 = setmodem(10000, 2000); // creates and initializes modem
FileOutputStream fout2 = makefile("gps", ".jpeg"); // opening file to store input data
modem2.open("ithaki");
for ( ; ; ) { //// it's for emptying the initial message
try {
k2=modem2.read();
if (k2==-1){ break;}
System.out.print((char)k2);
} catch (Exception x) {
break;
}
}
for (int i = 0; i<1; i++){
modem2.write(newgpscode.getBytes());
for ( ; ; ) { //// it's for reading the characters
try {
k2=modem2.read();
if (k2==-1){fout2.write("\r\n".getBytes()); break;}
System.out.print((char)k2);
fout2.write(k2);
} catch (Exception x) {
break;
}
}
}
modem2.close();
}// end of gpspackets
//////////////////removes empty lines from files (it isn't used eventually)
public void blankremover(String args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File(args));
writer = new PrintWriter("gpstest100.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
//Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
} // end of blankremover
} // end of class |
1470_10 | package gr.aueb.cf.c1.ch10;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Scanner;
public class MobileContactsApp {
final static String[][] contacts = new String[500][3];
static int pivot = -1;
final static Path path = Paths.get("C:/tmp/log-mobile.txt");
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
boolean quit = false;
String s;
int choice;
String phoneNumber;
do {
printMenu();
s = getChoice();
if (s.matches("[qQ]")) quit = true;
else {
try {
choice = Integer.parseInt(s);
if (!(isValid(choice))) {
throw new IllegalArgumentException("Error - Choice");
}
switch (choice) {
case 1:
printContactMenu();
insertController(getFirstname(), getLastname(), getPhoneNumber());
System.out.println("Επιτυχής Εισαγωγή");
break;
case 2:
phoneNumber = getPhoneNumber();
deleteController(phoneNumber);
System.out.println("Επιτυχής Διαγραφή");
break;
case 3:
phoneNumber = getPhoneNumber();
printContactMenu();
updateController(phoneNumber, getFirstname(), getLastname(), getPhoneNumber());
System.out.println("Επιτυχής Ενημέρωση");
break;
case 4:
phoneNumber = getPhoneNumber();
String[] contact = getOneController(phoneNumber);
printContact(contact);
break;
case 5:
String[][] allContacts = getAllController();
printAllContacts(allContacts);
break;
default:
throw new IllegalArgumentException("Bad choice");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}while (!quit);
}
public static void printContact(String[] contact) {
for (String s : contact) {
System.out.print(s + " ");
}
}
public static void printAllContacts(String[][] contacts) {
for (String[] contact : contacts) {
printContact(contact);
}
}
public static boolean isValid(int choice) {
return ((choice >= 1) && (choice <= 5));
}
public static void printMenu() {
System.out.println("Επιλέξτε ένα από τα παρακάτω");
System.out.println("1. Εισαγωγή επαφής");
System.out.println("2. Διαγραφή επαφής");
System.out.println("3. Ενημέρωση επαφής");
System.out.println("4. Αναζήτηση επαφής");
System.out.println("5. Εκτύπωση επαφής");
System.out.println("Q. Έξοδος επαφής");
}
public static String getChoice() {
System.out.println("Εισάγετε επιλογή");
return in.nextLine().trim();
}
public static void printContactMenu() {
System.out.println("Εισάγετε όνομα, επώνυμο, τηλέφωνο");
}
public static String getFirstname(){
System.out.println("Εισάγετε όνομα");
return in.nextLine().trim();
}
public static String getLastname(){
System.out.println("Εισάγετε επώνυμο");
return in.nextLine().trim();
}
public static String getPhoneNumber(){
System.out.println("Εισάγετε τηλέφωνο");
return in.nextLine().trim();
}
public static void insertController(String firstname, String lastname, String phoneNumber) {
try {
//validation
if (firstname == null || lastname == null || phoneNumber == null){
throw new IllegalArgumentException("Null are not allowed");
}
if (firstname.length() < 2 || firstname.length() > 50) {
throw new IllegalArgumentException("Firstname is not valid");
}
if (lastname.length() < 2 || lastname.length() > 50) {
throw new IllegalArgumentException("Last name is not valid");
}
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
//call services
insertContactServices(firstname.trim(), lastname.trim(), phoneNumber.trim());
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static void updateController(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
try {
//validation
if (oldPhoneNumber == null || firstname == null || lastname == null || newPhoneNumber == null){
throw new IllegalArgumentException("Null are not allowed");
}
if (oldPhoneNumber.length() < 2 || oldPhoneNumber.length() > 50) {
throw new IllegalArgumentException("Old number is not valid");
}
if (firstname.length() < 2 || firstname.length() > 50) {
throw new IllegalArgumentException("First name is not valid");
}
if (lastname.length() < 2 || lastname.length() > 50) {
throw new IllegalArgumentException("Last number is not valid");
}
if (newPhoneNumber.length() < 2 || newPhoneNumber.length() > 12) {
throw new IllegalArgumentException("New phone number is not valid");
}
//call services
updateContactServices(oldPhoneNumber.trim(), firstname.trim(), lastname.trim(), newPhoneNumber.trim());
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[] deleteController(String phoneNumber) {
try {
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
return deleteController(phoneNumber);
}catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[] getOneController(String phoneNumber) {
try {
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
return getOneController(phoneNumber);
}catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[][] getAllController() {
try {
return getAllContactsServices();
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
/*
CRUD services that are provided to
Services Layer
*/
public static int getIndexByPhone(String phoneNumber) {
for (int i = 0; i <= pivot; i++) {
if (contacts[i][2].equals(phoneNumber)) {
return i;
}
}
return -1; // if not found
}
public static boolean insert(String firstname, String lastname, String phoneNumber) {
boolean inserted = false;
if(isFull(contacts)) {
return false;
}
if (getIndexByPhone(phoneNumber) != -1) {
return false;
}
pivot++;
contacts[pivot][0] = firstname;
contacts[pivot][1] = lastname;
contacts[pivot][2] = phoneNumber;
return true;
}
public static boolean update(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
int positionToUpdate = getIndexByPhone(oldPhoneNumber);
String[] contact = new String[3];
if (positionToUpdate == -1) {
return false;
// return new String[] {};
}
// contact[0] = contacts[positionToUpdate][0];
// contact[1] = contacts[positionToUpdate][1];
// contact[2] = contacts[positionToUpdate][2];
contacts[positionToUpdate][0] = firstname;
contacts[positionToUpdate][1] = lastname;
contacts[positionToUpdate][2] = newPhoneNumber;
return true;
}
public static String[] delete(String phoneNumber) {
int positionToDelete = getIndexByPhone(phoneNumber);
String[] contact = new String[3];
if (positionToDelete == -1) {
return new String[] {};
}
System.arraycopy(contacts[positionToDelete], 0, contact, 0, contact.length);
if (!(positionToDelete == contacts.length - 1)) {
System.arraycopy(contacts, positionToDelete + 1, contacts, positionToDelete, pivot - positionToDelete);
}
pivot--;
return contact;
}
public static String[] getContactByPhoneNumber(String phoneNumber) {
int positionToReturn = getIndexByPhone(phoneNumber);
if (positionToReturn == -1) {
return new String[] {};
}
return contacts[positionToReturn];
}
public static String[][] getAllContacts() {
return Arrays.copyOf(contacts, pivot + 1);
}
// όταν ο pivot δείχνει στην arr.length - 1 αυτό σημαίνει ότι δείχνει στην τελευταία θέση και είναι full
public static boolean isFull(String[][] arr) {
return pivot == arr.length - 1;
}
/*
* Service layer
*/
public static String[] getOneContactService(String phoneNumber) {
try {
String[] contact = getContactByPhoneNumber(phoneNumber);
if (contact.length == 0) {
throw new IllegalArgumentException("Contact not found");
}
return contact;
}catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static String[][] getAllContactsServices() {
try {
String[][] contactsList = getAllContacts();
if (contactsList.length == 0) {
throw new IllegalArgumentException("List is empty");
}
return contactsList;
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static void insertContactServices(String firstname, String lastname, String phoneNumber){
try {
if (!(insert(firstname,lastname,phoneNumber))) {
throw new IllegalArgumentException("Error in insert");
}
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static void updateContactServices(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
try {
if (!(update(oldPhoneNumber, firstname, lastname, newPhoneNumber))) {
throw new IllegalArgumentException("Error in update");
}
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static String[] deleteContactServices(String phoneNumber) {
String[] contact;
try {
contact = delete(phoneNumber);
if (contact.length == 0) {
throw new IllegalArgumentException("Error in delete");
}
return contact;
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
/*
* Custom logger
* ... varargs
*/
public static void log(Exception e, String... message) {
try(PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) {
ps.println(LocalDateTime.now() + "\n" + e.toString());
ps.printf("%s", (message.length == 1) ? message[0] : "");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
| KONSTANTINOS-EL/MobileContact | MobileContactsApp.java | 2,789 | // όταν ο pivot δείχνει στην arr.length - 1 αυτό σημαίνει ότι δείχνει στην τελευταία θέση και είναι full | line_comment | el | package gr.aueb.cf.c1.ch10;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Scanner;
public class MobileContactsApp {
final static String[][] contacts = new String[500][3];
static int pivot = -1;
final static Path path = Paths.get("C:/tmp/log-mobile.txt");
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
boolean quit = false;
String s;
int choice;
String phoneNumber;
do {
printMenu();
s = getChoice();
if (s.matches("[qQ]")) quit = true;
else {
try {
choice = Integer.parseInt(s);
if (!(isValid(choice))) {
throw new IllegalArgumentException("Error - Choice");
}
switch (choice) {
case 1:
printContactMenu();
insertController(getFirstname(), getLastname(), getPhoneNumber());
System.out.println("Επιτυχής Εισαγωγή");
break;
case 2:
phoneNumber = getPhoneNumber();
deleteController(phoneNumber);
System.out.println("Επιτυχής Διαγραφή");
break;
case 3:
phoneNumber = getPhoneNumber();
printContactMenu();
updateController(phoneNumber, getFirstname(), getLastname(), getPhoneNumber());
System.out.println("Επιτυχής Ενημέρωση");
break;
case 4:
phoneNumber = getPhoneNumber();
String[] contact = getOneController(phoneNumber);
printContact(contact);
break;
case 5:
String[][] allContacts = getAllController();
printAllContacts(allContacts);
break;
default:
throw new IllegalArgumentException("Bad choice");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}while (!quit);
}
public static void printContact(String[] contact) {
for (String s : contact) {
System.out.print(s + " ");
}
}
public static void printAllContacts(String[][] contacts) {
for (String[] contact : contacts) {
printContact(contact);
}
}
public static boolean isValid(int choice) {
return ((choice >= 1) && (choice <= 5));
}
public static void printMenu() {
System.out.println("Επιλέξτε ένα από τα παρακάτω");
System.out.println("1. Εισαγωγή επαφής");
System.out.println("2. Διαγραφή επαφής");
System.out.println("3. Ενημέρωση επαφής");
System.out.println("4. Αναζήτηση επαφής");
System.out.println("5. Εκτύπωση επαφής");
System.out.println("Q. Έξοδος επαφής");
}
public static String getChoice() {
System.out.println("Εισάγετε επιλογή");
return in.nextLine().trim();
}
public static void printContactMenu() {
System.out.println("Εισάγετε όνομα, επώνυμο, τηλέφωνο");
}
public static String getFirstname(){
System.out.println("Εισάγετε όνομα");
return in.nextLine().trim();
}
public static String getLastname(){
System.out.println("Εισάγετε επώνυμο");
return in.nextLine().trim();
}
public static String getPhoneNumber(){
System.out.println("Εισάγετε τηλέφωνο");
return in.nextLine().trim();
}
public static void insertController(String firstname, String lastname, String phoneNumber) {
try {
//validation
if (firstname == null || lastname == null || phoneNumber == null){
throw new IllegalArgumentException("Null are not allowed");
}
if (firstname.length() < 2 || firstname.length() > 50) {
throw new IllegalArgumentException("Firstname is not valid");
}
if (lastname.length() < 2 || lastname.length() > 50) {
throw new IllegalArgumentException("Last name is not valid");
}
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
//call services
insertContactServices(firstname.trim(), lastname.trim(), phoneNumber.trim());
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static void updateController(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
try {
//validation
if (oldPhoneNumber == null || firstname == null || lastname == null || newPhoneNumber == null){
throw new IllegalArgumentException("Null are not allowed");
}
if (oldPhoneNumber.length() < 2 || oldPhoneNumber.length() > 50) {
throw new IllegalArgumentException("Old number is not valid");
}
if (firstname.length() < 2 || firstname.length() > 50) {
throw new IllegalArgumentException("First name is not valid");
}
if (lastname.length() < 2 || lastname.length() > 50) {
throw new IllegalArgumentException("Last number is not valid");
}
if (newPhoneNumber.length() < 2 || newPhoneNumber.length() > 12) {
throw new IllegalArgumentException("New phone number is not valid");
}
//call services
updateContactServices(oldPhoneNumber.trim(), firstname.trim(), lastname.trim(), newPhoneNumber.trim());
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[] deleteController(String phoneNumber) {
try {
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
return deleteController(phoneNumber);
}catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[] getOneController(String phoneNumber) {
try {
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
return getOneController(phoneNumber);
}catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[][] getAllController() {
try {
return getAllContactsServices();
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
/*
CRUD services that are provided to
Services Layer
*/
public static int getIndexByPhone(String phoneNumber) {
for (int i = 0; i <= pivot; i++) {
if (contacts[i][2].equals(phoneNumber)) {
return i;
}
}
return -1; // if not found
}
public static boolean insert(String firstname, String lastname, String phoneNumber) {
boolean inserted = false;
if(isFull(contacts)) {
return false;
}
if (getIndexByPhone(phoneNumber) != -1) {
return false;
}
pivot++;
contacts[pivot][0] = firstname;
contacts[pivot][1] = lastname;
contacts[pivot][2] = phoneNumber;
return true;
}
public static boolean update(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
int positionToUpdate = getIndexByPhone(oldPhoneNumber);
String[] contact = new String[3];
if (positionToUpdate == -1) {
return false;
// return new String[] {};
}
// contact[0] = contacts[positionToUpdate][0];
// contact[1] = contacts[positionToUpdate][1];
// contact[2] = contacts[positionToUpdate][2];
contacts[positionToUpdate][0] = firstname;
contacts[positionToUpdate][1] = lastname;
contacts[positionToUpdate][2] = newPhoneNumber;
return true;
}
public static String[] delete(String phoneNumber) {
int positionToDelete = getIndexByPhone(phoneNumber);
String[] contact = new String[3];
if (positionToDelete == -1) {
return new String[] {};
}
System.arraycopy(contacts[positionToDelete], 0, contact, 0, contact.length);
if (!(positionToDelete == contacts.length - 1)) {
System.arraycopy(contacts, positionToDelete + 1, contacts, positionToDelete, pivot - positionToDelete);
}
pivot--;
return contact;
}
public static String[] getContactByPhoneNumber(String phoneNumber) {
int positionToReturn = getIndexByPhone(phoneNumber);
if (positionToReturn == -1) {
return new String[] {};
}
return contacts[positionToReturn];
}
public static String[][] getAllContacts() {
return Arrays.copyOf(contacts, pivot + 1);
}
// ότ<SUF>
public static boolean isFull(String[][] arr) {
return pivot == arr.length - 1;
}
/*
* Service layer
*/
public static String[] getOneContactService(String phoneNumber) {
try {
String[] contact = getContactByPhoneNumber(phoneNumber);
if (contact.length == 0) {
throw new IllegalArgumentException("Contact not found");
}
return contact;
}catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static String[][] getAllContactsServices() {
try {
String[][] contactsList = getAllContacts();
if (contactsList.length == 0) {
throw new IllegalArgumentException("List is empty");
}
return contactsList;
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static void insertContactServices(String firstname, String lastname, String phoneNumber){
try {
if (!(insert(firstname,lastname,phoneNumber))) {
throw new IllegalArgumentException("Error in insert");
}
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static void updateContactServices(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
try {
if (!(update(oldPhoneNumber, firstname, lastname, newPhoneNumber))) {
throw new IllegalArgumentException("Error in update");
}
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static String[] deleteContactServices(String phoneNumber) {
String[] contact;
try {
contact = delete(phoneNumber);
if (contact.length == 0) {
throw new IllegalArgumentException("Error in delete");
}
return contact;
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
/*
* Custom logger
* ... varargs
*/
public static void log(Exception e, String... message) {
try(PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) {
ps.println(LocalDateTime.now() + "\n" + e.toString());
ps.printf("%s", (message.length == 1) ? message[0] : "");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
|
2352_6 | import java.io.IOException;
import java.util.HashSet;
import java.util.Scanner;
public interface UIMethods
{
/**
* Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος σε όλες τις βάσεις δεδομένων που χρησιμοποιούνται
*/
static void updateDatabases() throws IOException
{
User.updateDatabase(UI.user);
Messages.updateDatabase();
Rental.updateDatabase();
Date.updateDatabase();
}
/**
* Διαβάζει έναν αριθμό από το terminal και σιγουρεύεται πως βρίσκεται σε ένα εύρος ακεραίων
*
* @param from αρχή εύρους
* @param to τέλος εύρους(μπορεί να παραληφθεί)
* @return τον ακεραιο που διάβασε
*/
static int validityCheck(int from, int to)
{
boolean go = false;
int entry = 0;
while (!go)
{
entry = UI.input.nextInt();
if (entry >= from && entry <= to)
{
go = true;
}
else
{
System.out.println("=======================================");
System.out.println("Please enter a number from " + from + " to " + to);
System.out.println("=======================================");
}
}
return entry;
}
/**
* @see #validityCheck(int, int)
*/
static int validityCheck(int from)
{
boolean go = false;
int entry = 0;
while (!go)
{
entry = UI.input.nextInt();
if (entry >= from)
{
go = true;
}
else
{
System.out.println("=======================================");
System.out.println("Please enter a number larger than " + from);
System.out.println("=======================================");
}
}
return entry;
}
/**
* Διαβάζει ένα username, και ανάλογα με τη μεταβλητή available επιτρέπει usernames που υπάρχουν ή δεν υπάρχουν στο database
*
* @param available αν true, σιγουρεύεται πως το username δεν ανήκει σε κανέναν χρήστη <p>
* αν false, σιγουρεύεται πως το username ανήκει σε κάποιον χρήστη
* @return το username που διάβασε
*/
static String inputUserName(boolean available)
{
boolean go = false;
String username = "";
while (!go)
{
username = UI.input.next();
if (User.checkUsernameAvailability(username) != available)
{
if (available)
{
System.out.println("=======================================");
System.out.println("Username taken");
System.out.println("Username :");
}
else
{
System.out.println("=======================================");
System.out.println("User doesn't exist");
System.out.println("Username :");
}
}
else
{
go = true;
}
}
return username;
}
/**
* Διαβάζει ένα id που αντιστοιχεί σε κάποιο κατάλυμα
*
* @return το id που διάβασε
*/
static String inputValidId()
{
boolean go = false;
String id = "";
while (!go)
{
id = UI.input.next();
if (Rental.checkIdAvailability(id))
{
System.out.println("=======================================");
System.out.println("Id doesn't correspond to an existing rental");
System.out.println("Input id:");
System.out.println("=======================================");
}
else
{
go = true;
}
}
return id;
}
/**
* Διαβάζει και ελέγχει το password του χρήστη που προσπαθεί να κάνει login
* Αν βάλει 5 φορές λάθος password τότε κλείνει την εφαρμογή
*
* @return το έγκυρο password του χρήστη
*/
static String inputPassword()
{
String password = "";
boolean go = false;
int tries = 0;
while (!go)
{
password = UI.input.next();
if (!password.equals(UI.user.getCredential("password")))
{
tries++;
if (tries == 5)
{
System.out.println("=======================================");
System.out.println("Failed to enter password too many times");
System.out.println("Goodbye :)");
System.out.println("=======================================");
System.exit(0);
}
else
{
System.out.println("=======================================");
System.out.println("Incorrect password");
System.out.println(5 - tries + " tries remaining");
System.out.println("Password :");
}
}
else
{
go = true;
}
}
return password;
}
/**
* Διαβάζει ένα καινούργιο password από το terminal
*
* @return το νέο password
*/
static String newPassword()
{
boolean go = false;
String pass1 = " ";
while (!go)
{
pass1 = UI.input.next();
if (pass1.equals("password") || pass1.equals("Password"))
{
System.out.println("=======================================");
System.out.println("Your Password cant be '" + pass1 + "'");
System.out.println("Try something else");
System.out.println("Password :");
}
else
{
go = true;
}
}
System.out.println("=======================================");
System.out.println("Please re-enter your Password :");
String pass2 = "";
go = false;
while (!go)
{
pass2 = UI.input.next();
if (!pass2.equals(pass1))
{
System.out.println("=======================================");
System.out.println("Passwords don't match");
System.out.println("Re-enter Password :");
}
else
{
go = true;
}
}
return pass1;
}
/**
* Διαβάζει ένα καινούργιο email από το terminal
*
* @return το νέο email
*/
static String newEmail()
{
boolean go = false;
String email = "";
while (!go)
{
email = UI.input.next();
if (!email.contains(".") || !email.contains("@"))
{
System.out.println("=======================================");
System.out.println("Invalid email address");
System.out.println("Enter email :");
}
else if (!User.checkCredentialAvailability("email", email))
{
System.out.println("=======================================");
System.out.println("Email already in use");
System.out.println("Enter email :");
}
else
{
go = true;
}
}
return email;
}
/**
* Διαβάζει ένα καινούργιο τηλεφωνικό αριθμό από το terminal
*
* @return το νέο αριθμό
*/
static String newPhone()
{
boolean go = false;
String newPhone = "";
while (!go)
{
newPhone = UI.input.next();
if (newPhone.length() != 10)
{
System.out.println("=======================================");
System.out.println("Invalid Phone Number");
System.out.println("Phone :");
}
else
{
go = true;
}
}
System.out.println("=======================================");
return newPhone;
}
/**
* Επιτρέπει την επεξεργασία όλων των χαρακτηριστικών ενός καταλύματος από το terminal
*
* @param rental το κατάλυμα προς επεξεργασία
*/
static void editRental(Rental rental)
{
System.out.println("=======================================");
System.out.println("What would you like to edit?");
System.out.println("0.Nothing");
System.out.println("1.Name");
System.out.println("2.Type");
System.out.println("3.Location");
System.out.println("4.m^2");
System.out.println("5.Price");
System.out.println("6.Wifi");
System.out.println("7.Parking");
System.out.println("8.Pool");
System.out.println("=======================================");
int entry = validityCheck(0,8);
Scanner lineScanner = new Scanner(System.in);
if (entry == 1)
{
System.out.println("Please enter new Name:");
String name = lineScanner.nextLine();
rental.setCharacteristic("name", name);
System.out.println("Name changed");
System.out.println("=======================================");
}
else if (entry == 2)
{
System.out.println("Please enter new Type:");
String type = lineScanner.nextLine();
rental.setCharacteristic("type", type);
System.out.println("Type changed");
System.out.println("=======================================");
}
else if (entry == 3)
{
System.out.println("Please enter new Location:");
String location = lineScanner.nextLine();
rental.setCharacteristic("location", location);
System.out.println("Location changed");
System.out.println("=======================================");
}
else if (entry==4)
{
System.out.println("Please enter new m^2");
String m2 = lineScanner.nextLine();
rental.setCharacteristic("m2",m2);
System.out.println("m^2 changed");
System.out.println("=======================================");
}
else if (entry == 5)
{
System.out.println("Please enter new price:");
String price = lineScanner.nextLine();
rental.setCharacteristic("price", price);
System.out.println("Price changed");
System.out.println("=======================================");
}
else if (entry == 6)
{
System.out.println("Does your Rental Provide Wifi?:");
boolCharacteristicEntry(rental,"wifi");
System.out.println("Wifi changed");
System.out.println("=======================================");
}
else if (entry == 7)
{
System.out.println("Does your Rental Provide Parking?:");
boolCharacteristicEntry(rental,"parking");
System.out.println("Parking changed");
System.out.println("=======================================");
}
else if (entry == 8)
{
System.out.println("Does your Rental Provide Pool?:");
boolCharacteristicEntry(rental,"pool");
System.out.println("Pool changed");
System.out.println("=======================================");
}
rental.updateCharacteristics();
}
/**
* Εκτυπώνει τα στοιχεία ενός καταλύματος στο terminal
*
* @param rental to κατάλυμα προς εκτύπωση
*/
static void showRental(Rental rental)
{
System.out.println("=======================================");
System.out.println("Id: " + rental.getId());
System.out.println("Name: " + rental.getCharacteristic("name"));
System.out.println("Type: " + rental.getCharacteristic("type"));
System.out.println("Location: " + rental.getCharacteristic("location"));
System.out.println("m^2 :" + rental.getCharacteristic("m2"));
System.out.println("Per Day Price: " + rental.getCharacteristic("price"));
System.out.println("Wifi: " + rental.getCharacteristic("wifi"));
System.out.println("Parking :" + rental.getCharacteristic("parking"));
System.out.println("Pool :" + rental.getCharacteristic("pool"));
System.out.println("=======================================");
}
/**
* Διαβάζει μία ημερομηνία από το terminal
*
* @return την ημερομηνία
*/
static Date inputDate()
{
System.out.println("Year:");
int year = validityCheck(2021);
System.out.println("Month:");
int month = validityCheck(1, 12);
System.out.println("Day:");
int day = validityCheck(1, 30);
Date date = new Date(day, month, year);
return date;
}
/**
* Διαβάζει δυαδικά χαρακτηριστικά καταλυμάτων (πχ wifi, ναι ή οχι)
* @param rental το κατάλυμα του οποίου το χαρακτηριστικό διαβάζουμε
* @param type το χαρακτηριστικό που θα διαβάσουμε
*/
static void boolCharacteristicEntry(Rental rental, String type)
{
System.out.println("1.Yes");
System.out.println("2.No");
int entry = validityCheck(1,2);
if(entry==1)
{
rental.addCharacteristic(type,"yes");
}
else
{
rental.addCharacteristic(type,"no");
}
}
/**
* Συγκεκριμένος τύπος φίλτρου για αριθμητικά φάσματα
* @param ids τα ids που είναι διαθέσιμα πριν το φιλτράρισμα
* @param type ο τύπος χαρακτηριστικού που φιλτράρουμε
* @return τα ids που είναι διαθέσιμα μετά το φιλτράρισμα
*/
static HashSet<String> filterIntRange(HashSet<String> ids, String type)
{
System.out.println("=======================================");
System.out.println("Minimum:");
int min = validityCheck(0);
System.out.println("Maximum:");
int max = validityCheck(min);
System.out.println("=======================================");
HashSet<String> toKeep = new HashSet<>();
for (int i = min; i <= max; i++)
{
Integer value = i;
HashSet<String> tIds = Rental.strongFilter(ids,type,value.toString());
toKeep.addAll(tIds);
}
ids.retainAll(toKeep);
return ids;
}
/**
* Φιλτράρει τα αποτελέσματα της αναζήτησης με διάφορα κριτήρια
* @param ids τα ids που είναι διαθέσιμα πριν το φιλτράρισμα
* @return τα ids που είναι διαθέσιμα μετά το φιλτράρισμα
*/
static HashSet<String> addFilters(HashSet<String> ids)
{
System.out.println("=======================================");
System.out.println("Specify Rental Type? (Hotel,bnb,etc.):");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
int entry = validityCheck(1,2);
if (entry == 1)
{
System.out.println("What type of rental would you like to see?");
Scanner lineScanner2 = new Scanner(System.in);
String type = lineScanner2.nextLine();
ids = Rental.filter(ids,"type",type);
}
System.out.println("=======================================");
System.out.println("Specify Location?");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
entry = validityCheck(1,2);
if (entry == 1)
{
System.out.println("Where are you going?");
Scanner lineScan = new Scanner(System.in);
String location = lineScan.nextLine();
ids = Rental.filter(ids,"location",location);
}
System.out.println("=======================================");
System.out.println("Specify Square Meters ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
entry = validityCheck(1,2);
if (entry == 1)
{
ids = filterIntRange(ids,"m2");
}
System.out.println("=======================================");
System.out.println("Specify Price Range ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
entry = validityCheck(1,2);
if (entry == 1)
{
ids = filterIntRange(ids,"price");
}
System.out.println("=======================================");
System.out.println("WiFi ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("3.Don't Care");
System.out.println("=======================================");
entry = validityCheck(1,3);
if (entry == 1)
{
ids = Rental.strongFilter(ids,"wifi","yes");
}
else if (entry == 2)
{
ids = Rental.strongFilter(ids,"wifi","no");
}
System.out.println("=======================================");
System.out.println("Parking ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("3.Don't Care");
System.out.println("=======================================");
entry = validityCheck(1,3);
if (entry == 1)
{
ids = Rental.strongFilter(ids,"parking","yes");
}
else if (entry == 2)
{
ids = Rental.strongFilter(ids,"parking","no");
}
System.out.println("=======================================");
System.out.println("Pool ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("3.Don't Care");
System.out.println("=======================================");
entry = validityCheck(1,3);
if (entry == 1)
{
ids = Rental.strongFilter(ids,"pool","yes");
}
else if (entry == 2)
{
ids = Rental.strongFilter(ids,"pool","no");
}
return ids;
}
}
| KonnosBaz/AUTh_CSD_Projects | Object Oriented Programming (2021)/src/UIMethods.java | 4,945 | /**
* Διαβάζει ένα καινούργιο password από το terminal
*
* @return το νέο password
*/ | block_comment | el | import java.io.IOException;
import java.util.HashSet;
import java.util.Scanner;
public interface UIMethods
{
/**
* Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος σε όλες τις βάσεις δεδομένων που χρησιμοποιούνται
*/
static void updateDatabases() throws IOException
{
User.updateDatabase(UI.user);
Messages.updateDatabase();
Rental.updateDatabase();
Date.updateDatabase();
}
/**
* Διαβάζει έναν αριθμό από το terminal και σιγουρεύεται πως βρίσκεται σε ένα εύρος ακεραίων
*
* @param from αρχή εύρους
* @param to τέλος εύρους(μπορεί να παραληφθεί)
* @return τον ακεραιο που διάβασε
*/
static int validityCheck(int from, int to)
{
boolean go = false;
int entry = 0;
while (!go)
{
entry = UI.input.nextInt();
if (entry >= from && entry <= to)
{
go = true;
}
else
{
System.out.println("=======================================");
System.out.println("Please enter a number from " + from + " to " + to);
System.out.println("=======================================");
}
}
return entry;
}
/**
* @see #validityCheck(int, int)
*/
static int validityCheck(int from)
{
boolean go = false;
int entry = 0;
while (!go)
{
entry = UI.input.nextInt();
if (entry >= from)
{
go = true;
}
else
{
System.out.println("=======================================");
System.out.println("Please enter a number larger than " + from);
System.out.println("=======================================");
}
}
return entry;
}
/**
* Διαβάζει ένα username, και ανάλογα με τη μεταβλητή available επιτρέπει usernames που υπάρχουν ή δεν υπάρχουν στο database
*
* @param available αν true, σιγουρεύεται πως το username δεν ανήκει σε κανέναν χρήστη <p>
* αν false, σιγουρεύεται πως το username ανήκει σε κάποιον χρήστη
* @return το username που διάβασε
*/
static String inputUserName(boolean available)
{
boolean go = false;
String username = "";
while (!go)
{
username = UI.input.next();
if (User.checkUsernameAvailability(username) != available)
{
if (available)
{
System.out.println("=======================================");
System.out.println("Username taken");
System.out.println("Username :");
}
else
{
System.out.println("=======================================");
System.out.println("User doesn't exist");
System.out.println("Username :");
}
}
else
{
go = true;
}
}
return username;
}
/**
* Διαβάζει ένα id που αντιστοιχεί σε κάποιο κατάλυμα
*
* @return το id που διάβασε
*/
static String inputValidId()
{
boolean go = false;
String id = "";
while (!go)
{
id = UI.input.next();
if (Rental.checkIdAvailability(id))
{
System.out.println("=======================================");
System.out.println("Id doesn't correspond to an existing rental");
System.out.println("Input id:");
System.out.println("=======================================");
}
else
{
go = true;
}
}
return id;
}
/**
* Διαβάζει και ελέγχει το password του χρήστη που προσπαθεί να κάνει login
* Αν βάλει 5 φορές λάθος password τότε κλείνει την εφαρμογή
*
* @return το έγκυρο password του χρήστη
*/
static String inputPassword()
{
String password = "";
boolean go = false;
int tries = 0;
while (!go)
{
password = UI.input.next();
if (!password.equals(UI.user.getCredential("password")))
{
tries++;
if (tries == 5)
{
System.out.println("=======================================");
System.out.println("Failed to enter password too many times");
System.out.println("Goodbye :)");
System.out.println("=======================================");
System.exit(0);
}
else
{
System.out.println("=======================================");
System.out.println("Incorrect password");
System.out.println(5 - tries + " tries remaining");
System.out.println("Password :");
}
}
else
{
go = true;
}
}
return password;
}
/**
* Δια<SUF>*/
static String newPassword()
{
boolean go = false;
String pass1 = " ";
while (!go)
{
pass1 = UI.input.next();
if (pass1.equals("password") || pass1.equals("Password"))
{
System.out.println("=======================================");
System.out.println("Your Password cant be '" + pass1 + "'");
System.out.println("Try something else");
System.out.println("Password :");
}
else
{
go = true;
}
}
System.out.println("=======================================");
System.out.println("Please re-enter your Password :");
String pass2 = "";
go = false;
while (!go)
{
pass2 = UI.input.next();
if (!pass2.equals(pass1))
{
System.out.println("=======================================");
System.out.println("Passwords don't match");
System.out.println("Re-enter Password :");
}
else
{
go = true;
}
}
return pass1;
}
/**
* Διαβάζει ένα καινούργιο email από το terminal
*
* @return το νέο email
*/
static String newEmail()
{
boolean go = false;
String email = "";
while (!go)
{
email = UI.input.next();
if (!email.contains(".") || !email.contains("@"))
{
System.out.println("=======================================");
System.out.println("Invalid email address");
System.out.println("Enter email :");
}
else if (!User.checkCredentialAvailability("email", email))
{
System.out.println("=======================================");
System.out.println("Email already in use");
System.out.println("Enter email :");
}
else
{
go = true;
}
}
return email;
}
/**
* Διαβάζει ένα καινούργιο τηλεφωνικό αριθμό από το terminal
*
* @return το νέο αριθμό
*/
static String newPhone()
{
boolean go = false;
String newPhone = "";
while (!go)
{
newPhone = UI.input.next();
if (newPhone.length() != 10)
{
System.out.println("=======================================");
System.out.println("Invalid Phone Number");
System.out.println("Phone :");
}
else
{
go = true;
}
}
System.out.println("=======================================");
return newPhone;
}
/**
* Επιτρέπει την επεξεργασία όλων των χαρακτηριστικών ενός καταλύματος από το terminal
*
* @param rental το κατάλυμα προς επεξεργασία
*/
static void editRental(Rental rental)
{
System.out.println("=======================================");
System.out.println("What would you like to edit?");
System.out.println("0.Nothing");
System.out.println("1.Name");
System.out.println("2.Type");
System.out.println("3.Location");
System.out.println("4.m^2");
System.out.println("5.Price");
System.out.println("6.Wifi");
System.out.println("7.Parking");
System.out.println("8.Pool");
System.out.println("=======================================");
int entry = validityCheck(0,8);
Scanner lineScanner = new Scanner(System.in);
if (entry == 1)
{
System.out.println("Please enter new Name:");
String name = lineScanner.nextLine();
rental.setCharacteristic("name", name);
System.out.println("Name changed");
System.out.println("=======================================");
}
else if (entry == 2)
{
System.out.println("Please enter new Type:");
String type = lineScanner.nextLine();
rental.setCharacteristic("type", type);
System.out.println("Type changed");
System.out.println("=======================================");
}
else if (entry == 3)
{
System.out.println("Please enter new Location:");
String location = lineScanner.nextLine();
rental.setCharacteristic("location", location);
System.out.println("Location changed");
System.out.println("=======================================");
}
else if (entry==4)
{
System.out.println("Please enter new m^2");
String m2 = lineScanner.nextLine();
rental.setCharacteristic("m2",m2);
System.out.println("m^2 changed");
System.out.println("=======================================");
}
else if (entry == 5)
{
System.out.println("Please enter new price:");
String price = lineScanner.nextLine();
rental.setCharacteristic("price", price);
System.out.println("Price changed");
System.out.println("=======================================");
}
else if (entry == 6)
{
System.out.println("Does your Rental Provide Wifi?:");
boolCharacteristicEntry(rental,"wifi");
System.out.println("Wifi changed");
System.out.println("=======================================");
}
else if (entry == 7)
{
System.out.println("Does your Rental Provide Parking?:");
boolCharacteristicEntry(rental,"parking");
System.out.println("Parking changed");
System.out.println("=======================================");
}
else if (entry == 8)
{
System.out.println("Does your Rental Provide Pool?:");
boolCharacteristicEntry(rental,"pool");
System.out.println("Pool changed");
System.out.println("=======================================");
}
rental.updateCharacteristics();
}
/**
* Εκτυπώνει τα στοιχεία ενός καταλύματος στο terminal
*
* @param rental to κατάλυμα προς εκτύπωση
*/
static void showRental(Rental rental)
{
System.out.println("=======================================");
System.out.println("Id: " + rental.getId());
System.out.println("Name: " + rental.getCharacteristic("name"));
System.out.println("Type: " + rental.getCharacteristic("type"));
System.out.println("Location: " + rental.getCharacteristic("location"));
System.out.println("m^2 :" + rental.getCharacteristic("m2"));
System.out.println("Per Day Price: " + rental.getCharacteristic("price"));
System.out.println("Wifi: " + rental.getCharacteristic("wifi"));
System.out.println("Parking :" + rental.getCharacteristic("parking"));
System.out.println("Pool :" + rental.getCharacteristic("pool"));
System.out.println("=======================================");
}
/**
* Διαβάζει μία ημερομηνία από το terminal
*
* @return την ημερομηνία
*/
static Date inputDate()
{
System.out.println("Year:");
int year = validityCheck(2021);
System.out.println("Month:");
int month = validityCheck(1, 12);
System.out.println("Day:");
int day = validityCheck(1, 30);
Date date = new Date(day, month, year);
return date;
}
/**
* Διαβάζει δυαδικά χαρακτηριστικά καταλυμάτων (πχ wifi, ναι ή οχι)
* @param rental το κατάλυμα του οποίου το χαρακτηριστικό διαβάζουμε
* @param type το χαρακτηριστικό που θα διαβάσουμε
*/
static void boolCharacteristicEntry(Rental rental, String type)
{
System.out.println("1.Yes");
System.out.println("2.No");
int entry = validityCheck(1,2);
if(entry==1)
{
rental.addCharacteristic(type,"yes");
}
else
{
rental.addCharacteristic(type,"no");
}
}
/**
* Συγκεκριμένος τύπος φίλτρου για αριθμητικά φάσματα
* @param ids τα ids που είναι διαθέσιμα πριν το φιλτράρισμα
* @param type ο τύπος χαρακτηριστικού που φιλτράρουμε
* @return τα ids που είναι διαθέσιμα μετά το φιλτράρισμα
*/
static HashSet<String> filterIntRange(HashSet<String> ids, String type)
{
System.out.println("=======================================");
System.out.println("Minimum:");
int min = validityCheck(0);
System.out.println("Maximum:");
int max = validityCheck(min);
System.out.println("=======================================");
HashSet<String> toKeep = new HashSet<>();
for (int i = min; i <= max; i++)
{
Integer value = i;
HashSet<String> tIds = Rental.strongFilter(ids,type,value.toString());
toKeep.addAll(tIds);
}
ids.retainAll(toKeep);
return ids;
}
/**
* Φιλτράρει τα αποτελέσματα της αναζήτησης με διάφορα κριτήρια
* @param ids τα ids που είναι διαθέσιμα πριν το φιλτράρισμα
* @return τα ids που είναι διαθέσιμα μετά το φιλτράρισμα
*/
static HashSet<String> addFilters(HashSet<String> ids)
{
System.out.println("=======================================");
System.out.println("Specify Rental Type? (Hotel,bnb,etc.):");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
int entry = validityCheck(1,2);
if (entry == 1)
{
System.out.println("What type of rental would you like to see?");
Scanner lineScanner2 = new Scanner(System.in);
String type = lineScanner2.nextLine();
ids = Rental.filter(ids,"type",type);
}
System.out.println("=======================================");
System.out.println("Specify Location?");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
entry = validityCheck(1,2);
if (entry == 1)
{
System.out.println("Where are you going?");
Scanner lineScan = new Scanner(System.in);
String location = lineScan.nextLine();
ids = Rental.filter(ids,"location",location);
}
System.out.println("=======================================");
System.out.println("Specify Square Meters ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
entry = validityCheck(1,2);
if (entry == 1)
{
ids = filterIntRange(ids,"m2");
}
System.out.println("=======================================");
System.out.println("Specify Price Range ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("=======================================");
entry = validityCheck(1,2);
if (entry == 1)
{
ids = filterIntRange(ids,"price");
}
System.out.println("=======================================");
System.out.println("WiFi ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("3.Don't Care");
System.out.println("=======================================");
entry = validityCheck(1,3);
if (entry == 1)
{
ids = Rental.strongFilter(ids,"wifi","yes");
}
else if (entry == 2)
{
ids = Rental.strongFilter(ids,"wifi","no");
}
System.out.println("=======================================");
System.out.println("Parking ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("3.Don't Care");
System.out.println("=======================================");
entry = validityCheck(1,3);
if (entry == 1)
{
ids = Rental.strongFilter(ids,"parking","yes");
}
else if (entry == 2)
{
ids = Rental.strongFilter(ids,"parking","no");
}
System.out.println("=======================================");
System.out.println("Pool ?:");
System.out.println("1.Yes");
System.out.println("2.No");
System.out.println("3.Don't Care");
System.out.println("=======================================");
entry = validityCheck(1,3);
if (entry == 1)
{
ids = Rental.strongFilter(ids,"pool","yes");
}
else if (entry == 2)
{
ids = Rental.strongFilter(ids,"pool","no");
}
return ids;
}
}
|
1175_20 | package gr.aueb.cf.ch10miniprojects;
import static java.lang.Math.max;
/**
* Finds the maximum sum subArray of a given Array. Popular algorithm called Kadane's algorithm.
* It is based on the simple notion that , while using a for loop to examine the whole Array once
* (in order to not increase the time complexity), because each next possible array we
* examine has next number of the array added to it , we don't need to recalculate. We just examine
* if the past max array , when having the next array element added to it . . . if it has bigger sum than the previous.
*
* @author kountouris panagiotis
*/
public class MaximumSumSubArray {
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1};
printSeparator();
System.out.println("The expanded solution for the Max Sum Sub Array gives us: " + myLargeSumSubArraySolution(arr));
System.out.println("The short solution with the use of java.lang.math method we learned: " + myCompactSolution(arr));
printSeparator();
}
public static int myLargeSumSubArraySolution(int[] arr) {
//Κάνουμε initialize το γενικό μέγιστο στην ελάχιστη τιμή που η Java κλάση Integer μπορεί να μας δώσει
// για να μην παρεμβληθεί στην πρώτη IF σύγκριση που θα βρούμε με το τοπικό μέγιστο.
int myTotalFinalMaxSoFar = Integer.MIN_VALUE;
// Τοπικό μέγιστο αρχικοποιούμε στο μηδέν αλλά στην πραγματικότητα στην πρώτη επανάληψη θα πάρει την τιμή
// του πρώτου στοιχείου του Array. Η πρώτη επανάληψη δηλαδή θεωρεί ως τοπικό μέγιστό μόνο την πρώτη τιμή
// του πίνακα.
int myMaxEndingUntilHere = 0;
//Μια for loop επανάληψης για να έχουμε γραμμική πολυπλοκότητα χρόνου. Να είναι γραμμικής μορφής δηλαδή
//η αύξηση τον computations που χρειάζεται να γίνουν (όχι ο χρόνος) εάν αυξηθεί το μέγεθος του πίνακα.
//Σε αυτή την περίπτωση εάν διπλασιαστεί το μέγεθος του πίνακα, θα διπλασιαστεί και ο αριθμός των υπολογισμών
// που πρέπει να κάνει ο υπολογιστής για να κάνει τους υπολογισμούς. Γραμμική σχέση της μορφής y = ax
for (int i = 0; i < arr.length; i++) {
//Στο πρώτο loop θα πάρει την τιμή του πρώτου στοιχείου του πίνακα, από το δεύτερο και μετά
// προσθέτει το κάθε στοιχείο του πίνακα.
myMaxEndingUntilHere = myMaxEndingUntilHere + arr[i];
//Επειδή σε όλα τα πιθανά sub array μέχρι εδώ, προστίθεται το καινούριο arr[i], αρκεί να
//κάνουμε τη σύγκριση να δούμε εάν με την πρόσθεση αυτού του στοιχείου, το καινούριο υπό εξέταση
// array θα είναι το καινούριο max sum subArray. Δηλαδή εάν θα συμπεριλαμβάνετε και
//αυτό το στοιχείο στο max sum subArray.
if (myTotalFinalMaxSoFar < myMaxEndingUntilHere)
//Εαν είναι μεγαλύτερο τότε αυτό παίρνει τη θέση του υποθετικού max. Μπορεί να αλλάξει πάλι
// εάν π.χ. το επόμενο στοιχείο arr[i] δημιουργεί μεγαλύτερο sum sub Array μέχρι να φτάσουμε στο τέλος
// του array που εξετάζουμε.
myTotalFinalMaxSoFar = myMaxEndingUntilHere;
// Εδώ εάν το subArray μέχρι το σημείο ελέγχου είναι μικρότερο από το μηδέν, το θέτουμε με μηδέν.
// Εδώ παρουσιάζετε και το πρόβλημα με αυτήν μεθοδολογία για τον αλγόριθμο του Kadane.
// Μόνο πρόβλημα εδώ, εάν υπάρξουν αρκετοί αρνητικοί αριθμοί έτσι ώστε το άθροισμα του
// sub-array να είναι αρνητικός αριθμός.
// Εάν υπάρχουν μόνο αρνητικοί αριθμοί θα επιστρέψει απλά όλο το array ! :-D
if (myMaxEndingUntilHere < 0)
myMaxEndingUntilHere = 0;
}
return myTotalFinalMaxSoFar;
}
/**
* Alternative way with the use of the Math method that java.lang provides us.
* @param arr The given Array
* @return The max sum sub array
*/
public static int myCompactSolution(int[] arr){
int myMaxEndingUntilHere = Integer.MIN_VALUE;
//Με τη βοήθεια του java.lang.math που μάθαμε
for (int i = 0; i < arr.length; i++) {
myMaxEndingUntilHere = max((myMaxEndingUntilHere + arr[i]) , arr[i]);
}
return myMaxEndingUntilHere;
}
public static void printSeparator(){
System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
}
}
| KountourisPanagiotis/aueb-mini-projects | MaximumSumSubArray.java | 2,117 | // Εδώ παρουσιάζετε και το πρόβλημα με αυτήν μεθοδολογία για τον αλγόριθμο του Kadane. | line_comment | el | package gr.aueb.cf.ch10miniprojects;
import static java.lang.Math.max;
/**
* Finds the maximum sum subArray of a given Array. Popular algorithm called Kadane's algorithm.
* It is based on the simple notion that , while using a for loop to examine the whole Array once
* (in order to not increase the time complexity), because each next possible array we
* examine has next number of the array added to it , we don't need to recalculate. We just examine
* if the past max array , when having the next array element added to it . . . if it has bigger sum than the previous.
*
* @author kountouris panagiotis
*/
public class MaximumSumSubArray {
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1};
printSeparator();
System.out.println("The expanded solution for the Max Sum Sub Array gives us: " + myLargeSumSubArraySolution(arr));
System.out.println("The short solution with the use of java.lang.math method we learned: " + myCompactSolution(arr));
printSeparator();
}
public static int myLargeSumSubArraySolution(int[] arr) {
//Κάνουμε initialize το γενικό μέγιστο στην ελάχιστη τιμή που η Java κλάση Integer μπορεί να μας δώσει
// για να μην παρεμβληθεί στην πρώτη IF σύγκριση που θα βρούμε με το τοπικό μέγιστο.
int myTotalFinalMaxSoFar = Integer.MIN_VALUE;
// Τοπικό μέγιστο αρχικοποιούμε στο μηδέν αλλά στην πραγματικότητα στην πρώτη επανάληψη θα πάρει την τιμή
// του πρώτου στοιχείου του Array. Η πρώτη επανάληψη δηλαδή θεωρεί ως τοπικό μέγιστό μόνο την πρώτη τιμή
// του πίνακα.
int myMaxEndingUntilHere = 0;
//Μια for loop επανάληψης για να έχουμε γραμμική πολυπλοκότητα χρόνου. Να είναι γραμμικής μορφής δηλαδή
//η αύξηση τον computations που χρειάζεται να γίνουν (όχι ο χρόνος) εάν αυξηθεί το μέγεθος του πίνακα.
//Σε αυτή την περίπτωση εάν διπλασιαστεί το μέγεθος του πίνακα, θα διπλασιαστεί και ο αριθμός των υπολογισμών
// που πρέπει να κάνει ο υπολογιστής για να κάνει τους υπολογισμούς. Γραμμική σχέση της μορφής y = ax
for (int i = 0; i < arr.length; i++) {
//Στο πρώτο loop θα πάρει την τιμή του πρώτου στοιχείου του πίνακα, από το δεύτερο και μετά
// προσθέτει το κάθε στοιχείο του πίνακα.
myMaxEndingUntilHere = myMaxEndingUntilHere + arr[i];
//Επειδή σε όλα τα πιθανά sub array μέχρι εδώ, προστίθεται το καινούριο arr[i], αρκεί να
//κάνουμε τη σύγκριση να δούμε εάν με την πρόσθεση αυτού του στοιχείου, το καινούριο υπό εξέταση
// array θα είναι το καινούριο max sum subArray. Δηλαδή εάν θα συμπεριλαμβάνετε και
//αυτό το στοιχείο στο max sum subArray.
if (myTotalFinalMaxSoFar < myMaxEndingUntilHere)
//Εαν είναι μεγαλύτερο τότε αυτό παίρνει τη θέση του υποθετικού max. Μπορεί να αλλάξει πάλι
// εάν π.χ. το επόμενο στοιχείο arr[i] δημιουργεί μεγαλύτερο sum sub Array μέχρι να φτάσουμε στο τέλος
// του array που εξετάζουμε.
myTotalFinalMaxSoFar = myMaxEndingUntilHere;
// Εδώ εάν το subArray μέχρι το σημείο ελέγχου είναι μικρότερο από το μηδέν, το θέτουμε με μηδέν.
// Εδ<SUF>
// Μόνο πρόβλημα εδώ, εάν υπάρξουν αρκετοί αρνητικοί αριθμοί έτσι ώστε το άθροισμα του
// sub-array να είναι αρνητικός αριθμός.
// Εάν υπάρχουν μόνο αρνητικοί αριθμοί θα επιστρέψει απλά όλο το array ! :-D
if (myMaxEndingUntilHere < 0)
myMaxEndingUntilHere = 0;
}
return myTotalFinalMaxSoFar;
}
/**
* Alternative way with the use of the Math method that java.lang provides us.
* @param arr The given Array
* @return The max sum sub array
*/
public static int myCompactSolution(int[] arr){
int myMaxEndingUntilHere = Integer.MIN_VALUE;
//Με τη βοήθεια του java.lang.math που μάθαμε
for (int i = 0; i < arr.length; i++) {
myMaxEndingUntilHere = max((myMaxEndingUntilHere + arr[i]) , arr[i]);
}
return myMaxEndingUntilHere;
}
public static void printSeparator(){
System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
}
}
|
2682_4 | package gr.aueb.cf.unitconverter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* The MainActivity class represents the main activity of the Unit Converter application.
* It allows the user to convert kilograms to pounds.
*
* @Author Kountouris Panagiotis
*/
public class MainActivity extends AppCompatActivity {
private Button button1;
private EditText inputET;
private TextView outputTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
inputET = findViewById(R.id.inputET);
outputTV = findViewById(R.id.outputTV);
outputTV.setVisibility(View.INVISIBLE);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String kilograms = inputET.getText().toString().trim();
double pounds;
String message = "Please enter a valid value";
final double KILOGRAMS_TO_POUNDS_RATIO = 2.20462;
// Regular Expression για να σιγουρεψουμε πως ο χρήστης θα δώσει :
// χαρακτήρες ψηφία από το 0 μέχρι το 9 , (+) μία η περισσότερες φορές
// δεν μπορεί να δώσει αρνητικές τιμές διότι δεν έχουμε βάλει το (-)
if(kilograms.isEmpty() || !kilograms.matches("[0-9.]+")) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}else{
pounds = Double.parseDouble(kilograms) * KILOGRAMS_TO_POUNDS_RATIO;
outputTV.setText(String.valueOf(pounds));
outputTV.setVisibility(View.VISIBLE); // Εμφανίζουμε το textView με το αποτέλεσμα
}
}
});
}
} | KountourisPanagiotis/unit-converter | app/src/main/java/gr/aueb/cf/unitconverter/MainActivity.java | 619 | // Εμφανίζουμε το textView με το αποτέλεσμα | line_comment | el | package gr.aueb.cf.unitconverter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* The MainActivity class represents the main activity of the Unit Converter application.
* It allows the user to convert kilograms to pounds.
*
* @Author Kountouris Panagiotis
*/
public class MainActivity extends AppCompatActivity {
private Button button1;
private EditText inputET;
private TextView outputTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
inputET = findViewById(R.id.inputET);
outputTV = findViewById(R.id.outputTV);
outputTV.setVisibility(View.INVISIBLE);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String kilograms = inputET.getText().toString().trim();
double pounds;
String message = "Please enter a valid value";
final double KILOGRAMS_TO_POUNDS_RATIO = 2.20462;
// Regular Expression για να σιγουρεψουμε πως ο χρήστης θα δώσει :
// χαρακτήρες ψηφία από το 0 μέχρι το 9 , (+) μία η περισσότερες φορές
// δεν μπορεί να δώσει αρνητικές τιμές διότι δεν έχουμε βάλει το (-)
if(kilograms.isEmpty() || !kilograms.matches("[0-9.]+")) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}else{
pounds = Double.parseDouble(kilograms) * KILOGRAMS_TO_POUNDS_RATIO;
outputTV.setText(String.valueOf(pounds));
outputTV.setVisibility(View.VISIBLE); // Εμ<SUF>
}
}
});
}
} |
2339_3 | package gr.aueb.cf.ch9;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Locale;
import java.util.Scanner;
/**
* να διαβάσουμε ακέραιους αριθμούς όσο
* υπάρχει επόμενος και να τους προσθέτουμε και να
* βρίσκουμε τον μέσο όρο
* • Στη συνέχεια να γράφουμε τον μέσο όρο σε
* ένα αρχείο εξόδου intOut.txt
*/
public class IOIntDemo {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("C:/temp/intIn.txt"));
PrintStream ps = new PrintStream("C:/temp/intOut.txt");
String token;
int num = 0, sum = 0, count = 0;
double average = 0.0;
/*
Μέσα σε μια do-while διαβάζουμε όσο υπάρχει token
Κάθε φορά που διαβάζουμε ένα String, ελέγχουμε αν είναι ακέραιος
με την isInt() και αν είναι τότε αυξάνουμε τον μετρητή i κατά 1
και επίσης αθροίζουμε στο sum
*/
while (sc.hasNext()) {
token = sc.next();
if(isInt(token)) {
num = Integer.parseInt(token);
count++;
sum += num;
}
}
/**
* Κάνουμε casting το sum σε double και όλη η παράσταση γίνεται double γιατί
* διαφορετικά το αποτέλεσμα θα είναι int.
* • Επίσης, χρησιμοποιούμε Locale US ώστε η υποδιαστολή να είναι η τελεία
* διαφορετικά το default Locale ήταν el_GR και η υποδιαστολή θα ήταν το κόμμα
*/
average = (double) sum / count;
ps.printf("Το άθροισμα είναι %d%n", sum);
ps.printf(Locale.ENGLISH, "Ο μέσος όρος είναι %.2f", average);
sc.close();
ps.close();
}
//Ελέγχει αν ένα String είναι ακέραιος
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| KruglovaOlga/CodingFactoryJava | src/gr/aueb/cf/ch9/IOIntDemo.java | 874 | //Ελέγχει αν ένα String είναι ακέραιος | line_comment | el | package gr.aueb.cf.ch9;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Locale;
import java.util.Scanner;
/**
* να διαβάσουμε ακέραιους αριθμούς όσο
* υπάρχει επόμενος και να τους προσθέτουμε και να
* βρίσκουμε τον μέσο όρο
* • Στη συνέχεια να γράφουμε τον μέσο όρο σε
* ένα αρχείο εξόδου intOut.txt
*/
public class IOIntDemo {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("C:/temp/intIn.txt"));
PrintStream ps = new PrintStream("C:/temp/intOut.txt");
String token;
int num = 0, sum = 0, count = 0;
double average = 0.0;
/*
Μέσα σε μια do-while διαβάζουμε όσο υπάρχει token
Κάθε φορά που διαβάζουμε ένα String, ελέγχουμε αν είναι ακέραιος
με την isInt() και αν είναι τότε αυξάνουμε τον μετρητή i κατά 1
και επίσης αθροίζουμε στο sum
*/
while (sc.hasNext()) {
token = sc.next();
if(isInt(token)) {
num = Integer.parseInt(token);
count++;
sum += num;
}
}
/**
* Κάνουμε casting το sum σε double και όλη η παράσταση γίνεται double γιατί
* διαφορετικά το αποτέλεσμα θα είναι int.
* • Επίσης, χρησιμοποιούμε Locale US ώστε η υποδιαστολή να είναι η τελεία
* διαφορετικά το default Locale ήταν el_GR και η υποδιαστολή θα ήταν το κόμμα
*/
average = (double) sum / count;
ps.printf("Το άθροισμα είναι %d%n", sum);
ps.printf(Locale.ENGLISH, "Ο μέσος όρος είναι %.2f", average);
sc.close();
ps.close();
}
//Ελ<SUF>
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
6460_12 | package com.example.physiohut.R2;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.physiohut.NetworkConstants;
import com.example.physiohut.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
/**
* A simple {@link Fragment} subclass.
* Use the {@link R2Fragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class R2Fragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public R2Fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment R2Fragment.
*/
// TODO: Rename and change types and number of parameters
public static R2Fragment newInstance(String param1, String param2) {
R2Fragment fragment = new R2Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_r2, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.back:
case R.id.home:
Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
break;
}
return false;
}
});
//code_Flora
Button buttonSubmission =getActivity().findViewById(R.id.buttonCreation);
buttonSubmission.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText EditTextCode = (EditText) getActivity().findViewById(R.id.editText_code);
String sCode = String.valueOf(EditTextCode.getText());
EditText EditTextName = (EditText) getActivity().findViewById(R.id.editText_name);
String sName = String.valueOf(EditTextName.getText());
EditText EditTextDescription = (EditText) getActivity().findViewById(R.id.editText_description);
String sDescription = String.valueOf(EditTextDescription.getText());
EditText EditTextPrice = (EditText) getActivity().findViewById(R.id.editText_price);
String sPrice = String.valueOf(EditTextPrice.getText());
clear_EditTexts(EditTextCode, EditTextName,EditTextDescription,EditTextPrice);
String incorrectFields =" ";
boolean flag=true;
if (sCode.matches("")) {
EditTextCode.requestFocus();
EditTextCode.setError("Το πεδίο Κωδικός είναι κένo!");
flag = false;
incorrectFields="Κωδικός";
} else if (sCode.length() <= 7) {
EditTextCode.requestFocus();
EditTextCode.setError("Το πεδίο Κωδικός έχει μη έγκυρα δεδομένα!");
flag = false;
incorrectFields=" Κωδικός";
}
if (sName.matches("")) {
EditTextName.requestFocus();
EditTextName.setError("Το πεδίο Όνομα Παροχής είναι κενό!");
flag = false;
if (flag)
{incorrectFields="Όνομα Παροχής";}
else{incorrectFields="Kωδικός, Όνομα Παροχής";}
}
else if (sName.length() <= 3) {
EditTextName.requestFocus();
EditTextName.setError("Το πεδίο Όνομα Παροχής έχει λάθος δεδομένα!");
flag = false;
if (flag)
{incorrectFields="Όνομα Παροχής";}
else {incorrectFields="Κωδικός ,Όνομα Παροχής";}
}
if (sDescription.matches("")) {
EditTextDescription.requestFocus();
EditTextDescription.setError("Το πεδίο Περιγραφή είναι κενό!");
flag = false;
if (flag)
{incorrectFields="Περιγραφή";}
else {incorrectFields+=" ,Περιγραφή";}
}
if (sPrice.matches("")) {
EditTextPrice.requestFocus();
EditTextPrice.setError("Το πεδίο Τιμή είναι κενό!");
flag = false;
if (flag)
{incorrectFields="Τιμή";}
else {incorrectFields+=" ,Τιμή";}
}
//pop-up message
AlertDialog.Builder builder= new AlertDialog.Builder(getActivity());
builder.setCancelable(true); //επιτρέπω στον χρήστη να πατάει έκτος παραθύρου
if(flag){
builder.setTitle("Υποβολή Παροχής");
builder.setMessage("Κωδικός:{"+sCode+"}\n"+"Όνομα:{"+sName+"}\n"+"Περιγραφή:{"+sDescription+"}\n"+"Τιμή:{"+sPrice+"}");
builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast myToast= Toast.makeText(getActivity(),"H υποβολή ακυρώθηκε!",Toast.LENGTH_SHORT);
myToast.show();
Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
dialogInterface.cancel();
}
});
builder.setPositiveButton("Υποβολή", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast myToast= Toast.makeText(getActivity(),"H υποβολή έγινε!",Toast.LENGTH_SHORT);
myToast.show();
// Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
//σε αυτό το σημείο θα αποστέλω τα δεδομένα στη ΒΔ
String url = NetworkConstants.getUrlOfFile("r2.php")+"?CODE="+sCode+"&description="+sDescription+"&price="+sPrice;;
try {
R2DataFetcher r2DataLog = new R2DataFetcher() ;
System.out.println(url);
r2DataLog.physioLog(url);
Toast.makeText(getContext(), "CODE: "+sCode+"description: "+sDescription+"price: "+sPrice,Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}
}
});
builder.show();}
else
{
builder.setTitle("Υποβολή Παροχής");
builder.setMessage("Tα παρακάτω πεδία είναι συμπληρωμένα λάθος:\n"+incorrectFields+".\nΠαρακαλώ επαναλάβετε την διαδικάσια εξ αρχής.");
builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast myToast= Toast.makeText(getActivity(),"H υποβολή ακυρώθηκε!",Toast.LENGTH_SHORT);
myToast.show();
Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
dialogInterface.cancel();
}
});
builder.show();
}
}
});
}
private void clear_EditTexts(EditText EditTextCode, EditText EditTextName, EditText EditTextDescription, EditText EditTextPrice ) {
EditTextCode.setText(" ");
EditTextName.setText(" ");
EditTextDescription.setText(" ");
EditTextPrice.setText(" ");
}
} | Lab-eurs/physiohut-code | app/src/main/java/com/example/physiohut/R2/R2Fragment.java | 2,420 | //σε αυτό το σημείο θα αποστέλω τα δεδομένα στη ΒΔ | line_comment | el | package com.example.physiohut.R2;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.physiohut.NetworkConstants;
import com.example.physiohut.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
/**
* A simple {@link Fragment} subclass.
* Use the {@link R2Fragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class R2Fragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public R2Fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment R2Fragment.
*/
// TODO: Rename and change types and number of parameters
public static R2Fragment newInstance(String param1, String param2) {
R2Fragment fragment = new R2Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_r2, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.back:
case R.id.home:
Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
break;
}
return false;
}
});
//code_Flora
Button buttonSubmission =getActivity().findViewById(R.id.buttonCreation);
buttonSubmission.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText EditTextCode = (EditText) getActivity().findViewById(R.id.editText_code);
String sCode = String.valueOf(EditTextCode.getText());
EditText EditTextName = (EditText) getActivity().findViewById(R.id.editText_name);
String sName = String.valueOf(EditTextName.getText());
EditText EditTextDescription = (EditText) getActivity().findViewById(R.id.editText_description);
String sDescription = String.valueOf(EditTextDescription.getText());
EditText EditTextPrice = (EditText) getActivity().findViewById(R.id.editText_price);
String sPrice = String.valueOf(EditTextPrice.getText());
clear_EditTexts(EditTextCode, EditTextName,EditTextDescription,EditTextPrice);
String incorrectFields =" ";
boolean flag=true;
if (sCode.matches("")) {
EditTextCode.requestFocus();
EditTextCode.setError("Το πεδίο Κωδικός είναι κένo!");
flag = false;
incorrectFields="Κωδικός";
} else if (sCode.length() <= 7) {
EditTextCode.requestFocus();
EditTextCode.setError("Το πεδίο Κωδικός έχει μη έγκυρα δεδομένα!");
flag = false;
incorrectFields=" Κωδικός";
}
if (sName.matches("")) {
EditTextName.requestFocus();
EditTextName.setError("Το πεδίο Όνομα Παροχής είναι κενό!");
flag = false;
if (flag)
{incorrectFields="Όνομα Παροχής";}
else{incorrectFields="Kωδικός, Όνομα Παροχής";}
}
else if (sName.length() <= 3) {
EditTextName.requestFocus();
EditTextName.setError("Το πεδίο Όνομα Παροχής έχει λάθος δεδομένα!");
flag = false;
if (flag)
{incorrectFields="Όνομα Παροχής";}
else {incorrectFields="Κωδικός ,Όνομα Παροχής";}
}
if (sDescription.matches("")) {
EditTextDescription.requestFocus();
EditTextDescription.setError("Το πεδίο Περιγραφή είναι κενό!");
flag = false;
if (flag)
{incorrectFields="Περιγραφή";}
else {incorrectFields+=" ,Περιγραφή";}
}
if (sPrice.matches("")) {
EditTextPrice.requestFocus();
EditTextPrice.setError("Το πεδίο Τιμή είναι κενό!");
flag = false;
if (flag)
{incorrectFields="Τιμή";}
else {incorrectFields+=" ,Τιμή";}
}
//pop-up message
AlertDialog.Builder builder= new AlertDialog.Builder(getActivity());
builder.setCancelable(true); //επιτρέπω στον χρήστη να πατάει έκτος παραθύρου
if(flag){
builder.setTitle("Υποβολή Παροχής");
builder.setMessage("Κωδικός:{"+sCode+"}\n"+"Όνομα:{"+sName+"}\n"+"Περιγραφή:{"+sDescription+"}\n"+"Τιμή:{"+sPrice+"}");
builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast myToast= Toast.makeText(getActivity(),"H υποβολή ακυρώθηκε!",Toast.LENGTH_SHORT);
myToast.show();
Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
dialogInterface.cancel();
}
});
builder.setPositiveButton("Υποβολή", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast myToast= Toast.makeText(getActivity(),"H υποβολή έγινε!",Toast.LENGTH_SHORT);
myToast.show();
// Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
//σε<SUF>
String url = NetworkConstants.getUrlOfFile("r2.php")+"?CODE="+sCode+"&description="+sDescription+"&price="+sPrice;;
try {
R2DataFetcher r2DataLog = new R2DataFetcher() ;
System.out.println(url);
r2DataLog.physioLog(url);
Toast.makeText(getContext(), "CODE: "+sCode+"description: "+sDescription+"price: "+sPrice,Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}
}
});
builder.show();}
else
{
builder.setTitle("Υποβολή Παροχής");
builder.setMessage("Tα παρακάτω πεδία είναι συμπληρωμένα λάθος:\n"+incorrectFields+".\nΠαρακαλώ επαναλάβετε την διαδικάσια εξ αρχής.");
builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast myToast= Toast.makeText(getActivity(),"H υποβολή ακυρώθηκε!",Toast.LENGTH_SHORT);
myToast.show();
Navigation.findNavController(view).navigate(R.id.action_r2Fragment_to_psfFragment);
dialogInterface.cancel();
}
});
builder.show();
}
}
});
}
private void clear_EditTexts(EditText EditTextCode, EditText EditTextName, EditText EditTextDescription, EditText EditTextPrice ) {
EditTextCode.setText(" ");
EditTextName.setText(" ");
EditTextDescription.setText(" ");
EditTextPrice.setText(" ");
}
} |
7926_1 | package com.evaluation.servlet;
import com.evaluation.beans.Users;
import static com.evaluation.encryption.Encryption.getHash;
import com.evaluation.utils.DBUtils;
import com.evaluation.utils.MyUtils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(/*name = "LoginServlet", */urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
dispatcher.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String userName = req.getParameter("username");
String password = req.getParameter("password");
String rememberMeStr = req.getParameter("rememberMe");
boolean remember = "Y".equals(rememberMeStr);
Users user = null;
boolean hasError = false;
String errorString = null;
if (userName == null || password == null || userName.length() == 0 || password.length() == 0) {
hasError = true;
errorString = "Username and password are required";
} else {
Connection conn = MyUtils.getStoredConnection(req);
try {
password = getHash(req.getParameter("password"));
user = DBUtils.findUser(conn, userName, password);
if (user == null) {
hasError = true;
errorString = "Username or password are invalid";
}
} catch (SQLException ex) {
hasError = true;
errorString = ex.getMessage();
}
}
if (hasError) {
System.out.println("error");
user = new Users();
user.setUsername(userName);
user.setPassword(password);
req.setAttribute("errorString", errorString);
req.setAttribute("user", user);
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
dispatcher.forward(req, resp);
} else {
System.out.println("all good");
HttpSession session = req.getSession();
MyUtils.storeLoginUser(session, user);
int IDu = user.getIdu();
session.setAttribute("IDu", IDu);
MyUtils.storeUserCookie(resp, user);
resp.sendRedirect(req.getContextPath() + "/mainPage"); // εναλλακτικά χρησιμοποιώ τον dispatcher
}
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| Lefteris-Souflas/Java-Web-App-For-Military-Staff-Evaluation | application/Evaluation/src/main/java/com/evaluation/servlet/LoginServlet.java | 694 | // εναλλακτικά χρησιμοποιώ τον dispatcher | line_comment | el | package com.evaluation.servlet;
import com.evaluation.beans.Users;
import static com.evaluation.encryption.Encryption.getHash;
import com.evaluation.utils.DBUtils;
import com.evaluation.utils.MyUtils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(/*name = "LoginServlet", */urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
dispatcher.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String userName = req.getParameter("username");
String password = req.getParameter("password");
String rememberMeStr = req.getParameter("rememberMe");
boolean remember = "Y".equals(rememberMeStr);
Users user = null;
boolean hasError = false;
String errorString = null;
if (userName == null || password == null || userName.length() == 0 || password.length() == 0) {
hasError = true;
errorString = "Username and password are required";
} else {
Connection conn = MyUtils.getStoredConnection(req);
try {
password = getHash(req.getParameter("password"));
user = DBUtils.findUser(conn, userName, password);
if (user == null) {
hasError = true;
errorString = "Username or password are invalid";
}
} catch (SQLException ex) {
hasError = true;
errorString = ex.getMessage();
}
}
if (hasError) {
System.out.println("error");
user = new Users();
user.setUsername(userName);
user.setPassword(password);
req.setAttribute("errorString", errorString);
req.setAttribute("user", user);
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
dispatcher.forward(req, resp);
} else {
System.out.println("all good");
HttpSession session = req.getSession();
MyUtils.storeLoginUser(session, user);
int IDu = user.getIdu();
session.setAttribute("IDu", IDu);
MyUtils.storeUserCookie(resp, user);
resp.sendRedirect(req.getContextPath() + "/mainPage"); // εν<SUF>
}
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
11717_3 | package bookstorePack;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BookDao {
// Συνδεόμαστε στην βάση δεδομένων books, με username "Vaggelis" και password "123456789".
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/bookstore", "Vaggelis", "123456789");
} catch (ClassNotFoundException | SQLException ex) {}
return conn;
}
// Λειτουργια 1. Παίρνουμε μια λίστα με όλα τα διαθέσιμα βιβλία.
public static List<Book> getAvailableBooks(){
List<Book> list = new ArrayList<>();
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE AVAILABILITY > 0");
ResultSet rs=ps.executeQuery();
while(rs.next()){
Book book = new Book();
book.setId(rs.getInt(1));
book.setTitle(rs.getString(2));
book.setAuthor(rs.getString(3));
book.setPublisher(rs.getString(4));
book.setPages(rs.getInt(5));
book.setPubl_year(rs.getInt(6));
book.setGenre(rs.getString(7));
book.setAvailability(rs.getInt(8));
list.add(book);
}
conn.close();
} catch (SQLException ex) {}
return list;
}
// Λειτουργία 2. Παίρνουμε ένα βιβλίο με ένα ID
public static Book getBook(int id){
Book book = null;
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE ID = ?");
ps.setInt(1, id);
ResultSet rs=ps.executeQuery();
if(rs.next()){
book = new Book();
book.setId(rs.getInt(1));
book.setTitle(rs.getString(2));
book.setAuthor(rs.getString(3));
book.setPublisher(rs.getString(4));
book.setPages(rs.getInt(5));
book.setPubl_year(rs.getInt(6));
book.setGenre(rs.getString(7));
book.setAvailability(rs.getInt(8));
}
conn.close();
} catch (SQLException ex) {}
return book;
}
// Λειτουργίας 3. Παραγγελία ενός συγγράματος, x αντίτυπα.
public static int orderBook(int id, int x){
Book book = BookDao.getBook(id);
if((book == null) || (x <= 0)){
return 2; // Order Error
}
else if(x >= book.getAvailability()){
return 1; // Out of Stock
}
else{
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("UPDATE books SET AVAILABILITY = AVAILABILITY - ? WHERE ID = ?;");
ps.setInt(1, x);
ps.setInt(2, id);
ps.executeQuery();
conn.close();
} catch (SQLException ex) {}
return 0; // Succesfull Order
}
}
// Λειτουργία 4. Καταχώρηση νέου συγγράματος.
public static int addBook(Book newBook){
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO books (TITLE, AUTHOR, PUBLISHER, PAGES, PUBL_YEAR, GENRE, AVAILABILITY) VALUES(?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, newBook.getTitle());
ps.setString(2, newBook.getAuthor());
ps.setString(3, newBook.getPublisher());
ps.setInt(4, newBook.getPages());
ps.setInt(5, newBook.getPubl_year());
ps.setString(6, newBook.getGenre());
ps.setInt(7, newBook.getAvailability());
ps.executeQuery();
conn.close();
} catch (SQLException ex) {
return 1; // Insert Error
}
return 0; // Insert Completed
}
// Λειτουργία 5. Ενημέρωση συγγράματος.
public static int updateBook(Book updatedBook){
Book oldBook = BookDao.getBook(updatedBook.getId());
if(oldBook == null){
return 1; // Update Error
}
else{
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement(
"UPDATE books SET TITLE = ?, AUTHOR = ?, PUBLISHER = ?, PAGES = ?, PUBL_YEAR = ?, GENRE = ?, AVAILABILITY = ? WHERE ID = ?");
ps.setString(1, updatedBook.getTitle());
ps.setString(2, updatedBook.getAuthor());
ps.setString(3, updatedBook.getPublisher());
ps.setInt(4, updatedBook.getPages());
ps.setInt(5, updatedBook.getPubl_year());
ps.setString(6, updatedBook.getGenre());
ps.setInt(7, updatedBook.getAvailability());
ps.setInt(8, updatedBook.getId());
ps.executeQuery();
conn.close();
} catch (SQLException ex) {
return 2; // Update Error
}
return 0; // Update Completed
}
}
// Λειτουργία 6. Διαγραφή συγγράματος.
public static int deleteBook(int id){
Book book = BookDao.getBook(id);
if(book == null){
return 1; // Delete Error
}else{
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement(
"DELETE FROM books WHERE ID = ?");
ps.setInt(1, id);
ps.executeQuery();
conn.close();
} catch (SQLException ex) {
return 1; // Delete Error
}
return 0; // Delete Completed
}
}
}
| Lefti97/UniversityWorks | Network Programming (JAVA)/Final Work/Bookstore/src/java/bookstorePack/BookDao.java | 1,628 | // Λειτουργία 2. Παίρνουμε ένα βιβλίο με ένα ID | line_comment | el | package bookstorePack;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BookDao {
// Συνδεόμαστε στην βάση δεδομένων books, με username "Vaggelis" και password "123456789".
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/bookstore", "Vaggelis", "123456789");
} catch (ClassNotFoundException | SQLException ex) {}
return conn;
}
// Λειτουργια 1. Παίρνουμε μια λίστα με όλα τα διαθέσιμα βιβλία.
public static List<Book> getAvailableBooks(){
List<Book> list = new ArrayList<>();
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE AVAILABILITY > 0");
ResultSet rs=ps.executeQuery();
while(rs.next()){
Book book = new Book();
book.setId(rs.getInt(1));
book.setTitle(rs.getString(2));
book.setAuthor(rs.getString(3));
book.setPublisher(rs.getString(4));
book.setPages(rs.getInt(5));
book.setPubl_year(rs.getInt(6));
book.setGenre(rs.getString(7));
book.setAvailability(rs.getInt(8));
list.add(book);
}
conn.close();
} catch (SQLException ex) {}
return list;
}
// Λε<SUF>
public static Book getBook(int id){
Book book = null;
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE ID = ?");
ps.setInt(1, id);
ResultSet rs=ps.executeQuery();
if(rs.next()){
book = new Book();
book.setId(rs.getInt(1));
book.setTitle(rs.getString(2));
book.setAuthor(rs.getString(3));
book.setPublisher(rs.getString(4));
book.setPages(rs.getInt(5));
book.setPubl_year(rs.getInt(6));
book.setGenre(rs.getString(7));
book.setAvailability(rs.getInt(8));
}
conn.close();
} catch (SQLException ex) {}
return book;
}
// Λειτουργίας 3. Παραγγελία ενός συγγράματος, x αντίτυπα.
public static int orderBook(int id, int x){
Book book = BookDao.getBook(id);
if((book == null) || (x <= 0)){
return 2; // Order Error
}
else if(x >= book.getAvailability()){
return 1; // Out of Stock
}
else{
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement("UPDATE books SET AVAILABILITY = AVAILABILITY - ? WHERE ID = ?;");
ps.setInt(1, x);
ps.setInt(2, id);
ps.executeQuery();
conn.close();
} catch (SQLException ex) {}
return 0; // Succesfull Order
}
}
// Λειτουργία 4. Καταχώρηση νέου συγγράματος.
public static int addBook(Book newBook){
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO books (TITLE, AUTHOR, PUBLISHER, PAGES, PUBL_YEAR, GENRE, AVAILABILITY) VALUES(?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, newBook.getTitle());
ps.setString(2, newBook.getAuthor());
ps.setString(3, newBook.getPublisher());
ps.setInt(4, newBook.getPages());
ps.setInt(5, newBook.getPubl_year());
ps.setString(6, newBook.getGenre());
ps.setInt(7, newBook.getAvailability());
ps.executeQuery();
conn.close();
} catch (SQLException ex) {
return 1; // Insert Error
}
return 0; // Insert Completed
}
// Λειτουργία 5. Ενημέρωση συγγράματος.
public static int updateBook(Book updatedBook){
Book oldBook = BookDao.getBook(updatedBook.getId());
if(oldBook == null){
return 1; // Update Error
}
else{
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement(
"UPDATE books SET TITLE = ?, AUTHOR = ?, PUBLISHER = ?, PAGES = ?, PUBL_YEAR = ?, GENRE = ?, AVAILABILITY = ? WHERE ID = ?");
ps.setString(1, updatedBook.getTitle());
ps.setString(2, updatedBook.getAuthor());
ps.setString(3, updatedBook.getPublisher());
ps.setInt(4, updatedBook.getPages());
ps.setInt(5, updatedBook.getPubl_year());
ps.setString(6, updatedBook.getGenre());
ps.setInt(7, updatedBook.getAvailability());
ps.setInt(8, updatedBook.getId());
ps.executeQuery();
conn.close();
} catch (SQLException ex) {
return 2; // Update Error
}
return 0; // Update Completed
}
}
// Λειτουργία 6. Διαγραφή συγγράματος.
public static int deleteBook(int id){
Book book = BookDao.getBook(id);
if(book == null){
return 1; // Delete Error
}else{
Connection conn = BookDao.getConnection();
try {
PreparedStatement ps = conn.prepareStatement(
"DELETE FROM books WHERE ID = ?");
ps.setInt(1, id);
ps.executeQuery();
conn.close();
} catch (SQLException ex) {
return 1; // Delete Error
}
return 0; // Delete Completed
}
}
}
|
477_3 | //ics 20033
import java.util.*;
public class Connect4 {
public static void main(String[] args) {
System.out.println("This is score4");
//δημιουργια ενος αντικειμενου scanner για τις εισαγωσες απο το πληκτρολογιο
Scanner scan = new Scanner(System.in);
// προτροπή των παιχτων να δωσουν το ονομα τους και διαβασμα των ονοματων
System.out.print("Please enter the name of the 1st player:");
Player player1 = new Player(scan.nextLine());
System.out.print("Please enter the name of the 2nd player:");
Player player2 = new Player(scan.nextLine());
System.out.println("The chip can be 'x' or 'o' ");
/*προτροπη του πρωτου παιχτη να επιλεξει το chip του και επιλογη του chip
*που απεμεινε στον δευτερο παιχτη*/
System.out.print(player1.getName()+", please select your chip:");
player1.setChip(scan);
player2.remained_chip(player1);
System.out.println(player2.getName() + ", Your chip is:" + player2.getChip());
// δημιουργια του ταμπλο του παιχνιδιου
Board board = new Board(scan);
/* τυχαια επιλογη του παιχτη που θα παιξει πρωτος χρησιμοποιωντας
* την random.nextInt(2) που παραγει τυχαια τους αριθμους 0 ή 1
*/
Player player_to_move;
Random random = new Random();
int first_to_start=random.nextInt(2);
if(first_to_start == 0) {
player_to_move = player1;
}
else {
player_to_move = player2;
}
/* δηλωση μιας boolean μεταβλητης ωστε να ειναι η τιμη φρουρος
* στην επαναληψη του παιχνιδιου
*/
boolean play=true;
while(play) {
//ξεκιναει το παιχνιδι και εμφανιζει τον πινακα στην οθονη
board.display();
/*προτροπη στον παιχτη που παιζει να επιλεξη την στηλη
*στην οποια θα τοποθετηση το chip του και τοποθετηση του chip στην στηλη
*με την βοηθεια της μεθοδου putcoint()
*/
System.out.print(player_to_move.getName() + ", your turn. Select column: " );
board.putcoin(player_to_move, scan);
System.out.println();
/*ελεγχος για το αν υπαρχει νικητης με την μεθοδο is_winner
* ή αν εχει γεμισει ο πινακας και στις δυο περιπτωσεις
* πρεπει να τερματιστει το παιχνιδι
*
*/
if(board.is_winner(player_to_move) || board.fullboard()) {
play = false;
board.display();
}
//εναλλαγη παιχτων δηλαδη παιζει ο επομενος παιχτης
player_to_move=player_to_move.switch_player(player1, player2);
}
/* αφου τερματιστει το παιχνιδι γινεται ο ελεγχος για το ποιος ειναι
* ο νικητης και τον εμφανιζει αν δεν υπαρχει νικητης τοτε υπαρχει ισοπαλια
*/
if(board.is_winner(player1)) {
System.out.println(" GAME OVER. THE WINNER IS " + player1.getName());
}
else if(board.is_winner(player2)) {
System.out.println(" GAME OVER. THE WINNER IS " + player2.getName());
}
else{
System.out.println("GAME OVER. WE HAVE A DRAW");
}
scan.close();
}
}
| Leonardpepa/Connect4 | src/Connect4.java | 1,453 | /*προτροπη του πρωτου παιχτη να επιλεξει το chip του και επιλογη του chip
*που απεμεινε στον δευτερο παιχτη*/ | block_comment | el | //ics 20033
import java.util.*;
public class Connect4 {
public static void main(String[] args) {
System.out.println("This is score4");
//δημιουργια ενος αντικειμενου scanner για τις εισαγωσες απο το πληκτρολογιο
Scanner scan = new Scanner(System.in);
// προτροπή των παιχτων να δωσουν το ονομα τους και διαβασμα των ονοματων
System.out.print("Please enter the name of the 1st player:");
Player player1 = new Player(scan.nextLine());
System.out.print("Please enter the name of the 2nd player:");
Player player2 = new Player(scan.nextLine());
System.out.println("The chip can be 'x' or 'o' ");
/*προ<SUF>*/
System.out.print(player1.getName()+", please select your chip:");
player1.setChip(scan);
player2.remained_chip(player1);
System.out.println(player2.getName() + ", Your chip is:" + player2.getChip());
// δημιουργια του ταμπλο του παιχνιδιου
Board board = new Board(scan);
/* τυχαια επιλογη του παιχτη που θα παιξει πρωτος χρησιμοποιωντας
* την random.nextInt(2) που παραγει τυχαια τους αριθμους 0 ή 1
*/
Player player_to_move;
Random random = new Random();
int first_to_start=random.nextInt(2);
if(first_to_start == 0) {
player_to_move = player1;
}
else {
player_to_move = player2;
}
/* δηλωση μιας boolean μεταβλητης ωστε να ειναι η τιμη φρουρος
* στην επαναληψη του παιχνιδιου
*/
boolean play=true;
while(play) {
//ξεκιναει το παιχνιδι και εμφανιζει τον πινακα στην οθονη
board.display();
/*προτροπη στον παιχτη που παιζει να επιλεξη την στηλη
*στην οποια θα τοποθετηση το chip του και τοποθετηση του chip στην στηλη
*με την βοηθεια της μεθοδου putcoint()
*/
System.out.print(player_to_move.getName() + ", your turn. Select column: " );
board.putcoin(player_to_move, scan);
System.out.println();
/*ελεγχος για το αν υπαρχει νικητης με την μεθοδο is_winner
* ή αν εχει γεμισει ο πινακας και στις δυο περιπτωσεις
* πρεπει να τερματιστει το παιχνιδι
*
*/
if(board.is_winner(player_to_move) || board.fullboard()) {
play = false;
board.display();
}
//εναλλαγη παιχτων δηλαδη παιζει ο επομενος παιχτης
player_to_move=player_to_move.switch_player(player1, player2);
}
/* αφου τερματιστει το παιχνιδι γινεται ο ελεγχος για το ποιος ειναι
* ο νικητης και τον εμφανιζει αν δεν υπαρχει νικητης τοτε υπαρχει ισοπαλια
*/
if(board.is_winner(player1)) {
System.out.println(" GAME OVER. THE WINNER IS " + player1.getName());
}
else if(board.is_winner(player2)) {
System.out.println(" GAME OVER. THE WINNER IS " + player2.getName());
}
else{
System.out.println("GAME OVER. WE HAVE A DRAW");
}
scan.close();
}
}
|
12_1 | package order;
import java.awt.Color;
import java.util.Date;
import java.util.Random;
import gui.windows.CartWindow;
import login.Login;
import resources.TextResources;
public class CouponFactory {
static Random rand = new Random();
public static Coupon GenerateCoupon(String email) {
String code = "";
// Βαλαμε στατικο για τεστ αλλα θα παιρνει ορισμα τον χρηστη και θα παιρνουμε
// απο κει το μειλ
for (int i = 0; i < 3; i++) {
code += email.toCharArray()[rand.nextInt(email.length())];
}
int randomNumber = rand.nextInt(9990 + 1 - 1000) + 1000;
code += Integer.toString(randomNumber);
return new Coupon(code.toUpperCase(), new Date());
}
public static boolean isValid(String code) {
Coupon couponProvided = searchCoupon(code);
Date today = new Date();
try {
// calculates the time that takes for a useer to use the coupon in milliseconds
long mill = today.getTime() - couponProvided.getDate().getTime();
// converts the millseconds to days
long days = (long) (mill / (1000 * 60 * 60 * 24));
if (days < 3) {
Login.loggedCustomer.removeCoupon(couponProvided);
CartWindow.couponField.setBackground(new Color(158, 232, 178));
CartWindow.couponField.setText(TextResources.submitted);
return true;
}
} catch (NullPointerException e) {
CartWindow.couponField.setBackground(new Color(232, 158, 158));
CartWindow.couponField.setText(TextResources.invalidCoupon);
}
return false;
}
public static Coupon searchCoupon(String code) {
for (Coupon coupon : Login.loggedCustomer.getCoupons()) {
if (coupon.getCode().equals(code)) {
return coupon;
}
}
return null;
}
}
| Leonardpepa/Segaleo | src/order/CouponFactory.java | 574 | // απο κει το μειλ | line_comment | el | package order;
import java.awt.Color;
import java.util.Date;
import java.util.Random;
import gui.windows.CartWindow;
import login.Login;
import resources.TextResources;
public class CouponFactory {
static Random rand = new Random();
public static Coupon GenerateCoupon(String email) {
String code = "";
// Βαλαμε στατικο για τεστ αλλα θα παιρνει ορισμα τον χρηστη και θα παιρνουμε
// απ<SUF>
for (int i = 0; i < 3; i++) {
code += email.toCharArray()[rand.nextInt(email.length())];
}
int randomNumber = rand.nextInt(9990 + 1 - 1000) + 1000;
code += Integer.toString(randomNumber);
return new Coupon(code.toUpperCase(), new Date());
}
public static boolean isValid(String code) {
Coupon couponProvided = searchCoupon(code);
Date today = new Date();
try {
// calculates the time that takes for a useer to use the coupon in milliseconds
long mill = today.getTime() - couponProvided.getDate().getTime();
// converts the millseconds to days
long days = (long) (mill / (1000 * 60 * 60 * 24));
if (days < 3) {
Login.loggedCustomer.removeCoupon(couponProvided);
CartWindow.couponField.setBackground(new Color(158, 232, 178));
CartWindow.couponField.setText(TextResources.submitted);
return true;
}
} catch (NullPointerException e) {
CartWindow.couponField.setBackground(new Color(232, 158, 158));
CartWindow.couponField.setText(TextResources.invalidCoupon);
}
return false;
}
public static Coupon searchCoupon(String code) {
for (Coupon coupon : Login.loggedCustomer.getCoupons()) {
if (coupon.getCode().equals(code)) {
return coupon;
}
}
return null;
}
}
|
621_9 | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.BeatmapMeta;
import tillerino.tillerinobot.IRCBot.IRCBotUser;
import tillerino.tillerinobot.RecommendationsManager.Recommendation;
/**
* @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345
*/
public class Greek implements Language {
@Override
public String unknownBeatmap() {
return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ;
}
@Override
public String internalException(String marker) {
return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου."
+" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000"
+ " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε."
+ " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ;
}
@Override
public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
user.message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
user.message(apiUser.getUserName() + "...");
user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!");
user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;");
} else {
String[] messages = {
"Φαίνεσαι σαν να θες μια πρόταση.",
"Πόσο ωραίο να σε βλέπω :)",
"Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)",
"Τι ευχάριστη έκπληξη! ^.^",
"Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3",
"Τι έχεις την διάθεση να κάνεις σήμερα;",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
user.message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Άγνωστη εντολή \"" + command
+ "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!";
}
@Override
public String noInformationForMods() {
return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή";
}
@Override
public String malformattedMods(String mods) {
return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού...";
}
@Override
public String tryWithMods() {
return "Δοκίμασε αυτό το τραγούδι με μερικά mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods);
}
/**
* The user's IRC nick name could not be resolved to an osu user id. The
* message should suggest to contact @Tillerinobot or /u/Tillerino.
*
* @param exceptionMarker
* a marker to reference the created log entry. six or eight
* characters.
* @param name
* the irc nick which could not be resolved
* @return
*/
public String unresolvableName(String exceptionMarker, String name) {
return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference "
+ exceptionMarker + ")";
}
@Override
public String excuseForError() {
return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;";
}
@Override
public String complaint() {
return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει.";
}
@Override
public void hug(final IRCBotUser user, OsuApiUser apiUser) {
user.message("Έλα εδώ εσυ!");
user.action("Αγκαλιάζει " + apiUser.getUserName());
}
@Override
public String help() {
return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά."
+ " [https://twitter.com/Tillerinobot status και updates]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]";
}
@Override
public String faq() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + ".";
}
@Override
public String mixedNomodAndMods() {
return "Τί εννοείς nomods με mods;";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. "
+ " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help.";
}
@Override
public String notRanked() {
return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο.";
}
@Override
public void optionalCommentOnNP(IRCBotUser user,
OsuApiUser apiUser, BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser,
BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnRecommendation(IRCBotUser user,
OsuApiUser apiUser, Recommendation meta) {
// regular Tillerino doesn't comment on this
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Άκυρη ακρίβεια: \"" + acc + "\"";
}
@Override
public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) {
user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Συγνώμη, αλλά \"" + invalid
+ "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!";
}
@Override
public String setFormat() {
return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
}
| Liby99/Tillerinobot | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java | 3,750 | //github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; | line_comment | el | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.BeatmapMeta;
import tillerino.tillerinobot.IRCBot.IRCBotUser;
import tillerino.tillerinobot.RecommendationsManager.Recommendation;
/**
* @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345
*/
public class Greek implements Language {
@Override
public String unknownBeatmap() {
return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ;
}
@Override
public String internalException(String marker) {
return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου."
+" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000"
+ " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε."
+ " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ;
}
@Override
public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
user.message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
user.message(apiUser.getUserName() + "...");
user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!");
user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;");
} else {
String[] messages = {
"Φαίνεσαι σαν να θες μια πρόταση.",
"Πόσο ωραίο να σε βλέπω :)",
"Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)",
"Τι ευχάριστη έκπληξη! ^.^",
"Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3",
"Τι έχεις την διάθεση να κάνεις σήμερα;",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
user.message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Άγνωστη εντολή \"" + command
+ "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!";
}
@Override
public String noInformationForMods() {
return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή";
}
@Override
public String malformattedMods(String mods) {
return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού...";
}
@Override
public String tryWithMods() {
return "Δοκίμασε αυτό το τραγούδι με μερικά mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods);
}
/**
* The user's IRC nick name could not be resolved to an osu user id. The
* message should suggest to contact @Tillerinobot or /u/Tillerino.
*
* @param exceptionMarker
* a marker to reference the created log entry. six or eight
* characters.
* @param name
* the irc nick which could not be resolved
* @return
*/
public String unresolvableName(String exceptionMarker, String name) {
return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference "
+ exceptionMarker + ")";
}
@Override
public String excuseForError() {
return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;";
}
@Override
public String complaint() {
return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει.";
}
@Override
public void hug(final IRCBotUser user, OsuApiUser apiUser) {
user.message("Έλα εδώ εσυ!");
user.action("Αγκαλιάζει " + apiUser.getUserName());
}
@Override
public String help() {
return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά."
+ " [https://twitter.com/Tillerinobot status και updates]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]";
}
@Override
public String faq() {
return "[https://gi<SUF>
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + ".";
}
@Override
public String mixedNomodAndMods() {
return "Τί εννοείς nomods με mods;";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. "
+ " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help.";
}
@Override
public String notRanked() {
return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο.";
}
@Override
public void optionalCommentOnNP(IRCBotUser user,
OsuApiUser apiUser, BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser,
BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
}
@Override
public void optionalCommentOnRecommendation(IRCBotUser user,
OsuApiUser apiUser, Recommendation meta) {
// regular Tillerino doesn't comment on this
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Άκυρη ακρίβεια: \"" + acc + "\"";
}
@Override
public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) {
user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Συγνώμη, αλλά \"" + invalid
+ "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!";
}
@Override
public String setFormat() {
return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
}
|
29430_4 | import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
public class DuidokuGUI {
Duidoku logic;
JFrame main;
JPanel board;
JPanel side;
JButton[][] tiles;
int display;
JLabel label;
JLabel label1;
String player_name;
private ResourceBundle bundle;
public DuidokuGUI(String player, int display, Locale loc) {
bundle = ResourceBundle.getBundle("i18n.MessageListBundle", loc);
this.display=display;
player_name=player;
logic = new Duidoku(display);
main = new JFrame("Duidoku 4x4");
board = new JPanel();
label=new JLabel(bundle.getString("gl"));
label1=new JLabel();
label.setFont(new Font("Arial", Font.BOLD, 30));
label.setForeground (Color.lightGray.darker());
main.setForeground(Color.BLACK);
board.setSize(600, 600);
board.setLayout(new GridLayout(5, 5));
side = new JPanel();
side.setSize(30, 200);
side.setLayout(new GridLayout(3, 1));
side.setVisible(true);
JPanel pn=new JPanel();
pn.add(label);
side.add(label1);
side.add(pn);
tiles = new Tile[4][4]; //See code for the tiles
for (int i = 0; i < 4; i++) {
tiles[i] = new Tile[4];
for (int j = 0; j < 4; j++) {
tiles[i][j] = new Tile(' ', false, i + 1, j + 1, display);
if((i==j)||(i==0 && j==1)||(i==1 && j==0)||(i==2 && j==3)||(i==3 && j==2)){
tiles[i][j].setBorder(BorderFactory.createLineBorder(Color.gray.darker(),2));
}
tiles[i][j].setSize(15, 15);
tiles[i][j].setVisible(true);
board.add(tiles[i][j]);
}
}
JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
sp.setResizeWeight(0.55);
sp.setEnabled(false);
sp.setDividerSize(0);
sp.add(board);
sp.add(side);
JButton back = new JButton(bundle.getString("back"));
back.setPreferredSize(new Dimension(100, 50));
back.setBackground(Color.WHITE);
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent)
{
if(!logic.isFull()) {
int b = JOptionPane.showConfirmDialog(main, bundle.getString("backmsg"), bundle.getString("main"), JOptionPane.YES_NO_OPTION);
if (b == 0) {
main.dispose();
Menu main = new Menu(loc);
}
}else{
main.dispose();
Menu main = new Menu(loc);
}
}
});
JButton select = new JButton(bundle.getString("new"));
select.setBackground(Color.WHITE);
select.setPreferredSize(new Dimension(100, 50));
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (!logic.isFull())
{
int n = JOptionPane.showConfirmDialog(main, bundle.getString("newgame"), bundle.getString("new"), JOptionPane.YES_NO_OPTION);
if (n == 0) {
main.dispose();
DuidokuGUI dui = new DuidokuGUI(player, display, loc);
}
} else {
main.dispose();
DuidokuGUI dui = new DuidokuGUI(player, display, loc);
}
}
});
JPanel header = new JPanel();
header.setSize(400, 50);
header.add(back);
header.add(select);
header.setVisible(true);
JSplitPane sp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp1.setResizeWeight(0.1);
sp1.setEnabled(false);
sp1.setDividerSize(0);
sp1.add(header);
sp1.add(sp);
main.add(sp1);
main.setSize(800, 600);
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
main.setVisible(true);
main.setResizable(true);
}
public class Tile extends JButton {
Coordinates c;
JButton[] choices;
char value;
boolean locked;
JFrame help;
public Tile(char value, boolean locked, int x, int y, int display) {
this.value = value;
this.setText(String.valueOf(value));
c = new Coordinates(x, y, logic.dimensions);
choices = new JButton[4];
this.locked = locked;
setFont(new Font("Arial", Font.BOLD, 30));
setBackground(Color.WHITE.brighter());
if (!locked) {
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
main.setEnabled(false);
help = new JFrame(bundle.getString("choose"));
help.setResizable(false);
help.setSize(250, 250);
help.setLocationRelativeTo(DuidokuGUI.Tile.this);
choose(display);
help.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
main.setEnabled(true);
}
});
}
});
}
}
public void choose(int display) {
JPanel pane = new JPanel();
pane.setVisible(true);
setFont(new Font("Arial", Font.BOLD, 30));
pane.setLayout(new GridLayout(2, 2, 2, 2));
for (int i = 0; i < 4; i++) {
if (display == 1) //If i chose to display numbers
{
choices[i] = new DuidokuGUI.Tile.Choice(Integer.toString(i + 1));
choices[i].setFont(new Font("Arial", Font.BOLD, 30));
if (!logic.Helper(c.getX(), c.getY()).contains((char) ('0' + (i + 1)))) {
choices[i].setEnabled(false);
choices[i].setBackground(Color.lightGray);
}else{
choices[i].setBackground(Color.WHITE);
}
} else {
choices[i] = new DuidokuGUI.Tile.Choice(Character.toString(logic.getLetters().get(i)));
choices[i].setFont(new Font("Arial", Font.BOLD, 30));
if (!logic.Helper(c.getX(), c.getY()).contains(logic.getLetters().get(i))) {
choices[i].setEnabled(false);
choices[i].setBackground(Color.lightGray);
}else{
choices[i].setBackground(Color.WHITE.brighter());
}
}
pane.add(choices[i]);
}
help.add(pane);
help.setVisible(true);
}
public class Choice extends JButton {
char val;
public Choice(String text) {
this.setText(text);
val = text.charAt(0);
this.setSize(30, 30);
this.setVisible(true);
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(!logic.isFull()) {
main.setEnabled(true);
logic.player(c.getX(), c.getY(), val);
setBackground(Color.LIGHT_GRAY);
DuidokuGUI.Tile.this.setText(Character.toString(logic.getTable()[c.getX() - 1][c.getY() - 1].getValue())); //Goes to the logic's table and matches the numbers to the UI display because putting in the value may not have vbeen successful
DuidokuGUI.Tile.this.help.dispose();
DuidokuGUI.Tile.this.setEnabled(false);
check();
if (logic.isFull()) {
label.setText(bundle.getString("win"));
//εδω κανει το save για τα score(οταν κερδιζει)
if(!player_name.equals("Anonymous"))
{
PlayerReaderWriter save = new PlayerReaderWriter();
ArrayList<Player> players = save.Read("scores.txt");
if (players == null)
{
players = new ArrayList<>();
}
boolean found = false;
for (Player p : players)
{
if(p.getName().equals(player_name))
{
p.setVictories(p.getVictories() + 1);
found = true;
break;
}
}
if(!found)
{
players.add(new Player(player_name, 1, 0, null, null));
}
save.Write(players, "scores.txt");
}
}
if(!logic.isFull()) {
logic.pc();
tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setText(Character.toString(logic.getCurrent_c_pc()));
tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setBackground(Color.pink);
tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setEnabled(false);
check();
if (logic.isFull()) {
label.setText(bundle.getString("lose"));
// εδω κανει το save για τα score(οταν χανει)
if(!player_name.equals("Anonymous"))
{
PlayerReaderWriter save = new PlayerReaderWriter();
ArrayList<Player> players = save.Read("scores.txt");
if (players == null)
{
players = new ArrayList<>();
}
boolean found = false;
for (Player p : players)
{
if(p.getName().equals(player_name))
{
p.setDefeats(p.getDefeats() + 1);
found = true;
break;
}
}
if(!found)
{
players.add(new Player(player_name, 0, 1, null, null));
}
save.Write(players, "scores.txt");
}
}
}
}
}
});
}
}
public void check() {
logic.check_duidoku();
for (int i = 0; i < logic.dimensions; i++) {
for (int j = 0; j < logic.dimensions; j++) {
if (logic.getTable()[i][j].isBlocked_cell()) {
tiles[i][j].setEnabled(false);
tiles[i][j].setBackground(Color.black.brighter());
}
}
}
}
}
}
| LukaSt99/Sudoku-GUI | src/DuidokuGUI.java | 2,624 | // εδω κανει το save για τα score(οταν χανει) | line_comment | el | import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
public class DuidokuGUI {
Duidoku logic;
JFrame main;
JPanel board;
JPanel side;
JButton[][] tiles;
int display;
JLabel label;
JLabel label1;
String player_name;
private ResourceBundle bundle;
public DuidokuGUI(String player, int display, Locale loc) {
bundle = ResourceBundle.getBundle("i18n.MessageListBundle", loc);
this.display=display;
player_name=player;
logic = new Duidoku(display);
main = new JFrame("Duidoku 4x4");
board = new JPanel();
label=new JLabel(bundle.getString("gl"));
label1=new JLabel();
label.setFont(new Font("Arial", Font.BOLD, 30));
label.setForeground (Color.lightGray.darker());
main.setForeground(Color.BLACK);
board.setSize(600, 600);
board.setLayout(new GridLayout(5, 5));
side = new JPanel();
side.setSize(30, 200);
side.setLayout(new GridLayout(3, 1));
side.setVisible(true);
JPanel pn=new JPanel();
pn.add(label);
side.add(label1);
side.add(pn);
tiles = new Tile[4][4]; //See code for the tiles
for (int i = 0; i < 4; i++) {
tiles[i] = new Tile[4];
for (int j = 0; j < 4; j++) {
tiles[i][j] = new Tile(' ', false, i + 1, j + 1, display);
if((i==j)||(i==0 && j==1)||(i==1 && j==0)||(i==2 && j==3)||(i==3 && j==2)){
tiles[i][j].setBorder(BorderFactory.createLineBorder(Color.gray.darker(),2));
}
tiles[i][j].setSize(15, 15);
tiles[i][j].setVisible(true);
board.add(tiles[i][j]);
}
}
JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
sp.setResizeWeight(0.55);
sp.setEnabled(false);
sp.setDividerSize(0);
sp.add(board);
sp.add(side);
JButton back = new JButton(bundle.getString("back"));
back.setPreferredSize(new Dimension(100, 50));
back.setBackground(Color.WHITE);
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent)
{
if(!logic.isFull()) {
int b = JOptionPane.showConfirmDialog(main, bundle.getString("backmsg"), bundle.getString("main"), JOptionPane.YES_NO_OPTION);
if (b == 0) {
main.dispose();
Menu main = new Menu(loc);
}
}else{
main.dispose();
Menu main = new Menu(loc);
}
}
});
JButton select = new JButton(bundle.getString("new"));
select.setBackground(Color.WHITE);
select.setPreferredSize(new Dimension(100, 50));
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (!logic.isFull())
{
int n = JOptionPane.showConfirmDialog(main, bundle.getString("newgame"), bundle.getString("new"), JOptionPane.YES_NO_OPTION);
if (n == 0) {
main.dispose();
DuidokuGUI dui = new DuidokuGUI(player, display, loc);
}
} else {
main.dispose();
DuidokuGUI dui = new DuidokuGUI(player, display, loc);
}
}
});
JPanel header = new JPanel();
header.setSize(400, 50);
header.add(back);
header.add(select);
header.setVisible(true);
JSplitPane sp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp1.setResizeWeight(0.1);
sp1.setEnabled(false);
sp1.setDividerSize(0);
sp1.add(header);
sp1.add(sp);
main.add(sp1);
main.setSize(800, 600);
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
main.setVisible(true);
main.setResizable(true);
}
public class Tile extends JButton {
Coordinates c;
JButton[] choices;
char value;
boolean locked;
JFrame help;
public Tile(char value, boolean locked, int x, int y, int display) {
this.value = value;
this.setText(String.valueOf(value));
c = new Coordinates(x, y, logic.dimensions);
choices = new JButton[4];
this.locked = locked;
setFont(new Font("Arial", Font.BOLD, 30));
setBackground(Color.WHITE.brighter());
if (!locked) {
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
main.setEnabled(false);
help = new JFrame(bundle.getString("choose"));
help.setResizable(false);
help.setSize(250, 250);
help.setLocationRelativeTo(DuidokuGUI.Tile.this);
choose(display);
help.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
main.setEnabled(true);
}
});
}
});
}
}
public void choose(int display) {
JPanel pane = new JPanel();
pane.setVisible(true);
setFont(new Font("Arial", Font.BOLD, 30));
pane.setLayout(new GridLayout(2, 2, 2, 2));
for (int i = 0; i < 4; i++) {
if (display == 1) //If i chose to display numbers
{
choices[i] = new DuidokuGUI.Tile.Choice(Integer.toString(i + 1));
choices[i].setFont(new Font("Arial", Font.BOLD, 30));
if (!logic.Helper(c.getX(), c.getY()).contains((char) ('0' + (i + 1)))) {
choices[i].setEnabled(false);
choices[i].setBackground(Color.lightGray);
}else{
choices[i].setBackground(Color.WHITE);
}
} else {
choices[i] = new DuidokuGUI.Tile.Choice(Character.toString(logic.getLetters().get(i)));
choices[i].setFont(new Font("Arial", Font.BOLD, 30));
if (!logic.Helper(c.getX(), c.getY()).contains(logic.getLetters().get(i))) {
choices[i].setEnabled(false);
choices[i].setBackground(Color.lightGray);
}else{
choices[i].setBackground(Color.WHITE.brighter());
}
}
pane.add(choices[i]);
}
help.add(pane);
help.setVisible(true);
}
public class Choice extends JButton {
char val;
public Choice(String text) {
this.setText(text);
val = text.charAt(0);
this.setSize(30, 30);
this.setVisible(true);
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(!logic.isFull()) {
main.setEnabled(true);
logic.player(c.getX(), c.getY(), val);
setBackground(Color.LIGHT_GRAY);
DuidokuGUI.Tile.this.setText(Character.toString(logic.getTable()[c.getX() - 1][c.getY() - 1].getValue())); //Goes to the logic's table and matches the numbers to the UI display because putting in the value may not have vbeen successful
DuidokuGUI.Tile.this.help.dispose();
DuidokuGUI.Tile.this.setEnabled(false);
check();
if (logic.isFull()) {
label.setText(bundle.getString("win"));
//εδω κανει το save για τα score(οταν κερδιζει)
if(!player_name.equals("Anonymous"))
{
PlayerReaderWriter save = new PlayerReaderWriter();
ArrayList<Player> players = save.Read("scores.txt");
if (players == null)
{
players = new ArrayList<>();
}
boolean found = false;
for (Player p : players)
{
if(p.getName().equals(player_name))
{
p.setVictories(p.getVictories() + 1);
found = true;
break;
}
}
if(!found)
{
players.add(new Player(player_name, 1, 0, null, null));
}
save.Write(players, "scores.txt");
}
}
if(!logic.isFull()) {
logic.pc();
tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setText(Character.toString(logic.getCurrent_c_pc()));
tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setBackground(Color.pink);
tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setEnabled(false);
check();
if (logic.isFull()) {
label.setText(bundle.getString("lose"));
// εδ<SUF>
if(!player_name.equals("Anonymous"))
{
PlayerReaderWriter save = new PlayerReaderWriter();
ArrayList<Player> players = save.Read("scores.txt");
if (players == null)
{
players = new ArrayList<>();
}
boolean found = false;
for (Player p : players)
{
if(p.getName().equals(player_name))
{
p.setDefeats(p.getDefeats() + 1);
found = true;
break;
}
}
if(!found)
{
players.add(new Player(player_name, 0, 1, null, null));
}
save.Write(players, "scores.txt");
}
}
}
}
}
});
}
}
public void check() {
logic.check_duidoku();
for (int i = 0; i < logic.dimensions; i++) {
for (int j = 0; j < logic.dimensions; j++) {
if (logic.getTable()[i][j].isBlocked_cell()) {
tiles[i][j].setEnabled(false);
tiles[i][j].setBackground(Color.black.brighter());
}
}
}
}
}
}
|
14919_14 | package com.emmanouilpapadimitrou.healthapp.Fragments;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.emmanouilpapadimitrou.healthapp.Activities.PatientsActivity;
import com.emmanouilpapadimitrou.healthapp.Adapters.ExaminationsAdapter;
import com.emmanouilpapadimitrou.healthapp.Adapters.HistoryAdapter;
import com.emmanouilpapadimitrou.healthapp.POJOs.*;
import com.emmanouilpapadimitrou.healthapp.R;
import com.google.firebase.auth.FirebaseAuth;
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.google.firebase.storage.FirebaseStorage;
import java.util.ArrayList;
public class HistoryFragment extends Fragment {
private ArrayList<History> allHistory;
private FirebaseAuth firebaseAuth;
private String userID;
private DatabaseReference referenceDB;
private ListView historyList;
private Users currentUser;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_history,container,false);
//Παίρνουμε τον χρήστη
currentUser = ((PatientsActivity)getActivity()).getCurrentUser();
//Ορισμός της λίστας που περιέχει όλα τα αντικείμενα των εξετάσεων
allHistory = new ArrayList<History>();
//Μεταβλητή που μας δίνει τα στοιχεία του συνδεδεμένου χρήστη
firebaseAuth = FirebaseAuth.getInstance();
//Ανάθεση του ID σε μεταβλητή για μελλοντική χρήστη
userID = firebaseAuth.getCurrentUser().getUid();
//Ορισμός της βάσης στην μεταβλητή για οποιαδήποτε μελλοντική χρήστη
referenceDB = FirebaseDatabase.getInstance().getReference();
//Σύνδεση μεταβλητής με την λίστα στο layout
historyList = (ListView) view.findViewById(R.id.historyList);
//Παίρνουμε τον επιλεγμένο χρήστη με όλα του τα στοιχεία
final Patient patient = ((PatientsActivity)getActivity()).getCurrentPatient();
//Παίρνουμε όλες τις εξετάσεις από την βάση
referenceDB.child("history").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(final DataSnapshot history : dataSnapshot.getChildren()){
final History h = new History();
for(final DataSnapshot historyChild : history.child("users").getChildren()){
//Θα βρούμε το όνομα του γιατρού από το id
final String docID = String.valueOf(historyChild.getKey());
referenceDB.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot1) {
for(DataSnapshot userTemp : dataSnapshot1.getChildren()){
if(docID.equals(String.valueOf(userTemp.getKey()))){
h.setId(String.valueOf(history.getKey()));
for(DataSnapshot typeTempID : history.child("type").getChildren()){
h.setType(String.valueOf(typeTempID.getKey()));
}
for(DataSnapshot typeTempID : history.child("type").getChildren()){
h.setTypeId(String.valueOf(typeTempID.getValue()));
}
h.setDate(String.valueOf( history.child("date").getValue()));
if(String.valueOf(userTemp.child("type").getValue()).equals("doctor")){
h.setDoctor("Δρ. "+ String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue()));
}
else{
h.setDoctor(String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue()));
}
h.setCondition(String.valueOf( history.child("condition").getValue()));
for(DataSnapshot patientTempID : history.child("patients").getChildren()){
//Αν είναι ο χρήστης που επιλέχθηκε βάλε την εξέταση στην λίστα
if(patient.getId().equals(String.valueOf(patientTempID.getKey()))){
allHistory.add(h);
}
}
}
}
//Εμφανίζουμε όλες τις εξετάσεις του ασθενούς με τις απαραίτητες πληροφορίες
//Create the adapter to convert the array to views
HistoryAdapter adapter = new HistoryAdapter(getActivity(),allHistory);
// Attach the adapter to a ListView
historyList.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Προβολή λεπτομερειών
historyList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final History historySelected = (History) historyList.getItemAtPosition(position);
//Προβολή παραθύρου για επιβεβαίωση διαγραφής φαρμάκου
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
View mView = getLayoutInflater().inflate(R.layout.view_history_details,null);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
//textview που θα προβληθούν οι λεπτομέρειες
final TextView detailsView = (TextView) mView.findViewById(R.id.detailsView);
//Κουμπιά
Button denyButton = (Button) mView.findViewById(R.id.denyButton);
//Παίρνουμε τις λεπτομέρειες του επιλεγμένου ιστορικού
referenceDB.child("history").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(final DataSnapshot history : dataSnapshot.getChildren()){
if(history.getKey().equals(historySelected.getId())){
detailsView.setText(String.valueOf(history.child("details").getValue()));
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Κουμπί για πίσω
denyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
return false;
}
});
return view;
}
}
| ManolisPapd/HealthApp | Android/HealthApp/app/src/main/java/com/emmanouilpapadimitrou/healthapp/Fragments/HistoryFragment.java | 2,079 | //Προβολή παραθύρου για επιβεβαίωση διαγραφής φαρμάκου | line_comment | el | package com.emmanouilpapadimitrou.healthapp.Fragments;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.emmanouilpapadimitrou.healthapp.Activities.PatientsActivity;
import com.emmanouilpapadimitrou.healthapp.Adapters.ExaminationsAdapter;
import com.emmanouilpapadimitrou.healthapp.Adapters.HistoryAdapter;
import com.emmanouilpapadimitrou.healthapp.POJOs.*;
import com.emmanouilpapadimitrou.healthapp.R;
import com.google.firebase.auth.FirebaseAuth;
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.google.firebase.storage.FirebaseStorage;
import java.util.ArrayList;
public class HistoryFragment extends Fragment {
private ArrayList<History> allHistory;
private FirebaseAuth firebaseAuth;
private String userID;
private DatabaseReference referenceDB;
private ListView historyList;
private Users currentUser;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_history,container,false);
//Παίρνουμε τον χρήστη
currentUser = ((PatientsActivity)getActivity()).getCurrentUser();
//Ορισμός της λίστας που περιέχει όλα τα αντικείμενα των εξετάσεων
allHistory = new ArrayList<History>();
//Μεταβλητή που μας δίνει τα στοιχεία του συνδεδεμένου χρήστη
firebaseAuth = FirebaseAuth.getInstance();
//Ανάθεση του ID σε μεταβλητή για μελλοντική χρήστη
userID = firebaseAuth.getCurrentUser().getUid();
//Ορισμός της βάσης στην μεταβλητή για οποιαδήποτε μελλοντική χρήστη
referenceDB = FirebaseDatabase.getInstance().getReference();
//Σύνδεση μεταβλητής με την λίστα στο layout
historyList = (ListView) view.findViewById(R.id.historyList);
//Παίρνουμε τον επιλεγμένο χρήστη με όλα του τα στοιχεία
final Patient patient = ((PatientsActivity)getActivity()).getCurrentPatient();
//Παίρνουμε όλες τις εξετάσεις από την βάση
referenceDB.child("history").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(final DataSnapshot history : dataSnapshot.getChildren()){
final History h = new History();
for(final DataSnapshot historyChild : history.child("users").getChildren()){
//Θα βρούμε το όνομα του γιατρού από το id
final String docID = String.valueOf(historyChild.getKey());
referenceDB.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot1) {
for(DataSnapshot userTemp : dataSnapshot1.getChildren()){
if(docID.equals(String.valueOf(userTemp.getKey()))){
h.setId(String.valueOf(history.getKey()));
for(DataSnapshot typeTempID : history.child("type").getChildren()){
h.setType(String.valueOf(typeTempID.getKey()));
}
for(DataSnapshot typeTempID : history.child("type").getChildren()){
h.setTypeId(String.valueOf(typeTempID.getValue()));
}
h.setDate(String.valueOf( history.child("date").getValue()));
if(String.valueOf(userTemp.child("type").getValue()).equals("doctor")){
h.setDoctor("Δρ. "+ String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue()));
}
else{
h.setDoctor(String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue()));
}
h.setCondition(String.valueOf( history.child("condition").getValue()));
for(DataSnapshot patientTempID : history.child("patients").getChildren()){
//Αν είναι ο χρήστης που επιλέχθηκε βάλε την εξέταση στην λίστα
if(patient.getId().equals(String.valueOf(patientTempID.getKey()))){
allHistory.add(h);
}
}
}
}
//Εμφανίζουμε όλες τις εξετάσεις του ασθενούς με τις απαραίτητες πληροφορίες
//Create the adapter to convert the array to views
HistoryAdapter adapter = new HistoryAdapter(getActivity(),allHistory);
// Attach the adapter to a ListView
historyList.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Προβολή λεπτομερειών
historyList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final History historySelected = (History) historyList.getItemAtPosition(position);
//Πρ<SUF>
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
View mView = getLayoutInflater().inflate(R.layout.view_history_details,null);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
//textview που θα προβληθούν οι λεπτομέρειες
final TextView detailsView = (TextView) mView.findViewById(R.id.detailsView);
//Κουμπιά
Button denyButton = (Button) mView.findViewById(R.id.denyButton);
//Παίρνουμε τις λεπτομέρειες του επιλεγμένου ιστορικού
referenceDB.child("history").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(final DataSnapshot history : dataSnapshot.getChildren()){
if(history.getKey().equals(historySelected.getId())){
detailsView.setText(String.valueOf(history.child("details").getValue()));
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Κουμπί για πίσω
denyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
return false;
}
});
return view;
}
}
|
5517_0 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Υπολογίζει το 1 + 2 + .. + n,
* όπου το ν το δίνει ο χρήστης.
*/
public class SumGenericApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int endValue = 0;
int i = 1;
int result = 0;
System.out.println("Please insert a num");
endValue = scanner.nextInt();
while (i <= endValue) {
result += i;
i++;
}
System.out.printf("Sum 1+2+...+%d = %d", endValue, result);
}
}
| ManosDaskalelis/Java | cf/ch3/SumGenericApp.java | 201 | /**
* Υπολογίζει το 1 + 2 + .. + n,
* όπου το ν το δίνει ο χρήστης.
*/ | block_comment | el | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Υπο<SUF>*/
public class SumGenericApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int endValue = 0;
int i = 1;
int result = 0;
System.out.println("Please insert a num");
endValue = scanner.nextInt();
while (i <= endValue) {
result += i;
i++;
}
System.out.printf("Sum 1+2+...+%d = %d", endValue, result);
}
}
|
315_0 | package gr.aueb.cf.ch2;public class InitialsApp {
/**
* Πρόγραμμα που εκτυπώνει τα
* αρχικά του ονόματός μου.
*/
public static void main(String[] args) {
System.out.println("*********" + "\t\t\t\t\t\t\t *" );
System.out.println("*" + "\t\t\t\t\t\t *" + " *");
System.out.println("*" + "\t\t\t\t\t\t *" + "\t*");
System.out.println("*********" + "\t\t\t\t\t\t *" + "\t *");
System.out.println("*" + "\t\t\t\t\t\t\t *" + "\t\t *");
System.out.println("*" + "\t\t\t\t\t\t *" + "\t\t *");
System.out.println("*********" + "\t\t\t\t\t *************");
}
}
| ManosDaskalelis/java-exc | ch2/InitialsApp.java | 284 | /**
* Πρόγραμμα που εκτυπώνει τα
* αρχικά του ονόματός μου.
*/ | block_comment | el | package gr.aueb.cf.ch2;public class InitialsApp {
/**
* Πρό<SUF>*/
public static void main(String[] args) {
System.out.println("*********" + "\t\t\t\t\t\t\t *" );
System.out.println("*" + "\t\t\t\t\t\t *" + " *");
System.out.println("*" + "\t\t\t\t\t\t *" + "\t*");
System.out.println("*********" + "\t\t\t\t\t\t *" + "\t *");
System.out.println("*" + "\t\t\t\t\t\t\t *" + "\t\t *");
System.out.println("*" + "\t\t\t\t\t\t *" + "\t\t *");
System.out.println("*********" + "\t\t\t\t\t *************");
}
}
|
7573_4 | package View.UI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Πάνελ για το αρχικό μενού.
public class StartingUI extends JPanel {
MouseListener hover = new HoverMouse();
private JPanel buttons;
private final JButton[] button = new JButton[3];
private JLabel chooseMode;
public StartingUI(int width, int height, MouseListener handler){
this.setSize(width, height);
this.addComponentListener(new Resize());
this.setBackground(Color.BLACK);
this.setupPanels(handler);
this.setVisible(true);
}
// Αρχικοποιεί τα panels, κουμπιά.
private void setupPanels(MouseListener handler){
chooseMode = new JLabel("Choose Mode");
chooseMode.setOpaque(true);
chooseMode.setBackground(Color.BLACK);
chooseMode.setForeground(Color.WHITE);
chooseMode.setHorizontalAlignment(SwingConstants.CENTER);
buttons = new JPanel();
buttons.setLayout(new GridLayout(2, 1));
button[0] = new JButton();
button[0].setOpaque(true);
button[0].setBackground(Color.BLACK);
button[0].setText("No Step Back");
button[0].setForeground(Color.WHITE);
button[0].setHorizontalAlignment(SwingConstants.CENTER);
button[0].addMouseListener(hover);
button[0].addMouseListener(handler);
button[0].setFocusPainted(false);
button[0].setBorderPainted(false);
button[0].setName("1");
buttons.add(button[0]);
button[1] = new JButton();
button[1].setOpaque(true);
button[1].setBackground(Color.BLACK);
button[1].setText("Reduced Army");
button[1].setForeground(Color.WHITE);
button[1].setHorizontalAlignment(SwingConstants.CENTER);
button[1].addMouseListener(hover);
button[1].setBorderPainted(false);
button[1].setFocusPainted(false);
button[1].addMouseListener(handler);
button[1].setName("2");
buttons.add(button[1]);
button[2] = new JButton();
button[2].setOpaque(true);
button[2].setBackground(Color.BLACK);
button[2].setText("Proceed to Game");
button[2].setForeground(Color.WHITE);
button[2].setBorderPainted(false);
button[2].addMouseListener(hover);
button[2].addMouseListener(handler);
button[2].setFocusPainted(false);
button[2].setHorizontalAlignment(SwingConstants.CENTER);
button[2].setName("3");
this.scalePanels();
this.add(chooseMode, BorderLayout.NORTH);
this.add(buttons, BorderLayout.CENTER);
this.add(button[2], BorderLayout.SOUTH);
}
// Scale τα panels.
private void scalePanels(){
int size = this.getHeight() / 15;
chooseMode.setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
buttons.setPreferredSize(new Dimension(getWidth(), size * 11));
button[0].setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
button[1].setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
button[2].setPreferredSize(new Dimension(this.getWidth(), 3 * size));
button[2].setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
}
//Scale το panel.
private void scalePanel(int width, int height){
this.setSize(width, height);
this.scalePanels();
}
public void disableUI(){
this.setVisible(false);
this.setEnabled(false);
}
// Αλλάζει χρώμα στο mode που το mouse περιφέρεται κάποια στιγμή.
private static class HoverMouse implements MouseListener {
// Αλλαγή χρώματος του κουμπιού κατόπιν επιλογής.
@Override
public void mouseClicked(MouseEvent e) {
JButton button = (JButton) e.getSource();
button.setBackground(Color.GRAY);
button.setEnabled(false);
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
JButton hover = (JButton) e.getSource();
hover.setForeground(Color.RED);
}
@Override
public void mouseExited(MouseEvent e) {
JButton hover = (JButton) e.getSource();
hover.setForeground(Color.WHITE);
}
}
private class Resize implements ComponentListener{
@Override
public void componentResized(ComponentEvent e) {
scalePanel(getWidth(), getHeight());
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
}
}
| ManosKast/Online_Stratego | src/View/UI/StartingUI.java | 1,236 | // Αλλάζει χρώμα στο mode που το mouse περιφέρεται κάποια στιγμή.
| line_comment | el | package View.UI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Πάνελ για το αρχικό μενού.
public class StartingUI extends JPanel {
MouseListener hover = new HoverMouse();
private JPanel buttons;
private final JButton[] button = new JButton[3];
private JLabel chooseMode;
public StartingUI(int width, int height, MouseListener handler){
this.setSize(width, height);
this.addComponentListener(new Resize());
this.setBackground(Color.BLACK);
this.setupPanels(handler);
this.setVisible(true);
}
// Αρχικοποιεί τα panels, κουμπιά.
private void setupPanels(MouseListener handler){
chooseMode = new JLabel("Choose Mode");
chooseMode.setOpaque(true);
chooseMode.setBackground(Color.BLACK);
chooseMode.setForeground(Color.WHITE);
chooseMode.setHorizontalAlignment(SwingConstants.CENTER);
buttons = new JPanel();
buttons.setLayout(new GridLayout(2, 1));
button[0] = new JButton();
button[0].setOpaque(true);
button[0].setBackground(Color.BLACK);
button[0].setText("No Step Back");
button[0].setForeground(Color.WHITE);
button[0].setHorizontalAlignment(SwingConstants.CENTER);
button[0].addMouseListener(hover);
button[0].addMouseListener(handler);
button[0].setFocusPainted(false);
button[0].setBorderPainted(false);
button[0].setName("1");
buttons.add(button[0]);
button[1] = new JButton();
button[1].setOpaque(true);
button[1].setBackground(Color.BLACK);
button[1].setText("Reduced Army");
button[1].setForeground(Color.WHITE);
button[1].setHorizontalAlignment(SwingConstants.CENTER);
button[1].addMouseListener(hover);
button[1].setBorderPainted(false);
button[1].setFocusPainted(false);
button[1].addMouseListener(handler);
button[1].setName("2");
buttons.add(button[1]);
button[2] = new JButton();
button[2].setOpaque(true);
button[2].setBackground(Color.BLACK);
button[2].setText("Proceed to Game");
button[2].setForeground(Color.WHITE);
button[2].setBorderPainted(false);
button[2].addMouseListener(hover);
button[2].addMouseListener(handler);
button[2].setFocusPainted(false);
button[2].setHorizontalAlignment(SwingConstants.CENTER);
button[2].setName("3");
this.scalePanels();
this.add(chooseMode, BorderLayout.NORTH);
this.add(buttons, BorderLayout.CENTER);
this.add(button[2], BorderLayout.SOUTH);
}
// Scale τα panels.
private void scalePanels(){
int size = this.getHeight() / 15;
chooseMode.setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
buttons.setPreferredSize(new Dimension(getWidth(), size * 11));
button[0].setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
button[1].setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
button[2].setPreferredSize(new Dimension(this.getWidth(), 3 * size));
button[2].setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size));
}
//Scale το panel.
private void scalePanel(int width, int height){
this.setSize(width, height);
this.scalePanels();
}
public void disableUI(){
this.setVisible(false);
this.setEnabled(false);
}
// Αλ<SUF>
private static class HoverMouse implements MouseListener {
// Αλλαγή χρώματος του κουμπιού κατόπιν επιλογής.
@Override
public void mouseClicked(MouseEvent e) {
JButton button = (JButton) e.getSource();
button.setBackground(Color.GRAY);
button.setEnabled(false);
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
JButton hover = (JButton) e.getSource();
hover.setForeground(Color.RED);
}
@Override
public void mouseExited(MouseEvent e) {
JButton hover = (JButton) e.getSource();
hover.setForeground(Color.WHITE);
}
}
private class Resize implements ComponentListener{
@Override
public void componentResized(ComponentEvent e) {
scalePanel(getWidth(), getHeight());
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
}
}
|
3735_8 | package com.example.tecktrove.util;
import java.util.Calendar;
/**
* Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών
* αγνοώντας την ώρα.
*
*/
public class SimpleCalendar implements Comparable<SimpleCalendar> {
private static final long MILLIS_PER_DAY = 86400000;
private Calendar date;
/**
* Κατασκευάζει μία ημερομηνία με βάση το έτος,
* το μήνα και την ημέρα του μήνα.
* @param year Το έτος
* @param month Ο μήνας από 1 έως 12
* @param day Η ημέρα του μήνα
*/
public SimpleCalendar(int year, int month, int day) {
date = Calendar.getInstance();
date.set(year, month - 1, day);
trimToDays(this.date);
}
/**
* Κατασκευάζει μία ημερομηνία λαμβάνοντας.
* ως παράμετρο αντικείμενο της κλάσης {@code Calendar}
* @param date Η ημερομηνία
*/
public SimpleCalendar(Calendar date) {
this.date = Calendar.getInstance();
this.date.setTimeInMillis(date.getTimeInMillis());
trimToDays(this.date);
}
private void trimToDays(Calendar javaDate) {
javaDate.set(Calendar.HOUR_OF_DAY, 0);
javaDate.set(Calendar.MINUTE, 0);
javaDate.set(Calendar.SECOND, 0);
javaDate.set(Calendar.MILLISECOND, 0);
}
/**
* Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία.
* @param other Η δεύτερη ημερομηνία για την οποία
* υπολογίζεται η διάρκεια
* @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών
* σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη,
* ενώ αρνητικός το αντίθετο.
*/
public long durationInDays(SimpleCalendar other) {
long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis();
return timeDiff / MILLIS_PER_DAY;
}
/**
* Επιστρέφει το έτος της ημερομηνίας.
* @return Το έτος
*/
public int getYear() {
return date.get(Calendar.YEAR);
}
/**
* Επιστρέφει το μήνα της ημερομηνίας (1-12).
* @return Ο μήνας
*/
public int getMonth() {
return date.get(Calendar.MONTH) + 1;
}
/**
* Επιστρέφει την ημέρα σε του μήνα.
* @return Η ημέρα του μήνα
*/
public int getDayOfMonth() {
return date.get(Calendar.DAY_OF_MONTH);
}
/**
* Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας.
* @return Η ημέρα της εβδομάδας
*/
public int getDayOfWeek() {
return date.get(Calendar.DAY_OF_WEEK);
}
/**
* Επιστρέφει {@code true} αν η ημερομηνία είναι.
* μεταγενέστερη μίας άλλης ημερομηνίας
* @param other Η άλλη ημερομηνία
* @return {@code true} αν η ημερομηνία είναι
* μεταγενέστερη της άλλης
*/
public boolean after(SimpleCalendar other) {
if (equals(other)) {
return false;
}
return date.after(other.date);
}
/**
* Επιστρέφει {@code true} αν η ημερομηνία είναι.
* προγενέστερη μίας άλλης ημερομηνίας
* @param other Η άλλη ημερομηνία
* @return {@code true} αν η ημερομηνία είναι
* προγενέστερη της άλλης
*/
public boolean before(SimpleCalendar other) {
if (equals(other)) {
return false;
}
return date.before(other.date);
}
/**
* Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο
* αριθμό ημερών.
* @param days Ο αριθμός των ημερών που προστίθενται
* @return Η νέα ημερομηνία
*/
public SimpleCalendar addDays(int days) {
Calendar newDate = Calendar.getInstance();
newDate.setTimeInMillis(date.getTimeInMillis());
newDate.add(Calendar.DAY_OF_MONTH, days);
return new SimpleCalendar(newDate);
}
/**
* Επιστρέφει μία ημερομηνία τύπου {@code Calendar}.
* @return Η ημερομηνία
*/
public Calendar getJavaCalendar() {
Calendar javaCalendar = Calendar.getInstance();
javaCalendar.setTimeInMillis(date.getTimeInMillis());
trimToDays(javaCalendar);
return javaCalendar;
}
/**
* {@inheritDoc}
*/
public int compareTo(SimpleCalendar other) {
return date.compareTo(other.date);
}
/**
* Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης.
* @param other Το άλλο αντικείμενο προς έλεγχο
* @return {@code true} αν τα αντικείμενα είναι ίσα
*/
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (this == other) {
return true;
}
if (!(other instanceof SimpleCalendar)) {
return false;
}
SimpleCalendar theDate = (SimpleCalendar) other;
if (getYear() != theDate.getYear()) {
return false;
}
if (getMonth() != theDate.getMonth()) {
return false;
}
if (getDayOfMonth() != theDate.getDayOfMonth()) {
return false;
}
return true;
}
/**
* Το HashCode μίας ημερομηνίας
* @return Το HashCode
*/
@Override
public int hashCode() {
return date == null ? 0 : date.hashCode();
}
}
| MariaSchoinaki/TechTrove-App | app/src/main/java/com/example/tecktrove/util/SimpleCalendar.java | 2,161 | /**
* Επιστρέφει {@code true} αν η ημερομηνία είναι.
* μεταγενέστερη μίας άλλης ημερομηνίας
* @param other Η άλλη ημερομηνία
* @return {@code true} αν η ημερομηνία είναι
* μεταγενέστερη της άλλης
*/ | block_comment | el | package com.example.tecktrove.util;
import java.util.Calendar;
/**
* Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών
* αγνοώντας την ώρα.
*
*/
public class SimpleCalendar implements Comparable<SimpleCalendar> {
private static final long MILLIS_PER_DAY = 86400000;
private Calendar date;
/**
* Κατασκευάζει μία ημερομηνία με βάση το έτος,
* το μήνα και την ημέρα του μήνα.
* @param year Το έτος
* @param month Ο μήνας από 1 έως 12
* @param day Η ημέρα του μήνα
*/
public SimpleCalendar(int year, int month, int day) {
date = Calendar.getInstance();
date.set(year, month - 1, day);
trimToDays(this.date);
}
/**
* Κατασκευάζει μία ημερομηνία λαμβάνοντας.
* ως παράμετρο αντικείμενο της κλάσης {@code Calendar}
* @param date Η ημερομηνία
*/
public SimpleCalendar(Calendar date) {
this.date = Calendar.getInstance();
this.date.setTimeInMillis(date.getTimeInMillis());
trimToDays(this.date);
}
private void trimToDays(Calendar javaDate) {
javaDate.set(Calendar.HOUR_OF_DAY, 0);
javaDate.set(Calendar.MINUTE, 0);
javaDate.set(Calendar.SECOND, 0);
javaDate.set(Calendar.MILLISECOND, 0);
}
/**
* Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία.
* @param other Η δεύτερη ημερομηνία για την οποία
* υπολογίζεται η διάρκεια
* @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών
* σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη,
* ενώ αρνητικός το αντίθετο.
*/
public long durationInDays(SimpleCalendar other) {
long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis();
return timeDiff / MILLIS_PER_DAY;
}
/**
* Επιστρέφει το έτος της ημερομηνίας.
* @return Το έτος
*/
public int getYear() {
return date.get(Calendar.YEAR);
}
/**
* Επιστρέφει το μήνα της ημερομηνίας (1-12).
* @return Ο μήνας
*/
public int getMonth() {
return date.get(Calendar.MONTH) + 1;
}
/**
* Επιστρέφει την ημέρα σε του μήνα.
* @return Η ημέρα του μήνα
*/
public int getDayOfMonth() {
return date.get(Calendar.DAY_OF_MONTH);
}
/**
* Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας.
* @return Η ημέρα της εβδομάδας
*/
public int getDayOfWeek() {
return date.get(Calendar.DAY_OF_WEEK);
}
/**
* Επι<SUF>*/
public boolean after(SimpleCalendar other) {
if (equals(other)) {
return false;
}
return date.after(other.date);
}
/**
* Επιστρέφει {@code true} αν η ημερομηνία είναι.
* προγενέστερη μίας άλλης ημερομηνίας
* @param other Η άλλη ημερομηνία
* @return {@code true} αν η ημερομηνία είναι
* προγενέστερη της άλλης
*/
public boolean before(SimpleCalendar other) {
if (equals(other)) {
return false;
}
return date.before(other.date);
}
/**
* Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο
* αριθμό ημερών.
* @param days Ο αριθμός των ημερών που προστίθενται
* @return Η νέα ημερομηνία
*/
public SimpleCalendar addDays(int days) {
Calendar newDate = Calendar.getInstance();
newDate.setTimeInMillis(date.getTimeInMillis());
newDate.add(Calendar.DAY_OF_MONTH, days);
return new SimpleCalendar(newDate);
}
/**
* Επιστρέφει μία ημερομηνία τύπου {@code Calendar}.
* @return Η ημερομηνία
*/
public Calendar getJavaCalendar() {
Calendar javaCalendar = Calendar.getInstance();
javaCalendar.setTimeInMillis(date.getTimeInMillis());
trimToDays(javaCalendar);
return javaCalendar;
}
/**
* {@inheritDoc}
*/
public int compareTo(SimpleCalendar other) {
return date.compareTo(other.date);
}
/**
* Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης.
* @param other Το άλλο αντικείμενο προς έλεγχο
* @return {@code true} αν τα αντικείμενα είναι ίσα
*/
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (this == other) {
return true;
}
if (!(other instanceof SimpleCalendar)) {
return false;
}
SimpleCalendar theDate = (SimpleCalendar) other;
if (getYear() != theDate.getYear()) {
return false;
}
if (getMonth() != theDate.getMonth()) {
return false;
}
if (getDayOfMonth() != theDate.getDayOfMonth()) {
return false;
}
return true;
}
/**
* Το HashCode μίας ημερομηνίας
* @return Το HashCode
*/
@Override
public int hashCode() {
return date == null ? 0 : date.hashCode();
}
}
|
13461_0 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Εμφανίζει επαναληπτικά ένα μενού
* επιλογών μέχρι ο χρήστης να επιλέξει
* έξοδο.
*/
public class MenuApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int choice = 0;
do {
System.out.println("Επιλέξτε ένα από τα παρακάτω");
System.out.println("1. Add product");
System.out.println("2. Delete product");
System.out.println("3. Exit");
System.out.flush();
choice = in.nextInt();
} while (choice !=3);
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch3/MenuApp.java | 244 | /**
* Εμφανίζει επαναληπτικά ένα μενού
* επιλογών μέχρι ο χρήστης να επιλέξει
* έξοδο.
*/ | block_comment | el | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Εμφ<SUF>*/
public class MenuApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int choice = 0;
do {
System.out.println("Επιλέξτε ένα από τα παρακάτω");
System.out.println("1. Add product");
System.out.println("2. Delete product");
System.out.println("3. Exit");
System.out.flush();
choice = in.nextInt();
} while (choice !=3);
}
}
|
2888_0 | package com.ethelontismos;
import java.util.List;
public class Ethelo_1 { // main class και σύνδεση με ΑΙ
public static void main(String[] args) throws Exception {
System.out.println("Καλώς ήρθατε στον εΘΕΛΩντισμό! Είστε έτοιμοι για ένα νέο εθελοντικό ταξίδι;");
UsersProfile userProfile = UsersProfile.collectUserInformation();
UsersProfileManager.newUser(userProfile);
String userName = userProfile.getUsername();
System.out.println("Ας ανακαλύψουμε τι σας ταιριάζει!");
String result = UsersInterests.return_result();
VolunteerDB.fillDB();
List<VolunteerAction> allActions = VolunteerDB.getAllVolunteerActions();
String targetKeyword = RemoveNegativeInterests.removeNegativeInterests(result);
//1η γραμμή σύνδεση μέσω Chat
String promptDBandKeyword = ChatDbKeyword.promptBuilder(targetKeyword,allActions,userName);
String answer1 = ChatConn.chatGPT(promptDBandKeyword);
System.out.println(answer1);
/*
String actions = /* εδω συνδεση με db
String prompt = "Ο χρήστης με το όνομα " + userName + " ενδιαφέρεται να λάβει μέρος σε μια εθελοντική δράση. Ενδιαφέρεται για: " + result + ". Πρότεινέ του την πιο κατάλληλη εθελοντική δράση από τις ακόλουθες: " + allActions ;
String answer2 = ChatConn.chatGPT(prompt);
System.out.println(answer2);
*/
}
}
| MariliaGait/TeaMET | src/main/java/com/ethelontismos/Ethelo_1.java | 555 | // main class και σύνδεση με ΑΙ | line_comment | el | package com.ethelontismos;
import java.util.List;
public class Ethelo_1 { // ma<SUF>
public static void main(String[] args) throws Exception {
System.out.println("Καλώς ήρθατε στον εΘΕΛΩντισμό! Είστε έτοιμοι για ένα νέο εθελοντικό ταξίδι;");
UsersProfile userProfile = UsersProfile.collectUserInformation();
UsersProfileManager.newUser(userProfile);
String userName = userProfile.getUsername();
System.out.println("Ας ανακαλύψουμε τι σας ταιριάζει!");
String result = UsersInterests.return_result();
VolunteerDB.fillDB();
List<VolunteerAction> allActions = VolunteerDB.getAllVolunteerActions();
String targetKeyword = RemoveNegativeInterests.removeNegativeInterests(result);
//1η γραμμή σύνδεση μέσω Chat
String promptDBandKeyword = ChatDbKeyword.promptBuilder(targetKeyword,allActions,userName);
String answer1 = ChatConn.chatGPT(promptDBandKeyword);
System.out.println(answer1);
/*
String actions = /* εδω συνδεση με db
String prompt = "Ο χρήστης με το όνομα " + userName + " ενδιαφέρεται να λάβει μέρος σε μια εθελοντική δράση. Ενδιαφέρεται για: " + result + ". Πρότεινέ του την πιο κατάλληλη εθελοντική δράση από τις ακόλουθες: " + allActions ;
String answer2 = ChatConn.chatGPT(prompt);
System.out.println(answer2);
*/
}
}
|
3997_3 | /*
This file is part of "Ηλεκτρονική Διακίνηση Εγγράφων Δήμου Αθηναίων(ΗΔΕ)
Documents' Digital Handling/Digital Signature of Municipality of Athens(DDHDS)".
Complementary service to allow digital signing from browser
Copyright (C) <2018> Municipality Of Athens
Service Author Panagiotis Skarvelis [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
<authors' emails : [email protected], [email protected], [email protected]>
<authors' address : Λιοσίων 22, Αθήνα - Ελλάδα, ΤΚ:10438 ---- Liosion 22, Athens - Greeece, PC:10438>
*/
package moa.ds.service.athens.gr;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfDate;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignature;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.PdfPKCS7;
import moa.ds.service.athens.gr.radweriel;
import moa.ds.service.athens.gr.MOASSUtils;
import moa.ds.service.athens.gr.MOASSConfig;
import java.lang.String;
/**
* Servlet implementation class preSign
*/
@WebServlet(
description = "Get PDF from radweriel uuid and returns hash",
urlPatterns = { "/preSign" },
initParams = {
@WebInitParam(name = "reason", value = "", description = "reason to sign"),
@WebInitParam(name = "signers", value = "", description = "signers of pdf file"),
@WebInitParam(name = "uuid", value = "", description = "uuid of pdf file"),
@WebInitParam(name = "taskUUID", value = "", description = "uuid of runing task"),
@WebInitParam(name = "loggedUser", value = "", description = "the bonita logged user")
})
public class preSign extends HttpServlet {
private static final long serialVersionUID = 1L;
private static X509Certificate cer = null;
private static Calendar cal = null;
private static String reason = null;
private static String uuid = null;
private static String taskUUID = null;
private static String loggedUser = null;
private static String crtEmail = null;
private static Integer sigpage = 1;
private static Rectangle size = null;
private static PdfSignatureAppearance sap=null;
private static PdfStamper stamper = null;
private static PdfReader reader = null;
private static ByteArrayOutputStream baos = null;
private static float signHeight=50;
private static String signers[]=null;
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* @see HttpServlet#HttpServlet()
*/
public preSign() {
super();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void setPlaceHolders(int numOfSignatures) throws DocumentException, IOException{
float offset=20;
float pageHeight = (numOfSignatures*signHeight)+offset;
stamper.insertPage(sigpage, new Rectangle(0, 0, size.getWidth(),pageHeight));
String path = getServletContext().getRealPath("/assets/arialuni.ttf");
BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
fonty.setSubset(true);//Όλες οι θέσεις των υπογραφών πρέπει να συμπληρωθούν απο τους υπογράφοντες ώστε το έγγραφο να είναι έγκυρο
Phrase myWarning = new Phrase("----- Θέσεις Υπογραφών -----", new Font(fonty,10));
ColumnText.showTextAligned(stamper.getOverContent(sigpage),Element.ALIGN_LEFT, myWarning, 0, pageHeight-(offset/2), 0);
for (int i=1; i<=numOfSignatures; i++ ) {
//TODO na vazo ta cn auton pou prepei na ypograpsoun
//TODO on reverse order
stamper.addSignature("sig-"+i, sigpage, 0,((signHeight)*(i-1)) , size.getWidth(), (signHeight*i));
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
int numOfSignatures=0;
try{
signers = request.getParameter("signers").split(",");
numOfSignatures=signers.length;
if (numOfSignatures<1||numOfSignatures>6) throw new RuntimeException("λάθος υπογράφοντες");
cer = MOASSUtils.getCer(request.getParameter("cer").getBytes("UTF-8"));
reason = request.getParameter("reason");
if (reason=="") reason="signed";
uuid = request.getParameter("uuid").trim();
taskUUID = request.getParameter("taskUUID").trim();
loggedUser = request.getParameter("loggedUser").trim();
} catch (Exception e) {
response.getWriter().println("{\"error\":\" Πρόβλημα στις παραμέτρους "+e.getMessage()+"\"}");
return;
}
try {
cal = Calendar.getInstance(); //cal.set(1969, 3, 1,5, 0,0); //cal.setTimeInMillis(5000);
baos = new ByteArrayOutputStream();
reader = new PdfReader(radweriel.getDocByID("workspace://SpacesStore/"+uuid));
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// AUTHORIZE CHECKS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Elenxos an o katoxos tou certificate einai o idios me auton pou exei kanei login
crtEmail=MOASSUtils.getCertificateEmail(cer);
String userUID= galgallin.getUIDbyEmail(crtEmail);
if (!Objects.equals(userUID,loggedUser)) throw new RuntimeException("Δεν έχετε δικαίωμα υπογραφής σε αυτό το βήμα");
//Elegxos an o logged user paei na ypograpsei eggrafo se site pou anikei
//String UserOU = galgallin.getOUbyUID(userUID).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "");
String UserOU = MOASSUtils.setOuInAppropriateFormat(userUID);
String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "");
//TODO Dirty workarrounds FIX!!!!
/*
boolean isProtocolMember = galgallin.checkMembershipInGroupByUID(loggedUser, "protocol", "ou=groups,ou=DIAKINISI_EGGRAFON,ou=APPLICATIONS");
if (!isProtocolMember && !UserOU.equals("ΓΕΝΙΚΟΣ ΓΡΑΜΜΑΤΕΑΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("ΔΗΜΑΡΧΟΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("Αντιδήμαρχος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("Εντεταλμένος Σύμβουλος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("ΓΕΝΙΚΟΣ ΔΙΕΥΘΥΝΤΗΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""))){
String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "");
if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης");
}
*/
if(!MOASSUtils.transcendPersonRole(userUID)){
if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης");
}
//elenxos an o xristis einai allowed sto sygkekrimeno taskUUID
if (!thales.cantitateIsValid(taskUUID,loggedUser)) throw new RuntimeException("2 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Stoixeia tou xrhsth
String certInfo = cer.getSubjectX500Principal().getName();
String creator = certInfo.substring(certInfo.indexOf("CN=") + 3,certInfo.indexOf(",OU", certInfo.indexOf("CN=") + 3));
//System.out.println(reader.getCertificationLevel()); //TODO isos prepei na to koitao
AcroFields fields = reader.getAcroFields();
ArrayList<String> names = fields.getSignatureNames();
int sigs=names.size();
if ((sigs+1)>numOfSignatures) throw new RuntimeException("Έχουν πραγματοποιηθεί όλες οι υπογραφές");
//if (MOASSUtils.isSignedBy(fields,loggedUser)) throw new RuntimeException("Έχετε ήδη υπογράψει");
if (!Objects.equals(userUID,signers[sigs])) throw new RuntimeException("Δεν αναμένεται υπογραφή απο εσάς σε αύτο το βήμα");
if (sigs==0)
{
//Create signatures placeholders in new created page
stamper = new PdfStamper(reader,baos);
Map<String, String> info = reader.getInfo();
//info.put("Title", "Hello World");
//info.put("Subject", "Hello World with changed metadata");
//info.put("Keywords", signers);
info.put("Creator", "MOASS signer");
info.put("Author", creator);
info.put("ModDate", cal.getTime().toString());
info.put("CreationDate", cal.getTime().toString()); //info.put("CreationDate", "D:20120816122649+02'00'");
stamper.setMoreInfo(info);
//create new page to hold signatures
int pages =reader.getNumberOfPages();
size = reader.getPageSize(1);
sigpage=pages+1;
setPlaceHolders(numOfSignatures);
stamper.close();
reader.close();
//Create a copy from modified PDF with signature placeholders
PdfReader copy = new PdfReader(new ByteArrayInputStream(baos.toByteArray()));
baos.reset();//Reset stream to reuse it
stamper = PdfStamper.createSignature(copy, baos, '7', new File("/tmp"),false);
sap = stamper.getSignatureAppearance();
sap.setVisibleSignature("sig-1"); //H proth ypografh einai gia to certificate
//CERTIFIED_NO_CHANGES_ALLOWED Gia eggrafa pou den dexontai alles ypografes.TODO Na do ta locks gia thn teleutea ypografh
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS);
}
else{
stamper = PdfStamper.createSignature(reader, baos, '7', new File("/tmp"),true);
sap = stamper.getSignatureAppearance();
// sap.setVisibleSignature(new Rectangle(0, 0, size.getWidth(), 200), sigpage, "sig1");
sap.setVisibleSignature("sig-"+(sigs+1));//TODO select based on logged user
sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
}
//set Font
String path = getServletContext().getRealPath(MOASSConfig.getProperty("font"));
BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
fonty.setSubset(true);
Font sapFont = new Font(fonty,8);
sap.setLayer2Font(sapFont);
sap.setCertificate(cer);
sap.setSignDate(cal);
sap.setReason(reason);
sap.setLocation("Athens");
sap.setSignatureCreator(creator);
sap.setContact("Municipality of Athens");
//set the dic
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.setReason(sap.getReason());
dic.setLocation(sap.getLocation());
dic.setName(creator);
dic.setSignatureCreator(sap.getSignatureCreator());
dic.setContact(sap.getContact());
dic.setDate(new PdfDate(sap.getSignDate()));
dic.setCert(cer.getEncoded());
sap.setCryptoDictionary(dic);
HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
int estimatedSize =16384;
exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));//
sap.preClose(exc);
ExternalDigest externalDigest = new ExternalDigest() {
public MessageDigest getMessageDigest(String hashAlgorithm)
throws GeneralSecurityException {
return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
}
};
PdfPKCS7 sgn = new PdfPKCS7(null, new Certificate[] { cer }, "SHA256", null, externalDigest, false);
InputStream data = sap.getRangeStream();
byte hash[] = DigestAlgorithms.digest(data,externalDigest.getMessageDigest("SHA256"));
byte[] aab = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
byte[] sh = MessageDigest.getInstance("SHA256", "BC").digest(aab);
HttpSession session = request.getSession(true);
session.setAttribute("sgn", sgn);
session.setAttribute("hash", hash);
session.setAttribute("cal", cal);
session.setAttribute("sap", sap);
session.setAttribute("baos", baos);
session.setAttribute("uuid", uuid);
String HASH2SIGN = new String(String.format("%064x", new java.math.BigInteger(1, sh)));
response.getWriter().println("{\"HASH2SIGN\":\""+HASH2SIGN+"\"}");
} catch (DocumentException e) {
throw new IOException(e);
} catch (GeneralSecurityException e) {
throw new IOException(e);
} catch (Exception e) {
System.out.println(e);
//e.printStackTrace();
response.getWriter().println("{\"error\":\""+e.getMessage()+"\"}");
}
}
}
| MunicipalityOfAthens/MOASS | src/moa/ds/service/athens/gr/preSign.java | 4,749 | //Όλες οι θέσεις των υπογραφών πρέπει να συμπληρωθούν απο τους υπογράφοντες ώστε το έγγραφο να είναι έγκυρο | line_comment | el | /*
This file is part of "Ηλεκτρονική Διακίνηση Εγγράφων Δήμου Αθηναίων(ΗΔΕ)
Documents' Digital Handling/Digital Signature of Municipality of Athens(DDHDS)".
Complementary service to allow digital signing from browser
Copyright (C) <2018> Municipality Of Athens
Service Author Panagiotis Skarvelis [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
<authors' emails : [email protected], [email protected], [email protected]>
<authors' address : Λιοσίων 22, Αθήνα - Ελλάδα, ΤΚ:10438 ---- Liosion 22, Athens - Greeece, PC:10438>
*/
package moa.ds.service.athens.gr;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfDate;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignature;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.PdfPKCS7;
import moa.ds.service.athens.gr.radweriel;
import moa.ds.service.athens.gr.MOASSUtils;
import moa.ds.service.athens.gr.MOASSConfig;
import java.lang.String;
/**
* Servlet implementation class preSign
*/
@WebServlet(
description = "Get PDF from radweriel uuid and returns hash",
urlPatterns = { "/preSign" },
initParams = {
@WebInitParam(name = "reason", value = "", description = "reason to sign"),
@WebInitParam(name = "signers", value = "", description = "signers of pdf file"),
@WebInitParam(name = "uuid", value = "", description = "uuid of pdf file"),
@WebInitParam(name = "taskUUID", value = "", description = "uuid of runing task"),
@WebInitParam(name = "loggedUser", value = "", description = "the bonita logged user")
})
public class preSign extends HttpServlet {
private static final long serialVersionUID = 1L;
private static X509Certificate cer = null;
private static Calendar cal = null;
private static String reason = null;
private static String uuid = null;
private static String taskUUID = null;
private static String loggedUser = null;
private static String crtEmail = null;
private static Integer sigpage = 1;
private static Rectangle size = null;
private static PdfSignatureAppearance sap=null;
private static PdfStamper stamper = null;
private static PdfReader reader = null;
private static ByteArrayOutputStream baos = null;
private static float signHeight=50;
private static String signers[]=null;
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* @see HttpServlet#HttpServlet()
*/
public preSign() {
super();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void setPlaceHolders(int numOfSignatures) throws DocumentException, IOException{
float offset=20;
float pageHeight = (numOfSignatures*signHeight)+offset;
stamper.insertPage(sigpage, new Rectangle(0, 0, size.getWidth(),pageHeight));
String path = getServletContext().getRealPath("/assets/arialuni.ttf");
BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
fonty.setSubset(true);//Όλ<SUF>
Phrase myWarning = new Phrase("----- Θέσεις Υπογραφών -----", new Font(fonty,10));
ColumnText.showTextAligned(stamper.getOverContent(sigpage),Element.ALIGN_LEFT, myWarning, 0, pageHeight-(offset/2), 0);
for (int i=1; i<=numOfSignatures; i++ ) {
//TODO na vazo ta cn auton pou prepei na ypograpsoun
//TODO on reverse order
stamper.addSignature("sig-"+i, sigpage, 0,((signHeight)*(i-1)) , size.getWidth(), (signHeight*i));
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
int numOfSignatures=0;
try{
signers = request.getParameter("signers").split(",");
numOfSignatures=signers.length;
if (numOfSignatures<1||numOfSignatures>6) throw new RuntimeException("λάθος υπογράφοντες");
cer = MOASSUtils.getCer(request.getParameter("cer").getBytes("UTF-8"));
reason = request.getParameter("reason");
if (reason=="") reason="signed";
uuid = request.getParameter("uuid").trim();
taskUUID = request.getParameter("taskUUID").trim();
loggedUser = request.getParameter("loggedUser").trim();
} catch (Exception e) {
response.getWriter().println("{\"error\":\" Πρόβλημα στις παραμέτρους "+e.getMessage()+"\"}");
return;
}
try {
cal = Calendar.getInstance(); //cal.set(1969, 3, 1,5, 0,0); //cal.setTimeInMillis(5000);
baos = new ByteArrayOutputStream();
reader = new PdfReader(radweriel.getDocByID("workspace://SpacesStore/"+uuid));
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// AUTHORIZE CHECKS
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Elenxos an o katoxos tou certificate einai o idios me auton pou exei kanei login
crtEmail=MOASSUtils.getCertificateEmail(cer);
String userUID= galgallin.getUIDbyEmail(crtEmail);
if (!Objects.equals(userUID,loggedUser)) throw new RuntimeException("Δεν έχετε δικαίωμα υπογραφής σε αυτό το βήμα");
//Elegxos an o logged user paei na ypograpsei eggrafo se site pou anikei
//String UserOU = galgallin.getOUbyUID(userUID).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "");
String UserOU = MOASSUtils.setOuInAppropriateFormat(userUID);
String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "");
//TODO Dirty workarrounds FIX!!!!
/*
boolean isProtocolMember = galgallin.checkMembershipInGroupByUID(loggedUser, "protocol", "ou=groups,ou=DIAKINISI_EGGRAFON,ou=APPLICATIONS");
if (!isProtocolMember && !UserOU.equals("ΓΕΝΙΚΟΣ ΓΡΑΜΜΑΤΕΑΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("ΔΗΜΑΡΧΟΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("Αντιδήμαρχος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("Εντεταλμένος Σύμβουλος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) &&
!UserOU.equals("ΓΕΝΙΚΟΣ ΔΙΕΥΘΥΝΤΗΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""))){
String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "");
if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης");
}
*/
if(!MOASSUtils.transcendPersonRole(userUID)){
if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης");
}
//elenxos an o xristis einai allowed sto sygkekrimeno taskUUID
if (!thales.cantitateIsValid(taskUUID,loggedUser)) throw new RuntimeException("2 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Stoixeia tou xrhsth
String certInfo = cer.getSubjectX500Principal().getName();
String creator = certInfo.substring(certInfo.indexOf("CN=") + 3,certInfo.indexOf(",OU", certInfo.indexOf("CN=") + 3));
//System.out.println(reader.getCertificationLevel()); //TODO isos prepei na to koitao
AcroFields fields = reader.getAcroFields();
ArrayList<String> names = fields.getSignatureNames();
int sigs=names.size();
if ((sigs+1)>numOfSignatures) throw new RuntimeException("Έχουν πραγματοποιηθεί όλες οι υπογραφές");
//if (MOASSUtils.isSignedBy(fields,loggedUser)) throw new RuntimeException("Έχετε ήδη υπογράψει");
if (!Objects.equals(userUID,signers[sigs])) throw new RuntimeException("Δεν αναμένεται υπογραφή απο εσάς σε αύτο το βήμα");
if (sigs==0)
{
//Create signatures placeholders in new created page
stamper = new PdfStamper(reader,baos);
Map<String, String> info = reader.getInfo();
//info.put("Title", "Hello World");
//info.put("Subject", "Hello World with changed metadata");
//info.put("Keywords", signers);
info.put("Creator", "MOASS signer");
info.put("Author", creator);
info.put("ModDate", cal.getTime().toString());
info.put("CreationDate", cal.getTime().toString()); //info.put("CreationDate", "D:20120816122649+02'00'");
stamper.setMoreInfo(info);
//create new page to hold signatures
int pages =reader.getNumberOfPages();
size = reader.getPageSize(1);
sigpage=pages+1;
setPlaceHolders(numOfSignatures);
stamper.close();
reader.close();
//Create a copy from modified PDF with signature placeholders
PdfReader copy = new PdfReader(new ByteArrayInputStream(baos.toByteArray()));
baos.reset();//Reset stream to reuse it
stamper = PdfStamper.createSignature(copy, baos, '7', new File("/tmp"),false);
sap = stamper.getSignatureAppearance();
sap.setVisibleSignature("sig-1"); //H proth ypografh einai gia to certificate
//CERTIFIED_NO_CHANGES_ALLOWED Gia eggrafa pou den dexontai alles ypografes.TODO Na do ta locks gia thn teleutea ypografh
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS);
}
else{
stamper = PdfStamper.createSignature(reader, baos, '7', new File("/tmp"),true);
sap = stamper.getSignatureAppearance();
// sap.setVisibleSignature(new Rectangle(0, 0, size.getWidth(), 200), sigpage, "sig1");
sap.setVisibleSignature("sig-"+(sigs+1));//TODO select based on logged user
sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
}
//set Font
String path = getServletContext().getRealPath(MOASSConfig.getProperty("font"));
BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
fonty.setSubset(true);
Font sapFont = new Font(fonty,8);
sap.setLayer2Font(sapFont);
sap.setCertificate(cer);
sap.setSignDate(cal);
sap.setReason(reason);
sap.setLocation("Athens");
sap.setSignatureCreator(creator);
sap.setContact("Municipality of Athens");
//set the dic
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.setReason(sap.getReason());
dic.setLocation(sap.getLocation());
dic.setName(creator);
dic.setSignatureCreator(sap.getSignatureCreator());
dic.setContact(sap.getContact());
dic.setDate(new PdfDate(sap.getSignDate()));
dic.setCert(cer.getEncoded());
sap.setCryptoDictionary(dic);
HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
int estimatedSize =16384;
exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));//
sap.preClose(exc);
ExternalDigest externalDigest = new ExternalDigest() {
public MessageDigest getMessageDigest(String hashAlgorithm)
throws GeneralSecurityException {
return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
}
};
PdfPKCS7 sgn = new PdfPKCS7(null, new Certificate[] { cer }, "SHA256", null, externalDigest, false);
InputStream data = sap.getRangeStream();
byte hash[] = DigestAlgorithms.digest(data,externalDigest.getMessageDigest("SHA256"));
byte[] aab = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
byte[] sh = MessageDigest.getInstance("SHA256", "BC").digest(aab);
HttpSession session = request.getSession(true);
session.setAttribute("sgn", sgn);
session.setAttribute("hash", hash);
session.setAttribute("cal", cal);
session.setAttribute("sap", sap);
session.setAttribute("baos", baos);
session.setAttribute("uuid", uuid);
String HASH2SIGN = new String(String.format("%064x", new java.math.BigInteger(1, sh)));
response.getWriter().println("{\"HASH2SIGN\":\""+HASH2SIGN+"\"}");
} catch (DocumentException e) {
throw new IOException(e);
} catch (GeneralSecurityException e) {
throw new IOException(e);
} catch (Exception e) {
System.out.println(e);
//e.printStackTrace();
response.getWriter().println("{\"error\":\""+e.getMessage()+"\"}");
}
}
}
|
698_1 | package gr.aueb.cf.ch2;
/**
* Demonstrates int data types
*/
public class IntApp {
public static void main(String[] args) {
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %,d, \tMax: %,d\n",
Integer.TYPE, Integer.BYTES * 8, Integer.MIN_VALUE, Integer.MAX_VALUE);
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %d, \tMax: %d\n",
Byte.TYPE, Byte.BYTES * 8, Byte.MIN_VALUE, Byte.MAX_VALUE);
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %,d, \tMax: %,d\n",
Short.TYPE, Short.BYTES * 8, Short.MIN_VALUE, Short.MAX_VALUE);
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %,d, \tMax: %,d\n",
Long.TYPE, Long.BYTES * 8, Long.MIN_VALUE, Long.MAX_VALUE); // %s placeholder για κείμενο. \t (tab) σε κείμενο
}
}
| MytilinisV/codingfactorytestbed | ch2/IntApp.java | 324 | // %s placeholder για κείμενο. \t (tab) σε κείμενο | line_comment | el | package gr.aueb.cf.ch2;
/**
* Demonstrates int data types
*/
public class IntApp {
public static void main(String[] args) {
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %,d, \tMax: %,d\n",
Integer.TYPE, Integer.BYTES * 8, Integer.MIN_VALUE, Integer.MAX_VALUE);
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %d, \tMax: %d\n",
Byte.TYPE, Byte.BYTES * 8, Byte.MIN_VALUE, Byte.MAX_VALUE);
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %,d, \tMax: %,d\n",
Short.TYPE, Short.BYTES * 8, Short.MIN_VALUE, Short.MAX_VALUE);
System.out.printf("Type: %s\t, Size: %2d bits\tMin: %,d, \tMax: %,d\n",
Long.TYPE, Long.BYTES * 8, Long.MIN_VALUE, Long.MAX_VALUE); // %s<SUF>
}
}
|
1075_34 | public class SinglyLinkedList <E> { // E = element
protected static class Node <E> {
protected E element; // Αναφορά στο στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος
protected Node <E> next; // Αναφορά στον αμέσως επόμενο κόμβο της λίστας
public Node (E e, Node<E> n) { // constructor
element = e; // Το στοιχείο της λίστας στον συγκεκριμένο κόμβο (ή θέση)
next = n; // Η σύνδεση μεταξύ των κόμβων της λίστας, δηλαδή η αναφορά σε ένα αντικείμενο Node.
} // Συγκεκριμένα στο ακριβώς επόμενο από το συγκεκριμένο
public E getElement() {return element;} // Επιστρέφει το στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος
public Node <E> getNext() {return next;} // Επιστρέφει τον επόμενο κόμβο από τον συγκεκριμένο
public void setNext(Node<E> n) {next = n;} // Αλλάζει τον αμέσως επόμενο κόμβο από τον συγκεκριμένο
}
// Μεταβλητές αρχικοποίησης της SinglyLinkedList
protected Node<E> head = null; // Κόμβος head της λίστας (null αν είναι κενή)
protected Node<E> tail = null; // Κόμβος tail της λίστας (null αν είναι κενή)
protected int size = 0; // Πλήθος κόμβων της λίστας, αρχικά 0
public SinglyLinkedList() { // constructor
// Δημιουργεί μία αρχικά κενή λίστα
// με head και tail ίσα με null και size = 0
}
// Μέθοδοι
public int size() {return size;} // Επιστρέφει το μέγεθος της λίστας, δηλαδή το πλήθος των κόμβων της
public boolean isEmpty() {return size == 0;} // Αν η λίστα είναι άδεια, θα έχει και 0 κόμβους. Οπότε θα επιστραφεί true
public E getFirst() { // Επιστρέφει τo πρώτο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν
if (isEmpty()) {return null;}
return head.getElement();
}
public E getLast() { // Επιστρέφει τo τελευταίο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν
if (isEmpty()) {return null;}
return tail.getElement();
}
public void addFirst(E e) { // Προσθέτει το στοιχείο e στην αρχή της λίστας
head = new Node<E>(e, head); // Δημιορυργία νέο κόμβου και σύνδεσή του με την πρώτη θέση (head) της λίστας
if (isEmpty()) {
tail = head;} // Αν η λίστα είναι άδεια ο νέος κόμβος γίνεται και tail
size++; // Αύξηση κατά 1 του πλήθους των κόμβων του πίνακα
}
public void addLast(E e) { // Προσθέτει το στοιχείο e στο τέλος της λίστας
Node<E> newest = new Node<E>(e, null); // Δημιουργία νέο κόμβου με τιμή null διότι θα καταλήξει ως το tail της λίστας
if (isEmpty()) {
head = newest;
}else {tail.setNext(newest);} // Νέος κόμβος μετά το tail
tail = newest; // Ο νέος αυτός κόμβος γίνεται το tail
size++; // Αύξηση κατά 1 του πλήθους των κόμβων του πίνακα
}
public E removeFirst() { // Αφαιρεί από την λίστα το πρώτο στοιχείο και το επιστρέφει
if (isEmpty()) {return null;} // Άδεια λίστα, οπότε δεν έχει να επιστρέψει κάτι
E a = head.getElement();
head = head.getNext(); // Αν η λίστα είχε μόνο 1 κόμβο θα γινόταν null
size--; // Μείωση κατά 1 του πλήθους των κόμβων του πίνακα
if (size == 0) {
tail = null; // Αν άδειασε η λίστα, πρέπει το tail να γίνει null
}
return a; // Επιστροφή του αφαιρούμενου στοιχείου
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" ");
SinglyLinkedList.Node<E> current = head;
while (current != null) {
sb.append(current.element);
sb.append(", ");
current = current.next;
}
sb.append(" ");
return sb.toString();
}
}
| NIKOMAHOS/AUEB_Projects-Exercises | Data Structures with Java/Εργασία 2/src/SinglyLinkedList.java | 1,942 | // Μείωση κατά 1 του πλήθους των κόμβων του πίνακα
| line_comment | el | public class SinglyLinkedList <E> { // E = element
protected static class Node <E> {
protected E element; // Αναφορά στο στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος
protected Node <E> next; // Αναφορά στον αμέσως επόμενο κόμβο της λίστας
public Node (E e, Node<E> n) { // constructor
element = e; // Το στοιχείο της λίστας στον συγκεκριμένο κόμβο (ή θέση)
next = n; // Η σύνδεση μεταξύ των κόμβων της λίστας, δηλαδή η αναφορά σε ένα αντικείμενο Node.
} // Συγκεκριμένα στο ακριβώς επόμενο από το συγκεκριμένο
public E getElement() {return element;} // Επιστρέφει το στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος
public Node <E> getNext() {return next;} // Επιστρέφει τον επόμενο κόμβο από τον συγκεκριμένο
public void setNext(Node<E> n) {next = n;} // Αλλάζει τον αμέσως επόμενο κόμβο από τον συγκεκριμένο
}
// Μεταβλητές αρχικοποίησης της SinglyLinkedList
protected Node<E> head = null; // Κόμβος head της λίστας (null αν είναι κενή)
protected Node<E> tail = null; // Κόμβος tail της λίστας (null αν είναι κενή)
protected int size = 0; // Πλήθος κόμβων της λίστας, αρχικά 0
public SinglyLinkedList() { // constructor
// Δημιουργεί μία αρχικά κενή λίστα
// με head και tail ίσα με null και size = 0
}
// Μέθοδοι
public int size() {return size;} // Επιστρέφει το μέγεθος της λίστας, δηλαδή το πλήθος των κόμβων της
public boolean isEmpty() {return size == 0;} // Αν η λίστα είναι άδεια, θα έχει και 0 κόμβους. Οπότε θα επιστραφεί true
public E getFirst() { // Επιστρέφει τo πρώτο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν
if (isEmpty()) {return null;}
return head.getElement();
}
public E getLast() { // Επιστρέφει τo τελευταίο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν
if (isEmpty()) {return null;}
return tail.getElement();
}
public void addFirst(E e) { // Προσθέτει το στοιχείο e στην αρχή της λίστας
head = new Node<E>(e, head); // Δημιορυργία νέο κόμβου και σύνδεσή του με την πρώτη θέση (head) της λίστας
if (isEmpty()) {
tail = head;} // Αν η λίστα είναι άδεια ο νέος κόμβος γίνεται και tail
size++; // Αύξηση κατά 1 του πλήθους των κόμβων του πίνακα
}
public void addLast(E e) { // Προσθέτει το στοιχείο e στο τέλος της λίστας
Node<E> newest = new Node<E>(e, null); // Δημιουργία νέο κόμβου με τιμή null διότι θα καταλήξει ως το tail της λίστας
if (isEmpty()) {
head = newest;
}else {tail.setNext(newest);} // Νέος κόμβος μετά το tail
tail = newest; // Ο νέος αυτός κόμβος γίνεται το tail
size++; // Αύξηση κατά 1 του πλήθους των κόμβων του πίνακα
}
public E removeFirst() { // Αφαιρεί από την λίστα το πρώτο στοιχείο και το επιστρέφει
if (isEmpty()) {return null;} // Άδεια λίστα, οπότε δεν έχει να επιστρέψει κάτι
E a = head.getElement();
head = head.getNext(); // Αν η λίστα είχε μόνο 1 κόμβο θα γινόταν null
size--; // Με<SUF>
if (size == 0) {
tail = null; // Αν άδειασε η λίστα, πρέπει το tail να γίνει null
}
return a; // Επιστροφή του αφαιρούμενου στοιχείου
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" ");
SinglyLinkedList.Node<E> current = head;
while (current != null) {
sb.append(current.element);
sb.append(", ");
current = current.next;
}
sb.append(" ");
return sb.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.