diff --git a/.gitignore b/.gitignore
index 8b13789..6af3edd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
-
+cmpe443
+cmpe487/final-project
diff --git a/README.md b/README.md
index 2a8788a..2584a59 100644
--- a/README.md
+++ b/README.md
@@ -42,17 +42,17 @@ Programming projects that I have written at university
- [Project 1](/cmpe321/project1) `Latex`
- [Project 2](/cmpe321/project2) `Java`
- [Project 3](/cmpe321/project3) `PHP`
--
+
### [CmpE322 - Operating Systems](/cmpe322)
- [Project 1](/cmpe322/project1) `C++`
- [Project 2](/cmpe322/project2) `C++`
- [Project 3](/cmpe322/project3) `C++`
--
+
### [CmpE362 - Intro to Signal Processing](/cmpe362)
- [Project 1](/cmpe362/project1) `Matlab`
- [Project 2](/cmpe362/project2) `Matlab`
- [Project 3](/cmpe362/project3) `Matlab`
--
+
### [CmpE493 - Introduction to Information Retrieval](/cmpe493)
- [Project 1](/cmpe493/project1) `Python`
- [Project 2](/cmpe493/project2) `Python`
diff --git a/cmpe230/project1/test.stm b/cmpe230/project1/test.stm
new file mode 100644
index 0000000..e69de29
diff --git a/cmpe436/final-project/Auctioner/.gitignore b/cmpe436/final-project/Auctioner/.gitignore
new file mode 100644
index 0000000..fd45b12
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/.gitignore
@@ -0,0 +1,11 @@
+*.iml
+.gradle
+/local.properties
+/.idea/caches/build_file_checksums.ser
+/.idea/libraries
+/.idea/modules.xml
+/.idea/workspace.xml
+.DS_Store
+/build
+/captures
+.externalNativeBuild
diff --git a/cmpe436/final-project/Auctioner/README.md b/cmpe436/final-project/Auctioner/README.md
new file mode 100644
index 0000000..34bae4a
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/README.md
@@ -0,0 +1,4 @@
+## Real-time Auction Android App
+It has 2 different activities.
+
+`MainActivity` is using for auction listing and `DetailActivity` is using for auction bidding page.
diff --git a/cmpe436/final-project/Auctioner/app/.gitignore b/cmpe436/final-project/Auctioner/app/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/cmpe436/final-project/Auctioner/app/build.gradle b/cmpe436/final-project/Auctioner/app/build.gradle
new file mode 100644
index 0000000..824fd83
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/build.gradle
@@ -0,0 +1,32 @@
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 28
+ defaultConfig {
+ applicationId "com.enescakir.auctioner"
+ minSdkVersion 15
+ targetSdkVersion 28
+ versionCode 1
+ versionName "1.0"
+ testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+}
+
+dependencies {
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
+ implementation 'com.android.support:appcompat-v7:28.0.0'
+ implementation 'com.android.support.constraint:constraint-layout:1.1.3'
+ testImplementation 'junit:junit:4.12'
+ androidTestImplementation 'com.android.support.test:runner:1.0.2'
+ androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
+ implementation 'com.android.support:recyclerview-v7:28.0.0'
+ implementation 'com.android.support:cardview-v7:28.0.0'
+ implementation 'com.google.code.gson:gson:2.8.5'
+ implementation 'com.android.support:design:28.0.0'
+}
diff --git a/cmpe436/final-project/Auctioner/app/proguard-rules.pro b/cmpe436/final-project/Auctioner/app/proguard-rules.pro
new file mode 100644
index 0000000..f1b4245
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
diff --git a/cmpe436/final-project/Auctioner/app/src/androidTest/java/com/enescakir/auctioner/ExampleInstrumentedTest.java b/cmpe436/final-project/Auctioner/app/src/androidTest/java/com/enescakir/auctioner/ExampleInstrumentedTest.java
new file mode 100644
index 0000000..db73b60
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/androidTest/java/com/enescakir/auctioner/ExampleInstrumentedTest.java
@@ -0,0 +1,26 @@
+package com.enescakir.auctioner;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * @see Testing documentation
+ */
+@RunWith(AndroidJUnit4.class)
+public class ExampleInstrumentedTest {
+ @Test
+ public void useAppContext() {
+ // Context of the app under test.
+ Context appContext = InstrumentationRegistry.getTargetContext();
+
+ assertEquals("com.enescakir.auctioner", appContext.getPackageName());
+ }
+}
diff --git a/cmpe436/final-project/Auctioner/app/src/main/AndroidManifest.xml b/cmpe436/final-project/Auctioner/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..2793a8c
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/AndroidManifest.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/ic_launcher-web.png b/cmpe436/final-project/Auctioner/app/src/main/ic_launcher-web.png
new file mode 100644
index 0000000..ce8faa8
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/ic_launcher-web.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/AuctionAdapter.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/AuctionAdapter.java
new file mode 100644
index 0000000..ebb6158
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/AuctionAdapter.java
@@ -0,0 +1,79 @@
+package com.enescakir.auctioner;
+
+import android.content.Context;
+import android.content.Intent;
+import android.support.v7.widget.RecyclerView;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import com.enescakir.auctioner.Model.Auction;
+
+import java.util.ArrayList;
+
+public class AuctionAdapter extends RecyclerView.Adapter {
+
+ ArrayList auctions;
+ LayoutInflater inflater;
+
+ public AuctionAdapter(Context context, ArrayList auctions) {
+ inflater = LayoutInflater.from(context);
+ this.auctions = auctions;
+ }
+
+
+ @Override
+ public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+ View view = inflater.inflate(R.layout.row_auction, parent, false);
+ return new MyViewHolder(view);
+ }
+
+ @Override
+ public void onBindViewHolder(MyViewHolder holder, int position) {
+ holder.setData(auctions.get(position), position);
+ }
+
+ @Override
+ public int getItemCount() {
+ return auctions.size();
+ }
+
+
+ class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
+ TextView nameView, dateView;
+ ImageView imageView;
+ Auction auction;
+ int position;
+
+ public MyViewHolder(View view) {
+ super(view);
+ nameView = (TextView) view.findViewById(R.id.nameView);
+ dateView = (TextView) view.findViewById(R.id.dateView);
+ imageView = (ImageView) view.findViewById(R.id.imageView);
+ view.setOnClickListener(this);
+ }
+
+ public void setData(Auction auction, int position) {
+ this.auction = auction;
+ this.position = position;
+ this.nameView.setText(auction.getName());
+ this.dateView.setText(String.format("Until: %s", auction.getHumanDate()));
+ Context context = imageView.getContext();
+ int image = context.getResources().getIdentifier(auction.getImageName(), "drawable", context.getPackageName());
+ this.imageView.setImageResource(image);
+ }
+
+ @Override
+ public void onClick(View view) {
+ Context context = view.getContext();
+ Intent intent = new Intent(view.getContext(), DetailActivity.class);
+ intent.putExtra("auctionId", auction.getId());
+ intent.putExtra("auctionName", auction.getName());
+ intent.putExtra("auctionDescription", auction.getDescription());
+ intent.putExtra("auctionDate", auction.getDate());
+ context.startActivity(intent);
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/BaseActivity.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/BaseActivity.java
new file mode 100644
index 0000000..e72983b
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/BaseActivity.java
@@ -0,0 +1,34 @@
+package com.enescakir.auctioner;
+
+import android.app.ProgressDialog;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.support.v7.app.AppCompatActivity;
+import android.widget.Toast;
+
+import com.enescakir.auctioner.Model.User;
+
+public class BaseActivity extends AppCompatActivity {
+ public static String username;
+ public static int points;
+ public SharedPreferences preferences;
+ ProgressDialog progressDialog;
+
+ public void showToast(Context context, String message) {
+ Toast.makeText(context, message, Toast.LENGTH_LONG).show();
+ }
+
+ public void showProgress(Context context) {
+ progressDialog = ProgressDialog.show(context, "", "Loading. Please wait...", true);
+ }
+
+ public void dismissProgress() {
+ if (progressDialog != null) {
+ progressDialog.dismiss();
+ }
+ }
+
+ public final void runOnThread(Thread action) {
+ action.start();
+ }
+}
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/BidAdapter.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/BidAdapter.java
new file mode 100644
index 0000000..8fc0e9c
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/BidAdapter.java
@@ -0,0 +1,68 @@
+package com.enescakir.auctioner;
+
+import android.content.Context;
+import android.support.v7.widget.RecyclerView;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import com.enescakir.auctioner.Model.Bid;
+
+import java.util.ArrayList;
+
+public class BidAdapter extends RecyclerView.Adapter {
+
+ ArrayList bids;
+ LayoutInflater inflater;
+
+ public BidAdapter(Context context, ArrayList bids) {
+ inflater = LayoutInflater.from(context);
+ this.bids = bids;
+ }
+
+
+ @Override
+ public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+ View view = inflater.inflate(R.layout.row_bid, parent, false);
+ return new MyViewHolder(view);
+ }
+
+ @Override
+ public void onBindViewHolder(MyViewHolder holder, int position) {
+ holder.setData(bids.get(position), position);
+
+ }
+
+ @Override
+ public int getItemCount() {
+ return bids.size();
+ }
+
+ public void addBid(Bid bid) {
+ bids.add(0, bid);
+ notifyItemInserted(0);
+ }
+
+ class MyViewHolder extends RecyclerView.ViewHolder {
+ TextView usernameView, pointView, dateView;
+ Bid bid;
+ int position;
+
+ public MyViewHolder(View view) {
+ super(view);
+ usernameView = (TextView) view.findViewById(R.id.usernameView);
+ pointView = (TextView) view.findViewById(R.id.pointView);
+ dateView = (TextView) view.findViewById(R.id.dateView);
+ }
+
+ public void setData(Bid bid, int position) {
+ this.bid = bid;
+ this.position = position;
+ this.usernameView.setText(bid.getUsername());
+ this.pointView.setText(String.format("%d points", bid.getPoint()));
+ this.dateView.setText(bid.getHumanDate());
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/DetailActivity.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/DetailActivity.java
new file mode 100644
index 0000000..f41ce45
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/DetailActivity.java
@@ -0,0 +1,283 @@
+package com.enescakir.auctioner;
+
+import android.app.Dialog;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.CountDownTimer;
+import android.support.v7.app.ActionBar;
+import android.support.v7.widget.LinearLayoutManager;
+import android.support.v7.widget.RecyclerView;
+import android.support.v7.widget.Toolbar;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import com.enescakir.auctioner.Model.Auction;
+import com.enescakir.auctioner.Model.Packet;
+import com.enescakir.auctioner.Model.SocketThread;
+import com.enescakir.auctioner.Model.Bid;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+
+import static com.enescakir.auctioner.Model.Packet.Type.*;
+
+public class DetailActivity extends BaseActivity {
+
+ TextView descView;
+ TextView pointView;
+ TextView timeView;
+ ImageView imageView;
+ RecyclerView bidsView;
+ Button bidButton;
+ Auction auction;
+ Dialog bidDialog;
+ BidThread bidThread;
+ BidAdapter bidAdapter;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_detail);
+
+ preferences = getSharedPreferences("user", MODE_PRIVATE);
+
+ getAuctionDetails();
+ setTitle();
+ setAuctionDetails();
+ handleBidClick();
+ setBidDialog();
+
+ bidThread = new BidThread();
+ bidThread.start();
+ }
+
+ private void getAuctionDetails() {
+ Intent intent = getIntent();
+ int id = intent.getIntExtra("auctionId", 0);
+ String name = intent.getStringExtra("auctionName");
+ String description = intent.getStringExtra("auctionDescription");
+ String date = intent.getStringExtra("auctionDate");
+ auction = new Auction(id, name, description, date);
+ }
+
+ private void setTitle() {
+ Toolbar toolbar = findViewById(R.id.toolbar);
+ setSupportActionBar(toolbar);
+
+ ActionBar actionBar = getSupportActionBar();
+ actionBar.setTitle(auction.getName());
+ actionBar.setHomeButtonEnabled(true);
+ actionBar.setDisplayHomeAsUpEnabled(true);
+ }
+
+ private void setAuctionDetails() {
+ bidButton = findViewById(R.id.bidButton);
+ descView = findViewById(R.id.descView);
+ descView.setText(auction.getDescription());
+ pointView = findViewById(R.id.tvPoint);
+ pointView.setText(String.format("Your points: %d", points));
+ imageView = findViewById(R.id.imageView);
+ imageView.setImageResource(getResources().getIdentifier(auction.getImageName(), "drawable", getPackageName()));
+ timeView = findViewById(R.id.timeView);
+ long diff = auction.getDateObject().getTime() - new Date().getTime();
+ CountDown counter = new CountDown(diff, 1000);
+ counter.start();
+ }
+
+ private void setBidDialog() {
+ bidDialog = new Dialog(this);
+ bidDialog.setContentView(R.layout.dialog_bid);
+ bidDialog.setCancelable(true);
+ final TextView nameTextView = bidDialog.findViewById(R.id.tvName);
+ final EditText pointInput = bidDialog.findViewById(R.id.etPoint);
+ final Button cancelButton = bidDialog.findViewById(R.id.bCancel);
+ final Button offerButton = bidDialog.findViewById(R.id.bOffer);
+ nameTextView.setText(String.format("Bid Offer for \"%s\"", auction.getName()));
+
+ cancelButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ bidDialog.dismiss();
+ pointInput.setText("");
+ }
+ });
+ offerButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ bidDialog.dismiss();
+ if (!TextUtils.isEmpty(pointInput.getText())) {
+ int offer = Integer.parseInt(pointInput.getText().toString());
+ pointInput.setText("");
+ final Bid bid = new Bid(username, offer, new Date());
+ runOnThread(new Thread() {
+ @Override
+ public void run() {
+ bidThread.sendMessage(new Packet(BID_STORE, bid).toJson());
+ }
+ });
+ } else {
+ showError("You have to give offer that is greater than zero");
+ }
+ }
+ });
+
+ }
+
+ private void handleBidClick() {
+ bidButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(final View view) {
+ bidDialog.show();
+ }
+ });
+ }
+
+ private void setBidsView(ArrayList bids) {
+ bidsView = findViewById(R.id.bidsView);
+ bidAdapter = new BidAdapter(this, bids);
+ bidsView.setAdapter(bidAdapter);
+ LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
+ linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
+ bidsView.setLayoutManager(linearLayoutManager);
+ }
+
+ @Override
+ public boolean onSupportNavigateUp() {
+ runOnThread(new Thread() {
+ @Override
+ public void run() {
+ bidThread.close();
+ }
+ });
+ finish();
+ return true;
+ }
+
+ public class CountDown extends CountDownTimer {
+ CountDown(long millisInFuture, long countDownInterval) {
+ super(millisInFuture, countDownInterval);
+ }
+
+ @Override
+ public void onFinish() {
+ timeView.setText("Finished!");
+ }
+
+ @Override
+ public void onTick(long millisUntilFinished) {
+ long millis = millisUntilFinished;
+ String hms = String.format("%d days %02d:%02d:%02d",
+ TimeUnit.MILLISECONDS.toDays(millis),
+ (TimeUnit.MILLISECONDS.toHours(millis) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millis))),
+ (TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))),
+ (TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)))
+ );
+ timeView.setText(hms);
+ }
+ }
+
+ class BidThread extends SocketThread {
+ @Override
+ public void run() {
+ super.run();
+ try {
+ sendMessage(new Packet(BID_LISTEN, Integer.toString(auction.getId())).toJson());
+
+ final Packet response = Packet.fromJson(in.readLine());
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ setBidsView(response.toArrayList(Bid.class));
+ }
+ });
+ this.listen();
+
+ } catch (Exception e1) {
+ Log.e("LOOP", "First loop error");
+ try {
+ this.listen();
+ } catch (Exception e2) {
+ Log.e("LOOP", "Second loop error");
+ }
+ }
+ }
+
+ public void listen() throws IOException {
+ String message;
+ while ((message = in.readLine()) != null) {
+ Packet packet;
+ try {
+ packet = Packet.fromJson(message);
+ } catch (Exception e) {
+ packet = new Packet(UNKNOWN, "");
+ Log.e("PACKET", "Parse error");
+ }
+ switch (packet.getType()) {
+ case BID_STORE:
+ final int result = packet.toObject(Integer.class);
+ if (result == -2) {
+ showError(String.format("You had to bid more than last bid that is %d points", bidAdapter.bids.get(0).getPoint()));
+ } else if (result == -1) {
+ showError(String.format("You have %d points, so it's not enough", points));
+ } else {
+ runOnThread(new Thread() {
+ @Override
+ public void run() {
+ points = result;
+ preferences.edit().putInt("points", result).apply();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ pointView.setText(String.format("Your points: %d", points));
+ }
+ });
+ }
+ });
+ }
+ break;
+ case BID_NEW:
+ final Bid bid = packet.toObject(Bid.class);
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ bidAdapter.addBid(bid);
+ bidsView.scrollToPosition(0);
+ }
+ });
+ break;
+ default:
+ Log.e("UNKNOWN_PACKET", "Unknown packet from :" + message);
+ }
+ }
+ }
+ }
+
+ public void showError(String message) {
+ final String m = message;
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ final Dialog alert = new Dialog(DetailActivity.this);
+ alert.setContentView(R.layout.dialog_alert);
+ alert.setCancelable(true);
+ final TextView nameTextView = alert.findViewById(R.id.tvMessage);
+ final Button closeButton = alert.findViewById(R.id.bClose);
+ nameTextView.setText(m);
+ closeButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ alert.dismiss();
+ }
+ });
+ alert.show();
+ }
+ });
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/MainActivity.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/MainActivity.java
new file mode 100644
index 0000000..a42f9d3
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/MainActivity.java
@@ -0,0 +1,177 @@
+package com.enescakir.auctioner;
+
+import android.app.Dialog;
+import android.os.Bundle;
+import android.support.v7.widget.LinearLayoutManager;
+import android.support.v7.widget.RecyclerView;
+import android.support.v7.widget.Toolbar;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.Button;
+import android.widget.EditText;
+
+import com.enescakir.auctioner.Model.Auction;
+import com.enescakir.auctioner.Model.Packet;
+import com.enescakir.auctioner.Model.SocketThread;
+import com.enescakir.auctioner.Model.User;
+
+import java.util.ArrayList;
+
+import static com.enescakir.auctioner.Model.Packet.Type.AUCTIONS;
+import static com.enescakir.auctioner.Model.Packet.Type.USER;
+
+
+public class MainActivity extends BaseActivity {
+ RecyclerView auctionsView;
+ Dialog loginDialog;
+ private Toolbar toolbar;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ toolbar = findViewById(R.id.toolbar);
+ setSupportActionBar(toolbar);
+
+ final AuctionThread thread = new AuctionThread();
+ thread.start();
+
+ preferences = getSharedPreferences("user", MODE_PRIVATE);
+
+ if (preferences.getString("username", null) == null) {
+ authUser();
+ } else {
+ username = preferences.getString("username", null);
+ points = preferences.getInt("points", 1000);
+ showToast(MainActivity.this, "Welcome " + username);
+ }
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.menu_main, menu);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ int id = item.getItemId();
+
+ if (id == R.id.action_logout) {
+ username = null;
+ points = 0;
+ preferences.edit().remove("username").apply();
+ preferences.edit().remove("points").apply();
+ authUser();
+ return true;
+ }
+
+ return super.onOptionsItemSelected(item);
+ }
+
+ private void authUser() {
+ loginDialog = new Dialog(this);
+ loginDialog.setContentView(R.layout.dialog_login);
+ loginDialog.setCancelable(false);
+ loginDialog.show();
+ final EditText nameInput = loginDialog.findViewById(R.id.etUsername);
+ final EditText passwordInput = loginDialog.findViewById(R.id.etPassword);
+ final Button button = loginDialog.findViewById(R.id.button);
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ String username = nameInput.getText().toString();
+ String password = passwordInput.getText().toString();
+
+ if (TextUtils.isEmpty(username)) {
+ nameInput.setError("Username is required!");
+ showToast(MainActivity.this, "Username is required!");
+ } else if (TextUtils.isEmpty(password)) {
+ passwordInput.setError("Password is required!");
+ showToast(MainActivity.this, "Password is required!");
+ } else {
+ loginDialog.dismiss();
+ showProgress(MainActivity.this);
+ passwordInput.setText("");
+ final AuthThread thread = new AuthThread(username, password);
+ thread.start();
+ }
+ }
+ });
+ }
+
+ private void setAuctionsView(ArrayList auctions) {
+ auctionsView = findViewById(R.id.auctionsView);
+ auctionsView.setAdapter(new AuctionAdapter(this, auctions));
+ LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
+ linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
+ auctionsView.setLayoutManager(linearLayoutManager);
+ }
+
+ class AuctionThread extends SocketThread {
+ @Override
+ public void run() {
+ super.run();
+ try {
+ sendMessage(new Packet(AUCTIONS, "").toJson());
+ final Packet response = Packet.fromJson(in.readLine());
+ close();
+ Log.e("AUCTIONS", response.getData());
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ setAuctionsView(response.toArrayList(Auction.class));
+ }
+ });
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ class AuthThread extends SocketThread {
+ String username;
+ String password;
+
+ AuthThread(String username, String password) {
+ super();
+ this.username = username;
+ this.password = password;
+ }
+
+ @Override
+ public void run() {
+ super.run();
+ try {
+ sendMessage(new Packet(USER, new User(username, password)).toJson());
+
+ final Packet packet = Packet.fromJson(in.readLine());
+ Log.e("USER", packet.getData());
+ int response = packet.toObject(Integer.class);
+ close();
+ progressDialog.dismiss();
+ if (response == -1) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ showToast(MainActivity.this, "Wrong password");
+ loginDialog.show();
+ }
+ });
+ } else {
+ preferences.edit().putString("username", username).apply();
+ preferences.edit().putInt("points", response).apply();
+ BaseActivity.username = username;
+ BaseActivity.points = response;
+ showToast(MainActivity.this, "Welcome " + username);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Auction.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Auction.java
new file mode 100644
index 0000000..35107d6
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Auction.java
@@ -0,0 +1,82 @@
+package com.enescakir.auctioner.Model;
+
+import android.util.Log;
+
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+public class Auction {
+ private int id;
+ private String name;
+ private String description;
+ private int startPoint;
+ private String date;
+
+ public Auction() {
+ }
+
+ public Auction(int id, String name, String description, int startPoint, String date) {
+ this.id = id;
+ this.name = name;
+ this.description = description;
+ this.startPoint = startPoint;
+ this.date = date;
+ }
+
+ public Auction(int id, String name, String description, String date) {
+ this.id = id;
+ this.name = name;
+ this.description = description;
+ this.date = date;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public int getStartPoint() {
+ return startPoint;
+ }
+
+ public String getDate() {
+ return this.date;
+ }
+
+ public Date getDateObject() {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ try {
+ return sdf.parse(this.getDate());
+ } catch (Exception e) {
+ Log.e("Date Parsing", e.getMessage());
+ }
+ return null;
+ }
+
+ public String getHumanDate() {
+ SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy HH:mm");
+ try {
+ return sdf.format(this.getDateObject());
+ } catch (Exception e) {
+ Log.e("Date Parsing", e.getMessage());
+ }
+ return null;
+ }
+
+ public String getImageName() {
+ String filename = "auction[ID]";
+ return filename.replace("[ID]", Integer.toString(this.id));
+ }
+
+ @Override
+ public String toString() {
+ return "Auction #" + Integer.toString(id) + ": " + name;
+ }
+}
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Bid.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Bid.java
new file mode 100644
index 0000000..0bce14d
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Bid.java
@@ -0,0 +1,70 @@
+package com.enescakir.auctioner.Model;
+
+import android.util.Log;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+
+public class Bid {
+ private int point;
+ private String date;
+ private String username;
+
+ public Bid(String username, int point, String date) {
+ this.point = point;
+ this.date = date;
+ this.username = username;
+ }
+
+ public Bid(String username, int point, Date date) {
+ this.point = point;
+ this.username = username;
+
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ try {
+ this.date = sdf.format(date);
+ } catch (Exception e) {
+ this.date = "2018-12-11 11:11:11";
+ Log.e("Date Parsing", e.getMessage());
+ }
+
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public int getPoint() {
+ return point;
+ }
+
+ public String getDate() {
+ return this.date;
+ }
+
+ public Date getDateObject() {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ try {
+ return sdf.parse(this.getDate());
+ } catch (Exception e) {
+ Log.e("Date Parsing", e.getMessage());
+ }
+ return null;
+ }
+
+ public String getHumanDate() {
+ SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy HH:mm:ss");
+ try {
+ return sdf.format(this.getDateObject());
+ } catch (Exception e) {
+ Log.e("Date Parsing", e.getMessage());
+ }
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return Integer.toString(point) + " bid on by " + username;
+ }
+}
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Packet.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Packet.java
new file mode 100644
index 0000000..e30a079
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/Packet.java
@@ -0,0 +1,77 @@
+package com.enescakir.auctioner.Model;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Packet {
+ private Type type;
+ private String data;
+
+ public enum Type {
+ UNKNOWN(0), // Unknown package
+ AUCTIONS(1), // Get auctions request, and return it
+ BID_LISTEN(2), // Subscribe client to auction bid channel
+ BID_NEW(3), // Broadcast new bid to clients
+ BID_STORE(4), // Store bid and return result
+ USER(5); // Store user and return save user result
+
+ final int data;
+
+ Type(int data) {
+ this.data = data;
+ }
+ }
+
+ Packet(Type type, String data) {
+ this.type = type;
+ this.data = data;
+ }
+
+ public Packet(Type type, Object data) {
+ this.type = type;
+ this.data = this.getJsonBuilder().toJson(data);
+ }
+
+ public static Packet fromJson(String json) {
+ return getJsonBuilder().fromJson(json, Packet.class);
+ }
+
+ public ArrayList toArrayList(Class clazz) {
+ return getArrayList(this.data, clazz);
+ }
+
+ public T toObject(Class clazz) {
+ return getJsonBuilder().fromJson(this.data, clazz);
+ }
+
+ public String toJson() {
+ return getJsonBuilder().toJson(this);
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ public Type getType() {
+ return type;
+ }
+
+ public static Gson getJsonBuilder() {
+ return new GsonBuilder().create();
+ }
+
+ public static ArrayList getArrayList(String rawJson, Class clazz) {
+ java.lang.reflect.Type type = TypeToken.getParameterized(List.class, clazz).getType();
+ ArrayList data = getJsonBuilder().fromJson(rawJson, type);
+
+ if (data != null)
+ return data;
+
+ return new ArrayList<>();
+ }
+
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/SocketThread.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/SocketThread.java
new file mode 100644
index 0000000..07ec598
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/SocketThread.java
@@ -0,0 +1,51 @@
+package com.enescakir.auctioner.Model;
+
+import android.util.Log;
+
+import java.io.*;
+import java.net.*;
+
+public class SocketThread extends Thread {
+ public Socket socket;
+ public BufferedReader in;
+ public BufferedWriter out;
+
+ @Override
+ public void run() {
+ super.run();
+ try {
+// socket = new Socket("10.0.2.2", 5001);
+ socket = new Socket("18.224.60.222", 5001);
+ in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
+ } catch (Exception e) {
+ Log.e("SOCKET_THREAD", "Error");
+ e.printStackTrace();
+ }
+ }
+
+ public void sendMessage(String message) {
+ Log.e("SEND_MESSAGE", message);
+
+ try {
+ out.write(message);
+ out.newLine();
+ out.flush();
+ } catch (Exception e) {
+ Log.e("SEND_MESSAGE", "Error");
+ e.printStackTrace();
+ }
+ }
+
+ public void close() {
+ try {
+ in.close();
+ out.close();
+ socket.close();
+ this.interrupt();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/User.java b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/User.java
new file mode 100644
index 0000000..0974846
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/java/com/enescakir/auctioner/Model/User.java
@@ -0,0 +1,39 @@
+package com.enescakir.auctioner.Model;
+
+public class User {
+ private String name;
+ private String password;
+ private int point;
+
+ public User(String name, String password) {
+ this.name = name;
+ this.password = password;
+ }
+
+ public User(String name, String password, int point) {
+ this.name = name;
+ this.password = password;
+ this.point = point;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public int getPoint() {
+ return point;
+ }
+
+ public void setPoint(int point) {
+ this.point = point;
+ }
+
+ @Override
+ public String toString() {
+ return this.name + ":" + Integer.toString(this.point);
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/cmpe436/final-project/Auctioner/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
new file mode 100644
index 0000000..1f6bb29
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction1.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction1.png
new file mode 100644
index 0000000..029c87b
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction1.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction10.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction10.png
new file mode 100644
index 0000000..8c6797f
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction10.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction2.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction2.png
new file mode 100644
index 0000000..bc7858e
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction2.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction3.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction3.png
new file mode 100644
index 0000000..979e6f1
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction3.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction4.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction4.png
new file mode 100644
index 0000000..8531c49
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction4.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction5.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction5.png
new file mode 100644
index 0000000..15c84c9
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction5.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction6.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction6.png
new file mode 100644
index 0000000..d863e41
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction6.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction7.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction7.png
new file mode 100644
index 0000000..4e56de4
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction7.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction8.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction8.png
new file mode 100644
index 0000000..7f120e3
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/auction8.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/ic_launcher_background.xml b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..0d025f9
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,170 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/drawable/ic_logout.png b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/ic_logout.png
new file mode 100644
index 0000000..1ced963
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/drawable/ic_logout.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/layout/activity_detail.xml b/cmpe436/final-project/Auctioner/app/src/main/res/layout/activity_detail.xml
new file mode 100644
index 0000000..40285be
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/layout/activity_detail.xml
@@ -0,0 +1,109 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/layout/activity_main.xml b/cmpe436/final-project/Auctioner/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..eb700ca
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_alert.xml b/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_alert.xml
new file mode 100644
index 0000000..d912741
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_alert.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_bid.xml b/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_bid.xml
new file mode 100644
index 0000000..eceed46
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_bid.xml
@@ -0,0 +1,52 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_login.xml b/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_login.xml
new file mode 100644
index 0000000..b7518d6
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/layout/dialog_login.xml
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/layout/row_auction.xml b/cmpe436/final-project/Auctioner/app/src/main/res/layout/row_auction.xml
new file mode 100644
index 0000000..bde7cfb
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/layout/row_auction.xml
@@ -0,0 +1,56 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/layout/row_bid.xml b/cmpe436/final-project/Auctioner/app/src/main/res/layout/row_bid.xml
new file mode 100644
index 0000000..476992d
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/layout/row_bid.xml
@@ -0,0 +1,51 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/menu/menu_main.xml b/cmpe436/final-project/Auctioner/app/src/main/res/menu/menu_main.xml
new file mode 100644
index 0000000..2872f89
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/menu/menu_main.xml
@@ -0,0 +1,16 @@
+
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..036d09b
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..036d09b
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..08bb914
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..caa172e
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
new file mode 100644
index 0000000..31c413f
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..3691dd0
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..02b7be9
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
new file mode 100644
index 0000000..3da5d4c
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..6b0dd95
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..ff0e9db
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..b8c5cc7
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..7d1414d
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..19e0f04
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..9dd3654
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..64b4ff1
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..6f41bb5
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..bb423c9
Binary files /dev/null and b/cmpe436/final-project/Auctioner/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/values/colors.xml b/cmpe436/final-project/Auctioner/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..69b2233
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+
+
+ #008577
+ #00574B
+ #D81B60
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/values/ic_launcher_background.xml b/cmpe436/final-project/Auctioner/app/src/main/res/values/ic_launcher_background.xml
new file mode 100644
index 0000000..4e73a35
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/values/ic_launcher_background.xml
@@ -0,0 +1,4 @@
+
+
+ #4492FF
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/values/strings.xml b/cmpe436/final-project/Auctioner/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..ca5280c
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+
+ Auctioner
+ yyyy-MM-dd HH:mm:ss
+
diff --git a/cmpe436/final-project/Auctioner/app/src/main/res/values/styles.xml b/cmpe436/final-project/Auctioner/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..0eb88fe
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/main/res/values/styles.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
diff --git a/cmpe436/final-project/Auctioner/app/src/test/java/com/enescakir/auctioner/ExampleUnitTest.java b/cmpe436/final-project/Auctioner/app/src/test/java/com/enescakir/auctioner/ExampleUnitTest.java
new file mode 100644
index 0000000..4e15155
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/app/src/test/java/com/enescakir/auctioner/ExampleUnitTest.java
@@ -0,0 +1,17 @@
+package com.enescakir.auctioner;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * @see Testing documentation
+ */
+public class ExampleUnitTest {
+ @Test
+ public void addition_isCorrect() {
+ assertEquals(4, 2 + 2);
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Auctioner/build.gradle b/cmpe436/final-project/Auctioner/build.gradle
new file mode 100644
index 0000000..8d3ef8e
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/build.gradle
@@ -0,0 +1,27 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+
+ repositories {
+ google()
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:3.2.1'
+
+
+ // NOTE: Do not place your application dependencies here; they belong
+ // in the individual module build.gradle files
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ jcenter()
+ }
+}
+
+task clean(type: Delete) {
+ delete rootProject.buildDir
+}
diff --git a/cmpe436/final-project/Auctioner/gradle.properties b/cmpe436/final-project/Auctioner/gradle.properties
new file mode 100644
index 0000000..82618ce
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/gradle.properties
@@ -0,0 +1,15 @@
+# Project-wide Gradle settings.
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx1536m
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+
+
diff --git a/cmpe436/final-project/Auctioner/gradle/wrapper/gradle-wrapper.jar b/cmpe436/final-project/Auctioner/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..f6b961f
Binary files /dev/null and b/cmpe436/final-project/Auctioner/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/cmpe436/final-project/Auctioner/gradle/wrapper/gradle-wrapper.properties b/cmpe436/final-project/Auctioner/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..9a4163a
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/cmpe436/final-project/Auctioner/gradlew b/cmpe436/final-project/Auctioner/gradlew
new file mode 100755
index 0000000..cccdd3d
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/gradlew
@@ -0,0 +1,172 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=$(save "$@")
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+ cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/cmpe436/final-project/Auctioner/gradlew.bat b/cmpe436/final-project/Auctioner/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/cmpe436/final-project/Auctioner/settings.gradle b/cmpe436/final-project/Auctioner/settings.gradle
new file mode 100644
index 0000000..e7b4def
--- /dev/null
+++ b/cmpe436/final-project/Auctioner/settings.gradle
@@ -0,0 +1 @@
+include ':app'
diff --git a/cmpe436/final-project/Server/README.md b/cmpe436/final-project/Server/README.md
new file mode 100644
index 0000000..054b4cc
--- /dev/null
+++ b/cmpe436/final-project/Server/README.md
@@ -0,0 +1,18 @@
+## Real-time Auction App
+`server.AuctionServer` class is responsible for backend.
+It listens coming packets and handle connections.
+It's based on TCP sockets and use 5001 port.
+
+You can start server with:
+`$ java -cp gson.jar:./bin server.AuctionServer`
+
+You can simulate a client with `server.Client` class.
+`$ java -cp gson.jar:./bin server.Client`
+
+It has following methods;
+* `auctions`
+* `bid_listen [BID_ID]`
+* `bid_store [USERNAME] [POINTS]`
+* `auth [USERNAME] [PASSWORD]`
+
+Server and clients use `server.Packet` class for communication protocol.
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/Server.iml b/cmpe436/final-project/Server/Server.iml
new file mode 100644
index 0000000..d967e94
--- /dev/null
+++ b/cmpe436/final-project/Server/Server.iml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/bin/model/Auction.class b/cmpe436/final-project/Server/bin/model/Auction.class
new file mode 100644
index 0000000..808d842
Binary files /dev/null and b/cmpe436/final-project/Server/bin/model/Auction.class differ
diff --git a/cmpe436/final-project/Server/bin/model/Bid.class b/cmpe436/final-project/Server/bin/model/Bid.class
new file mode 100644
index 0000000..446a6b7
Binary files /dev/null and b/cmpe436/final-project/Server/bin/model/Bid.class differ
diff --git a/cmpe436/final-project/Server/bin/model/User.class b/cmpe436/final-project/Server/bin/model/User.class
new file mode 100644
index 0000000..2f484c1
Binary files /dev/null and b/cmpe436/final-project/Server/bin/model/User.class differ
diff --git a/cmpe436/final-project/Server/bin/persistence/Database.class b/cmpe436/final-project/Server/bin/persistence/Database.class
new file mode 100644
index 0000000..0ec9d9f
Binary files /dev/null and b/cmpe436/final-project/Server/bin/persistence/Database.class differ
diff --git a/cmpe436/final-project/Server/bin/persistence/Seeder.class b/cmpe436/final-project/Server/bin/persistence/Seeder.class
new file mode 100644
index 0000000..c34bd06
Binary files /dev/null and b/cmpe436/final-project/Server/bin/persistence/Seeder.class differ
diff --git a/cmpe436/final-project/Server/bin/persistence/data/auctions.json b/cmpe436/final-project/Server/bin/persistence/data/auctions.json
new file mode 100644
index 0000000..c57d811
--- /dev/null
+++ b/cmpe436/final-project/Server/bin/persistence/data/auctions.json
@@ -0,0 +1,58 @@
+[
+ {
+ "id": 1,
+ "name": "Mona Lisa Auction",
+ "description": "The Mona Lisa is a half-length portrait painting by the Italian Renaissance artist Leonardo da Vinci.",
+ "startPoint": 100,
+ "date": "2018-12-17 09:39:45"
+ },
+ {
+ "id": 2,
+ "name": "The Scream Auction",
+ "description": "The works show a figure with an agonized expression against a landscape with a tumultuous orange sky.",
+ "startPoint": 20,
+ "date": "2018-12-08 16:53:01"
+ },
+ {
+ "id": 3,
+ "name": "Wheat Field with Cypresses",
+ "description": "Very The works were inspired by the view from the window at the asylum towards the Alpilles mountains.",
+ "startPoint": 30,
+ "date": "2018-12-11 06:58:35"
+ },
+ {
+ "id": 4,
+ "name": "Byzantine Coin Auction",
+ "description": "A very popular denarius featuring the tools of minting coins.",
+ "startPoint": 400,
+ "date": "2018-12-22 04:57:50"
+ },
+ {
+ "id": 5,
+ "name": "Very Old Stamp Auction",
+ "description": "19th Century classics",
+ "startPoint": 400,
+ "date": "2019-01-01 05:07:32"
+ },
+ {
+ "id": 6,
+ "name": "Macintosh Auction",
+ "description": "The Macintosh is a family of personal computers designed, manufactured, and sold by Apple Inc. since January 1984",
+ "startPoint": 400,
+ "date": "2019-01-04 08:07:17"
+ },
+ {
+ "id": 7,
+ "name": "iPhone (1st generation)",
+ "description": "The iPhone is the first smartphone model designed and marketed by Apple Inc.",
+ "startPoint": 400,
+ "date": "2018-12-20 07:42:14"
+ },
+ {
+ "id": 8,
+ "name": "Apple Newton Auction",
+ "description": "The Newton is a series of personal digital assistants (PDA) developed and marketed by Apple Computer, Inc.",
+ "startPoint": 400,
+ "date": "2018-12-23 08:01:21"
+ }
+]
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/bin/server/AuctionServer.class b/cmpe436/final-project/Server/bin/server/AuctionServer.class
new file mode 100644
index 0000000..edefdc5
Binary files /dev/null and b/cmpe436/final-project/Server/bin/server/AuctionServer.class differ
diff --git a/cmpe436/final-project/Server/bin/server/Client.class b/cmpe436/final-project/Server/bin/server/Client.class
new file mode 100644
index 0000000..edb56c1
Binary files /dev/null and b/cmpe436/final-project/Server/bin/server/Client.class differ
diff --git a/cmpe436/final-project/Server/bin/server/Packet$Type.class b/cmpe436/final-project/Server/bin/server/Packet$Type.class
new file mode 100644
index 0000000..86a63bb
Binary files /dev/null and b/cmpe436/final-project/Server/bin/server/Packet$Type.class differ
diff --git a/cmpe436/final-project/Server/bin/server/Packet.class b/cmpe436/final-project/Server/bin/server/Packet.class
new file mode 100644
index 0000000..446e8ca
Binary files /dev/null and b/cmpe436/final-project/Server/bin/server/Packet.class differ
diff --git a/cmpe436/final-project/Server/bin/server/ServerThread$1.class b/cmpe436/final-project/Server/bin/server/ServerThread$1.class
new file mode 100644
index 0000000..b48524b
Binary files /dev/null and b/cmpe436/final-project/Server/bin/server/ServerThread$1.class differ
diff --git a/cmpe436/final-project/Server/bin/server/ServerThread.class b/cmpe436/final-project/Server/bin/server/ServerThread.class
new file mode 100644
index 0000000..0383d2c
Binary files /dev/null and b/cmpe436/final-project/Server/bin/server/ServerThread.class differ
diff --git a/cmpe436/final-project/Server/bin/util/BinarySemaphore.class b/cmpe436/final-project/Server/bin/util/BinarySemaphore.class
new file mode 100644
index 0000000..5646477
Binary files /dev/null and b/cmpe436/final-project/Server/bin/util/BinarySemaphore.class differ
diff --git a/cmpe436/final-project/Server/bin/util/Logger.class b/cmpe436/final-project/Server/bin/util/Logger.class
new file mode 100644
index 0000000..127e41f
Binary files /dev/null and b/cmpe436/final-project/Server/bin/util/Logger.class differ
diff --git a/cmpe436/final-project/Server/gson.jar b/cmpe436/final-project/Server/gson.jar
new file mode 100644
index 0000000..0d5baf3
Binary files /dev/null and b/cmpe436/final-project/Server/gson.jar differ
diff --git a/cmpe436/final-project/Server/src/model/Auction.java b/cmpe436/final-project/Server/src/model/Auction.java
new file mode 100644
index 0000000..c218b83
--- /dev/null
+++ b/cmpe436/final-project/Server/src/model/Auction.java
@@ -0,0 +1,59 @@
+package model;
+
+import persistence.Database;
+
+import java.util.*;
+
+public class Auction {
+ private int id;
+ private String name;
+ private String description;
+ private int startPoint;
+ private String date;
+
+ public Auction(int id, String name, String description, int startPoint, String date) {
+ this.id = id;
+ this.name = name;
+ this.description = description;
+ this.startPoint = startPoint;
+ this.date = date;
+ }
+
+ public Auction(int id) {
+ this.id = id;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public int getStartPoint() {
+ return startPoint;
+ }
+
+ public String getDate() {
+ return this.date;
+ }
+
+ public Date getDateObject() {
+ return Database.stringToDate(date);
+ }
+
+ public String getFilename() {
+ String filename = Database.BID_DB_SUFFIX;
+ return filename.replace("[ID]", Integer.toString(this.id));
+ }
+
+ @Override
+ public String toString() {
+ return "Auction #" + Integer.toString(id) + ": " + name;
+ }
+}
diff --git a/cmpe436/final-project/Server/src/model/Bid.java b/cmpe436/final-project/Server/src/model/Bid.java
new file mode 100644
index 0000000..dce3b7a
--- /dev/null
+++ b/cmpe436/final-project/Server/src/model/Bid.java
@@ -0,0 +1,45 @@
+package model;
+
+import persistence.Database;
+
+import java.util.*;
+
+public class Bid {
+ private int point;
+ private String date;
+ private String username;
+
+ public Bid(String username, int point, String date) {
+ this.point = point;
+ this.date = date;
+ this.username = username;
+ }
+
+ public Bid(String username, int point, Date date) {
+ this.point = point;
+ this.date = Database.dateToString(date);
+ this.username = username;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public int getPoint() {
+ return point;
+ }
+
+ public String getDate() {
+ return this.date;
+ }
+
+ public Date getDateObject() {
+ return Database.stringToDate(this.date);
+ }
+
+ @Override
+ public String toString() {
+ return Integer.toString(point) + " bid on by " + username;
+ }
+
+}
diff --git a/cmpe436/final-project/Server/src/model/User.java b/cmpe436/final-project/Server/src/model/User.java
new file mode 100644
index 0000000..896f2d3
--- /dev/null
+++ b/cmpe436/final-project/Server/src/model/User.java
@@ -0,0 +1,39 @@
+package model;
+
+public class User {
+ private String name;
+ private String password;
+ private int point;
+
+ public User(String name, String password) {
+ this.name = name;
+ this.password = password;
+ }
+
+ public User(String name, String password, int point) {
+ this.name = name;
+ this.password = password;
+ this.point = point;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public int getPoint() {
+ return point;
+ }
+
+ public void setPoint(int point) {
+ this.point = point;
+ }
+
+ @Override
+ public String toString() {
+ return this.name + ":" + Integer.toString(this.point);
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/persistence/Database.java b/cmpe436/final-project/Server/src/persistence/Database.java
new file mode 100644
index 0000000..ef0efbf
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/Database.java
@@ -0,0 +1,247 @@
+package persistence;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+import model.*;
+import util.*;
+
+import java.io.*;
+import java.util.*;
+import java.lang.reflect.Type;
+import java.text.SimpleDateFormat;
+
+/**
+ * Accesses files, handles data races and persistence
+ */
+public class Database {
+ // CONFIGURATIONS
+ public static final String DATA_PATH = "src/persistence/data";
+ public static final String AUCTION_DB = DATA_PATH + "/auctions.json";
+ public static final String BID_DB_SUFFIX = DATA_PATH + "/[ID]_bids.json";
+ public static final String USER_DB = DATA_PATH + "/users.json";
+ public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
+
+ public static HashMap bidLocks = new HashMap();
+ public static BinarySemaphore auctionLock = new BinarySemaphore();
+ public static BinarySemaphore userLock = new BinarySemaphore();
+
+ // JSON HELPERS
+ public static Gson getJsonBuilder() {
+ return new GsonBuilder().create();
+ }
+
+ public static ArrayList getArrayList(String rawJson, Class clazz) {
+ Type type = TypeToken.getParameterized(List.class, clazz).getType();
+ ArrayList data = getJsonBuilder().fromJson(rawJson, type);
+
+ if (data != null)
+ return data;
+
+ return new ArrayList<>();
+ }
+
+ // USER METHODS
+ public static ArrayList getUsers() {
+ return getArrayList(getContent(USER_DB), User.class);
+ }
+
+ public static User getUserByName(String username) {
+ userLock.P();
+ ArrayList users = getUsers();
+ User foundUser = null;
+ for (User user : users) {
+ if (username.equals(user.getName())) {
+ foundUser = user;
+ break;
+ }
+ }
+ userLock.V();
+ return foundUser;
+ }
+
+ public static int getUserPoint(String username) {
+ userLock.P();
+ ArrayList users = getUsers();
+ int point = -1;
+ for (User user : users) {
+ if (username.equals(user.getName())) {
+ point = user.getPoint();
+ break;
+ }
+ }
+ userLock.V();
+ return point;
+ }
+
+ public static boolean authUser(String username, String password) {
+ User authUser = getUserByName(username);
+
+ if (authUser != null) {
+ return Integer.parseInt(authUser.getPassword()) == password.hashCode();
+ }
+
+ return saveUser(username, password);
+ }
+
+ public static void updateUserPoint(String username, int point) {
+ userLock.P();
+
+ ArrayList users = getUsers();
+ User foundUser = null;
+ for (User user : users) {
+ if (username.equals(user.getName())) {
+ foundUser = user;
+ break;
+ }
+ }
+
+ if (foundUser != null) {
+ foundUser.setPoint(point);
+ }
+ writeContent(USER_DB, getJsonBuilder().toJson(users));
+
+ userLock.V();
+ }
+
+ public static boolean saveUser(String username, String password) {
+ userLock.P();
+ ArrayList users = getUsers();
+ boolean exist = false;
+
+ for (User user : users) {
+ if (username.equals(user.getName())) {
+ exist = true;
+ break;
+ }
+ }
+
+ if (!exist) {
+ User user = new User(username, Integer.toString(password.hashCode()), 2000);
+ users.add(user);
+ writeContent(USER_DB, getJsonBuilder().toJson(users));
+ }
+ userLock.V();
+
+ return !exist;
+ }
+
+ // AUCTION METHODS
+ public static ArrayList getAuctions() {
+ return getArrayList(getContent(AUCTION_DB), Auction.class);
+ }
+
+ public static void saveAuction(Auction auction) {
+ auctionLock.P();
+
+ ArrayList auctions = getAuctions();
+ auctions.add(auction);
+ writeContent(AUCTION_DB, getJsonBuilder().toJson(auctions));
+
+ auctionLock.V();
+ }
+
+ // BID METHODS
+ public static ArrayList getBids(Auction auction) {
+ return getArrayList(getContent(auction.getFilename()), Bid.class);
+ }
+
+ public static int saveBid(Auction auction, Bid bid) {
+ BinarySemaphore bidLock = new BinarySemaphore();
+
+ if (bidLocks.containsKey(auction.getId())) {
+ bidLock = bidLocks.get(auction.getId());
+ } else {
+ bidLocks.put(auction.getId(), bidLock);
+ }
+ bidLock.P();
+ User user = getUserByName(bid.getUsername());
+ ArrayList bids = getBids(auction);
+
+ int result = 0;
+
+ if (user.getPoint() < bid.getPoint()) {
+ result = -1;
+ } else if (bids.size() > 0 && (bid.getPoint() <= bids.get(0).getPoint())) {
+ result = -2;
+ } else {
+ result = 1;
+ bids.add(0, bid);
+ writeContent(auction.getFilename(), getJsonBuilder().toJson(bids));
+ updateUserPoint(user.getName(), user.getPoint() - bid.getPoint());
+ }
+ bidLock.V();
+
+ return result;
+ }
+
+ // FILE HELPERS
+ public static void writeContent(String filename, String content) {
+ File file = new File(filename);
+
+ File db = new File(DATA_PATH);
+
+ if (!db.exists())
+ db.mkdir();
+
+ try {
+ PrintWriter out = new PrintWriter(file);
+ out.print(content);
+ out.close();
+ } catch (IOException e) {
+ Logger.error("Couldn't write the pages to file");
+ }
+ }
+
+ public static String getContent(String filename) {
+ File file = new File(filename);
+ try {
+ BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
+ StringBuffer stringBuffer = new StringBuffer();
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ stringBuffer.append(line).append("\n");
+ }
+ return stringBuffer.toString();
+ } catch (Exception e) {
+ Logger.error("File open error: " + filename);
+ }
+ return "";
+ }
+
+ public static void flush() {
+ File db = new File(DATA_PATH);
+
+ if (db.exists()) {
+ String[] entries = db.list();
+ for (String s : entries) {
+ File currentFile = new File(db.getPath(), s);
+ currentFile.delete();
+ }
+ db.delete();
+ }
+ }
+
+ // DATE CONVERSION HELPERS
+ public static Date stringToDate(String date) {
+ SimpleDateFormat sdf = new SimpleDateFormat(Database.DATE_FORMAT);
+ try {
+ return sdf.parse(date);
+ } catch (Exception e) {
+ Logger.error("String to Date: " + date);
+ Logger.error(e.getMessage());
+ }
+ return null;
+ }
+
+ public static String dateToString(Date date) {
+ SimpleDateFormat sdf = new SimpleDateFormat(Database.DATE_FORMAT);
+ try {
+ return sdf.format(date);
+ } catch (Exception e) {
+ Logger.error("Date to String: " + date);
+ Logger.error(e.getMessage());
+ }
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/persistence/Seeder.java b/cmpe436/final-project/Server/src/persistence/Seeder.java
new file mode 100644
index 0000000..299e6c3
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/Seeder.java
@@ -0,0 +1,79 @@
+package persistence;
+
+import model.*;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Random;
+
+/**
+ * Generates dummy data for demo
+ */
+public class Seeder {
+ public static void main(String[] args) {
+ Seeder.init();
+ }
+
+ public static void init() {
+ Database.flush();
+ Auction auction1 = new Auction(1, "Mona Lisa Auction", "The Mona Lisa is a half-length portrait painting by the Italian Renaissance artist Leonardo da Vinci.", 100, Database.dateToString(getRandomDate()));
+ Auction auction2 = new Auction(2, "The Scream Auction", "The works show a figure with an agonized expression against a landscape with a tumultuous orange sky.", 20, Database.dateToString(getRandomDate()));
+ Auction auction6 = new Auction(6, "Macintosh Auction", "The Macintosh is a family of personal computers designed, manufactured, and sold by Apple Inc. since January 1984", 400, Database.dateToString(getRandomDate()));
+ Auction auction5 = new Auction(5, "Very Old Stamp Auction", "19th Century classics", 400, Database.dateToString(getRandomDate()));
+ Auction auction3 = new Auction(3, "Wheat Field with Cypresses", "Very The works were inspired by the view from the window at the asylum towards the Alpilles mountains.", 30, Database.dateToString(getRandomDate()));
+ Auction auction7 = new Auction(7, "iPhone (1st generation)", "The iPhone is the first smartphone model designed and marketed by Apple Inc.", 400, Database.dateToString(getRandomDate()));
+ Auction auction4 = new Auction(4, "Byzantine Coin Auction", "A very popular denarius featuring the tools of minting coins.", 400, Database.dateToString(getRandomDate()));
+ Auction auction8 = new Auction(8, "Apple Newton Auction", "The Newton is a series of personal digital assistants (PDA) developed and marketed by Apple Computer, Inc.", 400, Database.dateToString(getRandomDate()));
+
+ Database.saveAuction(auction1);
+ Database.saveAuction(auction2);
+ Database.saveAuction(auction3);
+ Database.saveAuction(auction4);
+ Database.saveAuction(auction5);
+ Database.saveAuction(auction6);
+ Database.saveAuction(auction7);
+ Database.saveAuction(auction8);
+
+ Database.saveUser("Enes", "Enes123");
+ Database.saveUser("Ahmet", "Ahmet123");
+ Database.saveUser("Mehmet", "Mehmet123");
+ Database.saveUser("Osman", "Osman123");
+
+ Database.saveBid(auction1, new Bid("Enes", 10, getRandomDate(false)));
+ Database.saveBid(auction1, new Bid("Enes", 26, getRandomDate(false)));
+ Database.saveBid(auction1, new Bid("Ahmet", 40, getRandomDate(false)));
+
+ Database.saveBid(auction2, new Bid("Osman", 10, getRandomDate(false)));
+ Database.saveBid(auction2, new Bid("Mehmet", 20, getRandomDate(false)));
+ Database.saveBid(auction2, new Bid("Enes", 24, getRandomDate(false)));
+
+ Database.saveBid(auction3, new Bid("Ahmet", 75, getRandomDate(false)));
+ Database.saveBid(auction3, new Bid("Osman", 86, getRandomDate(false)));
+ Database.saveBid(auction3, new Bid("Mehmet", 96, getRandomDate(false)));
+
+ Database.saveBid(auction4, new Bid("Enes", 34, getRandomDate(false)));
+ Database.saveBid(auction4, new Bid("Mehmet", 67, getRandomDate(false)));
+ Database.saveBid(auction4, new Bid("Ahmet", 85, getRandomDate(false)));
+ }
+
+ private static Date getRandomDate() {
+ return getRandomDate(true);
+ }
+
+ private static Date getRandomDate(boolean isFuture) {
+ Random rand = new Random();
+ Date date = new Date();
+ Calendar c = Calendar.getInstance();
+ c.setTime(date);
+ if (isFuture) {
+ c.add(Calendar.DATE, rand.nextInt(20));
+ } else {
+ c.add(Calendar.DATE, -1 * rand.nextInt(20));
+ }
+ c.add(Calendar.DATE, rand.nextInt(20));
+ c.add(Calendar.HOUR, rand.nextInt(24));
+ c.add(Calendar.MINUTE, rand.nextInt(60));
+ c.add(Calendar.SECOND, rand.nextInt(60));
+ return c.getTime();
+ }
+}
diff --git a/cmpe436/final-project/Server/src/persistence/data/1_bids.json b/cmpe436/final-project/Server/src/persistence/data/1_bids.json
new file mode 100644
index 0000000..e0bea7d
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/data/1_bids.json
@@ -0,0 +1 @@
+[{"point":40,"date":"2018-12-01 12:17:35","username":"Ahmet"},{"point":26,"date":"2018-12-04 06:00:12","username":"Enes"},{"point":10,"date":"2018-12-04 11:32:47","username":"Enes"}]
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/persistence/data/2_bids.json b/cmpe436/final-project/Server/src/persistence/data/2_bids.json
new file mode 100644
index 0000000..2f4eec9
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/data/2_bids.json
@@ -0,0 +1 @@
+[{"point":24,"date":"2018-12-07 13:05:37","username":"Enes"},{"point":20,"date":"2018-11-30 23:36:41","username":"Mehmet"},{"point":10,"date":"2018-11-25 12:18:08","username":"Osman"}]
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/persistence/data/3_bids.json b/cmpe436/final-project/Server/src/persistence/data/3_bids.json
new file mode 100644
index 0000000..fb9bd9f
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/data/3_bids.json
@@ -0,0 +1 @@
+[{"point":96,"date":"2018-11-25 14:43:28","username":"Mehmet"},{"point":86,"date":"2018-11-21 03:11:14","username":"Osman"},{"point":75,"date":"2018-11-22 19:22:18","username":"Ahmet"}]
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/persistence/data/4_bids.json b/cmpe436/final-project/Server/src/persistence/data/4_bids.json
new file mode 100644
index 0000000..7fd563a
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/data/4_bids.json
@@ -0,0 +1 @@
+[{"point":85,"date":"2018-11-27 19:51:50","username":"Ahmet"},{"point":67,"date":"2018-12-13 16:41:31","username":"Mehmet"},{"point":34,"date":"2018-11-20 18:56:53","username":"Enes"}]
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/persistence/data/auctions.json b/cmpe436/final-project/Server/src/persistence/data/auctions.json
new file mode 100644
index 0000000..c57d811
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/data/auctions.json
@@ -0,0 +1,58 @@
+[
+ {
+ "id": 1,
+ "name": "Mona Lisa Auction",
+ "description": "The Mona Lisa is a half-length portrait painting by the Italian Renaissance artist Leonardo da Vinci.",
+ "startPoint": 100,
+ "date": "2018-12-17 09:39:45"
+ },
+ {
+ "id": 2,
+ "name": "The Scream Auction",
+ "description": "The works show a figure with an agonized expression against a landscape with a tumultuous orange sky.",
+ "startPoint": 20,
+ "date": "2018-12-08 16:53:01"
+ },
+ {
+ "id": 3,
+ "name": "Wheat Field with Cypresses",
+ "description": "Very The works were inspired by the view from the window at the asylum towards the Alpilles mountains.",
+ "startPoint": 30,
+ "date": "2018-12-11 06:58:35"
+ },
+ {
+ "id": 4,
+ "name": "Byzantine Coin Auction",
+ "description": "A very popular denarius featuring the tools of minting coins.",
+ "startPoint": 400,
+ "date": "2018-12-22 04:57:50"
+ },
+ {
+ "id": 5,
+ "name": "Very Old Stamp Auction",
+ "description": "19th Century classics",
+ "startPoint": 400,
+ "date": "2019-01-01 05:07:32"
+ },
+ {
+ "id": 6,
+ "name": "Macintosh Auction",
+ "description": "The Macintosh is a family of personal computers designed, manufactured, and sold by Apple Inc. since January 1984",
+ "startPoint": 400,
+ "date": "2019-01-04 08:07:17"
+ },
+ {
+ "id": 7,
+ "name": "iPhone (1st generation)",
+ "description": "The iPhone is the first smartphone model designed and marketed by Apple Inc.",
+ "startPoint": 400,
+ "date": "2018-12-20 07:42:14"
+ },
+ {
+ "id": 8,
+ "name": "Apple Newton Auction",
+ "description": "The Newton is a series of personal digital assistants (PDA) developed and marketed by Apple Computer, Inc.",
+ "startPoint": 400,
+ "date": "2018-12-23 08:01:21"
+ }
+]
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/persistence/data/users.json b/cmpe436/final-project/Server/src/persistence/data/users.json
new file mode 100644
index 0000000..f22b07d
--- /dev/null
+++ b/cmpe436/final-project/Server/src/persistence/data/users.json
@@ -0,0 +1 @@
+[{"name":"Enes","password":"59201435","point":1906},{"name":"Ahmet","password":"-1652985379","point":1800},{"name":"Mehmet","password":"-776395642","point":1817},{"name":"Osman","password":"-1854711396","point":1904}]
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/server/AuctionServer.java b/cmpe436/final-project/Server/src/server/AuctionServer.java
new file mode 100644
index 0000000..89fa05a
--- /dev/null
+++ b/cmpe436/final-project/Server/src/server/AuctionServer.java
@@ -0,0 +1,54 @@
+package server;
+
+import model.Bid;
+import util.Logger;
+
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.*;
+
+/**
+ * Accepts socket connection requests and put them in a thread
+ */
+public class AuctionServer {
+ private static LinkedList threads = new LinkedList<>();
+ private static final int DEFAULT_PORT = 5001;
+
+ public static void main(String[] args) {
+ AuctionServer server = new AuctionServer();
+
+ int port = DEFAULT_PORT;
+
+ if (args.length > 1)
+ port = Integer.parseInt(args[0]);
+
+ server.start(port);
+ }
+
+ private void start(int port) {
+ try {
+ ServerSocket serverSocket = new ServerSocket(port);
+ while (true) {
+ Socket socket = serverSocket.accept();
+ ServerThread thread = new ServerThread(socket);
+ threads.add(thread);
+ thread.start();
+ }
+ } catch (Exception e) {
+ Logger.server("Socket construct error");
+ Logger.error(e.getMessage());
+ }
+ }
+
+ /**
+ * Sends new bid on active thread
+ */
+ public static void broadcastBid(int auctionID, Bid bid) {
+ Logger.server("Broadcasting " + Integer.toString(bid.getPoint()) + " point bid by " + bid.getUsername() + " on auction #" + Integer.toString(auctionID) + " ");
+ for (ServerThread thread : threads) {
+ if (thread.isAlive() && thread.getAuctionID() == auctionID) {
+ thread.sendMessage(new Packet(Packet.Type.BID_NEW, bid).toJson());
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/server/Client.java b/cmpe436/final-project/Server/src/server/Client.java
new file mode 100644
index 0000000..4e3c687
--- /dev/null
+++ b/cmpe436/final-project/Server/src/server/Client.java
@@ -0,0 +1,90 @@
+package server;
+
+import model.Bid;
+import model.User;
+import util.Logger;
+import server.Packet.Type;
+
+import java.io.*;
+import java.net.*;
+import java.util.Date;
+import java.util.Scanner;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Simulates a client for testing server
+ */
+class Client {
+ private Socket socket;
+ private BufferedReader in;
+ private BufferedWriter out;
+ private static final String HOST = "18.224.60.222";
+ // private static final String HOST = "localhost";
+ private static final int PORT = 5001;
+
+ public Client(Socket socket_) {
+ socket = socket_;
+ try {
+ in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
+ } catch (Exception e) {
+ Logger.error("Client construct error");
+ }
+ }
+
+ public static void main(String argv[]) throws Exception {
+ Client client = new Client(new Socket(HOST, PORT));
+ (new Thread(() -> {
+ try {
+ client.listen();
+ } catch (IOException e) {
+ Logger.client("Listen thread error");
+ Logger.error(e.getMessage());
+ }
+ })).start();
+
+ Scanner scanner = new Scanner(System.in);
+ label:
+ while (true) {
+ String command = scanner.nextLine();
+ String[] parts = command.split(" ");
+ switch (parts[0]) {
+ case "auctions":
+ client.sendMessage(new Packet(Type.AUCTIONS, "").toJson());
+ TimeUnit.SECONDS.sleep(5);
+ client.socket.close();
+ break label;
+ case "bid_listen":
+ client.sendMessage(new Packet(Type.BID_LISTEN, parts[1]).toJson());
+ break;
+ case "bid_store":
+ client.sendMessage(new Packet(Type.BID_STORE, new Bid(parts[1], Integer.parseInt(parts[2]), new Date())).toJson());
+ break;
+ case "auth":
+ client.sendMessage(new Packet(Type.USER, new User(parts[1], parts[2])).toJson());
+ break;
+ case "exit":
+ break label;
+ }
+ }
+ }
+
+ private void sendMessage(String message) {
+ try {
+ Logger.client("Message sent to server: " + message);
+ out.write(message);
+ out.newLine();
+ out.flush();
+ } catch (Exception e) {
+ Logger.client("Message sent error: " + message);
+ Logger.error(e.getMessage());
+ }
+ }
+
+ private void listen() throws IOException {
+ String message;
+ while ((message = in.readLine()) != null) {
+ Logger.server("Message from server: " + message);
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/server/Packet.java b/cmpe436/final-project/Server/src/server/Packet.java
new file mode 100644
index 0000000..1caed52
--- /dev/null
+++ b/cmpe436/final-project/Server/src/server/Packet.java
@@ -0,0 +1,62 @@
+package server;
+
+import persistence.Database;
+
+import java.util.ArrayList;
+
+/**
+ * Communication protocol between client and server
+ */
+public class Packet {
+ private Type type;
+ private String data;
+
+ public enum Type {
+ UNKNOWN(0), // Unknown package
+ AUCTIONS(1), // Get auctions request, and return it
+ BID_LISTEN(2), // Subscribe client to auction bid channel
+ BID_NEW(3), // Broadcast new bid to clients
+ BID_STORE(4), // Store bid and return result
+ USER(5); // Store user and return save user result
+
+ final int data;
+
+ Type(int data) {
+ this.data = data;
+ }
+ }
+
+ Packet(Type type, String data) {
+ this.type = type;
+ this.data = data;
+ }
+
+ public Packet(Type type, Object data) {
+ this.type = type;
+ this.data = Database.getJsonBuilder().toJson(data);
+ }
+
+ public static Packet fromJson(String json) {
+ return Database.getJsonBuilder().fromJson(json, Packet.class);
+ }
+
+ public ArrayList toArrayList(Class clazz) {
+ return Database.getArrayList(this.data, clazz);
+ }
+
+ public T toObject(Class clazz) {
+ return Database.getJsonBuilder().fromJson(this.data, clazz);
+ }
+
+ public String toJson() {
+ return Database.getJsonBuilder().toJson(this);
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ public Type getType() {
+ return type;
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/final-project/Server/src/server/ServerThread.java b/cmpe436/final-project/Server/src/server/ServerThread.java
new file mode 100644
index 0000000..c5371a1
--- /dev/null
+++ b/cmpe436/final-project/Server/src/server/ServerThread.java
@@ -0,0 +1,128 @@
+package server;
+
+import model.*;
+import persistence.Database;
+import server.Packet.Type;
+import util.Logger;
+
+import java.io.*;
+import java.net.Socket;
+import java.util.ArrayList;
+
+/**
+ * Handles TCP connection and listen new packets
+ */
+public class ServerThread extends Thread {
+ private Socket socket;
+ private BufferedReader in;
+ private BufferedWriter out;
+ private int auctionID;
+
+ ServerThread(Socket socket) {
+ this.socket = socket;
+ try {
+ in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
+ } catch (Exception e) {
+ Logger.thread("Thread construct error");
+ Logger.error(e.getMessage());
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ this.listen();
+ Logger.client(getHostAddress() + " connection is closed");
+ } catch (Exception e) {
+ Logger.thread("Thread listen error");
+ Logger.error(e.getMessage());
+ }
+ }
+
+ private void listen() throws IOException {
+ String message;
+
+ while ((message = in.readLine()) != null) {
+ Packet packet;
+
+ try {
+ packet = Packet.fromJson(message);
+ } catch (Exception e) {
+ packet = new Packet(Type.UNKNOWN, "");
+ }
+
+ switch (packet.getType()) {
+ case AUCTIONS:
+ Logger.server("Sending auctions to " + getHostAddress());
+ ArrayList auctions = Database.getAuctions();
+ this.sendMessage(new Packet(Type.AUCTIONS, auctions).toJson());
+ break;
+ case BID_LISTEN:
+ this.auctionID = packet.toObject(Integer.class);
+ Logger.client(getHostAddress() + " connected to auction #" + Integer.toString(this.auctionID));
+ ArrayList bids = Database.getBids(new Auction(this.auctionID));
+ this.sendMessage(new Packet(Type.BID_LISTEN, bids).toJson());
+ break;
+ case BID_STORE:
+ Bid bid = packet.toObject(Bid.class);
+ int result = Database.saveBid(new Auction(this.auctionID), bid);
+ if (result == 1) {
+ Logger.client(bid.getUsername() + " bid " + bid.getPoint() + " on auction #" + Integer.toString(auctionID));
+ this.sendMessage(new Packet(Type.BID_STORE, Database.getUserPoint(bid.getUsername())).toJson());
+ AuctionServer.broadcastBid(auctionID, bid);
+ } else {
+ Logger.client(bid.getUsername() + " could't bid on " + bid.getPoint() + " on auction #" + Integer.toString(auctionID));
+ if (result == -1)
+ Logger.client(bid.getUsername() + " hasn't enough points");
+ else if (result == -2)
+ Logger.client("New bid is smaller than last bid.");
+ this.sendMessage(new Packet(Type.BID_STORE, Integer.toString(result)).toJson());
+ }
+ break;
+ case USER:
+ User user = packet.toObject(User.class);
+
+ if (Database.authUser(user.getName(), user.getPassword())) {
+ Logger.client(user.getName() + " login");
+ this.sendMessage(new Packet(Type.USER, Database.getUserPoint(user.getName())).toJson());
+ } else {
+ Logger.client(user.getName() + " couldn't login");
+ this.sendMessage(new Packet(Type.USER, "-1").toJson());
+ }
+ break;
+ default:
+ Logger.client("Unknown packet from " + getHostAddress() + ": " + message);
+ }
+ }
+ }
+
+ private void close() {
+ try {
+ in.close();
+ out.close();
+ socket.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ void sendMessage(String message) {
+ try {
+ out.write(message);
+ out.newLine();
+ out.flush();
+ } catch (Exception e) {
+ Logger.client("Message send error to " + getHostAddress() + ": " + message);
+ Logger.error(e.getMessage());
+ }
+ }
+
+ private String getHostAddress() {
+ return socket.getInetAddress().getHostAddress();
+ }
+
+ int getAuctionID() {
+ return this.auctionID;
+ }
+}
diff --git a/cmpe436/final-project/Server/src/util/BinarySemaphore.java b/cmpe436/final-project/Server/src/util/BinarySemaphore.java
new file mode 100644
index 0000000..acf7056
--- /dev/null
+++ b/cmpe436/final-project/Server/src/util/BinarySemaphore.java
@@ -0,0 +1,33 @@
+package util;
+
+/**
+ * Binary Semaphore implementation from book. It solves mutex issues.
+ */
+public class BinarySemaphore {
+ boolean value;
+
+ public BinarySemaphore() {
+ this.value = true;
+ }
+
+ public BinarySemaphore(boolean initValue) {
+ this.value = initValue;
+ }
+
+ // Takes resource
+ public synchronized void P() {
+ while (!this.value)
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ }
+ this.value = false;
+ }
+
+ // Releases resource
+ public synchronized void V() {
+ this.value = true;
+ notify();
+ }
+}
+
diff --git a/cmpe436/final-project/Server/src/util/Logger.java b/cmpe436/final-project/Server/src/util/Logger.java
new file mode 100644
index 0000000..133b5da
--- /dev/null
+++ b/cmpe436/final-project/Server/src/util/Logger.java
@@ -0,0 +1,22 @@
+package util;
+
+/**
+ * Log helper
+ */
+public class Logger {
+ public static void error(String text) {
+ System.out.println("[Error] " + text);
+ }
+
+ public static void thread(String text) {
+ System.out.println("[Thread] " + text);
+ }
+
+ public static void server(String text) {
+ System.out.println("[Server] " + text);
+ }
+
+ public static void client(String text) {
+ System.out.println("[Client] " + text);
+ }
+}
diff --git a/cmpe436/hw1/.classpath b/cmpe436/hw1/.classpath
new file mode 100644
index 0000000..51a8bba
--- /dev/null
+++ b/cmpe436/hw1/.classpath
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/cmpe436/hw1/.project b/cmpe436/hw1/.project
new file mode 100644
index 0000000..ee46012
--- /dev/null
+++ b/cmpe436/hw1/.project
@@ -0,0 +1,17 @@
+
+
+ cmpe436_hw1
+
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+
+ org.eclipse.jdt.core.javanature
+
+
diff --git a/cmpe436/hw1/.settings/org.eclipse.jdt.core.prefs b/cmpe436/hw1/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..3a21537
--- /dev/null
+++ b/cmpe436/hw1/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,11 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.8
diff --git a/cmpe436/hw1/README.txt b/cmpe436/hw1/README.txt
new file mode 100644
index 0000000..3191480
--- /dev/null
+++ b/cmpe436/hw1/README.txt
@@ -0,0 +1,36 @@
+Mustafa Enes Çakır
+2013400105
+enes@cakir.web.tr
+CmpE436 Assignment 1
+
+Source code of project is "src" folder. All methods have JavaDoc comments.
+
+Question1 and Matrix classes are for solution of Question 1.
+Question2 and Population classes are for solution of Question 2.
+
+# Question 1 - Matrix Multiplication
+ Question1.java class manages flow of the solution. It takes file names from arguments and constructs matrix from them. Then it multiplies matrices.
+ It expects three arguments: [in] file name of first matrix, [in] file name of second matrix, [out] file name of result matrix.
+ Matrix files should be in the given structure that is in the assignment PDF.
+ Matrix.java class handles matrix operations.
+
+ ## Checked Errors
+ - Enough application arguments
+ - Positive integer dimensions
+ - All integer elements
+ - Valid input files
+ - Valid matrix dimensions for multiplication
+
+
+# Question 2 - Game of Life
+ Question2.java class manages flow of the solution. It takes population sizes, max generation number, optionally initial data file name and constructs population from them.
+ If initial population is not given, it generates random population. Then it runs population until reaches max generation. It print each population steps.
+ It expects three or four arguments: number of rows, number of columns, max generation number, [optional] initial population.
+ Initial population files should be in the given structure expect first dimension line is unnecessary.
+ Population.java class handles population operations. It extends from Matrix.class.
+ It's data array has 2 more rows and columns, because of neighbor count checking for border cells. Outer element has fixed zero values.
+
+ ## Checked Errors
+ - Same errors from Question 1
+ - All elements have to be 1 or 0
+ - Positive max generation number
\ No newline at end of file
diff --git a/cmpe436/hw1/bin/Matrix.class b/cmpe436/hw1/bin/Matrix.class
new file mode 100644
index 0000000..41bef1f
Binary files /dev/null and b/cmpe436/hw1/bin/Matrix.class differ
diff --git a/cmpe436/hw1/bin/Population.class b/cmpe436/hw1/bin/Population.class
new file mode 100644
index 0000000..3090ced
Binary files /dev/null and b/cmpe436/hw1/bin/Population.class differ
diff --git a/cmpe436/hw1/bin/Question1.class b/cmpe436/hw1/bin/Question1.class
new file mode 100644
index 0000000..51abf1f
Binary files /dev/null and b/cmpe436/hw1/bin/Question1.class differ
diff --git a/cmpe436/hw1/bin/Question2.class b/cmpe436/hw1/bin/Question2.class
new file mode 100644
index 0000000..1edd297
Binary files /dev/null and b/cmpe436/hw1/bin/Question2.class differ
diff --git a/cmpe436/hw1/cmpe436_hw1.iml b/cmpe436/hw1/cmpe436_hw1.iml
new file mode 100644
index 0000000..d6c9d93
--- /dev/null
+++ b/cmpe436/hw1/cmpe436_hw1.iml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/hw1/hw1.pdf b/cmpe436/hw1/hw1.pdf
new file mode 100644
index 0000000..fb29304
Binary files /dev/null and b/cmpe436/hw1/hw1.pdf differ
diff --git a/cmpe436/hw1/matrix1.txt b/cmpe436/hw1/matrix1.txt
new file mode 100644
index 0000000..1c8600f
--- /dev/null
+++ b/cmpe436/hw1/matrix1.txt
@@ -0,0 +1,3 @@
+2 3
+1 2 3
+4 5 6
\ No newline at end of file
diff --git a/cmpe436/hw1/matrix2.txt b/cmpe436/hw1/matrix2.txt
new file mode 100644
index 0000000..fabecc2
--- /dev/null
+++ b/cmpe436/hw1/matrix2.txt
@@ -0,0 +1,4 @@
+3 2
+7 8
+9 10
+11 12
\ No newline at end of file
diff --git a/cmpe436/hw1/population.txt b/cmpe436/hw1/population.txt
new file mode 100644
index 0000000..b9d1e5c
--- /dev/null
+++ b/cmpe436/hw1/population.txt
@@ -0,0 +1,5 @@
+0 0 0 0 0
+0 0 1 0 0
+0 0 1 0 0
+0 0 1 0 0
+0 0 0 0 0
\ No newline at end of file
diff --git a/cmpe436/hw1/src/Matrix.java b/cmpe436/hw1/src/Matrix.java
new file mode 100644
index 0000000..5241d66
--- /dev/null
+++ b/cmpe436/hw1/src/Matrix.java
@@ -0,0 +1,245 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 1
+// Question 1
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.PrintWriter;
+import java.util.Scanner;
+
+/**
+ * Encapsulation for matrix data
+ */
+public class Matrix {
+ /**
+ * Keeps matrix data
+ */
+ private int[][] data;
+
+ /**
+ * Constructs empty matrix object
+ */
+ public Matrix() {
+ this.data = null;
+ }
+
+ /**
+ * Constructs matrix object from 2 dimensional array
+ *
+ * @param data two dimensional int array for matrix data
+ */
+ public Matrix(int[][] data) {
+ this.data = data;
+ }
+
+ /**
+ * Constructs empty matrix object with given sizes
+ *
+ * @param rows number of the rows
+ * @param columns number of the columns
+ */
+ public Matrix(int rows, int columns) {
+ if (rows <= 0 || columns <= 0) {
+ abort("Dimensions of the matrix have to be positive");
+ }
+ this.data = new int[rows][columns];
+ }
+
+ /**
+ * Read given file and constructs new matrix from it
+ *
+ * @param filename data file for matrix
+ * @return new matrix from file data
+ */
+ public void read(String filename) {
+ Scanner scanner = this.openFile(filename);
+
+ int rows = scanner.nextInt();
+ int columns = scanner.nextInt();
+
+ if (rows <= 0 || columns <= 0) {
+ abort("Row and column numbers have to be positive");
+ }
+ this.data = new int[rows][columns];
+
+ this.readData(scanner);
+
+ scanner.close();
+ }
+
+ /**
+ * Read data part of the matrix
+ *
+ * @param scanner opened file
+ */
+ public void readData(Scanner scanner) {
+ for (int i = 0; i < getNumberOfRows(); i++) {
+ for (int j = 0; j < getNumberOfColumns(); j++) {
+ try {
+ this.setElement(i, j, scanner.nextInt());
+ } catch (Exception e) {
+ abort("Error at element [" + i + ", " + j + "]. \n Please make sure all elements are integers.");
+ }
+ }
+ }
+ }
+
+ /**
+ * Converts file to scanner
+ *
+ * @param filename Name of the file that opened
+ * @return opened file
+ */
+ public Scanner openFile(String filename) {
+ File file = new File(filename);
+ Scanner scanner = null;
+
+ try {
+ scanner = new Scanner(file);
+ } catch (FileNotFoundException e) {
+ abort("File " + filename + " not found.");
+ }
+ return scanner;
+ }
+
+ /**
+ * Writes this matrix to file with given name
+ *
+ * @param filename file for writing matrix
+ */
+ public void write(String filename) {
+ try {
+ PrintWriter writer = new PrintWriter(filename, "UTF-8");
+ writer.print(this.toString());
+ writer.close();
+ } catch (Exception e) {
+ abort("Couldn't write result to file");
+ }
+
+ }
+
+ /**
+ * Multiplies this matrix with given matrix
+ *
+ * @param second matrix for multiplications
+ * @return result matrix
+ */
+ public Matrix multiplyBy(Matrix second) {
+ if (this.getNumberOfColumns() != second.getNumberOfRows()) {
+ abort("Matrix size error. \n Column number of the first matrix and row number of the second matrix have to be equal.");
+ }
+
+ int rows = this.getNumberOfRows();
+ int columns = second.getNumberOfColumns();
+
+ Matrix result = new Matrix(rows, columns);
+
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < columns; j++) {
+ int sum = 0;
+ for (int k = 0; k < this.getNumberOfColumns(); k++) {
+ sum += this.getElement(i, k) * second.getElement(k, j);
+ }
+ result.setElement(i, j, sum);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Prints matrix to console
+ */
+ public void print() {
+ System.out.println(this);
+ }
+
+ /**
+ * Converts matrix to string
+ *
+ * @return string representation of matrix
+ */
+ @Override // Inherited from the Object class.
+ public String toString() {
+ StringBuilder result = new StringBuilder();
+ result.append(this.getNumberOfRows() + " " + this.getNumberOfColumns() + "\n");
+
+ for (int i = 0; i < this.getNumberOfRows(); i++) {
+ for (int j = 0; j < this.getNumberOfColumns(); j++) {
+ result.append(this.getElement(i, j) + " ");
+ }
+ result.append("\n");
+ }
+
+ return result.toString();
+ }
+
+ /**
+ * Returns number of the rows
+ *
+ * @return number of the rows
+ */
+ public int getNumberOfRows() {
+ return this.data.length;
+ }
+
+ /**
+ * Returns number of the columns
+ *
+ * @return number of the columns
+ */
+ public int getNumberOfColumns() {
+ return this.data[0].length;
+ }
+
+ /**
+ * Returns element at given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @return element at given coordinates
+ */
+ public int getElement(int i, int j) {
+ return this.data[i][j];
+ }
+
+ /**
+ * Changes element at given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @param element data to put position
+ */
+ public void setElement(int i, int j, int element) {
+ this.data[i][j] = element;
+ }
+
+ /**
+ * Returns data array of matrix
+ *
+ * @return two dimension array version of matrix
+ */
+ public int[][] getData() {
+ return this.data;
+ }
+
+ /**
+ * Changes whole data of matrix
+ *
+ * @param data new data for matrix
+ */
+ public void setData(int[][] data) {
+ this.data = data;
+ }
+
+ /**
+ * Aborts application with messages
+ *
+ * @param message error message for aborting
+ */
+ public void abort(String message) {
+ System.out.println(message);
+ System.exit(0);
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw1/src/Population.java b/cmpe436/hw1/src/Population.java
new file mode 100644
index 0000000..9d14025
--- /dev/null
+++ b/cmpe436/hw1/src/Population.java
@@ -0,0 +1,180 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 1
+// Question 2
+
+import java.util.Scanner;
+import java.util.Random;
+
+/**
+ * Encapsulation for game of life's population
+ * Data matrix has 2 more rows and columns.
+ * Outer line is always zero. It's for neighbor calculation of borders.
+ */
+public class Population extends Matrix {
+ /**
+ * Maximum number of last generation
+ */
+ private int maxGeneration;
+
+ /**
+ * Constructs empty matrix object with given sizes
+ *
+ * @param rows number of the rows
+ * @param columns number of the columns
+ * @param maxGeneration number of the max generations
+ */
+ public Population(int rows, int columns, int maxGeneration) {
+ super(rows + 2, columns + 2);
+ this.setMaxGeneration(maxGeneration);
+ }
+
+ /**
+ * Imports population from file
+ *
+ * @param filename data file for initial population
+ */
+ public void importPopulation(String filename) {
+ Scanner scanner = this.openFile(filename);
+ this.readData(scanner);
+ scanner.close();
+ }
+
+
+ /**
+ * Generates random population
+ */
+ public void generateRandom() {
+ Random random = new Random();
+ for (int i = 0; i < this.getNumberOfRows(); i++) {
+ for (int j = 0; j < this.getNumberOfColumns(); j++) {
+ this.setElement(i, j, random.nextInt(2));
+ }
+ }
+ }
+
+ /**
+ * Calculates next generation for current state
+ */
+ public void nextGeneration() {
+ Population next = new Population(getNumberOfRows(), getNumberOfColumns(), this.maxGeneration);
+
+ for (int i = 0; i < this.getNumberOfRows(); i++) {
+ for (int j = 0; j < this.getNumberOfColumns(); j++) {
+ next.setElement(i, j, this.getNextValue(i, j));
+ }
+ }
+ this.setData(next.getData());
+ }
+
+ /**
+ * Runs population until max generation
+ */
+ public void run() {
+ System.out.println("Initial Population");
+ this.print();
+
+ for (int i = 0; i < this.maxGeneration; i++) {
+ this.nextGeneration();
+ System.out.printf("%d. Generation\n", i + 1);
+ this.print();
+ }
+ }
+
+ /**
+ * Converts matrix to string
+ * It deletes first line, because it has dimension information
+ *
+ * @return string representation of matrix
+ */
+ @Override
+ public String toString() {
+ String result = super.toString();
+ return result.substring(result.indexOf("\n") + 1);
+ }
+
+ /**
+ * Calculates next value of given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @return next of element
+ */
+ public int getNextValue(int i, int j) {
+ int neighborCount = getNeighborCount(i, j);
+ if (this.getElement(i, j) == 1) {
+ return (neighborCount == 2 || neighborCount == 3) ? 1 : 0;
+ }
+
+ return (neighborCount == 3) ? 1 : 0;
+ }
+
+ /**
+ * Counts neighbors of given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @return count of neighbors
+ */
+ public int getNeighborCount(int i, int j) {
+ return this.getElement(i - 1, j - 1) + this.getElement(i - 1, j) + this.getElement(i - 1, j + 1) +
+ this.getElement(i, j - 1) + this.getElement(i, j + 1) +
+ this.getElement(i + 1, j - 1) + this.getElement(i + 1, j) + this.getElement(i + 1, j + 1);
+ }
+
+ /**
+ * Returns number of the rows. Subtracts 2 because of empty outer area.
+ *
+ * @return number of the rows
+ */
+ public int getNumberOfRows() {
+ return super.getNumberOfRows() - 2;
+ }
+
+ /**
+ * Returns number of the columns. Subtracts 2 because of empty outer area.
+ *
+ * @return number of the columns
+ */
+ public int getNumberOfColumns() {
+ return super.getNumberOfColumns() - 2;
+ }
+
+ /**
+ * Returns element at given coordinates. Adds 1 because of empty outer area
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @return element at given coordinates
+ */
+ public int getElement(int i, int j) {
+ return super.getElement(i + 1, j + 1);
+ }
+
+ /**
+ * Changes element at given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @param element data to put position
+ */
+ public void setElement(int i, int j, int element) {
+ if (element != 0 && element != 1) {
+ abort("Cell number have to be 1 or 0.");
+ }
+ super.setElement(i + 1, j + 1, element);
+ }
+
+ /**
+ * Changes max generation of population
+ *
+ * @param value new value of max generation
+ */
+ public void setMaxGeneration(int value) {
+ if (value <= 0) {
+ abort("Max generation number must be an positive integer.");
+ }
+ this.maxGeneration = value;
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw1/src/Question1.java b/cmpe436/hw1/src/Question1.java
new file mode 100644
index 0000000..a1909c4
--- /dev/null
+++ b/cmpe436/hw1/src/Question1.java
@@ -0,0 +1,41 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 1
+// Question 1
+
+/**
+ * Solutions for Question 1
+ */
+public class Question1 {
+
+ public static void main(String[] args) {
+ // Check arguments
+ if (args.length != 3) {
+ System.out.println("\nYou have to give 3 arguments but given " + args.length + " arguments.");
+ System.out.println("Example usage:");
+ System.out.println("\tjava Question1 [FIRST_MATRIX] [SECOND_MATRIX] [RESULT_MATRIX]");
+ System.exit(0);
+ }
+
+ // Parse arguments
+ String firstFile = args[0];
+ String secondFile = args[1];
+ String resultFile = args[2];
+
+ // Read files and construct matrices
+ Matrix first = new Matrix();
+ first.read(firstFile);
+ Matrix second = new Matrix();
+ second.read(secondFile);
+
+ // Multiply two matrices
+ Matrix result = first.multiplyBy(second);
+
+ // Write result to file
+ result.write(resultFile);
+
+ // Print result to console
+ result.print();
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw1/src/Question2.java b/cmpe436/hw1/src/Question2.java
new file mode 100644
index 0000000..739cd17
--- /dev/null
+++ b/cmpe436/hw1/src/Question2.java
@@ -0,0 +1,45 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 1
+// Question 2
+
+/**
+ * Solutions for Question 2
+ */
+public class Question2 {
+
+ public static void main(String[] args) {
+ // Check arguments
+ if (args.length < 3) {
+ System.out.println("\nYou have to give at least 3 arguments but given " + args.length + " arguments.");
+ System.out.println("Example usage:");
+ System.out.println("\tjava Question2 [NUMBER_OF_ROWS] [NUMBER_OF_COLUMNS] [MAX_GENERATIONS] [INITIAL_POPULATION]?");
+ System.exit(0);
+ }
+
+ try {
+ // Parse arguments
+ int numberOfRows = Integer.parseInt(args[0]);
+ int numberOfColumns = Integer.parseInt(args[1]);
+ int maxGeneration = Integer.parseInt(args[2]);
+
+ // Construct population
+ Population population = new Population(numberOfRows, numberOfColumns, maxGeneration);
+
+ if (args.length == 4) {
+ // Import initial population
+ population.importPopulation(args[3]);
+ } else {
+ // Generate random inital population
+ population.generateRandom();
+ }
+
+ // Run population
+ population.run();
+
+ } catch (Exception e) {
+ System.out.println("Matrix dimensions and max generation must be positive numbers.");
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw2/README.txt b/cmpe436/hw2/README.txt
new file mode 100644
index 0000000..59f1770
--- /dev/null
+++ b/cmpe436/hw2/README.txt
@@ -0,0 +1,26 @@
+Mustafa Enes Çakır
+2013400105
+enes@cakir.web.tr
+CmpE436 Assignment 2
+
+Source code of project is "src" folder. All methods have JavaDoc comments.
+
+Question1, Population, CountingSemaphore classes are for solution of Question 1.
+Question2, BinarySemaphore, Philosopher classes are for solution of Question 2.
+Question3, RaceThread classes are for solution of Question 3.
+
+# Question 1 - Game of Life
+ Question1.java class manages flow of the solution. General flow is same with Assignment 1 Question 2.
+ It expects three or four arguments: number of rows, number of columns, max generation number, [optional] initial population.
+ Each cell has thread. They are sync with barrier synchronization.
+ All threads enter critical session 2 times: calculating next value, changing current value with next value.
+ After each critical session, they are waiting all threads to complete this step.
+
+# Question 2 - Deadlock
+ Question2.java class manages flow of the solution. It representation of classical philosopher problem.
+ Each of them took left fork and locked.
+
+# Question 3 - Race Condition
+ Question3.java class manages flow of the solution.
+ Each thread takes common value to temporary value, change it, wait and write it to common place.
+ Threads overwrite each other's result
diff --git a/cmpe436/hw2/bin/BinarySemaphore.class b/cmpe436/hw2/bin/BinarySemaphore.class
new file mode 100644
index 0000000..67e51e0
Binary files /dev/null and b/cmpe436/hw2/bin/BinarySemaphore.class differ
diff --git a/cmpe436/hw2/bin/CellThread.class b/cmpe436/hw2/bin/CellThread.class
new file mode 100644
index 0000000..593bab0
Binary files /dev/null and b/cmpe436/hw2/bin/CellThread.class differ
diff --git a/cmpe436/hw2/bin/CountingSemaphore.class b/cmpe436/hw2/bin/CountingSemaphore.class
new file mode 100644
index 0000000..70886e6
Binary files /dev/null and b/cmpe436/hw2/bin/CountingSemaphore.class differ
diff --git a/cmpe436/hw2/bin/Philosopher.class b/cmpe436/hw2/bin/Philosopher.class
new file mode 100644
index 0000000..5968d6b
Binary files /dev/null and b/cmpe436/hw2/bin/Philosopher.class differ
diff --git a/cmpe436/hw2/bin/Population.class b/cmpe436/hw2/bin/Population.class
new file mode 100644
index 0000000..b8c9a94
Binary files /dev/null and b/cmpe436/hw2/bin/Population.class differ
diff --git a/cmpe436/hw2/bin/Question1.class b/cmpe436/hw2/bin/Question1.class
new file mode 100644
index 0000000..1b614b6
Binary files /dev/null and b/cmpe436/hw2/bin/Question1.class differ
diff --git a/cmpe436/hw2/bin/Question2.class b/cmpe436/hw2/bin/Question2.class
new file mode 100644
index 0000000..f834f14
Binary files /dev/null and b/cmpe436/hw2/bin/Question2.class differ
diff --git a/cmpe436/hw2/bin/Question3.class b/cmpe436/hw2/bin/Question3.class
new file mode 100644
index 0000000..489035d
Binary files /dev/null and b/cmpe436/hw2/bin/Question3.class differ
diff --git a/cmpe436/hw2/bin/RaceThread.class b/cmpe436/hw2/bin/RaceThread.class
new file mode 100644
index 0000000..4a047dc
Binary files /dev/null and b/cmpe436/hw2/bin/RaceThread.class differ
diff --git a/cmpe436/hw2/cmpe436_hw2.iml b/cmpe436/hw2/cmpe436_hw2.iml
new file mode 100644
index 0000000..7b6b5d8
--- /dev/null
+++ b/cmpe436/hw2/cmpe436_hw2.iml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/hw2/hw2.pdf b/cmpe436/hw2/hw2.pdf
new file mode 100644
index 0000000..0bbd4c7
Binary files /dev/null and b/cmpe436/hw2/hw2.pdf differ
diff --git a/cmpe436/hw2/population.txt b/cmpe436/hw2/population.txt
new file mode 100644
index 0000000..b9d1e5c
--- /dev/null
+++ b/cmpe436/hw2/population.txt
@@ -0,0 +1,5 @@
+0 0 0 0 0
+0 0 1 0 0
+0 0 1 0 0
+0 0 1 0 0
+0 0 0 0 0
\ No newline at end of file
diff --git a/cmpe436/hw2/src/BinarySemaphore.java b/cmpe436/hw2/src/BinarySemaphore.java
new file mode 100644
index 0000000..8dfd3b1
--- /dev/null
+++ b/cmpe436/hw2/src/BinarySemaphore.java
@@ -0,0 +1,13 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+
+/**
+ * Implementation of binary semaphore based on counting semaphore
+ */
+public class BinarySemaphore extends CountingSemaphore {
+ public BinarySemaphore() {
+ super(1);
+ }
+}
diff --git a/cmpe436/hw2/src/CellThread.java b/cmpe436/hw2/src/CellThread.java
new file mode 100644
index 0000000..cb35ccf
--- /dev/null
+++ b/cmpe436/hw2/src/CellThread.java
@@ -0,0 +1,120 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+// Question 1
+
+/**
+ * Represents thread of cell
+ */
+public class CellThread extends Thread {
+ /**
+ * The population that cell is belongs
+ */
+ Population population;
+
+ /**
+ * Coordinates and value of cell
+ */
+ private int i, j, value;
+
+
+ /**
+ * Constructs cell thread object with given coordinates and population
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @param population that cell is belongs
+ */
+ public CellThread(int i, int j, Population population) {
+ this.i = i;
+ this.j = j;
+ this.population = population;
+ }
+
+
+ /**
+ * Operates cell thread with barrier synchronization
+ */
+ @Override
+ public void run() {
+ // Run thread until the last generation
+ for (int generation = 0; generation < population.getMaxGeneration(); generation++) {
+ // Thread reserve ticket for this generation
+ population.generationThreads.P();
+
+ // Just one thread calculate next value at a time
+ // Enter critical session for calculating next value
+ population.mutex.P();
+ population.calculatedCellCount++;
+ int next = getNextValue();
+
+ // Release barrier if all threads calculated next
+ if (population.calculatedCellCount == population.getSize()) {
+ population.barrier.V();
+ }
+
+ // Exit critical session
+ population.mutex.V();
+
+ // If all threads are not calculate next value, put barrier to thread
+ population.barrier.P();
+
+ // Enter critical session for changing next value
+ population.mutex.P();
+
+ population.calculatedCellCount--;
+ this.value = next;
+
+ // Exit critical session
+ population.mutex.V();
+
+ // If all threads are not change next value, put barrier to thread
+ population.barrier.V();
+
+ // If all cell are calculated, jump to next generation
+ // Release barrier if all threads changes next value
+ if (population.calculatedCellCount == 0) {
+ // Print current generation
+ System.out.printf("%d. Generation\n", generation + 1);
+ population.print();
+
+ // Release barrier for threads to jump next generation
+ population.barrier.P();
+
+ // Release all tickets for next cycle.
+ for (int j = 0; j < population.getSize(); j++) {
+ population.generationThreads.V();
+ }
+ }
+ }
+ }
+
+ /**
+ * Changes value of cell
+ *
+ * @param value new value of cell
+ */
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ /**
+ * Return value of cell
+ *
+ * @return value of cell
+ */
+ public int getValue() {
+ return this.value;
+ }
+
+ /**
+ * Calculates next value of current cell
+ *
+ * @return next value of thread
+ */
+
+ private int getNextValue() {
+ return population.getNextValue(i, j, value);
+ }
+}
diff --git a/cmpe436/hw2/src/CountingSemaphore.java b/cmpe436/hw2/src/CountingSemaphore.java
new file mode 100644
index 0000000..5174e19
--- /dev/null
+++ b/cmpe436/hw2/src/CountingSemaphore.java
@@ -0,0 +1,41 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+
+/**
+ * Implementation of counting semaphore
+ */
+public class CountingSemaphore {
+ int value;
+
+ public CountingSemaphore(int initValue) {
+ this.value = initValue;
+ }
+
+ // Takes resource
+ public synchronized void P() {
+ while (this.value == 0)
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ }
+ this.value--;
+ }
+
+ // Releases resource
+ public synchronized void V() {
+ this.value++;
+ notify();
+ }
+
+ /**
+ * Returns available resource count
+ *
+ * @return Available resource count
+ */
+ public synchronized int getValue() {
+ return value;
+ }
+}
+
diff --git a/cmpe436/hw2/src/Philosopher.java b/cmpe436/hw2/src/Philosopher.java
new file mode 100644
index 0000000..2551a0b
--- /dev/null
+++ b/cmpe436/hw2/src/Philosopher.java
@@ -0,0 +1,64 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+// Question 2
+
+/**
+ * Represents philosopher for deadlock example
+ */
+public class Philosopher extends Thread {
+
+ /**
+ * Shared forks between philosophers
+ */
+ static BinarySemaphore[] forks;
+
+ /**
+ * Position of philosopher
+ */
+ int id;
+
+ /**
+ * Name of philosopher
+ */
+ String name;
+
+ /**
+ * Constructs new philosopher
+ *
+ * @param id Position of philosopher
+ * @param name Name of philosopher
+ */
+ public Philosopher(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ @Override
+ public void run() {
+ // Start process
+ System.out.println(name + " is thinking.");
+ System.out.println(name + " is hungry now.");
+
+ // Take one resourse
+ Philosopher.forks[id].P();
+ System.out.println(name + " took left fork.");
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+
+ }
+ // Try to take other resource. It already took by other philosopher
+ // DEADLOCK
+ Philosopher.forks[(id + 1) % forks.length].P();
+ System.out.println(name + " took right fork.");
+
+ System.out.println(name + " is eating.");
+
+ Philosopher.forks[id].V();
+ System.out.println(name + " put left fork.");
+ Philosopher.forks[(id + 1) % forks.length].V();
+ System.out.println(name + " put right fork.");
+ }
+}
diff --git a/cmpe436/hw2/src/Population.java b/cmpe436/hw2/src/Population.java
new file mode 100644
index 0000000..feed47a
--- /dev/null
+++ b/cmpe436/hw2/src/Population.java
@@ -0,0 +1,299 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 1
+// Question 2
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.Scanner;
+import java.util.Random;
+
+/**
+ * Encapsulation for game of life's population
+ * Data matrix has 2 more rows and columns.
+ * Outer line is always zero. It's for neighbor calculation of borders.
+ */
+public class Population {
+ /**
+ * Keeps threads in matrix
+ */
+ private CellThread[][] data;
+
+ /**
+ * Maximum number of last generation
+ */
+ private int maxGeneration;
+
+ /**
+ * Semaphores for synchronization barriers
+ */
+ int calculatedCellCount = 0;
+ /**
+ * Semaphore for critical section
+ */
+ CountingSemaphore mutex;
+ /**
+ * Semaphore for waiting all threads to calculate
+ */
+ CountingSemaphore barrier;
+ /**
+ * Semaphore for waiting all threads to finish generation
+ */
+ CountingSemaphore generationThreads;
+
+ /**
+ * Constructs empty matrix object thread with given sizes
+ *
+ * @param rows number of the rows
+ * @param columns number of the columns
+ * @param maxGeneration number of the max generations
+ */
+ public Population(int rows, int columns, int maxGeneration) {
+ if (rows <= 0 || columns <= 0) {
+ abort("Dimensions of the matrix have to be positive");
+ }
+ this.data = new CellThread[rows + 2][columns + 2];
+ for (int i = 0; i < this.getNumberOfRows() + 2; i++) {
+ for (int j = 0; j < this.getNumberOfColumns() + 2; j++) {
+ // Threads don't know about border empty cells. So we subtract 1.
+ data[i][j] = new CellThread(i - 1, j - 1, this);
+ }
+ }
+ this.setMaxGeneration(maxGeneration);
+ }
+
+ /**
+ * Imports population from file
+ *
+ * @param filename data file for initial population
+ */
+ public void importPopulation(String filename) {
+ Scanner scanner = this.openFile(filename);
+ this.readData(scanner);
+ scanner.close();
+ }
+
+ /**
+ * Converts file to scanner
+ *
+ * @param filename Name of the file that opened
+ * @return opened file
+ */
+ public Scanner openFile(String filename) {
+ File file = new File(filename);
+ Scanner scanner = null;
+
+ try {
+ scanner = new Scanner(file);
+ } catch (FileNotFoundException e) {
+ abort("File " + filename + " not found.");
+ }
+ return scanner;
+ }
+
+ /**
+ * Read data part of the matrix
+ *
+ * @param scanner opened file
+ */
+ public void readData(Scanner scanner) {
+ for (int i = 0; i < getNumberOfRows(); i++) {
+ for (int j = 0; j < getNumberOfColumns(); j++) {
+ try {
+ this.setElement(i, j, scanner.nextInt());
+ } catch (Exception e) {
+ abort("Error at element [" + i + ", " + j + "]. \n Please make sure all elements are integers.");
+ }
+ }
+ }
+ }
+
+ /**
+ * Generates random population
+ */
+ public void generateRandom() {
+ Random random = new Random();
+ for (int i = 0; i < this.getNumberOfRows(); i++) {
+ for (int j = 0; j < this.getNumberOfColumns(); j++) {
+ this.setElement(i, j, random.nextInt(2));
+ }
+ }
+ }
+
+
+ /**
+ * Runs population until max generation
+ */
+ public void run() {
+ System.out.println("Initial Population");
+ this.print();
+
+ // Initialize common resource for synchronization
+ calculatedCellCount = 0;
+ mutex = new CountingSemaphore(1);
+ barrier = new CountingSemaphore(0);
+ generationThreads = new CountingSemaphore(this.getSize());
+
+ // Start all threads
+ for (int i = 0; i < this.getNumberOfRows(); i++) {
+ for (int j = 0; j < this.getNumberOfColumns(); j++) {
+ this.data[i + 1][j + 1].start();
+ }
+ }
+ }
+
+ /**
+ * Converts matrix to string
+ * It deletes first line, because it has dimension information
+ *
+ * @return string representation of matrix
+ */
+ @Override // Inherited from the Object class.
+ public String toString() {
+ StringBuilder result = new StringBuilder();
+ for (int i = 0; i < this.getNumberOfRows(); i++) {
+ for (int j = 0; j < this.getNumberOfColumns(); j++) {
+ result.append(this.getElement(i, j) + " ");
+ }
+ result.append("\n");
+ }
+
+ return result.toString();
+ }
+
+ /**
+ * Prints matrix to console
+ */
+ public void print() {
+ System.out.println(this);
+ }
+
+ /**
+ * Calculates next value of given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @return next of element
+ */
+ public int getNextValue(int i, int j, int value) {
+ int neighborCount = getNeighborCount(i, j);
+ if (value == 1) {
+ return (neighborCount == 2 || neighborCount == 3) ? 1 : 0;
+ }
+
+ return (neighborCount == 3) ? 1 : 0;
+ }
+
+ /**
+ * Counts neighbors of given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @return count of neighbors
+ */
+ public int getNeighborCount(int i, int j) {
+ return this.getElement(i - 1, j - 1) + this.getElement(i - 1, j) + this.getElement(i - 1, j + 1) +
+ this.getElement(i, j - 1) + this.getElement(i, j + 1) +
+ this.getElement(i + 1, j - 1) + this.getElement(i + 1, j) + this.getElement(i + 1, j + 1);
+ }
+
+ /**
+ * Returns number of the rows. Subtracts 2 because of empty outer area.
+ *
+ * @return number of the rows
+ */
+ public int getNumberOfRows() {
+ return this.data.length - 2;
+ }
+
+ /**
+ * Returns number of the columns. Subtracts 2 because of empty outer area.
+ *
+ * @return number of the columns
+ */
+ public int getNumberOfColumns() {
+ return this.data[0].length - 2;
+ }
+
+ /**
+ * Returns element at given coordinates. Adds 1 because of empty outer area
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @return element at given coordinates
+ */
+ public int getElement(int i, int j) {
+ return this.data[i + 1][j + 1].getValue();
+ }
+
+ /**
+ * Changes element at given coordinates
+ *
+ * @param i row number of position
+ * @param j column number of position
+ * @param element data to put position
+ */
+ public void setElement(int i, int j, int element) {
+ if (element != 0 && element != 1) {
+ abort("Cell number have to be 1 or 0.");
+ }
+
+ this.data[i + 1][j + 1].setValue(element);
+
+ }
+
+ /**
+ * Changes max generation of population
+ *
+ * @param value new value of max generation
+ */
+ public void setMaxGeneration(int value) {
+ if (value <= 0) {
+ abort("Max generation number must be an positive integer.");
+ }
+ this.maxGeneration = value;
+ }
+
+ public int getMaxGeneration() {
+ return this.maxGeneration;
+ }
+
+ /**
+ * Returns data array of matrix
+ *
+ * @return two dimension array version of matrix
+ */
+ public CellThread[][] getData() {
+ return this.data;
+ }
+
+ /**
+ * Changes whole data of matrix
+ *
+ * @param data new data for matrix
+ */
+ public void setData(CellThread[][] data) {
+ this.data = data;
+ }
+
+ /**
+ * Returns number of cells
+ *
+ * @return number of cells
+ */
+ public int getSize() {
+ return this.getNumberOfRows() * this.getNumberOfColumns();
+ }
+
+ /**
+ * Aborts application with messages
+ *
+ * @param message error message for aborting
+ */
+ public void abort(String message) {
+ System.out.println(message);
+ System.exit(0);
+ }
+
+}
\ No newline at end of file
diff --git a/cmpe436/hw2/src/Question1.java b/cmpe436/hw2/src/Question1.java
new file mode 100644
index 0000000..6d79a41
--- /dev/null
+++ b/cmpe436/hw2/src/Question1.java
@@ -0,0 +1,45 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+// Question 1
+
+/**
+ * Solutions for Question 1
+ */
+public class Question1 {
+
+ public static void main(String[] args) {
+ // Check arguments
+ if (args.length < 3) {
+ System.out.println("\nYou have to give at least 3 arguments but given " + args.length + " arguments.");
+ System.out.println("Example usage:");
+ System.out.println("\tjava Question1 [NUMBER_OF_ROWS] [NUMBER_OF_COLUMNS] [MAX_GENERATIONS] [INITIAL_POPULATION]?");
+ System.exit(0);
+ }
+
+ try {
+ // Parse arguments
+ int numberOfRows = Integer.parseInt(args[0]);
+ int numberOfColumns = Integer.parseInt(args[1]);
+ int maxGeneration = Integer.parseInt(args[2]);
+
+ // Construct population
+ Population population = new Population(numberOfRows, numberOfColumns, maxGeneration);
+
+ if (args.length == 4) {
+ // Import initial population
+ population.importPopulation(args[3]);
+ } else {
+ // Generate random inital population
+ population.generateRandom();
+ }
+
+ // Run population
+ population.run();
+
+ } catch (Exception e) {
+ System.out.println("Matrix dimensions and max generation must be positive numbers.");
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw2/src/Question2.java b/cmpe436/hw2/src/Question2.java
new file mode 100644
index 0000000..1120790
--- /dev/null
+++ b/cmpe436/hw2/src/Question2.java
@@ -0,0 +1,32 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+// Question 2
+
+/**
+ * Solutions for Question 2
+ */
+
+public class Question2 {
+ public static final int NUMBER_OF_PHILOSOPHERS = 3;
+ public static final String[] PHILOSOPHERS_NAMES = {"Aristotle", "Plato", "Sun Tzu", "Confucius", "Descartes", "Descartes"};
+
+ public static void main(String[] args) {
+
+ Philosopher.forks = new BinarySemaphore[NUMBER_OF_PHILOSOPHERS];
+
+ for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
+ Philosopher.forks[i] = new BinarySemaphore();
+
+ Philosopher[] philosophers = new Philosopher[NUMBER_OF_PHILOSOPHERS];
+
+ for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
+ philosophers[i] = new Philosopher(i, PHILOSOPHERS_NAMES[i]);
+
+ for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
+ philosophers[i].start();
+
+ // All philosophers are locked
+ }
+}
diff --git a/cmpe436/hw2/src/Question3.java b/cmpe436/hw2/src/Question3.java
new file mode 100644
index 0000000..5114b09
--- /dev/null
+++ b/cmpe436/hw2/src/Question3.java
@@ -0,0 +1,42 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+// Question 3
+
+/**
+ * Solutions for Question 3
+ */
+public class Question3 {
+ public static final int NUMBER_OF_THREADS= 3;
+
+ public static void main(String[] args) {
+
+ // Create thread to race
+ RaceThread[] threads = new RaceThread[NUMBER_OF_THREADS];
+
+ // It's type is array, because it passed by reference not by value.
+ int[] commonValue = new int[1];
+
+ // Constructs threads
+ for (int i = 0; i < NUMBER_OF_THREADS; i++)
+ threads[i] = new RaceThread(i, commonValue);
+
+ // Start all threads
+ for (int i = 0; i < NUMBER_OF_THREADS; i++)
+ threads[i].start();
+
+ // All threads to be done
+ for (Thread thread : threads) {
+ try {
+ thread.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // Expected result is NUMBER_OF_THREADS * 10
+ // But 20 is printed
+ System.out.println(commonValue[0]);
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw2/src/RaceThread.java b/cmpe436/hw2/src/RaceThread.java
new file mode 100644
index 0000000..cc594d7
--- /dev/null
+++ b/cmpe436/hw2/src/RaceThread.java
@@ -0,0 +1,56 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 2
+// Question 3
+
+import java.util.Random;
+
+/**
+ * Threads that are racing
+ */
+public class RaceThread extends Thread {
+
+ /**
+ * Index of thread
+ */
+ int id;
+
+ /**
+ * Shared resources between threads
+ */
+ int[] commonValue;
+
+ /**
+ * Constructs new racer thread
+ *
+ * @param id Position of thread
+ * @param commonValue Shared resources between threads
+ */
+ RaceThread(int id, int[] commonValue) {
+ this.id = id;
+ this.commonValue = commonValue;
+ }
+
+ @Override
+ public void run() {
+ // Wait to get resource
+ threadWait();
+ // Get shared resource to temporary variable and wait for writing back common resource
+ int tmp = this.commonValue[0];
+ threadWait();
+ tmp += 10;
+ this.commonValue[0] = tmp;
+ }
+
+ /**
+ * Calculates waiting time for thread based on their id
+ */
+ public void threadWait() {
+ try {
+ Thread.sleep(10 / (id + 1));
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw3/README.md b/cmpe436/hw3/README.md
new file mode 100644
index 0000000..220ec13
--- /dev/null
+++ b/cmpe436/hw3/README.md
@@ -0,0 +1,38 @@
+## Question 1
+### Lockset Algorithm
+The lockset-based detectors never produces false negatives.
+They never miss a real race. So I couldn't find an example that data race is missed.
+But it may produce many false positives.
+`Lockset.java` shows a potential race that can be found by Lockset based race detection algorithm.
+Two thread overwrite same variable. Final value should be 6000, but it's not sometimes.
+
+To run Road Runner use this pattern:
+`javac Lockset.java && rrrun -quiet -tool=TL:RS:LS Lockset`
+
+### Happens-Before Algorithm
+`HappensBeforeThread` has a shared variable and counting semaphore.
+Not detectable version use counting semaphore to protect variable. But it has 2 resource.
+We don't know which thread will get resource. But it protected somehow. Happens before algorithm not detect it.
+`HappensBeforeNotDetect.java` class shows it.
+
+Detectable version is not using any lock. Algorithm detects it.
+`HappensBeforeDetect.java` class shows it.
+
+To run Road Runner use this pattern:
+`javac HappensBeforeDetect.java && rrrun -quiet -tool=FT2 HappensBeforeDetect`
+
+## Question 2
+`question2.pml` file contains solutions for Question 2.
+
+Promela has LTL unary operators
+[] the temporal operator always
+<> the temporal operator eventually
+! the boolean operator for negation
+
+Last part of code has 3 different LTL formulas for Question 2.
+`ltl mutex { [] !(cs[0] && cs[1]) }`
+`ltl unbounded_overtaking { (<> cs[0]) && (<> cs[1]) }`
+`ltl infinitely_often { ([]<> cs[0]) && ([]<> cs[1]) }`
+
+### Question 3
+`Question3_a.jpg` and `Question3_b.jpg` show answers.
\ No newline at end of file
diff --git a/cmpe436/hw3/question1/CountingSemaphore.java b/cmpe436/hw3/question1/CountingSemaphore.java
new file mode 100644
index 0000000..d95b1e2
--- /dev/null
+++ b/cmpe436/hw3/question1/CountingSemaphore.java
@@ -0,0 +1,41 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 3
+
+/**
+ * Implementation of counting semaphore
+ */
+public class CountingSemaphore {
+ int value;
+
+ public CountingSemaphore(int initValue) {
+ this.value = initValue;
+ }
+
+ // Takes resource
+ public synchronized void P() {
+ while (this.value == 0)
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ }
+ this.value--;
+ }
+
+ // Releases resource
+ public synchronized void V() {
+ this.value++;
+ notify();
+ }
+
+ /**
+ * Returns available resource count
+ *
+ * @return Available resource count
+ */
+ public synchronized int getValue() {
+ return value;
+ }
+}
+
diff --git a/cmpe436/hw3/question1/HappensBeforeDetect.java b/cmpe436/hw3/question1/HappensBeforeDetect.java
new file mode 100644
index 0000000..973f74f
--- /dev/null
+++ b/cmpe436/hw3/question1/HappensBeforeDetect.java
@@ -0,0 +1,27 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 3
+
+public class HappensBeforeDetect {
+ public static void main(String args[]) {
+ HappensBeforeThread thread1 = new HappensBeforeThread(20, true);
+ HappensBeforeThread thread2 = new HappensBeforeThread(25, true);
+ HappensBeforeThread thread3 = new HappensBeforeThread(30, true);
+ HappensBeforeThread thread4 = new HappensBeforeThread(35, true);
+
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+
+ try {
+ thread1.join();
+ thread2.join();
+ thread3.join();
+ thread4.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/cmpe436/hw3/question1/HappensBeforeNotDetect.java b/cmpe436/hw3/question1/HappensBeforeNotDetect.java
new file mode 100644
index 0000000..bc381c7
--- /dev/null
+++ b/cmpe436/hw3/question1/HappensBeforeNotDetect.java
@@ -0,0 +1,27 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 3
+
+public class HappensBeforeNotDetect {
+ public static void main(String args[]) {
+ HappensBeforeThread thread1 = new HappensBeforeThread(200, false);
+ HappensBeforeThread thread2 = new HappensBeforeThread(180, false);
+ HappensBeforeThread thread3 = new HappensBeforeThread(160, false);
+ HappensBeforeThread thread4 = new HappensBeforeThread(140, false);
+
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+
+ try {
+ thread1.join();
+ thread2.join();
+ thread3.join();
+ thread4.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/cmpe436/hw3/question1/HappensBeforeThread.java b/cmpe436/hw3/question1/HappensBeforeThread.java
new file mode 100644
index 0000000..2249124
--- /dev/null
+++ b/cmpe436/hw3/question1/HappensBeforeThread.java
@@ -0,0 +1,41 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 3
+
+public class HappensBeforeThread extends Thread {
+ static int[] sharedVariable = {0};
+ static CountingSemaphore semaphore = new CountingSemaphore(2);
+
+ int newValue;
+ // If it's true, it not use lock
+ // If it's false, it use lock
+ boolean isDetectable;
+
+ public HappensBeforeThread(int value, boolean isDetectable) {
+ this.newValue = value;
+ this.isDetectable = isDetectable;
+ }
+
+ @Override
+ public void run() {
+ threadWait();
+ if (isDetectable) {
+ sharedVariable[0] = newValue;
+ } else {
+ semaphore.P();
+ sharedVariable[0] = newValue;
+ semaphore.V();
+ }
+ System.out.println("New value: " + newValue);
+ }
+
+ public void threadWait() {
+ try {
+ Thread.sleep(10 / (newValue + 1));
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/cmpe436/hw3/question1/Lockset.java b/cmpe436/hw3/question1/Lockset.java
new file mode 100644
index 0000000..0f6a469
--- /dev/null
+++ b/cmpe436/hw3/question1/Lockset.java
@@ -0,0 +1,22 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 3
+
+public class Lockset {
+ public static void main(String args[]) {
+ LocksetThread thread1 = new LocksetThread();
+ LocksetThread thread2 = new LocksetThread();
+
+ thread1.start();
+ thread2.start();
+
+ try {
+ thread1.join();
+ thread2.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ System.out.println(LocksetThread.sharedVariable[0]);
+ }
+}
diff --git a/cmpe436/hw3/question1/LocksetThread.java b/cmpe436/hw3/question1/LocksetThread.java
new file mode 100644
index 0000000..891226f
--- /dev/null
+++ b/cmpe436/hw3/question1/LocksetThread.java
@@ -0,0 +1,15 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 3
+
+public class LocksetThread extends Thread {
+ static int[] sharedVariable = {0};
+
+ @Override
+ public void run() {
+ for (int i = 0; i < 3000; i++) {
+ sharedVariable[0] += 1;
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw3/question2/question2.pml b/cmpe436/hw3/question2/question2.pml
new file mode 100644
index 0000000..4f7c1fd
--- /dev/null
+++ b/cmpe436/hw3/question2/question2.pml
@@ -0,0 +1,48 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 3
+
+#define NUMBER_OF_PROCESS 2
+
+bool s = true; // Shared variable
+bit y[NUMBER_OF_PROCESS]; // local variable
+bit cs[NUMBER_OF_PROCESS]; // critical sections
+
+active proctype P(bit i) {
+ do
+ ::
+ // non-cs section
+ atomic {
+ y[i] = 1;
+ s = i;
+ }
+
+ // wait until
+ (y[1-i] == 0 || s != 0);
+
+ // cs section
+ cs[i] = 1;
+ y[i] = 0;
+ cs[i] = 0;
+ od
+}
+
+init {
+ int i;
+ for (i : 1 .. NUMBER_OF_PROCESS) {
+ run P(i);
+ }
+}
+
+// Q2.a
+// Mutual Exclusion
+ltl mutex { [] !(cs[0] && cs[1]) }
+
+// Q2.b
+// Ensures absence of unbounded overtaking
+ltl unbounded_overtaking { (<> cs[0]) && (<> cs[1]) }
+
+// Q2.c
+// Occupy its critical section infinitely often.
+ltl infinitely_often { ([]<> cs[0]) && ([]<> cs[1]) }
diff --git a/cmpe436/hw3/question3/question3_a.jpg b/cmpe436/hw3/question3/question3_a.jpg
new file mode 100644
index 0000000..95f7758
Binary files /dev/null and b/cmpe436/hw3/question3/question3_a.jpg differ
diff --git a/cmpe436/hw3/question3/question3_b.jpg b/cmpe436/hw3/question3/question3_b.jpg
new file mode 100644
index 0000000..9614270
Binary files /dev/null and b/cmpe436/hw3/question3/question3_b.jpg differ
diff --git a/cmpe436/hw4/README.txt b/cmpe436/hw4/README.txt
new file mode 100644
index 0000000..4454854
--- /dev/null
+++ b/cmpe436/hw4/README.txt
@@ -0,0 +1,30 @@
+Mustafa Enes Çakır
+2013400105
+enes@cakir.web.tr
+CmpE436 Assignment 4
+
+Source code of project is "src" folder.
+
+# Problem 6.1
+ Base code comes from book. I improved main method of NameServer class for fault-tolerant.
+ Name server is chosen randomly.
+ handleClient() method throws errors randomly.
+ If the server is down, other name server handle client and broken name server is restarted with current name table.
+ Entry point of server is main method of NameServer class.
+ To start server, nameServer constant in Problem61.Symbols class have to be your local IP.
+
+ You can use NameClient class for sending requests.
+ Example usage:
+ `java NameClient insert [NAME] [HOSTNAME] [PORT]`
+ `java NameClient search [NAME]`
+
+ Terminal usage:
+ `java -classpath . Problem61.NameClient insert google google.com 1000`
+
+# Problem 6.3
+ Connector, IntLinkedList, Linker, Msg and Topology classes are from book.
+ I developed SynchronousLinker that is extended from Linker class.
+ I override receiveMsg and sendMsg methods.
+ SynchronousLinker has an BinarySemaphore.
+ receiveMsg method sends message that has `done` tag to sender when receiving is done.
+ When sendMsg get done message, it unblocked.
\ No newline at end of file
diff --git a/cmpe436/hw4/bin/Problem61/NameClient.class b/cmpe436/hw4/bin/Problem61/NameClient.class
new file mode 100644
index 0000000..ce74520
Binary files /dev/null and b/cmpe436/hw4/bin/Problem61/NameClient.class differ
diff --git a/cmpe436/hw4/bin/Problem61/NameServer.class b/cmpe436/hw4/bin/Problem61/NameServer.class
new file mode 100644
index 0000000..d5ad41c
Binary files /dev/null and b/cmpe436/hw4/bin/Problem61/NameServer.class differ
diff --git a/cmpe436/hw4/bin/Problem61/NameTable.class b/cmpe436/hw4/bin/Problem61/NameTable.class
new file mode 100644
index 0000000..3b9e7e9
Binary files /dev/null and b/cmpe436/hw4/bin/Problem61/NameTable.class differ
diff --git a/cmpe436/hw4/bin/Problem61/Symbols.class b/cmpe436/hw4/bin/Problem61/Symbols.class
new file mode 100644
index 0000000..e91ee34
Binary files /dev/null and b/cmpe436/hw4/bin/Problem61/Symbols.class differ
diff --git a/cmpe436/hw4/hw4.iml b/cmpe436/hw4/hw4.iml
new file mode 100644
index 0000000..7b06c02
--- /dev/null
+++ b/cmpe436/hw4/hw4.iml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem61/NameClient.java b/cmpe436/hw4/src/Problem61/NameClient.java
new file mode 100644
index 0000000..90691be
--- /dev/null
+++ b/cmpe436/hw4/src/Problem61/NameClient.java
@@ -0,0 +1,78 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem61;
+
+import java.util.*;
+import java.net.*;
+import java.io.*;
+
+public class NameClient {
+ Scanner din;
+ PrintStream pout;
+ Socket server;
+
+ public void getSocket() throws IOException {
+ server = new Socket(Symbols.nameServer, Symbols.ServerPort);
+ din = new Scanner(server.getInputStream());
+ pout = new PrintStream(server.getOutputStream());
+ }
+
+ public int insertName(String name, String hname, int portnum)
+ throws IOException {
+ getSocket();
+ pout.println("insert " + name + " " + hname + " " + portnum);
+ pout.flush();
+ int retValue = din.nextInt();
+ server.close();
+ return retValue;
+ }
+
+ public InetSocketAddress searchName(String name, boolean isBlocking) throws IOException {
+ getSocket();
+ if (isBlocking)
+ pout.println("blockingFind " + name);
+ else
+ pout.println("search " + name);
+ pout.flush();
+ String result = din.nextLine();
+ System.out.println("NameServer returned: " + result);
+ Scanner sc = new Scanner(result);
+ server.close();
+ int portnum = sc.nextInt();
+ String hname = sc.next();
+ if (portnum == 0)
+ return null;
+ else
+ return new InetSocketAddress(hname, portnum);
+ }
+
+ public void clear() throws IOException {
+ getSocket();
+ pout.println("clear ");
+ pout.flush();
+ server.close();
+ }
+
+ public static void main(String[] args) {
+ if (args.length < 2 || (args[0].equals("insert") && args.length < 4)) {
+ System.out.println("Example usage: ");
+ System.out.println("java NameClient insert [NAME] [HOSTNAME] [PORT]");
+ System.out.println("java NameClient search [NAME]");
+ return;
+ }
+ NameClient client = new NameClient();
+
+ try {
+ if (args[0].equals("insert")) {
+ client.insertName(args[1], args[2], Integer.parseInt(args[3]));
+ } else if (args[0].equals("search")) {
+ InetSocketAddress pa = client.searchName(args[1], false);
+ }
+ } catch (Exception e) {
+ System.err.println("Server aborted: " + e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem61/NameServer.java b/cmpe436/hw4/src/Problem61/NameServer.java
new file mode 100644
index 0000000..71c885e
--- /dev/null
+++ b/cmpe436/hw4/src/Problem61/NameServer.java
@@ -0,0 +1,107 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem61;
+
+import java.net.*;
+import java.io.*;
+import java.util.*;
+
+public class NameServer {
+ NameTable table;
+
+ public NameServer() {
+ table = new NameTable();
+ }
+
+ /**
+ * Starts new name server with current table
+ *
+ * @param table Synchronized table
+ */
+ public NameServer(NameTable table) {
+ this.table = table;
+ }
+
+ /**
+ * Handles client connection
+ * It throws exception with %10 percentage for simulating name server downfall
+ *
+ * @param theClient socket that connection come from
+ * @param secondNameServer insert new names to other name server
+ * @param downable we assume at most one server goes down, second server is not downable
+ * @throws Exception server is down
+ */
+ private void handleClient(Socket theClient, NameServer secondNameServer, boolean downable) throws Exception {
+ // Simulate name server downfall
+ if (downable && new Random().nextInt(10) == 0) {
+ throw new Exception("Name server is down");
+ }
+
+ try {
+ BufferedReader din = new BufferedReader
+ (new InputStreamReader(theClient.getInputStream()));
+ PrintWriter pout = new PrintWriter(theClient.getOutputStream());
+ String getline = din.readLine();
+ System.out.println(getline);
+ StringTokenizer st = new StringTokenizer(getline);
+ String tag = st.nextToken();
+ if (tag.equals("search")) {
+ int index = table.search(st.nextToken());
+ if (index == -1) // not found
+ pout.println(-1 + " " + "nullhost");
+ else
+ pout.println(table.getPort(index) + " " + table.getHostName(index));
+ } else if (tag.equals("insert")) {
+ String name = st.nextToken();
+ String hostName = st.nextToken();
+ int port = Integer.parseInt(st.nextToken());
+ int retValue = table.insert(name, hostName, port);
+ // Add new hostname to other name server
+ secondNameServer.table.insert(name, hostName, port);
+ pout.println(retValue);
+ }
+ pout.flush();
+ } catch (IOException e) {
+ System.err.println(e);
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ // Starts two new name server
+ NameServer[] nameServers = new NameServer[2];
+ nameServers[0] = new NameServer();
+ nameServers[1] = new NameServer();
+
+ System.out.println("Name servers listening on " + Symbols.nameServer + ":" + Symbols.ServerPort);
+
+ try {
+ ServerSocket listener = new ServerSocket(Symbols.ServerPort);
+ while (true) {
+ Socket socket = listener.accept();
+ // Choose name server randomly
+ int selected = new Random().nextInt(2);
+ int other = 1 - selected;
+ System.out.println("[SELECT] NS " + (selected + 1));
+ try {
+ // Try handle connection with selected name server
+ nameServers[selected].handleClient(socket, nameServers[other], true);
+ } catch (Exception e) {
+ System.out.println("[DOWN] NS " + (selected + 1));
+ System.out.println("[CONNECT] NS " + (other + 1));
+
+ nameServers[other].handleClient(socket, nameServers[selected], false);
+
+ // Restart failed name server 1
+ System.out.println("[RESTART] NS " + (selected + 1));
+ nameServers[selected] = new NameServer(new NameTable(nameServers[other].table));
+ }
+ socket.close();
+ }
+ } catch (IOException e) {
+ System.err.println("Server aborted: " + e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem61/NameTable.java b/cmpe436/hw4/src/Problem61/NameTable.java
new file mode 100644
index 0000000..ae9bab3
--- /dev/null
+++ b/cmpe436/hw4/src/Problem61/NameTable.java
@@ -0,0 +1,54 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem61;
+
+import java.util.Arrays;
+
+public class NameTable {
+ final int maxSize = 100;
+ public String[] names = new String[maxSize];
+ public String[] hosts = new String[maxSize];
+ public int[] ports = new int[maxSize];
+ public int dirsize = 0;
+
+ NameTable() {
+
+ }
+
+ NameTable(NameTable table) {
+ names = Arrays.copyOf(table.names, table.names.length);
+ hosts = Arrays.copyOf(table.hosts, table.hosts.length);
+ ports = Arrays.copyOf(table.ports, table.ports.length);
+ dirsize = table.dirsize;
+ }
+
+ int search(String s) {
+ for (int i = 0; i < dirsize; i++)
+ if (names[i].equals(s))
+ return i;
+ return -1;
+ }
+
+ int insert(String s, String hostName, int portNumber) {
+ int oldIndex = search(s); // is it already there
+ if (oldIndex == -1) {
+ names[dirsize] = s;
+ hosts[dirsize] = hostName;
+ ports[dirsize] = portNumber;
+ dirsize++;
+ return 1;
+ } else
+ return 0;
+ }
+
+ int getPort(int index) {
+ return ports[index];
+ }
+
+ String getHostName(int index) {
+ return hosts[index];
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem61/Symbols.java b/cmpe436/hw4/src/Problem61/Symbols.java
new file mode 100644
index 0000000..629c83e
--- /dev/null
+++ b/cmpe436/hw4/src/Problem61/Symbols.java
@@ -0,0 +1,10 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+package Problem61;
+
+public class Symbols {
+ public static final String nameServer = "192.168.1.108";
+ public static final int ServerPort = 7033;
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem63/Connector.java b/cmpe436/hw4/src/Problem63/Connector.java
new file mode 100644
index 0000000..9de42bc
--- /dev/null
+++ b/cmpe436/hw4/src/Problem63/Connector.java
@@ -0,0 +1,73 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem63;
+
+import Problem61.*;
+
+import java.util.*;
+import java.net.*;
+import java.io.*;
+
+public class Connector {
+ ServerSocket listener;
+ Socket[] link;
+
+ public void Connect(String basename, int myId, int numProc, BufferedReader[] dataIn, PrintWriter[] dataOut) throws Exception {
+ NameClient myNameclient = new NameClient();
+ link = new Socket[numProc];
+ int localport = getLocalPort(myId);
+ listener = new ServerSocket(localport);
+
+ /* register in the name server */
+ myNameclient.insertName(basename + myId, (InetAddress.getLocalHost()).getHostName(), localport);
+
+ /* accept connections from all the smaller processes */
+ for (int i = 0; i < myId; i++) {
+ Socket s = listener.accept();
+ BufferedReader dIn = new BufferedReader(
+ new InputStreamReader(s.getInputStream()));
+ String getline = dIn.readLine();
+ StringTokenizer st = new StringTokenizer(getline);
+ int hisId = Integer.parseInt(st.nextToken());
+ int destId = Integer.parseInt(st.nextToken());
+ String tag = st.nextToken();
+ if (tag.equals("hello")) {
+ link[hisId] = s;
+ dataIn[hisId] = dIn;
+ dataOut[hisId] = new PrintWriter(s.getOutputStream());
+ }
+ }
+ /* contact all the bigger processes */
+ for (int i = myId + 1; i < numProc; i++) {
+ InetSocketAddress addr;
+ do {
+ addr = myNameclient.searchName(basename + i, false);
+ Thread.sleep(100);
+ } while (addr.getPort() == -1);
+ link[i] = new Socket(addr.getHostName(), addr.getPort());
+ dataOut[i] = new PrintWriter(link[i].getOutputStream());
+ dataIn[i] = new BufferedReader(new
+ InputStreamReader(link[i].getInputStream()));
+ /* send a hello message to P_i */
+ dataOut[i].println(myId + " " + i + " " + "hello" + " " + "null");
+ dataOut[i].flush();
+ }
+ }
+
+ int getLocalPort(int id) {
+ return Symbols.ServerPort + 10 + id;
+ }
+
+ public void closeSockets() {
+ try {
+ listener.close();
+ for (int i = 0; i < link.length; i++)
+ link[i].close();
+ } catch (Exception e) {
+ System.err.println(e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem63/CountingSemaphore.java b/cmpe436/hw4/src/Problem63/CountingSemaphore.java
new file mode 100644
index 0000000..8f469e7
--- /dev/null
+++ b/cmpe436/hw4/src/Problem63/CountingSemaphore.java
@@ -0,0 +1,42 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+package Problem63;
+
+/**
+ * Implementation of counting semaphore
+ */
+public class CountingSemaphore {
+ int value;
+
+ public CountingSemaphore(int initValue) {
+ this.value = initValue;
+ }
+
+ // Takes resource
+ public synchronized void P() {
+ while (this.value == 0)
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ }
+ this.value--;
+ }
+
+ // Releases resource
+ public synchronized void V() {
+ this.value++;
+ notify();
+ }
+
+ /**
+ * Returns available resource count
+ *
+ * @return Available resource count
+ */
+ public synchronized int getValue() {
+ return value;
+ }
+}
+
diff --git a/cmpe436/hw4/src/Problem63/IntLinkedList.java b/cmpe436/hw4/src/Problem63/IntLinkedList.java
new file mode 100644
index 0000000..0ed722a
--- /dev/null
+++ b/cmpe436/hw4/src/Problem63/IntLinkedList.java
@@ -0,0 +1,32 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem63;
+
+import java.util.LinkedList;
+
+public class IntLinkedList extends LinkedList {
+ public void add(int i) {
+ super.add(new Integer(i));
+ }
+
+ public boolean contains(int i) {
+ return super.contains(new Integer(i));
+ }
+
+ public int removeHead() {
+ Integer j = (Integer) super.removeFirst();
+ return j.intValue();
+ }
+
+ public boolean removeObject(int i) {
+ return super.remove(new Integer(i));
+ }
+
+ public int getEntry(int index) {
+ Integer j = (Integer) super.get(index);
+ return j.intValue();
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem63/Linker.java b/cmpe436/hw4/src/Problem63/Linker.java
new file mode 100644
index 0000000..a6ed23d
--- /dev/null
+++ b/cmpe436/hw4/src/Problem63/Linker.java
@@ -0,0 +1,67 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem63;
+
+import java.util.*;
+import java.io.*;
+
+public class Linker {
+ PrintWriter[] dataOut;
+ BufferedReader[] dataIn;
+ BufferedReader dIn;
+ int myId, N;
+ Connector connector;
+ public IntLinkedList neighbors = new IntLinkedList();
+
+ public Linker(String basename, int id, int numProc) throws Exception {
+ myId = id;
+ N = numProc;
+ dataIn = new BufferedReader[numProc];
+ dataOut = new PrintWriter[numProc];
+ Topology.readNeighbors(myId, N, neighbors);
+ connector = new Connector();
+ connector.Connect(basename, myId, numProc, dataIn, dataOut);
+ }
+
+ public void sendMsg(int destId, String tag, String msg) {
+ dataOut[destId].println(myId + " " + destId + " " +
+ tag + " " + msg + "#");
+ dataOut[destId].flush();
+ }
+
+ public void sendMsg(int destId, String tag) {
+ sendMsg(destId, tag, " 0 ");
+ }
+
+ public void multicast(IntLinkedList destIds, String tag, String msg) {
+ for (int i = 0; i < destIds.size(); i++) {
+ sendMsg(destIds.getEntry(i), tag, msg);
+ }
+ }
+
+ public Msg receiveMsg(int fromId) throws IOException {
+ String getline = dataIn[fromId].readLine();
+ System.out.println(" received message " + getline);
+ StringTokenizer st = new StringTokenizer(getline);
+ int srcId = Integer.parseInt(st.nextToken());
+ int destId = Integer.parseInt(st.nextToken());
+ String tag = st.nextToken();
+ String msg = st.nextToken("#");
+ return new Msg(srcId, destId, tag, msg);
+ }
+
+ public int getMyId() {
+ return myId;
+ }
+
+ public int getNumProc() {
+ return N;
+ }
+
+ public void close() {
+ connector.closeSockets();
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem63/Msg.java b/cmpe436/hw4/src/Problem63/Msg.java
new file mode 100644
index 0000000..b73c287
--- /dev/null
+++ b/cmpe436/hw4/src/Problem63/Msg.java
@@ -0,0 +1,54 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem63;
+
+import java.util.*;
+
+public class Msg {
+ int srcId, destId;
+ String tag;
+ String msgBuf;
+
+ public Msg(int s, int t, String msgType, String buf) {
+ this.srcId = s;
+ destId = t;
+ tag = msgType;
+ msgBuf = buf;
+ }
+
+ public int getSrcId() {
+ return srcId;
+ }
+
+ public int getDestId() {
+ return destId;
+ }
+
+ public String getTag() {
+ return tag;
+ }
+
+ public String getMessage() {
+ return msgBuf;
+ }
+
+ public int getMessageInt() {
+ StringTokenizer st = new StringTokenizer(msgBuf);
+ return Integer.parseInt(st.nextToken());
+ }
+
+ public static Msg parseMsg(StringTokenizer st) {
+ int srcId = Integer.parseInt(st.nextToken());
+ int destId = Integer.parseInt(st.nextToken());
+ String tag = st.nextToken();
+ String buf = st.nextToken("#");
+ return new Msg(srcId, destId, tag, buf);
+ }
+
+ public String toString() {
+ return String.valueOf(srcId) + " " + String.valueOf(destId) + " " + tag + " " + msgBuf + "#";
+ }
+}
\ No newline at end of file
diff --git a/cmpe436/hw4/src/Problem63/SynchronousLinker.java b/cmpe436/hw4/src/Problem63/SynchronousLinker.java
new file mode 100644
index 0000000..f555502
--- /dev/null
+++ b/cmpe436/hw4/src/Problem63/SynchronousLinker.java
@@ -0,0 +1,47 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem63;
+
+import java.io.*;
+
+public class SynchronousLinker extends Linker {
+ public CountingSemaphore mutex = new CountingSemaphore(1);
+
+ public SynchronousLinker(String basename, int id, int numProc) throws Exception {
+ super(basename, id, numProc);
+ }
+
+ public synchronized void sendMsg(int destId, String tag, String msg) {
+ mutex.P();
+ dataOut[destId].println(myId + " " + destId + " " + tag + " " + msg + "#");
+ dataOut[destId].flush();
+ boolean done = false;
+ // Wait until done message is received
+ while (!done) {
+ try {
+ Msg message = receiveMsg(destId);
+ if (message.tag.equals("done")) {
+ // Unblock
+ mutex.V();
+ done = true;
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+ }
+
+ public synchronized Msg receiveMsg(int fromId) throws IOException {
+ Msg message = super.receiveMsg(fromId);
+ // Send done message, if it is normal message
+ if (!message.tag.equals("done")) {
+ sendMsg(fromId, "done");
+ }
+ return message;
+ }
+
+}
diff --git a/cmpe436/hw4/src/Problem63/Topology.java b/cmpe436/hw4/src/Problem63/Topology.java
new file mode 100644
index 0000000..a3ef9d6
--- /dev/null
+++ b/cmpe436/hw4/src/Problem63/Topology.java
@@ -0,0 +1,30 @@
+// Mustafa Enes Çakır
+// 2013400105
+// enes@cakir.web.tr
+// CmpE436 Assignment 4
+
+package Problem63;
+
+import java.io.*;
+import java.util.*;
+
+public class Topology {
+ public static void readNeighbors(int myId, int N, IntLinkedList neighbors) {
+ System.out.println("Reading topology");
+ try {
+ BufferedReader dIn = new BufferedReader(new FileReader("topology" + myId));
+ StringTokenizer st = new StringTokenizer(dIn.readLine());
+ while (st.hasMoreTokens()) {
+ int neighbor = Integer.parseInt(st.nextToken());
+ neighbors.add(neighbor);
+ }
+ } catch (FileNotFoundException e) {
+ for (int j = 0; j < N; j++)
+ if (j != myId)
+ neighbors.add(j);
+ } catch (IOException e) {
+ System.err.println(e);
+ }
+ System.out.println(neighbors.toString());
+ }
+}
\ No newline at end of file
diff --git a/cmpe487/bash-chat/.gitignore b/cmpe487/bash-chat/.gitignore
new file mode 100644
index 0000000..f5fadfb
--- /dev/null
+++ b/cmpe487/bash-chat/.gitignore
@@ -0,0 +1,2 @@
+*.txt
+.idea
\ No newline at end of file
diff --git a/cmpe487/bash-chat/LICENSE b/cmpe487/bash-chat/LICENSE
new file mode 100644
index 0000000..bc4ea92
--- /dev/null
+++ b/cmpe487/bash-chat/LICENSE
@@ -0,0 +1,25 @@
+BSD 2-Clause License
+
+Copyright (c) 2018, Enes Çakır
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/cmpe487/bash-chat/README.md b/cmpe487/bash-chat/README.md
new file mode 100644
index 0000000..8b6f7e6
--- /dev/null
+++ b/cmpe487/bash-chat/README.md
@@ -0,0 +1,17 @@
+
+# CmpE 487 Workshop 1
+## P2P Bash Chat App
+### Requirements
+- bash
+- netcat
+- On the same network with other users
+
+### Usage
+```bash
+ $ ./chat.sh
+```
+
+![Main Menu](main-menu.png)
+
+### License
+P2P Bash Chat App is an open-sourced software licensed under the [BSD-2 license](https://opensource.org/licenses/BSD-2-Clause).
diff --git a/cmpe487/bash-chat/chat.sh b/cmpe487/bash-chat/chat.sh
new file mode 100755
index 0000000..fcb89f7
--- /dev/null
+++ b/cmpe487/bash-chat/chat.sh
@@ -0,0 +1,393 @@
+#!/usr/bin/env bash
+
+## P2P Bash Chat App
+## Author: Mustafa Enes Cakir (enes@cakir.web.tr)
+
+## CONFIGS ##
+DISCOVERY_PORT=5000
+MESSAGE_PORT=5001
+ADDRESS_BOOK=address_book.txt
+CIPHERS=ciphers.txt
+DISCOVERY_LOG=discovery_log.txt
+MESSAGE_LOG=message_log.txt
+CHAT_PREFIX=chat
+
+## GLOBAL VARIABLES ##
+USERNAME=""
+LOCAL_IP=""
+LOCAL_NET=""
+
+## METHODS ##
+# Remove old files and kill old chat clients
+clearHistory() {
+ pkill -f "nc -lk"
+ rm -f ${ADDRESS_BOOK}
+ rm -f ${CIPHERS}
+ rm -f ${DISCOVERY_LOG}
+ rm -f ${MESSAGE_LOG}
+ rm -f "$CHAT_PREFIX"*.txt
+}
+
+# Create current profile
+createProfile() {
+ printf "\nEnter your username: "
+ printf "$(tput bold)"
+ read USERNAME
+ printf "$(tput sgr0)"
+
+ LOCAL_IP=$(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
+ LOCAL_NET=$(echo "$LOCAL_IP" | cut -d\. -f1-3)
+
+ if [ -z "$LOCAL_IP" ]; then
+ clear
+ printError "You have to connect a network for using this chat client"
+ sleep 3
+ exit
+ fi
+
+ clear
+ printProfile
+}
+
+# Print current profile to console
+printProfile() {
+ printHeader "YOUR PROFILE"
+ printf "%045s\n" "" | sed -e "s/0/-/g"
+ printf "| $(changeStyle bold "%-20s")| %-20s|\n" "Username" "$USERNAME"
+ printf "%045s\n" "" | sed -e "s/0/-/g"
+ printf "| $(changeStyle bold "%-20s")| %-20s|\n" "Local IP" "$LOCAL_IP"
+ printf "%045s\n" "" | sed -e "s/0/-/g"
+ printf "| $(changeStyle bold "%-20s")| %-20s|\n" "Local Network" "$LOCAL_NET"
+ printf "%045s\n" "" | sed -e "s/0/-/g"
+}
+
+# Print text to console as header
+printHeader() {
+ printf "$(changeStyle header "\n\n=== $1 ===\n\n")"
+}
+
+# Ask user to enter for continue
+enterContinue() {
+ printf "$(changeStyle inverse "\n\n\nEnter to continue...")"
+ read -r tmp
+ clear
+}
+
+# Creates empty address book and cipher files
+createFiles() {
+ touch ${ADDRESS_BOOK}
+ touch ${CIPHERS}
+}
+
+# Say hello to all user on network, brute force
+informNetwork() {
+ printf "$(changeStyle green "Informing all device at same network...\n")"
+
+ for i in {1..254}
+ do
+ local target_ip="$LOCAL_NET.$i"
+
+ if [ "$target_ip" != "$LOCAL_IP" ]
+ then
+ echo "0;$LOCAL_IP;$USERNAME;$target_ip;;" | nc -G 1 ${target_ip} ${DISCOVERY_PORT} &
+ echo "0;$LOCAL_IP;$USERNAME;$target_ip;;" >> ${DISCOVERY_LOG}
+ fi
+ done
+}
+
+# Listening discovery port new packets
+listenDiscovery() {
+ printf "$(changeStyle green "Discovering on port $(changeStyle bold $DISCOVERY_PORT)\n")"
+
+ nc -lk ${DISCOVERY_PORT} | receiveDiscovery
+}
+
+# Save new discovered user to address book
+receiveDiscovery() {
+ while read discovery_packet
+ do
+ local type=$(echo ${discovery_packet} | cut -d\; -f1)
+ local source_ip=$(echo ${discovery_packet} | cut -d\; -f2)
+ local source_name=$(echo ${discovery_packet} | cut -d\; -f3)
+ local target_ip=$(echo ${discovery_packet} | cut -d\; -f4)
+ local target_name=$(echo ${discovery_packet} | cut -d\; -f5)
+
+ if [ "$type" == "1" ]
+ then
+ printNotification "$source_name is online"
+ setName "$source_ip" "$source_name"
+ elif [ "$type" == "0" ]
+ then
+ printNotification "$source_name open chat client"
+ setName "$source_ip" "$source_name"
+ echo "1;$LOCAL_IP;$USERNAME;$source_ip;$source_name;" | nc -G 1 ${source_ip} ${DISCOVERY_PORT} &
+ echo "1;$LOCAL_IP;$USERNAME;$source_ip;$source_name;" >> ${DISCOVERY_LOG}
+ else
+ printError "Unknown Discovery Packet"
+ fi
+
+ echo "$discovery_packet" >> ${DISCOVERY_LOG}
+ done
+}
+
+# Listening message port new packets
+listenMessage() {
+ printf "$(changeStyle green "Listening messages on port $(changeStyle bold $MESSAGE_PORT)\n")"
+ nc -lk ${MESSAGE_PORT} | receiveMessage
+}
+
+# Save new sent message to chat history
+receiveMessage() {
+ while read message_packet
+ do
+ local source_ip=$(echo "$message_packet" | cut -d\; -f1)
+ local source_cipher=$(echo "$message_packet" | cut -d\; -f2)
+ local body=$(echo "$message_packet" | cut -d\; -f3)
+
+ local target_cipher=$(getCipher ${source_ip})
+
+ if [ -z "$target_cipher" ] || [ "$(getMD5 "$target_cipher")" == "$source_cipher" ]
+ then
+ setCipher "$source_ip" "$source_cipher"
+ echo "0;$body" >> "$(getChat ${source_ip})"
+ printNotification "New message from $(getName ${source_ip})"
+ body="VALID;$message_packet"
+ else
+ body="NOTVALID;$message_packet"
+ printError "Not valid message from ${source_ip}"
+ fi
+
+ echo "$body" >> ${MESSAGE_LOG}
+ done
+}
+
+# Main command menu of the application
+enterCommand() {
+ printHeader "AVAILABLE COMMANDS"
+
+ commands=("List online users" "Send message" "Show my profile" "Discover user" "Quit")
+
+ for i in "${!commands[@]}"; do
+ printf "\t$(changeStyle bold "$(($i+1)))") ${commands[$i]} \n"
+ done
+
+ printf "\nPlease enter your command: "
+ printf "$(tput bold)"
+ read -r option
+ printf "$(tput sgr0)"
+
+ case ${option} in
+ 1) clear; printUsers; enterContinue;;
+ 2) clear; selectChat;;
+ 3) clear; printProfile; enterContinue;;
+ 4) clear; discoverUser;;
+ 5) clear; clearHistory; printNotification "Good bye $USERNAME \n\n"; break;;
+ *) clear; printError "Invalid option";;
+ esac
+}
+
+# Print online users to console
+printUsers() {
+ printHeader "ONLINE USERS"
+ printf "%045s\n" "" | sed -e "s/0/-/g"
+ printf "| %-20s| %-20s|\n" "IP" "NAME"
+ printf "|%021s|%021s|\n" "" "" | sed -e "s/0/-/g"
+ cat ${ADDRESS_BOOK} | sort -t. -k 4n | while read -r user ; do
+ printf "| $(changeStyle bold "%-20s")| $(changeStyle green "%-20s")|\n" "$(echo "$user" | cut -d" " -f1)" "$(echo "$user" | cut -d" " -f2)"
+ done
+ printf "%045s\n" "" | sed -e "s/0/-/g"
+}
+
+# Print online users to console and ask to select for entering chat
+selectChat() {
+ printHeader "SELECT ONLINE USER"
+
+ printf "\t$(changeStyle bold "%-5s") Go back\n" "0)"
+ cat ${ADDRESS_BOOK} | sort -t. -k 4n | while read -r user ; do
+ printf "\t$(changeStyle bold "%-5s") $(echo "$user" | cut -d" " -f2) \n" "$(echo "$user" | cut -d" " -f1 | cut -d"." -f4))"
+ done
+
+ printf "\nEnter user ID: "
+ printf "$(tput bold)"
+ read -r id
+ printf "$(tput sgr0)"
+
+ if [ "$id" == "0" ]
+ then
+ clear
+ else
+ showChat ${id}
+ fi
+}
+
+# Show messages of given chat and ask for new message
+showChat() {
+ clear
+ local id=$1
+ local target_ip="$LOCAL_NET.$id"
+ local chat="$(getChat "$target_ip")"
+ local target_name="$(getName "$target_ip")"
+
+ if [ -z "$target_name" ]
+ then
+ printError "Please enter valid user ID"
+ selectChat
+ else
+ printHeader "CHAT WITH $target_name"
+
+ if [ ! -f "$chat" ]; then
+ printError "You don't have any messages history with $target_name"
+ else
+ printf "\n"
+ cat ${chat} | sed -e "s/1;/ $(changeStyle receiver "$USERNAME:") /g" | sed -e "s/0;/ $(changeStyle sender "$target_name:") /g"
+ fi
+
+ printf "\n\nEnter your message [write 'exit' for go back]: \n> "
+ printf "$(tput bold)"
+ read -r body
+ printf "$(tput sgr0)"
+
+ if [ "$body" != "exit" ]
+ then
+ if [ ! -z "$body" ]
+ then
+ # SEND MESSAGE
+ echo "1;$body" >> "$chat"
+
+ local target_cipher=$(getCipher ${target_ip})
+ local new_cipher=$(getMD5 ${target_cipher})
+
+ if [ -z "$target_cipher" ]
+ then
+ new_cipher="$(getMD5 "test")"
+ fi
+
+ setCipher ${target_ip} "$new_cipher"
+
+ echo "$LOCAL_IP;$new_cipher;$body" | nc -G 2 "$target_ip" ${MESSAGE_PORT} &
+ echo "$LOCAL_IP;$new_cipher;$body" >> ${MESSAGE_LOG}
+
+ fi
+ showChat ${id}
+ fi
+ clear
+ fi
+}
+
+# Discover user manually
+discoverUser() {
+ printHeader "DISCOVER USER"
+
+ printf "\nEnter user IP for discovery: "
+ printf "$(tput bold)"
+ read -r ip
+ printf "$(tput sgr0)"
+
+ echo "0;$LOCAL_IP;$USERNAME;$ip;;" | nc -G 1 ${ip} ${DISCOVERY_PORT}
+ echo "0;$LOCAL_IP;$USERNAME;$ip;;" >> ${DISCOVERY_LOG}
+
+ printf "Discovering $ip..."
+
+ enterContinue
+}
+
+# Prints notification to the top of console
+# $1 => Message to print
+printNotification() {
+ printf "\e[s \e[100F \e[2K\r $(changeStyle bold "[!]") $(changeStyle success " $1 ") \e[u";
+}
+
+# Prints error to the top of console
+# $1 => Error to print
+printError() {
+ printf "\e[s \e[100F \e[2K\r $(changeStyle bold "[x]") $(changeStyle error " $1 ") \e[u";
+}
+
+# Returns MD5 hashed version of given string
+# $1 => String to hashed
+getMD5() {
+ echo "$(md5 -s "$1" | cut -d"=" -f2 | sed -e 's/ //')"
+}
+
+# Returns chat file name of given ip
+# $1 => IP address of user
+getChat() {
+ echo "$CHAT_PREFIX$(echo $1 | cut -d\. -f3-4 | sed -e 's/\./_/').txt"
+}
+
+# Returns user name of given ip
+# $1 => IP address of user
+getName() {
+ echo "$(cat ${ADDRESS_BOOK} | grep -w "$1" | cut -d " " -f2)"
+}
+
+# Changes name of the given IP
+# $1 => IP address of user
+# $2 => name of user
+setName() {
+ local name=$(getName $1)
+ if [ -z "$name" ]
+ then
+ echo "$1 $2" >> ${ADDRESS_BOOK}
+ else
+ sed -i '' -e 's/^'$1' .*$/'$1' '$2'/' ${ADDRESS_BOOK}
+ fi
+}
+
+# Returns cipher of given ip
+# $1 => IP address of user
+getCipher() {
+ echo "$(cat ${CIPHERS} | grep -w "$1" | cut -d " " -f2)"
+}
+
+# Changes cipher of the given IP
+# $1 => IP address of user
+# $2 => cipher of user
+setCipher() {
+ local cipher=$(getCipher $1)
+ if [ -z "$cipher" ]
+ then
+ echo "$1 $2" >> ${CIPHERS}
+ else
+ sed -i '' -e 's/^'$1' .*$/'$1' '$2'/' ${CIPHERS}
+ fi
+}
+
+# Change style of text
+# $1 => style: red, green, bold
+# $2 => text to change style
+changeStyle() {
+ case $1 in
+ "bold") echo "$(tput bold)$2$(tput sgr0)";;
+ "underline") echo "$(tput smul)$2$(tput sgr0)";;
+ "inverse") echo "$(tput rev)$2$(tput sgr0)";;
+ "red") echo "$(tput setaf 1)$2$(tput setaf 9)$(tput sgr0)";;
+ "green") echo "$(tput setaf 2)$2$(tput setaf 9)$(tput sgr0)";;
+ "error") echo "$(tput rev)$(tput setaf 1)$2$(tput setaf 9)$(tput sgr0)";;
+ "success") echo "$(tput rev)$(tput setaf 2)$2$(tput setaf 9)$(tput sgr0)";;
+ "header") echo "$(tput bold)$(tput setaf 4)$2$(tput setaf 9)$(tput sgr0)";;
+ "sender") echo "$(tput setaf 2)$(tput bold)$2$(tput setaf 9)$(tput sgr0)";;
+ "receiver") echo "$(tput setaf 6)$(tput bold)$2$(tput setaf 9)$(tput sgr0)";;
+ esac
+}
+
+
+## BEGINNING OF APPLICATION ##
+printHeader "WELCOME TO P2P BASH CHAT APP"
+
+clearHistory
+createFiles
+createProfile
+enterContinue
+listenDiscovery &
+informNetwork &
+sleep 1
+listenMessage &
+sleep 1
+clear
+
+while [ true ]
+do
+ enterCommand
+done
+
diff --git a/cmpe487/bash-chat/main-menu.png b/cmpe487/bash-chat/main-menu.png
new file mode 100644
index 0000000..a558b75
Binary files /dev/null and b/cmpe487/bash-chat/main-menu.png differ
diff --git a/cmpe487/python-chat/.gitignore b/cmpe487/python-chat/.gitignore
new file mode 100644
index 0000000..ed8ebf5
--- /dev/null
+++ b/cmpe487/python-chat/.gitignore
@@ -0,0 +1 @@
+__pycache__
\ No newline at end of file
diff --git a/cmpe487/python-chat/LICENSE b/cmpe487/python-chat/LICENSE
new file mode 100644
index 0000000..bc4ea92
--- /dev/null
+++ b/cmpe487/python-chat/LICENSE
@@ -0,0 +1,25 @@
+BSD 2-Clause License
+
+Copyright (c) 2018, Enes Çakır
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/cmpe487/python-chat/README.md b/cmpe487/python-chat/README.md
new file mode 100644
index 0000000..0fbb092
--- /dev/null
+++ b/cmpe487/python-chat/README.md
@@ -0,0 +1,23 @@
+# CmpE 487 Workshop 2
+## P2P Python Chat App
+### Requirements
+- Python 3
+- On the same network with other users
+
+### Usage
+```bash
+ $ python3 chat.py
+```
+
+![Main Menu](main-menu.png)
+
+### Testing
+You can create your test scenarios at main function of `test.py`
+```bash
+ $ python3 test.py ?[TARGET_IP]
+```
+
+![Testing](testing.png)
+
+### License
+P2P Python Chat App is an open-sourced software licensed under the [BSD-2 license](https://opensource.org/licenses/BSD-2-Clause).
diff --git a/cmpe487/python-chat/chat.py b/cmpe487/python-chat/chat.py
new file mode 100644
index 0000000..3276084
--- /dev/null
+++ b/cmpe487/python-chat/chat.py
@@ -0,0 +1,68 @@
+import sys
+import time
+from server import *
+
+# MAIN APPLICATION
+clear()
+print_header("WELCOME TO P2P PYTHON CHAT APP")
+
+# Kill old chat applications
+os.system('pkill -f "Python app.py"')
+
+# Get username
+username = input("\n" + change_style("Enter your username", 'underline') + ": ")
+
+# Start chat server
+clear()
+server = ChatServer(username, 5000, 5001)
+server.print_profile()
+enter_continue()
+server.listen_discovery()
+server.inform_network()
+server.listen_message()
+time.sleep(2)
+clear()
+
+while True:
+ print_header("AVAILABLE COMMANDS")
+
+ commands = ["List online users", "Send message", "Show my profile", "Discover user", "Quit"]
+
+ total_unread = server.get_total_unread()
+
+ if total_unread:
+ commands[1] = "Send message (" + change_style(str(total_unread) + " unread messages", "green") + ")"
+
+ for i, command in enumerate(commands):
+ print("\t", change_style(str(i + 1) + ")", 'bold'), " ", command)
+
+ option = input("\n" + change_style("Please enter your command", 'underline') + ": ")
+ if option == "1":
+ clear()
+ server.print_users()
+ enter_continue()
+ elif option == "2":
+ clear()
+ server.select_chat()
+ elif option == "3":
+ clear()
+ server.print_profile()
+ enter_continue()
+ elif option == "4":
+ clear()
+ print_header("DISCOVER NEW USERS")
+ ip = input("\n" + change_style("Enter user IP for discovery", 'underline') + ": ")
+ if ip:
+ server.discover_user(ip)
+ enter_continue()
+ clear()
+ else:
+ clear()
+ print_error("Invalid IP address")
+ elif option == "5":
+ clear()
+ print_notification("Good bye " + server.username + " \n\n")
+ sys.exit(0)
+ else:
+ clear()
+ print_error("Invalid option")
diff --git a/cmpe487/python-chat/main-menu.png b/cmpe487/python-chat/main-menu.png
new file mode 100644
index 0000000..32a8531
Binary files /dev/null and b/cmpe487/python-chat/main-menu.png differ
diff --git a/cmpe487/python-chat/server.py b/cmpe487/python-chat/server.py
new file mode 100644
index 0000000..2082e9f
--- /dev/null
+++ b/cmpe487/python-chat/server.py
@@ -0,0 +1,241 @@
+import socket
+from _thread import *
+import threading
+from utils import *
+import random
+import string
+
+
+class ChatServer:
+ users = {}
+
+ def __init__(self, username, discovery_port, message_port):
+ self.username = username
+
+ self.ip = socket.gethostbyname(socket.gethostname())
+ self.network = self.ip[:self.ip.rfind('.')]
+ self.discovery_port = discovery_port
+ self.message_port = message_port
+
+ def send_packet(self, host, port, message):
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(1)
+ s.connect((host, port))
+ s.send(message.encode('utf-8'))
+ s.close()
+ except:
+ pass
+
+ def send_discovery_response(self, host, name):
+ message = ';'.join(['1', self.ip, self.username, host, name, ''])
+ start_new_thread(self.send_packet, (host, self.discovery_port, message))
+
+ def receive_discovery(self):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind((self.ip, self.discovery_port))
+ s.listen()
+
+ while True:
+ conn, addr = s.accept()
+
+ data = conn.recv(1024)
+ if not data:
+ break
+
+ discovery_packet = str(data.decode('utf-8'))
+
+ try:
+ packet_type, source_ip, source_name, target_ip, target_name, *end = discovery_packet.split(";")
+ if packet_type == "1":
+ print_notification(source_name + " is online")
+ self.set_name(source_ip, source_name)
+ elif packet_type == "0":
+ print_notification(source_name + " open chat client")
+ self.set_name(source_ip, source_name)
+ self.send_discovery_response(source_ip, source_name)
+ else:
+ print_error("Unknown Discovery Packet")
+ except ValueError:
+ print_error("Unknown Discovery Packet")
+ conn.close()
+ s.close()
+
+ def listen_discovery(self):
+ print(change_style("Discovering on port " + change_style(str(self.discovery_port), 'bold'), 'green'))
+ discovery_thread = threading.Thread(target=self.receive_discovery)
+ discovery_thread.setDaemon(True)
+ discovery_thread.start()
+
+ def inform_client(self, ip):
+ message = ';'.join(['0', self.ip, self.username, ip, '', ''])
+ self.send_packet(ip, self.discovery_port, message)
+
+ def inform_network(self):
+ print(change_style("Informing all device at same network...", 'green'))
+ for i in range(1, 255):
+ target_ip = self.network + "." + str(i)
+ if target_ip != self.ip:
+ start_new_thread(self.inform_client, (target_ip,))
+
+ def discover_user(self, ip):
+ start_new_thread(self.inform_client, (ip,))
+ print(change_style('\n\nDiscovering ' + ip + '...', 'green'))
+
+ def receive_message(self):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind((self.ip, self.message_port))
+ s.listen()
+
+ while True:
+ conn, addr = s.accept()
+
+ data = conn.recv(1024)
+ if not data:
+ break
+
+ message_packet = str(data.decode('utf-8'))
+
+ try:
+ source_ip, source_cipher, body = message_packet.split(";")
+ target_cipher = self.get_cipher(source_ip)
+
+ if target_cipher is None or hash_MD5(target_cipher) == source_cipher:
+ user = self.get_user(source_ip)
+ user.cipher = source_cipher
+ user.add_message(body, False)
+ print_notification("New message from " + user.name)
+ else:
+ print_error("Not valid message from " + source_ip)
+ except ValueError:
+ pass
+ conn.close()
+
+ s.close()
+
+ def listen_message(self):
+ print(change_style("Listening messages on port " + change_style(str(self.message_port), 'bold'), 'green'))
+ message_thread = threading.Thread(target=self.receive_message)
+ message_thread.setDaemon(True)
+ message_thread.start()
+
+ def select_chat(self):
+ print_header("SELECT ONLINE USER")
+ print("\t{0:s} {1:s}".format("0)".ljust(5), "Go back"))
+ for ip, user in self.users.items():
+ unread = ""
+ if user.unread:
+ unread = "(" + change_style(str(user.unread) + " unread messages", "green") + ")"
+ print("\t{0:s} {1:s} {2:s}".format((ip[ip.rfind('.') + 1:] + ")").ljust(5), user.name, unread))
+
+ id = input("\nEnter use ID: ")
+ if id == "0":
+ clear()
+ else:
+ self.show_chat(id)
+
+ def show_chat(self, id):
+ clear()
+ target_ip = self.network + "." + id
+ user = self.get_user(target_ip)
+ if user is None:
+ print_error("Please enter valid user ID")
+ self.select_chat()
+ else:
+ print()
+ if user.messages:
+ for message in user.messages:
+ if message.is_sent:
+ print("{} {}".format((change_style(self.username + ": ", 'receiver')).ljust(25), message.body))
+ else:
+ notif = ""
+ if not message.is_read:
+ notif = change_style("*", "red")
+ print(
+ "{} {}".format((change_style(user.name + ": ", 'sender') + notif).ljust(25), message.body))
+ else:
+ print_error("You don't have any messages history with " + user.name)
+
+ user.read_message()
+
+ body = input("\n\nEnter your message [write 'exit' for go back]: \n> ")
+
+ if body != "exit":
+ if body:
+ user.messages.append(Message(body, True))
+ if user.cipher:
+ user.cipher = hash_MD5(user.cipher)
+ else:
+ user.cipher = hash_MD5(''.join(random.choices(string.ascii_uppercase + string.digits, k=10)))
+
+ message = ';'.join([self.ip, user.cipher, body])
+ start_new_thread(self.send_packet, (user.ip, self.message_port, message))
+ self.show_chat(id)
+ clear()
+
+ def print_users(self):
+ print_header("ONLINE USERS")
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format("IP".ljust(20), "NAME".ljust(20)))
+ print('-' * 46)
+ for ip, user in self.users.items():
+ print('| {0:s} | {1:s}|'.format(change_style(ip.ljust(20), 'bold'),
+ change_style(user.name.ljust(20), 'green')))
+ print('-' * 46)
+
+ def print_profile(self):
+ print_header("YOUR PROFILE")
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format(change_style("Username".ljust(20), 'bold'),
+ change_style(self.username.ljust(20), 'green')))
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format(change_style("Local IP".ljust(20), 'bold'),
+ change_style(self.ip.ljust(20), 'green')))
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format(change_style("Local Network".ljust(20), 'bold'),
+ change_style(self.network.ljust(20), 'green')))
+ print('-' * 46)
+
+ def get_users(self):
+ # TODO: order users
+ return self.users.items()
+ # [print(key, " :: ", value) for (key, value) in sorted(self.users.items())]
+ # return self.users.items().sort(key=lambda (k, v): (v, k))
+
+ def get_name(self, ip):
+ if ip in self.users:
+ return self.users[ip].name
+
+ def get_cipher(self, ip):
+ if ip in self.users:
+ return self.users[ip].cipher
+
+ def get_user(self, ip):
+ if ip in self.users:
+ return self.users[ip]
+
+ def get_total_unread(self):
+ total = 0
+ for ip, user in self.users.items():
+ total += user.unread
+ return total
+
+ def get_unread(self, ip):
+ if ip in self.users:
+ return self.users[ip].name
+ else:
+ return 0
+
+ def set_name(self, ip, name):
+ if ip in self.users:
+ self.users[ip].name = name
+ else:
+ self.users[ip] = User(ip, name)
+
+ def set_cipher(self, ip, cipher):
+ if ip in self.users:
+ self.users[ip].cipher = cipher
+ else:
+ self.users[ip] = User(ip, 'Unknown', cipher)
diff --git a/cmpe487/python-chat/test.py b/cmpe487/python-chat/test.py
new file mode 100644
index 0000000..935cd82
--- /dev/null
+++ b/cmpe487/python-chat/test.py
@@ -0,0 +1,80 @@
+import socket
+import sys
+import random
+from utils import *
+
+TARGET_HOST = socket.gethostbyname(socket.gethostname())
+if len(sys.argv) > 1:
+ TARGET_HOST = sys.argv[1]
+
+TARGET_NETWORK = TARGET_HOST[:TARGET_HOST.rfind('.')]
+NAMES = ['Enes', 'Emirhan', 'Deniz', 'Mehmet', 'Ali', 'Ceren', 'Buse', 'Büşra', 'Ahmet', 'Veli']
+MESSAGES = ['Naber', 'Nasılsın?', 'İyi misin?', 'Selamlar', 'Hava nasıl?', 'Güzel', 'Tebrikler']
+DISCOVER_PORT = 5000
+MESSAGE_PORT = 5001
+
+
+def send_packet(host, port, message):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ try:
+ s.connect((host, port))
+ s.send(message.encode('utf-8'))
+ s.close()
+ except:
+ print("Connection error")
+
+
+def get_random_name():
+ return random.choice(NAMES)
+
+
+def get_random_message():
+ return random.choice(MESSAGES)
+
+
+def get_random_ip():
+ return TARGET_NETWORK + "." + str(random.randint(1, 255))
+
+
+def send_discover_request(ip=None):
+ source_ip = ip if ip else get_random_ip()
+ print(change_style("Sent discovery request from " + source_ip, "green"))
+ packet = "0;{};{};{};;".format(source_ip, get_random_name(), TARGET_HOST)
+ send_packet(TARGET_HOST, DISCOVER_PORT, packet)
+ return source_ip
+
+
+def send_discover_response(ip=None):
+ source_ip = ip if ip else get_random_ip()
+ print(change_style("Sent discovery response from " + source_ip, "green"))
+ packet = "1;{};{};{};{};".format(source_ip, get_random_name(), TARGET_HOST, get_random_name())
+ send_packet(TARGET_HOST, DISCOVER_PORT, packet)
+ return source_ip
+
+
+def send_message(raw_cipher, hash_count=0, ip=None):
+ source_ip = ip if ip else get_random_ip()
+ cipher = raw_cipher
+ for x in range(hash_count):
+ cipher = hash_MD5(cipher)
+
+ print(change_style("Sent message from " + source_ip + " with '" + cipher + "' cipher", "green"))
+
+ packet = "{};{};{}".format(source_ip, cipher, get_random_message())
+ send_packet(TARGET_HOST, MESSAGE_PORT, packet)
+
+ return cipher
+
+
+if __name__ == "__main__":
+ clear()
+ print_header("TESTING " + TARGET_HOST + " CHAT SERVER")
+ ip = send_discover_request()
+ send_discover_response(ip)
+ send_message("test", 0, ip)
+ send_message("test", 1, ip)
+ send_message("test", 2, ip)
+
+ ip = send_discover_request()
+ ip = send_discover_request()
+ print("\n\n\n")
diff --git a/cmpe487/python-chat/testing.png b/cmpe487/python-chat/testing.png
new file mode 100644
index 0000000..017c81d
Binary files /dev/null and b/cmpe487/python-chat/testing.png differ
diff --git a/cmpe487/python-chat/utils.py b/cmpe487/python-chat/utils.py
new file mode 100644
index 0000000..7d232ac
--- /dev/null
+++ b/cmpe487/python-chat/utils.py
@@ -0,0 +1,81 @@
+import os
+import hashlib
+
+
+class Message:
+ def __init__(self, body, is_sent=False):
+ self.body = body
+ self.is_sent = is_sent
+ self.is_read = False
+
+
+class User:
+ def __init__(self, ip, name, chipher=None):
+ self.ip = ip
+ self.name = name
+ self.cipher = chipher
+ self.unread = 0
+ self.messages = []
+
+ def add_message(self, message, is_sent):
+ self.messages.append(Message(message, is_sent))
+ if not is_sent:
+ self.unread += 1
+
+ def read_message(self):
+ self.unread = 0
+ for message in self.messages:
+ message.is_read = True
+
+
+def clear():
+ os.system('clear')
+
+
+def enter_continue():
+ print(change_style("\n\n\nEnter to continue...", 'bold'))
+ tmp = input()
+ clear()
+
+
+def change_style(str, style):
+ if style == "green":
+ return "\033[92m{}\033[00m".format(str)
+ elif style == "header":
+ return "\033[34m \033[01m{}\033[00m".format(str)
+ elif style == "bold":
+ return "\033[01m{}\033[00m".format(str)
+ elif style == "red":
+ return "\033[31m{}\033[00m".format(str)
+ elif style == "error":
+ return "\033[41m \033[37m{}\033[00m".format(str)
+ elif style == "success":
+ return "\033[42m \033[37m{}\033[00m".format(str)
+ elif style == "underline":
+ return "\033[4m{}\033[00m".format(str)
+ elif style == "receiver":
+ return "\033[01m\033[35m{}\033[00m".format(str)
+ elif style == "sender":
+ return "\033[01m\033[36m{}\033[00m".format(str)
+
+ return str
+
+
+def print_notification(str):
+ print("\a \033[s \033[100F \033[2K \r {} {} \033[u".format(change_style(" [!] ", "bold"),
+ change_style(str + " ", "success")), end="")
+
+
+def print_error(str):
+ print("\a \033[s \033[100F \033[2K \r {} {} \033[u".format(change_style(" [x] ", "bold"),
+ change_style(str + " ", "error")), end="")
+
+
+def print_header(header):
+ print(change_style("\n\n=== " + header + " ===\n\n", 'header'))
+
+
+def hash_MD5(str):
+ m = hashlib.md5()
+ m.update(str.encode('utf-8'))
+ return m.hexdigest()
diff --git a/cmpe487/social-torrent/.gitignore b/cmpe487/social-torrent/.gitignore
new file mode 100644
index 0000000..c18dd8d
--- /dev/null
+++ b/cmpe487/social-torrent/.gitignore
@@ -0,0 +1 @@
+__pycache__/
diff --git a/cmpe487/social-torrent/LICENSE b/cmpe487/social-torrent/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/cmpe487/social-torrent/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/cmpe487/social-torrent/README.md b/cmpe487/social-torrent/README.md
new file mode 100644
index 0000000..a9ab6dc
--- /dev/null
+++ b/cmpe487/social-torrent/README.md
@@ -0,0 +1,21 @@
+# CmpE 487 Workshop 4
+
+## Torrent File Sharing App
+- We've implemented the bonus utility.
+- This is the result of at least 15 hour pair programming.
+- Program parameters can be found in config file with comments.
+
+### Usage
+```bash
+ $ python3 main.py
+```
+
+![Main Menu](main-menu.png)
+
+### Contributors:
+- [Abdullah Emirhan Karagül](https://github.com/emir350z)
+- [Mustafa Enes Çakır](https://github.com/EnesCakir)
+- [M. Hakan Kurtoğlu](https://github.com/memhak)
+
+### License
+Torrent File Sharing App is an open-sourced software licensed under the [BSD-2 license](https://opensource.org/licenses/BSD-2-Clause).
diff --git a/cmpe487/social-torrent/config.py b/cmpe487/social-torrent/config.py
new file mode 100644
index 0000000..dd59d3a
--- /dev/null
+++ b/cmpe487/social-torrent/config.py
@@ -0,0 +1,30 @@
+import socket
+
+
+def get_ip():
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ s.connect(('10.255.255.255', 1))
+ IP = s.getsockname()[0]
+ except:
+ IP = '127.0.0.1'
+ finally:
+ s.close()
+ return IP
+
+CHUNK_SIZE = 1480
+FILE_PATH = './shared_files/'
+SELF_IP = get_ip()
+DISCOVERY_PORT = 5000 # TCP
+CHUNK_PORT = 5001 # TCP
+FILE_PORT = 5001 # UDP
+ACK_PORT = 5001 # UDP
+
+DEFAULT_WINDOW_SIZE = 250 # Window size
+TRY_COUNT = 5 # Number of trials before giving up sending the packet
+TOLERANCE = 3 # The limit of packet count tolerated before reaching window size
+DRAINAGE = 0.01 # The timeout between the packets are processed from the queue (To simulate window size)
+
+SUBNET = SELF_IP[:SELF_IP.rfind('.')]
+
+MESSAGE_TYPES = {"request": 0, "response": 1}
diff --git a/cmpe487/social-torrent/fileClient.py b/cmpe487/social-torrent/fileClient.py
new file mode 100644
index 0000000..540e135
--- /dev/null
+++ b/cmpe487/social-torrent/fileClient.py
@@ -0,0 +1,182 @@
+import queue
+import socket
+import json
+from fileUtils import AvailableFile, File, Chunk
+import threading
+from threading import Lock
+from time import sleep
+import asyncio
+from config import *
+from utils import send_packet, print_notification
+from _thread import start_new_thread
+import base64
+
+
+class FileClient():
+ def __init__(self, send_file_callback, download_finish_callback):
+ self.available_files = {}
+ self.active_peers = 1
+ self.send_file_callback = send_file_callback
+ self.download_finish_callback = download_finish_callback
+ self.lock = Lock()
+
+ def start(self):
+ self.listen_discovery()
+ self.start_client()
+
+ def handle_file_definition(self, message):
+ source, type, dict = message.split('|')
+ file_list = json.loads(dict)
+ print_notification("Received " + str(len(file_list)) + " new files from " + source)
+ for file in file_list:
+ if file['checksum'] in self.available_files:
+ self.available_files[file['checksum']].add_peer(source)
+ else:
+ self.available_files[file['checksum']] = AvailableFile(file['name'], file['checksum'],
+ file['chunk_size'], source)
+ if int(type) == MESSAGE_TYPES["request"]:
+ self.send_file_callback(source, MESSAGE_TYPES["response"])
+
+ def receive_discovery(self):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind((SELF_IP, DISCOVERY_PORT))
+ s.listen()
+
+ while True:
+ conn, addr = s.accept()
+ with conn:
+ message = ""
+ while True:
+ data = conn.recv(1024)
+ if not data:
+ self.handle_file_definition(message)
+ conn.close()
+ break
+ message = message + data.decode('utf_8')
+
+ def send_chunk_requests(self):
+ while True:
+ sleep(0.2)
+ for file in self.available_files.values():
+ if file.status == "downloading":
+ for peer in file.peers:
+ requested_chunks = file.get_batch_new_chunks()
+ if len(requested_chunks) == 0:
+ continue
+ self.send_chunk_request(peer, file.checksum, requested_chunks)
+
+ def send_chunk_request(self, target_ip, checksum, chunks):
+ message = SELF_IP + "|" + checksum + "|" + json.dumps([chunk.offset for chunk in chunks])
+ for chunk in chunks:
+ chunk.status = "in_flight"
+ start_new_thread(send_packet, (target_ip, CHUNK_PORT, message,))
+
+ def start_client(self):
+ chunk_request_thread = threading.Thread(target=self.send_chunk_requests)
+ chunk_request_thread.setDaemon(True)
+ chunk_request_thread.start()
+
+ def listen_discovery(self):
+ discovery_thread = threading.Thread(target=self.receive_discovery)
+ discovery_thread.setDaemon(True)
+ discovery_thread.start()
+
+ def start_download(self, checksum):
+ file = self.available_files[checksum]
+ file.status = "downloading"
+ file.start_download()
+ self.lock.acquire()
+ self.active_peers += len(file.peers)
+ self.lock.release()
+
+ def end_download(self, checksum):
+ file = self.available_files[checksum]
+ if file.status == "finished":
+ return
+ file.status = "finished"
+ self.lock.acquire()
+ self.active_peers -= len(file.peers)
+ if self.active_peers < 0:
+ self.active_peers = 0
+ self.lock.release()
+ file.save_to_shared()
+ print_notification("Download Finished for: " + self.available_files[checksum].name)
+ self.download_finish_callback(self.available_files[checksum].name)
+
+
+class FileClientConnection:
+ def __init__(self, client):
+ self.buffer = queue.Queue(maxsize=DEFAULT_WINDOW_SIZE)
+ self.window_size = DEFAULT_WINDOW_SIZE
+ self.transport = None
+ self.client = client
+
+ def connection_made(self, transport):
+ self.transport = transport
+
+ def start(self):
+ for peer in self.file.peers:
+ chunks = self.file.get_batch_new_chunks(self.file.chunk_size // len(self.file.peers))
+ self.send_chunk_request(peer, chunks)
+
+ async def queue_handler(self):
+ while True:
+ try:
+ item = self.buffer.get(block=False)
+ file = self.client.available_files[item[0]]
+ chunk = file.chunks[int(item[1])]
+ chunk.data = item[2]
+ chunk.lock.acquire()
+ chunk.status = "done"
+ chunk.lock.release()
+ if len([1 for chnk in file.chunks if chnk.status != "done"]) == 0:
+ self.client.end_download(file.checksum)
+ except:
+ pass
+ # queue is empty here
+ await asyncio.sleep(DRAINAGE)
+
+ async def check_packets(self):
+ pass
+
+ def datagram_received(self, data, addr):
+ message = data.decode()
+ checksum, offset, *payload = message.split("|")
+ payload = "".join(payload)
+ # print(checksum)
+ # print(offset)
+ self.client.lock.acquire()
+ if self.client.active_peers == 0:
+ rwindow = str((self.window_size - self.buffer.qsize()) // 1)
+ else:
+ rwindow = str((self.window_size - self.buffer.qsize()) // self.client.active_peers)
+ return_msg = checksum + "|" + offset + "|" + rwindow
+ self.client.lock.release()
+ if offset != "-1":
+ data = base64.b64decode(payload)
+ self.buffer.put((checksum, offset, data))
+ self.transport.sendto(return_msg.encode(), addr)
+
+ def send_chunk_request(self, target_ip, chunks):
+ message = SELF_IP + "|" + self.file.checksum + "|" + json.dumps([chunk.offset for chunk in chunks])
+ for chunk in chunks:
+ chunk.status = "pending"
+ start_new_thread(send_packet, (target_ip, CHUNK_PORT, message,))
+
+
+async def start_listener(client):
+ loop = asyncio.get_running_loop()
+ listener = FileClientConnection(client)
+ transport, protocol = await loop.create_datagram_endpoint(
+ lambda: listener,
+ local_addr=(SELF_IP, ACK_PORT))
+ asyncio.ensure_future(listener.queue_handler())
+ try:
+ await asyncio.sleep(3600) # Serve for 1 hour.
+ finally:
+ transport.close()
+
+
+def start_download_queue(client):
+ start_new_thread(asyncio.run, (start_listener(client),))
diff --git a/cmpe487/social-torrent/fileServer.py b/cmpe487/social-torrent/fileServer.py
new file mode 100644
index 0000000..54af454
--- /dev/null
+++ b/cmpe487/social-torrent/fileServer.py
@@ -0,0 +1,250 @@
+import threading
+import os
+import json
+from fileUtils import File
+from _thread import *
+from config import *
+from shutil import copyfile
+import asyncio
+import random
+from utils import print_notification
+import base64
+
+
+class FileServer:
+
+ def __init__(self):
+ self.shared_files = {}
+ self.active_connections = {}
+ self.initialize_files()
+ self.loop = asyncio.get_event_loop()
+
+ def start(self):
+ self.broadcast_shared_files()
+ self.listen_chunk_request()
+
+ def initialize_files(self):
+ for filename in os.listdir('shared_files/'):
+ file = File(filename)
+ self.shared_files[file.checksum] = file
+
+ def handle_chunk_request(self, message):
+ source, file_hash, raw_chunks = message.split('|')
+ print_notification(source + " has requested the file with hash: " + file_hash)
+ chunk_list = json.loads(raw_chunks)
+
+ is_new = source not in self.active_connections
+ if not is_new and self.active_connections[source].ended:
+ temp = self.active_connections[source]
+ del self.active_connections[source]
+ del temp
+ self.active_connections[source] = FileServerConnection(self.loop)
+
+ file_connection = self.active_connections[source]
+
+ for chunk in chunk_list:
+ file_connection.add_chunk(file_hash, int(chunk), self.shared_files[file_hash].get_chunk(int(chunk)))
+ # if is_new:
+ # start_new_thread(asyncio.run, (self.start_connection(file_connection, source, ),))
+ start_new_thread(asyncio.run, (self.start_connection(file_connection, source, ),))
+
+ async def start_connection(self, connection, source):
+ loop = asyncio.get_event_loop()
+ transport, protocol = await loop.create_datagram_endpoint(
+ lambda: connection,
+ remote_addr=(source, FILE_PORT))
+ try:
+ await asyncio.sleep(3600)
+ finally:
+ del transport
+ del connection
+ transport.close()
+
+ def receive_chunk_request(self):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind((SELF_IP, CHUNK_PORT))
+ s.listen()
+ while True:
+ conn, addr = s.accept()
+ with conn:
+ message = ""
+ while True:
+ data = conn.recv(1024)
+ if not data:
+ # print(message)
+ self.handle_chunk_request(message)
+ # conn.send(b"OK")
+ conn.close()
+ break
+ message = message + data.decode('utf_8')
+
+ def listen_chunk_request(self):
+ chunk_thread = threading.Thread(target=self.receive_chunk_request)
+ chunk_thread.setDaemon(True)
+ chunk_thread.start()
+
+ def new_file_downloaded(self, filename):
+ file = File(filename)
+ self.shared_files[file.checksum] = file
+ self.broadcast_shared_files()
+
+ def add_file(self, filepath):
+ if os.path.isfile(filepath):
+ filename = os.path.basename(filepath)
+ copyfile(filepath, 'shared_files/' + filename)
+ file = File(filename)
+ self.shared_files[file.checksum] = file
+ self.broadcast_shared_files()
+ return True
+ else:
+ return False
+
+ def broadcast_shared_files(self):
+ for i in range(1, 255):
+ target_ip = SUBNET + "." + str(i)
+ if target_ip != SELF_IP:
+ self.send_shared_files(target_ip, MESSAGE_TYPES['request'])
+
+ def send_shared_files(self, target_ip, type):
+ message = SELF_IP + "|" + str(type) + "|" + json.dumps([data.get_dict() for data in self.shared_files.values()])
+ start_new_thread(self.send_packet, (target_ip, DISCOVERY_PORT, message,))
+
+ def send_packet(self, host, port, message):
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(5)
+ s.connect((host, port))
+ s.send(message.encode('utf-8'))
+ s.close()
+ except:
+ pass
+
+
+class SChunk:
+ def __init__(self, file_hash, offset, data):
+ self.offset = offset
+ self.file_hash = file_hash
+ self.data = data
+ self.status = 'new'
+
+ def get_key(self):
+ return self.file_hash + "|" + str(self.offset)
+
+ def get_bytes(self):
+ return self.get_key().encode() + "|".encode() + base64.b64encode(self.data)
+
+class FileServerConnection:
+ def __init__(self, loop):
+ self.loop = loop
+ self.transport = None
+ self.window_size = TOLERANCE + 1
+ self.in_flight = 0
+ self.chunks = {}
+ self.window_lock = threading.Lock()
+ self.flight_lock = threading.Lock()
+ self.on_con_lost = loop.create_future()
+ self.started = False
+ self.ended = False
+
+ def set_window_size(self, value):
+ self.window_lock.acquire()
+ self.window_size = value
+ self.window_lock.release()
+
+ def inc_flight(self):
+ self.flight_lock.acquire()
+ self.in_flight += 1
+ self.flight_lock.release()
+
+ def dec_flight(self):
+ self.flight_lock.acquire()
+ self.in_flight -= 1
+ self.flight_lock.release()
+
+ def add_chunk(self, file_hash, offset, data):
+ chunk = SChunk(file_hash, offset, data)
+ self.chunks[chunk.get_key()] = chunk
+ if self.started:
+ try:
+ asyncio.ensure_future(self.try_send(chunk, TRY_COUNT))
+ except:
+ return
+ # if asyncio.get_running_loop():
+ # asyncio.ensure_future(self.try_send(chunk, TRY_COUNT))
+ # else:
+ # return
+
+ def start(self):
+ self.started = True
+ for chunk in list(self.chunks.values()):
+ asyncio.ensure_future(self.try_send(chunk, TRY_COUNT))
+
+ async def probe(self):
+ if self.ended:
+ return
+ try:
+ self.window_lock.acquire()
+ if self.window_size <= TOLERANCE:
+ self.transport.sendto("None|-1|probe".encode())
+ self.window_lock.release()
+ await asyncio.sleep(1)
+ await self.probe()
+ except:
+ pass
+
+ async def try_send(self, chunk, count):
+ if self.ended:
+ return
+ if count == 0 or chunk.status == "done":
+ self.chunks.pop(chunk.get_key(), None)
+ self.check_if_complete()
+ return
+
+ if self.in_flight >= self.window_size - TOLERANCE:
+ await asyncio.sleep(random.random())
+ await self.try_send(chunk, count)
+ else:
+ # print("Try chunk #" + str(chunk) + " for " + str(self.try_count + 1 - count) + " times")
+ chunk.status = "flight"
+ self.inc_flight()
+ # print("sending: " + str(chunk.offset))
+ try:
+ self.transport.sendto(chunk.get_bytes())
+ except:
+ pass
+ # print("error: " + str(chunk.offset))
+ await asyncio.sleep(1)
+ if chunk.status != "done":
+ chunk.status = "new"
+ self.dec_flight()
+ await self.try_send(chunk, count - 1)
+
+ def connection_made(self, transport):
+ self.transport = transport
+ self.start()
+ asyncio.create_task(self.probe())
+
+ def error_received(self, exc):
+ pass
+ # print('Error received:', exc)
+
+ def connection_lost(self, exc):
+ self.on_con_lost.set_result(True)
+ self.ended = True
+
+ def check_if_complete(self):
+ if not bool(self.chunks):
+ self.transport.close()
+
+ def datagram_received(self, data, addr):
+ message = data.decode()
+
+ hash, chunk_num, window_size = message.split('|')
+ self.set_window_size(int(window_size))
+ if chunk_num == "-1":
+ return
+ self.chunks[hash + "|" + chunk_num].status = "done"
+ self.chunks.pop(hash + "|" + chunk_num, None)
+ self.dec_flight()
+ self.check_if_complete()
diff --git a/cmpe487/social-torrent/fileUtils.py b/cmpe487/social-torrent/fileUtils.py
new file mode 100644
index 0000000..a164ac7
--- /dev/null
+++ b/cmpe487/social-torrent/fileUtils.py
@@ -0,0 +1,83 @@
+import os
+import math
+import hashlib
+from config import FILE_PATH, CHUNK_SIZE
+import asyncio
+import random
+from _thread import start_new_thread
+from threading import Lock
+
+class File:
+ def __init__(self, name):
+ self.name = name
+ self.chunk_size = math.ceil(os.path.getsize(self.get_path()) / CHUNK_SIZE)
+ self.reader = open(self.get_path(), 'rb')
+ self.checksum = self.calculate_md5()
+
+ def get_dict(self):
+ dict = vars(self)
+ return {x: dict[x] for x in dict if x != "reader"}
+
+ def get_path(self):
+ return FILE_PATH + self.name
+
+ def calculate_md5(self):
+ checksum = hashlib.md5(self.reader.read()).hexdigest()
+ self.reader.seek(0)
+ return checksum
+
+ def get_chunk(self, offset):
+ self.reader.seek(CHUNK_SIZE * offset)
+ return self.reader.read(CHUNK_SIZE)
+
+class Chunk:
+ def __init__(self, offset):
+ self.offset = offset
+ self.data = None
+ self.status = 'new'
+ self.lock = Lock()
+
+class AvailableFile():
+ def __init__(self, name, checksum, chunk_size, first_peer):
+ self.name = name
+ self.checksum = checksum
+ self.chunk_size = chunk_size
+ self.peers = {first_peer}
+ self.status = 'discovered'
+ self.chunks = None
+
+ def save_to_shared(self):
+ self.status = "finished"
+ with open(FILE_PATH + self.name, 'wb') as writer:
+ for chunk in self.chunks:
+ # print("Writing chunk with offset:" + str(chunk.offset))
+ writer.write(chunk.data)
+ # print("successfully wrote")
+ writer.close()
+
+ def add_peer(self, ip):
+ self.peers.add(ip)
+
+ def start_download(self):
+ self.chunks = [Chunk(i) for i in range(self.chunk_size)]
+ self.status = 'downloading'
+
+ def count_in_flight(self):
+ return len([1 for chunk in self.chunks if chunk.status == 'in_flight'])
+
+ def check_if_finished(self):
+ return all(chunk.status == 'finished' for chunk in self.chunks)
+
+ async def check_chunks(self, chunks):
+ await asyncio.sleep(1)
+ for chunk in chunks:
+ chunk.lock.acquire()
+ if chunk.status == 'in_flight':
+ chunk.status = "new"
+ chunk.lock.release()
+
+ def get_batch_new_chunks(self, count=10):
+ pending = [chunk for chunk in self.chunks if chunk.status == "new"]
+ chunks = random.sample(pending, min(count, len(pending)))
+ start_new_thread(asyncio.run,(self.check_chunks(chunks),))
+ return chunks
diff --git a/cmpe487/social-torrent/main-menu.png b/cmpe487/social-torrent/main-menu.png
new file mode 100644
index 0000000..1dfeb73
Binary files /dev/null and b/cmpe487/social-torrent/main-menu.png differ
diff --git a/cmpe487/social-torrent/main.py b/cmpe487/social-torrent/main.py
new file mode 100644
index 0000000..b473553
--- /dev/null
+++ b/cmpe487/social-torrent/main.py
@@ -0,0 +1,129 @@
+import sys
+import time
+
+from fileClient import FileClient, start_download_queue
+from fileServer import FileServer
+from utils import *
+
+fileServer = FileServer()
+fileServer.start()
+fileClient = FileClient(fileServer.send_shared_files, fileServer.new_file_downloaded)
+fileClient.start()
+start_download_queue(fileClient)
+
+clear()
+while True:
+ print_header("AVAILABLE COMMANDS")
+
+ commands = [
+ "Share new file",
+ "List active connections",
+ "List available files",
+ "List shared files",
+ "Broadcast shared files",
+ "Quit"
+ ]
+
+ for i, command in enumerate(commands):
+ print("\t", change_style(str(i + 1) + ")", 'bold'), " ", command)
+
+ option = input("\n" + change_style("Please enter your command", 'underline') + ": ")
+ if option == "1":
+ clear()
+ print_header("SHARE NEW FILE")
+ filepath = input("\n" + change_style("Enter absolute file path", 'underline') + ": ")
+ if filepath:
+ filename = os.path.basename(filepath)
+ if fileServer.add_file(filepath):
+ print("\n\n")
+ print("\t" + change_style(filename, "bold") + change_style(" is added successfully", "green"))
+ else:
+ print("\n\n")
+ print("\t" + change_style(filename, "bold") + change_style(" is not valid file", "red"))
+ else:
+ print("\n\n")
+ print("\t" + change_style("Please enter a file path", "red"))
+ enter_continue()
+ elif option == "2":
+ while True:
+ clear()
+ print_header("UPLOADS")
+ print('-' * 89)
+ print('| {0:s}| {1:s}| {2:s}| {3:s}|'.format("TARGET".ljust(20), "CHUNKS".ljust(20), "IN FLIGHT".ljust(20),
+ "WINDOW SIZE".ljust(20)))
+ print('-' * 89)
+ for target, connection in fileServer.active_connections.items():
+ print('| {0:s}| {1:s}| {2:s}| {3:s}|'.format(target.ljust(20), str(len(connection.chunks)).ljust(20),
+ str(connection.in_flight).ljust(20),
+ str(connection.window_size).ljust(20)))
+ print('-' * 89)
+
+ print_header("DOWNLOADS")
+ print('-' * 89)
+ print('| {0:s}| {1:s}| {2:s}| {3:s}|'.format("FILE".ljust(20), "CHUNKS".ljust(20), "DOWNLOADED".ljust(20),
+ "STATUS".ljust(20)))
+ print('-' * 89)
+ for file in fileClient.available_files.values():
+ if file.status != "discovered":
+ print('| {0:s}| {1:s}| {2:s}| {3:s}|'.format(file.name.ljust(20), str(file.chunk_size).ljust(20),
+ str(len([1 for chunk in file.chunks if
+ chunk.status == 'done'])).ljust(20),
+ file.status.ljust(20)))
+ print('-' * 89)
+ tmp = input(change_style("\n\nEmpty for refresh, enter 0 for exit: ", "bold"))
+ if tmp == "0":
+ clear()
+ break
+ elif option == "3":
+ clear()
+ print_header("AVAILABLE FILES")
+ print('-' * 82)
+ print('| {0:s}| {1:s}| {2:s}| {3:s}| {4:s}|'.format("ID".ljust(3), "NAME".ljust(30), "CHUNK SIZE".ljust(12),
+ "PEERS".ljust(10), "STATUS".ljust(16)))
+ print('-' * 82)
+ for id, file in enumerate(fileClient.available_files.values()):
+ print('| {0:s}| {1:s}| {2:s}| {3:s}| {4:s}|'.format(str(id + 1).ljust(3),
+ change_style(file.name.ljust(30), 'bold'),
+ change_style(str(file.chunk_size).ljust(12), 'green'),
+ change_style(
+ (str(len(file.peers)) + " peers").ljust(10),
+ 'green'),
+ change_style((file.status).ljust(16), 'green')
+ ))
+ print('-' * 82)
+
+ id = input("\nEnter file ID for downloading: ")
+ if id is "":
+ clear()
+ else:
+ selectedFile = list(fileClient.available_files.values())[int(id) - 1]
+ fileClient.start_download(selectedFile.checksum)
+ print(change_style("\n" + selectedFile.name, "bold") + change_style(" is started to downloading", "green"))
+ enter_continue()
+ elif option == "4":
+ clear()
+ print_header("SHARED FILES")
+ print('-' * 83)
+ print('| {0:s} | {1:s}| {2:s}|'.format("NAME".ljust(30), "CHUNK SIZE".ljust(12), "CHECKSUM".ljust(33)))
+ print('-' * 83)
+ for file in fileServer.shared_files.values():
+ print('| {0:s} | {1:s}| {2:s}|'.format(change_style(file.name.ljust(30), 'bold'),
+ change_style(str(file.chunk_size).ljust(12), 'green'),
+ file.checksum.ljust(33)))
+ print('-' * 83)
+ enter_continue()
+ elif option == "5":
+ clear()
+ print_header("BROADCAST SHARED FILES")
+ fileServer.broadcast_shared_files()
+ print(change_style("Broadcasting all shared files to network", "green"))
+ time.sleep(1)
+ enter_continue()
+ elif option == "6":
+ clear()
+ print_notification("Good bye \n\n")
+ os.system("pkill -9 \"python3 main.py\"")
+ sys.exit(0)
+ else:
+ clear()
+ print_error("Invalid option")
diff --git a/cmpe487/social-torrent/shared_files/.gitignore b/cmpe487/social-torrent/shared_files/.gitignore
new file mode 100644
index 0000000..d6b7ef3
--- /dev/null
+++ b/cmpe487/social-torrent/shared_files/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
diff --git a/cmpe487/social-torrent/utils.py b/cmpe487/social-torrent/utils.py
new file mode 100644
index 0000000..aabe51f
--- /dev/null
+++ b/cmpe487/social-torrent/utils.py
@@ -0,0 +1,64 @@
+import os
+import socket
+
+
+def send_packet(host, port, message):
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(5)
+ s.connect((host, port))
+ s.send(message.encode('utf-8'))
+ s.close()
+ except Exception as ex:
+ #print("Error while sending packet: " + message)
+ #print(ex.__str__() + " " + str(port))
+ pass
+
+
+def clear():
+ os.system('clear')
+
+
+def enter_continue():
+ print(change_style("\n\n\nEnter to continue...", 'bold'))
+ tmp = input()
+ clear()
+
+
+def change_style(str, style):
+ if style == "green":
+ return "\033[92m{}\033[00m".format(str)
+ elif style == "blue":
+ return "\033[34m{}\033[00m".format(str)
+ elif style == "header":
+ return "\033[34m \033[01m{}\033[00m".format(str)
+ elif style == "bold":
+ return "\033[01m{}\033[00m".format(str)
+ elif style == "red":
+ return "\033[31m{}\033[00m".format(str)
+ elif style == "error":
+ return "\033[41m \033[37m{}\033[00m".format(str)
+ elif style == "success":
+ return "\033[42m \033[37m{}\033[00m".format(str)
+ elif style == "underline":
+ return "\033[4m{}\033[00m".format(str)
+ elif style == "receiver":
+ return "\033[01m\033[35m{}\033[00m".format(str)
+ elif style == "sender":
+ return "\033[01m\033[36m{}\033[00m".format(str)
+
+ return str
+
+
+def print_notification(str):
+ print("\a \033[s \033[100F \033[2K \r {} {} \033[u".format(change_style(" [!] ", "bold"),
+ change_style(str + " ", "success")), end="")
+
+
+def print_error(str):
+ print("\a \033[s \033[100F \033[2K \r {} {} \033[u".format(change_style(" [x] ", "bold"),
+ change_style(str + " ", "error")), end="")
+
+
+def print_header(header):
+ print(change_style("\n\n=== " + header + " ===\n\n", 'header'))
diff --git a/cmpe487/zeroconf-chat/LICENSE b/cmpe487/zeroconf-chat/LICENSE
new file mode 100644
index 0000000..bc4ea92
--- /dev/null
+++ b/cmpe487/zeroconf-chat/LICENSE
@@ -0,0 +1,25 @@
+BSD 2-Clause License
+
+Copyright (c) 2018, Enes Çakır
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/cmpe487/zeroconf-chat/README.md b/cmpe487/zeroconf-chat/README.md
new file mode 100644
index 0000000..0d0a8f2
--- /dev/null
+++ b/cmpe487/zeroconf-chat/README.md
@@ -0,0 +1,27 @@
+# CmpE 487 Workshop 3
+## P2P Zeroconf Chat App
+
+I tested it with Emirhan and Murat
+But lots of discovery packeges were not received, discovery is working with ~%20 success
+
+### Requirements
+- Python 3
+- On the same network with other users
+
+### Usage
+```bash
+ $ python3 chat.py
+```
+
+![Main Menu](main-menu.png)
+
+### Testing
+You can create your test scenarios at main function of `test.py`
+```bash
+ $ python3 test.py ?[TARGET_IP]
+```
+
+![Testing](testing.png)
+
+### License
+P2P Python Chat App is an open-sourced software licensed under the [BSD-2 license](https://opensource.org/licenses/BSD-2-Clause).
diff --git a/cmpe487/zeroconf-chat/chat.py b/cmpe487/zeroconf-chat/chat.py
new file mode 100644
index 0000000..278ab39
--- /dev/null
+++ b/cmpe487/zeroconf-chat/chat.py
@@ -0,0 +1,75 @@
+import sys
+import time
+from server import *
+
+# MAIN APPLICATION
+clear()
+print_header("WELCOME TO P2P PYTHON CHAT APP")
+
+# Kill old chat applications
+os.system('pkill -f "Python app.py"')
+
+# Get username
+username = input("\n" + change_style("Enter your username", 'underline') + ": ")
+
+# Start chat server
+clear()
+server = ChatServer(username, 5000, 5001)
+server.print_profile()
+enter_continue()
+server.listen_discovery()
+server.listen_broadcast_discovery()
+server.inform_network()
+server.listen_message()
+time.sleep(2)
+clear()
+
+while True:
+ print_header("AVAILABLE COMMANDS")
+
+ commands = ["List online users", "Send message", "Show my profile", "Discover user", "Discover broadcast", "Quit"]
+
+ total_unread = server.get_total_unread()
+
+ if total_unread:
+ commands[1] = "Send message (" + change_style(str(total_unread) + " unread messages", "green") + ")"
+
+ for i, command in enumerate(commands):
+ print("\t", change_style(str(i + 1) + ")", 'bold'), " ", command)
+
+ option = input("\n" + change_style("Please enter your command", 'underline') + ": ")
+ if option == "1":
+ clear()
+ server.print_users()
+ enter_continue()
+ elif option == "2":
+ clear()
+ server.select_chat()
+ elif option == "3":
+ clear()
+ server.print_profile()
+ enter_continue()
+ elif option == "4":
+ clear()
+ print_header("DISCOVER NEW USERS")
+ ip = input("\n" + change_style("Enter user IP for discovery", 'underline') + ": ")
+ if ip:
+ server.discover_user(ip)
+ enter_continue()
+ clear()
+ else:
+ clear()
+ print_error("Invalid IP address")
+ elif option == "5":
+ clear()
+ print_header("DISCOVER BROADCAST")
+ server.inform_network()
+ enter_continue()
+ clear()
+ elif option == "6":
+ clear()
+ print_notification("Good bye " + server.username + " \n\n")
+ sys.exit(0)
+ else:
+ clear()
+ print_error("Invalid option")
diff --git a/cmpe487/zeroconf-chat/main-menu.png b/cmpe487/zeroconf-chat/main-menu.png
new file mode 100644
index 0000000..32a8531
Binary files /dev/null and b/cmpe487/zeroconf-chat/main-menu.png differ
diff --git a/cmpe487/zeroconf-chat/server.py b/cmpe487/zeroconf-chat/server.py
new file mode 100644
index 0000000..589c3c9
--- /dev/null
+++ b/cmpe487/zeroconf-chat/server.py
@@ -0,0 +1,285 @@
+import socket
+from _thread import *
+import threading
+from utils import *
+import random
+import string
+import select
+
+class ChatServer:
+ users = {}
+
+ def __init__(self, username, discovery_port, message_port):
+ self.username = username
+
+ self.ip = socket.gethostbyname(socket.gethostname())
+ self.network = self.ip[:self.ip.rfind('.')]
+ self.discovery_port = discovery_port
+ self.message_port = message_port
+ self.buffer_size = 1024
+
+ def send_packet(self, host, port, message, rediscover=False):
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(3)
+ s.connect((host, port))
+ s.send(message.encode('utf-8'))
+ s.close()
+ except:
+ if rediscover:
+ print_error("Message couldn't sent")
+ self.inform_network()
+
+ def send_discovery_response(self, host, name):
+ message = ';'.join(['1', self.ip, self.username, host, name, ''])
+ start_new_thread(self.send_packet, (host, self.discovery_port, message))
+
+ def receive_discovery(self):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind((self.ip, self.discovery_port))
+ s.listen()
+
+ while True:
+ conn, addr = s.accept()
+
+ data = conn.recv(1024)
+ if not data:
+ break
+
+ discovery_packet = str(data.decode('utf-8'))
+
+ try:
+ packet_type, source_ip, source_name, target_ip, target_name, *end = discovery_packet.split(";")
+ if packet_type == "1":
+ print_notification(source_name + " is online")
+ self.set_name(source_ip, source_name)
+ elif packet_type == "0":
+ print_notification(source_name + " open chat client")
+ self.set_name(source_ip, source_name)
+ self.send_discovery_response(source_ip, source_name)
+ else:
+ print_error("Unknown Discovery TCP Packet")
+ except ValueError:
+ print_error("Unknown Discovery TCP Packet")
+ conn.close()
+ s.close()
+
+ def receive_broadcast(self):
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ s.bind(('', self.discovery_port))
+ s.setblocking(False)
+
+ while True:
+ data = select.select([s], [], [])
+
+ if not data:
+ break
+
+ message = data[0][0].recv(self.buffer_size)
+
+ if not message:
+ break
+
+ discovery_packet = str(message.decode('utf-8'))
+
+ try:
+ packet_type, source_ip, source_name, target_ip, target_name, *end = discovery_packet.split(";")
+ if source_ip != self.ip:
+ if packet_type == "0":
+ print_notification(source_name + " open chat client")
+ self.set_cipher(source_ip, None)
+ self.set_name(source_ip, source_name)
+ self.send_discovery_response(source_ip, source_name)
+ else:
+ print_error("Unknown Discovery UDP Packet")
+ except ValueError:
+ print_error("Unknown Discovery UDP Packet")
+
+ s.close()
+
+ def listen_discovery(self):
+ print(change_style("Discovering on port TCP " + change_style(str(self.discovery_port), 'bold'), 'green'))
+ discovery_thread = threading.Thread(target=self.receive_discovery)
+ discovery_thread.setDaemon(True)
+ discovery_thread.start()
+
+ def listen_broadcast_discovery(self):
+ print(change_style("Discovering on port UDP " + change_style(str(self.discovery_port), 'bold'), 'green'))
+ discovery_thread = threading.Thread(target=self.receive_broadcast)
+ discovery_thread.setDaemon(True)
+ discovery_thread.start()
+
+ def inform_client(self, ip):
+ message = ';'.join(['0', self.ip, self.username, ip, '', ''])
+ self.send_packet(ip, self.discovery_port, message)
+
+ def inform_network(self):
+ print(change_style("Informing all device at same network...", 'green'))
+ self.users = {}
+ message = ';'.join(['0', self.ip, self.username, '', '', ''])
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.bind(('', 0))
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
+ sock.sendto(message.encode('utf-8'), ('', self.discovery_port))
+
+ def discover_user(self, ip):
+ start_new_thread(self.inform_client, (ip,))
+ print(change_style('\n\nDiscovering ' + ip + '...', 'green'))
+
+ def receive_message(self):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind((self.ip, self.message_port))
+ s.listen()
+
+ while True:
+ conn, addr = s.accept()
+
+ data = conn.recv(1024)
+ if not data:
+ break
+
+ message_packet = str(data.decode('utf-8'))
+
+ try:
+ source_ip, source_cipher, body = message_packet.split(";")
+ target_cipher = self.get_cipher(source_ip)
+
+ if target_cipher is None or hash_MD5(target_cipher) == source_cipher:
+ user = self.get_user(source_ip)
+ user.cipher = source_cipher
+ user.add_message(body, False)
+ print_notification("New message from " + user.name)
+ else:
+ print_error("Not valid message from " + source_ip)
+ except ValueError:
+ pass
+ conn.close()
+
+ s.close()
+
+ def listen_message(self):
+ print(change_style("Listening messages on port " + change_style(str(self.message_port), 'bold'), 'green'))
+ message_thread = threading.Thread(target=self.receive_message)
+ message_thread.setDaemon(True)
+ message_thread.start()
+
+ def select_chat(self):
+ print_header("SELECT ONLINE USER")
+ print("\t{0:s} {1:s}".format("0)".ljust(5), "Go back"))
+ for ip, user in self.users.items():
+ unread = ""
+ if user.unread:
+ unread = "(" + change_style(str(user.unread) + " unread messages", "green") + ")"
+ print("\t{0:s} {1:s} {2:s}".format((ip[ip.rfind('.') + 1:] + ")").ljust(5), user.name, unread))
+
+ id = input("\nEnter use ID: ")
+ if id == "0":
+ clear()
+ else:
+ self.show_chat(id)
+
+ def show_chat(self, id):
+ clear()
+ target_ip = self.network + "." + id
+ user = self.get_user(target_ip)
+ if user is None:
+ print_error("Please enter valid user ID")
+ self.select_chat()
+ else:
+ print()
+ if user.messages:
+ for message in user.messages:
+ if message.is_sent:
+ print("{} {}".format((change_style(self.username + ": ", 'receiver')).ljust(25), message.body))
+ else:
+ notif = ""
+ if not message.is_read:
+ notif = change_style("*", "red")
+ print(
+ "{} {}".format((change_style(user.name + ": ", 'sender') + notif).ljust(25), message.body))
+ else:
+ print_error("You don't have any messages history with " + user.name)
+
+ user.read_message()
+
+ body = input("\n\nEnter your message [write 'exit' for go back]: \n> ")
+
+ if body != "exit":
+ if body:
+ user.messages.append(Message(body, True))
+ if user.cipher:
+ user.cipher = hash_MD5(user.cipher)
+ else:
+ user.cipher = hash_MD5(''.join(random.choices(string.ascii_uppercase + string.digits, k=10)))
+
+ message = ';'.join([self.ip, user.cipher, body])
+ start_new_thread(self.send_packet, (user.ip, self.message_port, message, True))
+ self.show_chat(id)
+ clear()
+
+ def print_users(self):
+ print_header("ONLINE USERS")
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format("IP".ljust(20), "NAME".ljust(20)))
+ print('-' * 46)
+ for ip, user in self.users.items():
+ print('| {0:s} | {1:s}|'.format(change_style(ip.ljust(20), 'bold'),
+ change_style(user.name.ljust(20), 'green')))
+ print('-' * 46)
+
+ def print_profile(self):
+ print_header("YOUR PROFILE")
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format(change_style("Username".ljust(20), 'bold'),
+ change_style(self.username.ljust(20), 'green')))
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format(change_style("Local IP".ljust(20), 'bold'),
+ change_style(self.ip.ljust(20), 'green')))
+ print('-' * 46)
+ print('| {0:s} | {1:s}|'.format(change_style("Local Network".ljust(20), 'bold'),
+ change_style(self.network.ljust(20), 'green')))
+ print('-' * 46)
+
+ def get_users(self):
+ # TODO: order users
+ return self.users.items()
+ # [print(key, " :: ", value) for (key, value) in sorted(self.users.items())]
+ # return self.users.items().sort(key=lambda (k, v): (v, k))
+
+ def get_name(self, ip):
+ if ip in self.users:
+ return self.users[ip].name
+
+ def get_cipher(self, ip):
+ if ip in self.users:
+ return self.users[ip].cipher
+
+ def get_user(self, ip):
+ if ip in self.users:
+ return self.users[ip]
+
+ def get_total_unread(self):
+ total = 0
+ for ip, user in self.users.items():
+ total += user.unread
+ return total
+
+ def get_unread(self, ip):
+ if ip in self.users:
+ return self.users[ip].name
+ else:
+ return 0
+
+ def set_name(self, ip, name):
+ if ip in self.users:
+ self.users[ip].name = name
+ else:
+ self.users[ip] = User(ip, name)
+
+ def set_cipher(self, ip, cipher):
+ if ip in self.users:
+ self.users[ip].cipher = cipher
+ else:
+ self.users[ip] = User(ip, 'Unknown', cipher)
diff --git a/cmpe487/zeroconf-chat/test.py b/cmpe487/zeroconf-chat/test.py
new file mode 100644
index 0000000..9637cc3
--- /dev/null
+++ b/cmpe487/zeroconf-chat/test.py
@@ -0,0 +1,92 @@
+import socket
+import sys
+import random
+from utils import *
+
+TARGET_HOST = socket.gethostbyname(socket.gethostname())
+if len(sys.argv) > 1:
+ TARGET_HOST = sys.argv[1]
+
+TARGET_NETWORK = TARGET_HOST[:TARGET_HOST.rfind('.')]
+NAMES = ['Enes', 'Emirhan', 'Deniz', 'Mehmet', 'Ali', 'Ceren', 'Buse', 'Büşra', 'Ahmet', 'Veli']
+MESSAGES = ['Naber', 'Nasılsın?', 'İyi misin?', 'Selamlar', 'Hava nasıl?', 'Güzel', 'Tebrikler']
+DISCOVER_PORT = 5000
+MESSAGE_PORT = 5001
+
+
+def send_packet(host, port, message):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ try:
+ s.connect((host, port))
+ s.send(message.encode('utf-8'))
+ s.close()
+ except:
+ print("Connection error")
+
+
+def get_random_name():
+ return random.choice(NAMES)
+
+
+def get_random_message():
+ return random.choice(MESSAGES)
+
+
+def get_random_ip():
+ return TARGET_NETWORK + "." + str(random.randint(1, 255))
+
+
+def send_discover_request(ip=None):
+ source_ip = ip if ip else get_random_ip()
+ print(change_style("Sent discovery request from " + source_ip, "green"))
+ packet = "0;{};{};{};;".format(source_ip, get_random_name(), TARGET_HOST)
+ send_packet(TARGET_HOST, DISCOVER_PORT, packet)
+ return source_ip
+
+def send_discover_brodcast(ip=None):
+ source_ip = ip if ip else get_random_ip()
+ print(change_style("Sent discovery request from " + source_ip, "green"))
+ packet = "0;{};{};{};;".format(source_ip, get_random_name(), TARGET_HOST)
+
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.bind(('', 0))
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
+ sock.sendto(packet.encode('utf-8'), ('', DISCOVER_PORT))
+
+ return source_ip
+
+
+def send_discover_response(ip=None):
+ source_ip = ip if ip else get_random_ip()
+ print(change_style("Sent discovery response from " + source_ip, "green"))
+ packet = "1;{};{};{};{};".format(source_ip, get_random_name(), TARGET_HOST, get_random_name())
+ send_packet(TARGET_HOST, DISCOVER_PORT, packet)
+ return source_ip
+
+
+def send_message(raw_cipher, hash_count=0, ip=None, message=None):
+ source_ip = ip if ip else get_random_ip()
+ sent_message = message if message else get_random_message()
+ cipher = raw_cipher
+ for x in range(hash_count):
+ cipher = hash_MD5(cipher)
+
+ print(change_style("Sent message from " + source_ip + " with '" + cipher + "' cipher", "green"))
+
+ packet = "{};{};{}".format(source_ip, cipher, sent_message)
+ send_packet(TARGET_HOST, MESSAGE_PORT, packet)
+
+ return cipher
+
+
+if __name__ == "__main__":
+ clear()
+ print_header("TESTING " + TARGET_HOST + " CHAT SERVER")
+ ip = send_discover_brodcast()
+ send_discover_response(ip)
+ send_message("test", 0, ip, 'deneme1')
+ send_message("test", 1, ip, 'deneme2')
+ send_message("test", 1, ip, 'deneme3')
+ send_discover_brodcast(ip)
+ send_message("test", 1, ip, 'deneme4')
+ print("\n\n\n")
diff --git a/cmpe487/zeroconf-chat/testing.png b/cmpe487/zeroconf-chat/testing.png
new file mode 100644
index 0000000..017c81d
Binary files /dev/null and b/cmpe487/zeroconf-chat/testing.png differ
diff --git a/cmpe487/zeroconf-chat/utils.py b/cmpe487/zeroconf-chat/utils.py
new file mode 100644
index 0000000..7d232ac
--- /dev/null
+++ b/cmpe487/zeroconf-chat/utils.py
@@ -0,0 +1,81 @@
+import os
+import hashlib
+
+
+class Message:
+ def __init__(self, body, is_sent=False):
+ self.body = body
+ self.is_sent = is_sent
+ self.is_read = False
+
+
+class User:
+ def __init__(self, ip, name, chipher=None):
+ self.ip = ip
+ self.name = name
+ self.cipher = chipher
+ self.unread = 0
+ self.messages = []
+
+ def add_message(self, message, is_sent):
+ self.messages.append(Message(message, is_sent))
+ if not is_sent:
+ self.unread += 1
+
+ def read_message(self):
+ self.unread = 0
+ for message in self.messages:
+ message.is_read = True
+
+
+def clear():
+ os.system('clear')
+
+
+def enter_continue():
+ print(change_style("\n\n\nEnter to continue...", 'bold'))
+ tmp = input()
+ clear()
+
+
+def change_style(str, style):
+ if style == "green":
+ return "\033[92m{}\033[00m".format(str)
+ elif style == "header":
+ return "\033[34m \033[01m{}\033[00m".format(str)
+ elif style == "bold":
+ return "\033[01m{}\033[00m".format(str)
+ elif style == "red":
+ return "\033[31m{}\033[00m".format(str)
+ elif style == "error":
+ return "\033[41m \033[37m{}\033[00m".format(str)
+ elif style == "success":
+ return "\033[42m \033[37m{}\033[00m".format(str)
+ elif style == "underline":
+ return "\033[4m{}\033[00m".format(str)
+ elif style == "receiver":
+ return "\033[01m\033[35m{}\033[00m".format(str)
+ elif style == "sender":
+ return "\033[01m\033[36m{}\033[00m".format(str)
+
+ return str
+
+
+def print_notification(str):
+ print("\a \033[s \033[100F \033[2K \r {} {} \033[u".format(change_style(" [!] ", "bold"),
+ change_style(str + " ", "success")), end="")
+
+
+def print_error(str):
+ print("\a \033[s \033[100F \033[2K \r {} {} \033[u".format(change_style(" [x] ", "bold"),
+ change_style(str + " ", "error")), end="")
+
+
+def print_header(header):
+ print(change_style("\n\n=== " + header + " ===\n\n", 'header'))
+
+
+def hash_MD5(str):
+ m = hashlib.md5()
+ m.update(str.encode('utf-8'))
+ return m.hexdigest()
diff --git a/ie310/capacities.txt b/ie310/capacities.txt
new file mode 100644
index 0000000..7f662b7
--- /dev/null
+++ b/ie310/capacities.txt
@@ -0,0 +1,5 @@
+1 350
+2 250
+3 500
+4 400
+5 200
diff --git a/ie310/distances.txt b/ie310/distances.txt
new file mode 100644
index 0000000..e71efbe
--- /dev/null
+++ b/ie310/distances.txt
@@ -0,0 +1,50 @@
+1.1 3.4
+1.2 1.4
+1.3 4.9
+1.4 7.4
+1.5 9.3
+2.1 2.4
+2.2 2.1
+2.3 8.3
+2.4 9.1
+2.5 8.8
+3.1 1.4
+3.2 2.9
+3.3 3.7
+3.4 9.4
+3.5 8.6
+4.1 2.6
+4.2 3.6
+4.3 4.5
+4.4 8.2
+4.5 8.9
+5.1 1.5
+5.2 3.1
+5.3 2.1
+5.4 7.9
+5.5 8.8
+6.1 4.2
+6.2 4.9
+6.3 6.5
+6.4 7.7
+6.5 6.1
+7.1 4.8
+7.2 6.2
+7.3 9.9
+7.4 6.2
+7.5 5.7
+8.1 5.4
+8.2 6.0
+8.3 5.2
+8.4 7.6
+8.5 4.9
+9.1 3.1
+9.2 4.1
+9.3 6.6
+9.4 7.5
+9.5 7.2
+10.1 3.2
+10.2 6.5
+10.3 7.1
+10.4 6.0
+10.5 8.3
diff --git a/ie310/estimates.txt b/ie310/estimates.txt
new file mode 100644
index 0000000..37fd4f6
--- /dev/null
+++ b/ie310/estimates.txt
@@ -0,0 +1,10 @@
+1 153
+2 152
+3 154
+4 138
+5 127
+6 129
+7 111
+8 110
+9 130
+10 135
diff --git a/ie310/quiz4-1.gms b/ie310/quiz4-1.gms
new file mode 100644
index 0000000..9a619af
--- /dev/null
+++ b/ie310/quiz4-1.gms
@@ -0,0 +1,38 @@
+SETS
+ i sector / 1*10 /
+ j disposal site / 1*5 / ;
+
+PARAMETER q(j) capacity of disposal site j /
+$include "capacities.txt"
+/;
+
+PARAMETER d(i,j) distance from sector i to disposal site j in kilometers /
+$include "distances.txt"
+/;
+
+PARAMETER e(i) estimated annual snow removal requirements of sector i /
+$include "estimates.txt"
+/;
+
+SCALAR C cost of the transporting one thousand cubic meter of snow one kilometer ;
+C = 0.10 * 1000;
+
+VARIABLE Z total cost for objective function ;
+BINARY VARIABLE X(i,j) 0 or 1 indicating assignment of sector i to disposal site j ;
+
+EQUATIONS
+COST define total objective function
+CAP(j) capacity constraints
+ASGN(i) sector assignment constraints;
+
+COST .. Z =e= SUM((i,j), X(i,j) * d(i,j) * e(i) * C);
+CAP(J) .. SUM(i, X(i,j) * e(i)) =L= q(j);
+ASGN(I) .. SUM(j, X(i,j)) =e= 1;
+
+MODEL GAP /ALL/ ;
+OPTION MIP = Cplex;
+OPTION optca=0;
+OPTION optcr=0;
+SOLVE GAP USING MIP MINIMIZING Z ;
+
+DISPLAY X.L;
diff --git a/ie310/quiz4-1.txt b/ie310/quiz4-1.txt
new file mode 100644
index 0000000..56cbbb7
--- /dev/null
+++ b/ie310/quiz4-1.txt
@@ -0,0 +1,7 @@
+
+MIP Solution: 547000.000000 (23 iterations, 0 nodes)
+Final Solve: 547000.000000 (0 iterations)
+
+Best possible: 547000.000000
+Absolute gap: 0.000000
+Relative gap: 0.000000
diff --git a/ie310/quiz4-2.gms b/ie310/quiz4-2.gms
new file mode 100644
index 0000000..791d585
--- /dev/null
+++ b/ie310/quiz4-2.gms
@@ -0,0 +1,41 @@
+SETS
+ i sector / 1*10 /
+ j disposal site / 1*5 / ;
+
+PARAMETER q(j) capacity of disposal site j /
+$include "capacities.txt"
+/;
+
+PARAMETER d(i,j) distance from sector i to disposal site j in kilometers /
+$include "distances.txt"
+/;
+
+PARAMETER e(i) estimated annual snow removal requirements of sector i /
+$include "estimates.txt"
+/;
+
+SCALAR C cost of the transporting one thousand cubic meter of snow one kilometer ;
+C = 0.10 * 1000;
+
+VARIABLE Z total cost for objective function ;
+
+VARIABLE X(i,j) indicating assignment of sector i to disposal site j;
+X.up(i,j) = 1;
+X.lo(i,j) = 0;
+
+EQUATIONS
+COST define total objective function
+CAP(j) capacity constraints
+ASGN(i) sector assignment constraints;
+
+COST .. Z =e= SUM((i,j), X(i,j) * d(i,j) * e(i) * C);
+CAP(J) .. SUM(i, X(i,j) * e(i)) =L= q(j);
+ASGN(I) .. SUM(j, X(i,j)) =e= 1;
+
+MODEL GAP /ALL/ ;
+OPTION MIP = Cplex;
+OPTION optca = 0;
+OPTION optcr = 0;
+SOLVE GAP USING MIP MINIMIZING Z ;
+
+DISPLAY X.L;
diff --git a/ie310/quiz4-2.txt b/ie310/quiz4-2.txt
new file mode 100644
index 0000000..7f6f6fd
--- /dev/null
+++ b/ie310/quiz4-2.txt
@@ -0,0 +1,4 @@
+LP status(1): optimal
+Cplex Time: 0.00sec (det. 0.06 ticks)
+Optimal solution found.
+Objective : 478490.000000
diff --git a/ie310/quiz4-31.gms b/ie310/quiz4-31.gms
new file mode 100644
index 0000000..d3e6ef0
--- /dev/null
+++ b/ie310/quiz4-31.gms
@@ -0,0 +1,41 @@
+SETS
+ i sector / 1*10 /
+ j disposal site / 1*5 / ;
+
+PARAMETER q(j) capacity of disposal site j /
+$include "capacities.txt"
+/;
+
+PARAMETER d(i,j) distance from sector i to disposal site j in kilometers /
+$include "distances.txt"
+/;
+
+PARAMETER e(i) estimated annual snow removal requirements of sector i /
+$include "estimates.txt"
+/;
+
+SCALAR C cost of the transporting one thousand cubic meter of snow one kilometer ;
+C = 0.10 * 1000;
+
+VARIABLE Z total cost for objective function ;
+BINARY VARIABLE X(i,j) 0 or 1 indicating assignment of sector i to disposal site j;
+BINARY VARIABLE Y(j) 0 or 1 indicating disposal site j capacity increased by 100;
+
+EQUATIONS
+COST define total objective function
+CAP(j) capacity constraints
+ASGN(i) sector assignment constraints
+ICAP only one disposal site can increase capacity;
+
+COST .. Z =e= SUM((i,j), X(i,j) * d(i,j) * e(i) * C);
+CAP(J) .. SUM(i, X(i,j) * e(i)) =L= q(j) + (Y(j) * 100);
+ASGN(I) .. SUM(j, X(i,j)) =e= 1;
+ICAP .. SUM(j, Y(j)) =e= 1;
+
+MODEL GAP /ALL/ ;
+OPTION MIP = Cplex;
+OPTION optca = 0;
+OPTION optcr = 0;
+SOLVE GAP USING MIP MINIMIZING Z ;
+
+DISPLAY X.L;
diff --git a/ie310/quiz4-31.txt b/ie310/quiz4-31.txt
new file mode 100644
index 0000000..568f900
--- /dev/null
+++ b/ie310/quiz4-31.txt
@@ -0,0 +1,13 @@
+MODEL STATISTICS
+
+BLOCKS OF EQUATIONS 4 SINGLE EQUATIONS 17
+BLOCKS OF VARIABLES 3 SINGLE VARIABLES 56
+NON ZERO ELEMENTS 161 DISCRETE VARIABLES 55
+
+**** THE MODEL EXCEEDS THE DEMO LIMITS
+**** MAX MATRIX ROWS 300
+**** MAX MATRIX COLUMNS 300
+**** MAX NON ZERO ELEMENTS 2000
+**** MAX NON LINEAR N-Z 1000
+**** MAX DISCRETE VARIABLES 50
+**** Terminated due to a licensing error
diff --git a/ie310/quiz4-32.gms b/ie310/quiz4-32.gms
new file mode 100644
index 0000000..cbe3240
--- /dev/null
+++ b/ie310/quiz4-32.gms
@@ -0,0 +1,45 @@
+SETS
+ i sector / 1*10 /
+ j disposal site / 1*5 / ;
+
+PARAMETER q(j) capacity of disposal site j /
+$include "capacities.txt"
+/;
+
+PARAMETER d(i,j) distance from sector i to disposal site j in kilometers /
+$include "distances.txt"
+/;
+
+PARAMETER e(i) estimated annual snow removal requirements of sector i /
+$include "estimates.txt"
+/;
+
+SCALAR C cost of the transporting one thousand cubic meter of snow one kilometer ;
+C = 0.10 * 1000;
+
+VARIABLE Z total cost for objective function ;
+
+VARIABLE X(i,j) indicating assignment of sector i to disposal site j;
+X.up(i,j) = 1;
+X.lo(i,j) = 0;
+
+BINARY VARIABLE Y(j) 0 or 1 indicating disposal site j capacity increased by 100;
+
+EQUATIONS
+COST define total objective function
+CAP(j) capacity constraints
+ASGN(i) sector assignment constraints
+ICAP only one disposal site can increase capacity;
+
+COST .. Z =e= SUM((i,j), X(i,j) * d(i,j) * e(i) * C);
+CAP(J) .. SUM(i, X(i,j) * e(i)) =L= q(j) + (Y(j) * 100);
+ASGN(I) .. SUM(j, X(i,j)) =e= 1;
+ICAP .. SUM(j, Y(j)) =e= 1;
+
+MODEL GAP /ALL/ ;
+OPTION MIP = Cplex;
+OPTION optca=0;
+OPTION optcr=0;
+SOLVE GAP USING MIP MINIMIZING Z ;
+
+DISPLAY X.L;
diff --git a/ie310/quiz4-32.txt b/ie310/quiz4-32.txt
new file mode 100644
index 0000000..bede0de
--- /dev/null
+++ b/ie310/quiz4-32.txt
@@ -0,0 +1,6 @@
+MIP Solution: 455100.000000 (10 iterations, 0 nodes)
+Final Solve: 455100.000000 (9 iterations)
+
+Best possible: 455100.000000
+Absolute gap: 0.000000
+Relative gap: 0.000000