file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
AccountActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/AccountActivity.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.utils.Global;
import com.example.glass.ui.GlassGestureDetector;
import org.json.JSONArray;
public class AccountActivity extends BaseActivity {
String username="";
RequestQueue mRequestQueue;
String AccountUserId;
String AccountUserName="";
String AccountEmail="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
Intent intent = getIntent();
username = intent.getStringExtra("username");
mRequestQueue = Volley.newRequestQueue((Context) this);
getAccountDetails();
}
private void getAccountDetails(){
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/getAccountDetails/"+username, response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
if(success){
AccountUserId = data.getJSONObject(0).optString("user_id");
AccountUserName = data.getJSONObject(0).optString("user_name");
AccountEmail = data.getJSONObject(0).optString("user_email");
TextView accountNameText =(TextView) findViewById(R.id.accountNameValue);
TextView accountEmailText =(TextView) findViewById(R.id.accountEmailValue);
accountNameText.setText(AccountUserName);
accountEmailText.setText(AccountEmail);
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
}
@Override
public boolean onGesture(GlassGestureDetector.Gesture gesture) {
switch (gesture) {
case SWIPE_DOWN:
Intent intent = new Intent(getBaseContext(),ProductsActivity.class);
intent.putExtra("username", username);
startActivity(intent);
return true;
default:
return false;
}
}
public void BackToProductList(View view)
{
Intent intent = new Intent(getBaseContext(),ProductsActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
} | 2,888 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
CheckoutActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/CheckoutActivity.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.utils.Global;
import com.example.glass.ui.GlassGestureDetector.Gesture;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class CheckoutActivity extends BaseActivity{
RequestQueue mRequestQueue;
String username = "";
String cart_id3 = "";
String credit_card_id="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
Intent intent = getIntent();
mRequestQueue = Volley.newRequestQueue((Context) this);
username = intent.getStringExtra("username");
cart_id3 = intent.getStringExtra("cart_id3"); // Retrieve the cart_id extra
EditText cardNumber = findViewById(R.id.CardNumber);
EditText userName = findViewById(R.id.CardUserName);
EditText expDate = findViewById(R.id.ExperationDate);
EditText cvv =findViewById(R.id.Cvv);
EditText phone =findViewById(R.id.phone);
EditText address=findViewById(R.id.address);
Button submit1 = (Button) findViewById(R.id.SubmitButton);
submit1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String cardNu1 = cardNumber.getText().toString();
String username2 = userName.getText().toString();
String exprDate = expDate.getText().toString();
String Cvv= cvv.getText().toString();
String Phone=phone.getText().toString();
String Address=address.getText().toString();
String userr_id = username.toString();
String cart_idd=cart_id3;
if((TextUtils.isEmpty(cardNu1) || TextUtils.isEmpty(username2) || TextUtils.isEmpty(exprDate) || TextUtils.isEmpty(Cvv) || TextUtils.isEmpty(Phone) || TextUtils.isEmpty(Address))) {
Toast.makeText(getApplicationContext(), "Please fill all the blanks", Toast.LENGTH_SHORT).show();
} else if (cardNumber.length()!=20) {
Toast.makeText(getApplicationContext(), "Card Number has to be 16 digits", Toast.LENGTH_SHORT).show();
} else if (cvv.length()!=3) {
Toast.makeText(getApplicationContext(), "Cvv has to be 3 digits", Toast.LENGTH_SHORT).show();
} else if (expDate.length()!=5) {
Toast.makeText(getApplicationContext(), "Write correct ExpDate", Toast.LENGTH_SHORT).show();
} else if (phone.length()!=10) {
Toast.makeText(getApplicationContext(), "Rewrite phone number(5xx xxx xx xx)", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("card_username", username2);
hm.put("card_number", cardNu1);
hm.put("expiration_date", exprDate);
hm.put("cvv", Cvv);
hm.put("user_id", userr_id);
hm.put("phone_number", Phone);
hm.put("cart_id", cart_idd);
hm.put("address", Address);
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/checkout", new JSONObject(hm), response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
if(success){
getgeneratedCreditCard(userr_id, new CheckoutActivity.CreditCardCallback() {
@Override
public void onCreditCardReceived(String CreditCard) {
if (CreditCard != null) {
OrderCompleted(userr_id,CreditCard,cart_id3);
Intent intent = new Intent(getBaseContext(), OrdersActivity.class);
intent.putExtra("user_id", userr_id);
intent.putExtra("credit_card_id", CreditCard);
credit_card_id = CreditCard;
startActivity(intent);
} else {
Toast.makeText(CheckoutActivity.this, "Error: Unable to generate OTP", Toast.LENGTH_LONG).show();
}
}
});
cardNumber.setText("");
userName.setText("");
expDate.setText("");
cvv.setText("");
phone.setText("");
address.setText("");
} else {
Toast.makeText(CheckoutActivity.this, "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
}
}
});
EditText cardNumberEditText = findViewById(R.id.CardNumber);
cardNumberEditText.addTextChangedListener(new TextWatcher() {
private boolean isFormatting;
private String previousText;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
previousText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// No-op
}
@Override
public void afterTextChanged(Editable s) {
if (isFormatting) {
return;
}
isFormatting = true;
// Remove all spaces from the string
String digitsOnly = s.toString().replaceAll("\\s", "");
StringBuilder formatted = new StringBuilder();
int digitCount = 0;
for (int i = 0; i < digitsOnly.length(); i++) {
formatted.append(digitsOnly.charAt(i));
digitCount++;
if (digitCount == 4) {
formatted.append(" ");
digitCount = 0;
}
}
// Update the text in the EditText
int selectionIndex = formatted.length();
cardNumberEditText.setText(formatted.toString());
cardNumberEditText.setSelection(selectionIndex);
// Prevent infinite recursion (afterTextChanged is called again)
isFormatting = false;
}
});
EditText cvvEditText = findViewById(R.id.ExperationDate);
cvvEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String cvvText = s.toString().trim();
if (cvvText.length() == 2 && before == 0) {
cvvEditText.setText(cvvText + "/");
cvvEditText.setSelection(cvvEditText.getText().length());
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(CheckoutActivity.this,CartActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
});
}
private void getgeneratedCreditCard(String userID, CheckoutActivity.CreditCardCallback callback) {
JsonObjectRequest mRequest = new JsonObjectRequest(Global.url + "/getlatestcreditCardID/" + userID, null, response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
if (success) {
JSONArray data = response.optJSONArray("Data");
try {
String generatedCreditCard = data.getJSONObject(0).optString("credit_card_id");
callback.onCreditCardReceived(generatedCreditCard);
} catch (JSONException e) {
callback.onCreditCardReceived(null);
}
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
callback.onCreditCardReceived(null);
}
} catch (Exception e) {
callback.onCreditCardReceived(null);
}
}, error -> {
callback.onCreditCardReceived(null);
});
mRequestQueue.add(mRequest);
}
interface CreditCardCallback {
void onCreditCardReceived(String CreditCardID);
}
@Override
public boolean onGesture(Gesture gesture) {
switch (gesture) {
case SWIPE_DOWN:
finish();
return true;
default:
return false;
}
}
public void OrderCompleted(String username,String credit_card_id,String cart_id3) {
if (username != null && credit_card_id != null && cart_id3 != null) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("user_id", username);
hm.put("credit_card_id", credit_card_id);
hm.put("cart_id", cart_id3);
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/orders", new JSONObject(hm), response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
if(success){
Toast.makeText(CheckoutActivity.this, "Order Completed!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CheckoutActivity.this, "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
} else {
}
}
}
| 11,519 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
CartActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/CartActivity.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.adapters.CartAdapter;
import com.example.glass.arshopping.models.Cart;
import com.example.glass.arshopping.utils.Global;
import com.example.glass.ui.GlassGestureDetector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class CartActivity extends BaseActivity implements GlassGestureDetector.OnGestureListener {
ListView cartList;
String username = "";
RequestQueue mRequestQueue;
String cart_id3;
String idd;
String sdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
username = intent.getStringExtra("username");
String cart_id2 = intent.getStringExtra("cart_id2");
Log.d("denemeyapma", "denemeyapma: " + cart_id3);
setContentView(R.layout.activity_cart);
mRequestQueue = Volley.newRequestQueue((Context) this);
getData(username);
findViewById(R.id.confirmCart).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (cart_id3 != null) {
Intent intent = new Intent(CartActivity.this, CheckoutActivity.class);
intent.putExtra("username", username);
intent.putExtra("cart_id3", cart_id3);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "There is no product in cart!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onRemoveButtonClick(View view) {
TextView text = findViewById(R.id.cidd);
if (text != null) {
String id = text.getText().toString();
if (!TextUtils.isEmpty(id)) {
HashMap<String, String> hm = new HashMap<>();
hm.put("id", id);
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url + "/removecart", new JSONObject(hm), response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
if (success) {
Toast.makeText(getApplicationContext(), "Product Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), ProductsActivity.class);
intent.putExtra("username", username);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
},
error -> {
error.printStackTrace();
});
mRequestQueue.add(mRequest);
} else {
Toast.makeText(getApplicationContext(), "Invalid cart ID", Toast.LENGTH_SHORT).show();
}
}
}
//end
@Override
public boolean onGesture(GlassGestureDetector.Gesture gesture) {
switch (gesture) {
case SWIPE_BACKWARD:
Intent intent = new Intent(getBaseContext(),ProductsActivity.class);
intent.putExtra("username", username);
startActivity(intent);
return true;
default:
return false;
}
} private void getData(String username){
List<Cart> cart = new ArrayList<Cart>();
Context ctx = this;
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/cart/"+username, response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
if(success){
for (int i=0; i< data.length(); i++) {
try {
String seller_id= data.getJSONObject(i).optString("seller_id");
String product_name = data.getJSONObject(i).optString("product_name");
String quantity = data.getJSONObject(i).optString("quantity");
String product_img = data.getJSONObject(i).optString("product_img");
String date = data.getJSONObject(i).optString("date");
String id = data.getJSONObject(i).optString("id");
String cart_id2 = data.getJSONObject(i).optString("cart_id");
cart_id3 = cart_id2; // Assign the value to cart_id3
idd=id;
cart.add(new Cart(seller_id, product_name, quantity, date,id,product_img,cart_id2));
} catch (JSONException e) {}
}
cartList = (ListView) findViewById(R.id.listCart);
CartAdapter aCart = new CartAdapter(ctx, cart);
cartList.setAdapter(aCart);
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
}
public void BackToProductList(View view)
{
Intent intent = new Intent(getBaseContext(),ProductsActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
} | 6,386 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
MainActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/MainActivity.java | package com.example.glass.arshopping;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.glass.ui.GlassGestureDetector.Gesture;
public class MainActivity extends BaseActivity {
private static final int REQUEST_CODE = 105;
private TextView resultLabel;
private TextView scanResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.SignUpButtonm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SignUp.class);
startActivity(intent);
}
});
findViewById(R.id.loginButtonm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,Login.class);
startActivity(intent);
}
});
}
@Override
public boolean onGesture(Gesture gesture) {
switch (gesture) {
case SWIPE_DOWN:
finishAffinity();
finish();
return true;
default:
return false;
}
}
} | 1,257 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
CameraActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/CameraActivity.java | package com.example.glass.arshopping;
import android.Manifest.permission;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Size;
import android.view.TextureView;
import androidx.annotation.NonNull;
import androidx.camera.core.CameraX;
import androidx.core.content.ContextCompat;
import com.example.glass.arshopping.R;
import com.example.glass.arshopping.QRCodeImageAnalysis.QrCodeAnalysisCallback;
import com.example.glass.ui.GlassGestureDetector.Gesture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CameraActivity extends BaseActivity implements QrCodeAnalysisCallback {
public static final String QR_SCAN_RESULT = "SCAN_RESULT";
private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 105;
private ExecutorService executorService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
executorService = Executors.newSingleThreadExecutor();
if (ContextCompat.checkSelfPermission(this,
permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
startCamera();
} else {
requestPermissions(new String[]{permission.CAMERA}, CAMERA_PERMISSIONS_REQUEST_CODE);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
executorService.shutdown();
}
@Override
public boolean onGesture(Gesture gesture) {
switch (gesture) {
case SWIPE_DOWN:
finishNoQR();
return true;
default:
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS_REQUEST_CODE) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
finishNoQR();
} else {
startCamera();
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public void onQrCodeDetected(String result) {
final Intent intent = new Intent();
intent.putExtra(QR_SCAN_RESULT, result);
setResult(Activity.RESULT_OK, intent);
finish();
}
private void startCamera() {
final TextureView textureView = findViewById(R.id.view_finder);
final QRCodePreview qrCodePreview = new QRCodePreview(
CameraConfigProvider.getPreviewConfig(getDisplaySize()),
textureView);
final QRCodeImageAnalysis qrCodeImageAnalysis = new QRCodeImageAnalysis(
CameraConfigProvider.getImageAnalysisConfig(), executorService, this);
CameraX.bindToLifecycle(this, qrCodePreview.getUseCase(), qrCodeImageAnalysis.getUseCase());
}
private void finishNoQR() {
setResult(Activity.RESULT_CANCELED);
finish();
}
private Size getDisplaySize() {
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return new Size(displayMetrics.widthPixels, displayMetrics.heightPixels);
}
}
| 3,234 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
OrderListActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/OrderListActivity.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.adapters.OrderListAdapter;
import com.example.glass.arshopping.models.Orders;
import com.example.glass.arshopping.utils.Global;
import com.example.glass.ui.GlassGestureDetector;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
public class OrderListActivity extends BaseActivity implements GlassGestureDetector.OnGestureListener {
ListView orderList;
String username = "";
String order_iddd = "";
RequestQueue mRequestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
username = intent.getStringExtra("username");
setContentView(R.layout.activity_order_list);
mRequestQueue = Volley.newRequestQueue((Context) this);
getData(username);
}
public void orderClick(View view) {
Intent intent = new Intent(getBaseContext(), OrdersActivity.class);
String order_idd = ((TextView)view.findViewById(R.id.order_idd)).getText().toString();
intent.putExtra("order_id", order_idd);
intent.putExtra("user_id", username);
startActivity(intent);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
getData(username);
}
}
@Override
public boolean onGesture(GlassGestureDetector.Gesture gesture) {
switch (gesture) {
case SWIPE_BACKWARD:
finish();
return true;
default:
return false;
}
}
private void getData(String user_Name) {
List<com.example.glass.arshopping.models.Orders> orders1 = new ArrayList<Orders>();
Context ctx = this;
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url + "/orderl/" + username, response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
if (success && data != null) {
for (int i = 0; i < data.length(); i++) {
try {
double total_amount = data.getJSONObject(i).optDouble("total_amount");
int order_id = data.getJSONObject(i).optInt("order_id");
order_iddd=order_id + "";
String order_date = data.getJSONObject(i).optString("order_date");
orders1.add(new com.example.glass.arshopping.models.Orders().createOrderWithMinimalData(
total_amount, order_id, order_date));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
orderList = findViewById(R.id.listOrderx);
OrderListAdapter aOrder = new OrderListAdapter(ctx, orders1);
orderList.setAdapter(aOrder);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}, error -> {
error.printStackTrace();
});
mRequestQueue.add(mRequest);
}
public void BackToProductList(View view)
{
Intent intent = new Intent(getBaseContext(),ProductsActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
} | 4,403 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
OrdersActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/OrdersActivity.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.adapters.CustomerInfoAdapter;
import com.example.glass.arshopping.adapters.OrdersAdapter;
import com.example.glass.arshopping.utils.Global;
import com.example.glass.ui.GlassGestureDetector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class OrdersActivity extends AppCompatActivity implements GlassGestureDetector.OnGestureListener {
String user_id;
String credit_card_id = "";
String order_iddd = "";
ListView myList;
RequestQueue mRequestQueue;
ListView orderList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
user_id = getIntent().getStringExtra("user_id");
credit_card_id = getIntent().getStringExtra("credit_card_id");
order_iddd = getIntent().getStringExtra("order_id");
mRequestQueue = Volley.newRequestQueue(this);
getData(credit_card_id,order_iddd);
getData2(credit_card_id,order_iddd);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
getData(credit_card_id,order_iddd);
getData2(credit_card_id,order_iddd);
}
}
private void getData(String credit_card_id, String order_idd) {
List<com.example.glass.arshopping.models.Orders> datasx = new ArrayList<>();
Context ctx = this;
String url = null;
if (credit_card_id != null) {
url = Global.url + "/orderlist/" + credit_card_id;
} else if(order_idd != null) {
url = Global.url + "/myorders/" + order_idd;
}
JsonObjectRequest mRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("Data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject orderObject = dataArray.getJSONObject(i);
double total_amount = orderObject.optDouble("total_amount");
int cart_id = orderObject.optInt("cart_id");
String credit_card_id2 = orderObject.optString("credit_card_id");
String user_id = orderObject.optString("user_id");
int order_id = orderObject.optInt("order_id");
int product_id = orderObject.optInt("product_id");
String quantity = orderObject.optString("quantity");
String address = orderObject.optString("address");
String product_img = orderObject.optString("product_img");
String product_name = orderObject.optString("product_name");
double product_price = orderObject.optDouble("product_price");
String seller_name = orderObject.optString("seller_name");
String order_date = orderObject.optString("order_date");
datasx.add(new com.example.glass.arshopping.models.Orders().createOrder(total_amount, order_id, cart_id, address,
credit_card_id2, user_id, product_img, product_name, seller_name, quantity, order_date, product_price, product_id));
}
ListView orderList = findViewById(R.id.listOrders2);
OrdersAdapter aOrder = new OrdersAdapter(ctx, datasx);
orderList.setAdapter(aOrder);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(ctx, "Error parsing JSON data", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(ctx, "Error retrieving data", Toast.LENGTH_LONG).show();
}
});
mRequestQueue.add(mRequest);
}
private void getData2(String credit_card_id, String order_idd) {
List<com.example.glass.arshopping.models.Orders> orders2 = new ArrayList<>();
Context ctx = this;
String url = null;
if (credit_card_id != null) {
url = Global.url + "/orderlist/" + credit_card_id;
}
else if(order_idd != null) {
url = Global.url + "/myorders/" + order_idd;
}
JsonObjectRequest mRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
if (success) {
try {
double total_amount = data.getJSONObject(0).optDouble("total_amount");
String card_number = data.getJSONObject(0).optString("card_number");
String user_id = data.getJSONObject(0).optString("user_id");
int order_id = data.getJSONObject(0).optInt("order_id");
String adress = data.getJSONObject(0).optString("adress");
String order_date = data.getJSONObject(0).optString("order_date");
orders2.add(new com.example.glass.arshopping.models.Orders().createOrderWithCardDetails(total_amount, card_number, adress, user_id, order_date, order_id));
} catch (JSONException e) {
e.printStackTrace();
}
try {
ListView myll = findViewById(R.id.listOrders1);
CustomerInfoAdapter ordersAdapter = new CustomerInfoAdapter(ctx, orders2);
myll.setAdapter(ordersAdapter);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(mRequest);
}
@Override
public boolean onGesture(GlassGestureDetector.Gesture gesture) {
switch (gesture) {
case SWIPE_BACKWARD:
finish();
return true;
default:
return false;
}
}
public void BackToOrderList(View view)
{
Intent intent = new Intent(getBaseContext(),OrderListActivity.class);
intent.putExtra("username", user_id);
startActivity(intent);
}
}
| 8,783 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
DBHelper.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/DBHelper.java | package com.example.glass.arshopping;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME="GlassDB.db";
public DBHelper(@Nullable Context context) {
super(context,"GlassDB.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase MyDB) {
MyDB.execSQL("create Table users(user_id INTEGER PRIMARY KEY AUTOINCREMENT,user_name TEXT,user_email TEXT,user_password TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
MyDB.execSQL("drop Table if exists users");
}
public Boolean insertData(String user_name,String user_email,String user_password){
SQLiteDatabase MyDB=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("user_name",user_name);
contentValues.put("user_email",user_email);
contentValues.put("user_password",user_password);
long result=MyDB.insert("users",null,contentValues);
if (result==1) return false;
else
return true;
}
public Boolean checkusername(String user_name){
SQLiteDatabase MyDB=this.getWritableDatabase();
Cursor cursor=MyDB.rawQuery("Select*from users where user_name =?",new String[] {user_name});
if(cursor.getCount()>0)
return true;
else
return false;
}
public Boolean checkusernamepassword(String user_name, String user_password) {
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from users where user_name = ? and user_password = ?", new String[]{user_name, user_password});
if(cursor.getCount()>0)
return true;
else
return false;
}
} | 2,060 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
BestSellerActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/BestSellerActivity.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.adapters.BestSellerAdapter;
import com.example.glass.arshopping.adapters.ProductAdapter;
import com.example.glass.arshopping.models.Product;
import com.example.glass.arshopping.models.ProductSeller;
import com.example.glass.arshopping.models.Seller;
import com.example.glass.arshopping.utils.Global;
import com.example.glass.ui.GlassGestureDetector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
public class BestSellerActivity extends BaseActivity implements GlassGestureDetector.OnGestureListener {
String username;
String productId = "";
ListView myList;
RequestQueue mRequestQueue;
Number seller_id = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_best_seller);
username = getIntent().getStringExtra("username");
productId = getIntent().getStringExtra("Product_Id");
mRequestQueue = Volley.newRequestQueue((Context) this);
getData();
getProduct();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
getProduct();
}
}
private void getData(){
ArrayList<ProductSeller> productSellers = new ArrayList<>();
Context ctx = this;
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/comparison/"+productId, response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
if(success){
for (int i=0; i< data.length(); i++) {
try {
int id = data.getJSONObject(i).optJSONObject("seller").optInt("seller_id");
String name = data.getJSONObject(i).optJSONObject("seller").optString("seller_name");
String image = data.getJSONObject(i).optJSONObject("seller").optString("seller_image");
double price = data.getJSONObject(i).optDouble("price");
productSellers.add(new ProductSeller(Integer.parseInt(productId), new Seller(id, name, image), price));
seller_id=id;
} catch (JSONException e) {}
}
myList = (ListView) findViewById(R.id.listProducts);
productSellers.sort(Comparator.comparing(o -> o.getPrice()));
BestSellerAdapter aBestSeller = new BestSellerAdapter(this, productSellers);
myList.setAdapter(aBestSeller);
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) { }
}, error -> {
});
mRequestQueue.add(mRequest);
}
private void getProduct(){
List<Product> products = new ArrayList<Product>();
Context ctx = this;
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/product/"+productId, response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
if(success){
try {
int id = data.getJSONObject(0).optInt("product_id");
String name = data.getJSONObject(0).optString("product_name");
String description = data.getJSONObject(0).optString("product_description");
String image = data.getJSONObject(0).optString("product_image");
products.add(new Product(id, name,image, description));
} catch (JSONException e) {}
try {
ListView productsList = (ListView) findViewById(R.id.myproduct);
ProductAdapter aProducts = new ProductAdapter(ctx, products);
productsList.setAdapter(aProducts);
} catch (Exception e){}
try {
ListView productsList = (ListView) findViewById(R.id.my_product2);
ProductAdapter aProducts = new ProductAdapter(ctx, products);
productsList.setAdapter(aProducts);
} catch (Exception e){}
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
}
public void addCartClick(View view) {
if (true) {
HashMap<String, String> hm = new HashMap<String, String>();
TextView sellerTextView = findViewById(R.id.seller_iddd);
String sellerId = sellerTextView.getText().toString();
hm.put("user_id", username);
hm.put("seller_id", String.valueOf(sellerId));
hm.put("product_id", productId);
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/addcart", new JSONObject(hm), response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
if(success){
Toast.makeText(BestSellerActivity.this, "Product added to cart", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(BestSellerActivity.this, "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
} else {
Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getBaseContext(), CartActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
public void onClickk(View view) {
if (username != null) {
Intent intent = new Intent(BestSellerActivity.this,ProductsActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
}
@Override
public boolean onGesture(GlassGestureDetector.Gesture gesture) {
switch (gesture) {
case SWIPE_BACKWARD:
finish();
return true;
default:
return false;
}
}
public void productClick(View view)
{
// Best Sellers sayfasındaki ürün detayına tıklayınca
// uyarı vermemesi için bu boş metodu oluşturduk
}
} | 7,721 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
Login.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/Login.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.utils.Global;
import com.example.glass.ui.GlassGestureDetector;
import org.json.JSONObject;
import java.util.HashMap;
public class Login extends BaseActivity implements GlassGestureDetector.OnGestureListener {
RequestQueue mRequestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
String username = getIntent().getStringExtra("username");
mRequestQueue = Volley.newRequestQueue((Context) this);
TextView user_name =(TextView) findViewById(R.id.loginusername);
TextView password =(TextView) findViewById(R.id.password);
Button loginbtn= (Button) findViewById(R.id.loginbtn);
if(username != null && !username.equals("")){
user_name.setText(username);
}
findViewById(R.id.reset).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Login.this,Forgotpassword.class);
startActivity(intent);
}
});
loginbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String user=user_name.getText().toString();
String pass=password.getText().toString();
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("user_name", user);
hm.put("user_password", pass);
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/login", new JSONObject(hm), response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
if(success){
user_name.setText("");
password.setText("");
Toast.makeText(getBaseContext(),"Login Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(),ProductsActivity.class);
intent.putExtra("username", user);
startActivity(intent);
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
}
});
findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Login.this,MainActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onGesture(GlassGestureDetector.Gesture gesture) {
switch (gesture) {
case SWIPE_DOWN:
Intent intent = new Intent(Login.this,MainActivity.class);
startActivity(intent);
return true;
default:
return false;
}
}
} | 3,732 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
BaseActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/BaseActivity.java | package com.example.glass.arshopping;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import com.example.glass.ui.GlassGestureDetector;
import com.example.glass.ui.GlassGestureDetector.OnGestureListener;
public abstract class BaseActivity extends FragmentActivity implements OnGestureListener {
private GlassGestureDetector glassGestureDetector;
private View decorView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener(visibility -> {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
hideSystemUI();
}
});
glassGestureDetector = new GlassGestureDetector(this, this);
}
@Override
protected void onResume() {
super.onResume();
hideSystemUI();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return glassGestureDetector.onTouchEvent(ev) || super.dispatchTouchEvent(ev);
}
private void hideSystemUI() {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_FULLSCREEN);
}
}
| 1,404 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
resetPassword.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/resetPassword.java | package com.example.glass.arshopping;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.utils.Global;
import org.json.JSONObject;
import java.util.HashMap;
public class resetPassword extends AppCompatActivity {
private RequestQueue mRequestQueue;
private String mEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
EditText passwordField1 = findViewById(R.id.password);
EditText passwordField2 = findViewById(R.id.RePassword);
mEmail = getIntent().getStringExtra("email");
mRequestQueue = Volley.newRequestQueue(this);
Button changePasswordBtn = findViewById(R.id.changeps);
changePasswordBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String password1 = passwordField1.getText().toString();
String password2 = passwordField2.getText().toString();
if(password1.length() > 4 || password2.length() > 4)
{
if (password1.equals(password2)) {
HashMap<String, String> requestBody = new HashMap<>();
requestBody.put("email", mEmail);
requestBody.put("password", password1);
JsonObjectRequest request = new JsonObjectRequest(Global.url + "/pswchange", new JSONObject(requestBody),
response -> {
try {
boolean success = response.getBoolean("Success");
String message = response.getString("Message");
if (success) {
Toast.makeText(resetPassword.this, "Password changed successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(resetPassword.this, Login.class);
startActivity(intent);
}else {
Toast.makeText(resetPassword.this, "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(resetPassword.this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
},
error -> {
Toast.makeText(resetPassword.this, "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
});
mRequestQueue.add(request);
}
else {
Toast.makeText(getApplicationContext(), "Passwords do not match", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(resetPassword.this, "Password length must be longer than 5", Toast.LENGTH_LONG).show();
}
}
});
}
public void BackButton(View view)
{
Intent intent = new Intent(getBaseContext(),otpCheck.class);
intent.putExtra("email", mEmail);
startActivity(intent);
}
}
| 3,832 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
QRMainActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/QRMainActivity.java | package com.example.glass.arshopping;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.example.glass.ui.GlassGestureDetector.Gesture;
public class QRMainActivity extends BaseActivity {
private static final int REQUEST_CODE = 105;
private TextView resultLabel;
private TextView scanResult;
String username="";
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
username = intent.getStringExtra("username");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrmain);
resultLabel = findViewById(R.id.resultLabel);
scanResult = findViewById(R.id.scanResult);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
final String qrData = data.getStringExtra(CameraActivity.QR_SCAN_RESULT);
Intent intent = new Intent(getBaseContext(), BestSellerActivity.class);
intent.putExtra("Product_Id", qrData.toString());
intent.putExtra("username", username);
startActivity(intent);
}
}
}
@Override
public boolean onGesture(Gesture gesture) {
switch (gesture) {
case TAP:
startActivityForResult(new Intent(this, CameraActivity.class), REQUEST_CODE);
resultLabel.setVisibility(View.GONE);
scanResult.setVisibility(View.GONE);
return true;
case SWIPE_DOWN:
finish();
return true;
default:
return false;
}
}
} | 1,984 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
ProductsActivity.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/ProductsActivity.java | package com.example.glass.arshopping;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.glass.arshopping.adapters.ProductAdapter;
import com.example.glass.arshopping.models.Category;
import com.example.glass.arshopping.models.Product;
import com.example.glass.arshopping.utils.Global;
import org.json.JSONArray;
import org.json.JSONException;
import org.tensorflow.lite.examples.detection.DetectorActivity;
import java.util.ArrayList;
import java.util.List;
public class ProductsActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String username="";
ListView productsList;
Spinner spinner;
RequestQueue mRequestQueue;
ArrayList<String> categoriess = new ArrayList<>();
List<Category> categories = new ArrayList<Category>();
String search = "0";
Button objDetect;
DetectorActivity da;
@Override
protected void onCreate(Bundle savedInstanceState) {
da = new DetectorActivity();
try {
search = getIntent().getStringExtra("search");
} catch (Exception e){ }
if(search == null){
search = "0";
}
super.onCreate(savedInstanceState);
Intent intent = getIntent();
username = intent.getStringExtra("username");
setContentView(R.layout.activity_products);
categoriess.add("|Category");
spinner = (Spinner)findViewById(R.id.spinner);
objDetect = (Button)findViewById(R.id.button);
ArrayAdapter<String>adapter = new ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_spinner_item,categoriess);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
mRequestQueue = Volley.newRequestQueue((Context) this);
getData(0, search);
getCategories();
findViewById(R.id.qrBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(),QRMainActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
});
findViewById(R.id.btnOrders).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(),OrderListActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
});
findViewById(R.id.cartBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(),CartActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
});
findViewById(R.id.btnInfo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(),AccountActivity.class);
intent.putExtra("username", username);
startActivity(intent);
}
});
}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
String i = text.substring(0,1);
getData(i.equals("|")? 0: Integer.parseInt(i), search);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void productClick(View view) {
Intent intent = new Intent(getBaseContext(), BestSellerActivity.class);
String product_id = ((TextView)view.findViewById(R.id.productid)).getText().toString();
intent.putExtra("Product_Id", product_id);
intent.putExtra("username", username);
startActivity(intent);
}
private void getData(int category, String search){
if(!search.equals("0")){
objDetect.setBackground(ContextCompat.getDrawable(this, R.drawable.search_background));
} else {
objDetect.setBackground(ContextCompat.getDrawable(this, R.drawable.black_button_background));
}
List<Product> products = new ArrayList<Product>();
Context ctx = this;
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/products/"+category+"/"+search, response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
if(success){
for (int i=0; i< data.length(); i++) {
try {
int id = data.getJSONObject(i).optInt("product_id");
String name = data.getJSONObject(i).optString("product_name");
String description = data.getJSONObject(i).optString("product_description");
String image = data.getJSONObject(i).optString("product_image");
products.add(new Product(id, name,image, description));
} catch (JSONException e) {}
}
if(products.size() == 0){
((TextView)findViewById(R.id.textView9)).setVisibility(View.VISIBLE);
} else {
((TextView)findViewById(R.id.textView9)).setVisibility(View.GONE);
}
productsList = (ListView) findViewById(R.id.listProducts);
ProductAdapter aProducts = new ProductAdapter(ctx, products);
productsList.setAdapter(aProducts);
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
}
private void getCategories(){
Context ctx = this;
JsonObjectRequest mRequest;
mRequest = new JsonObjectRequest(Global.url+"/categories", response -> {
try {
boolean success = response.optBoolean("Success");
String message = response.optString("Message");
JSONArray data = response.optJSONArray("Data");
categoriess = new ArrayList<>();
categoriess.add("|Category");
if(success){
for (int i=0; i< data.length(); i++) {
try {
int id = data.getJSONObject(i).optInt("category_id");
String name = data.getJSONObject(i).optString("category_name");
String image = data.getJSONObject(i).optString("category_image");
categories.add(new Category(id, name,image));
categoriess.add(id+"|"+name);
} catch (JSONException e) {}
}
ArrayAdapter<String>adapter = new ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_spinner_item,categoriess);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
} else {
Toast.makeText(getBaseContext(), "Error: " + message, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {}
}, error -> {
});
mRequestQueue.add(mRequest);
}
public void LogOut(View view)
{
Intent intent = new Intent(getBaseContext(),MainActivity.class);
startActivity(intent);
Toast.makeText(getBaseContext(), "Logged Out", Toast.LENGTH_LONG).show();
}
public void objectDetection(View view) {
if(objDetect.getBackground().getConstantState() == getResources().getDrawable(R.drawable.search_background).getConstantState()){
objDetect.setBackground(ContextCompat.getDrawable(this, R.drawable.black_button_background));
search = "0";
getData(0, "0");
} else {
Intent intent = new Intent(getBaseContext(), da.getClass());
intent.putExtra("username", username);
startActivity(intent);
}
}
} | 9,290 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
Orders.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/models/Orders.java | package com.example.glass.arshopping.models;
import android.content.Context;
import java.util.List;
public class Orders {
private String credit_card_id;
private int cart_id;
private int order_id;
private String product_img;
private String product_name;
private String seller_name;
private String quantity;
private String order_date;
private double product_price;
private String user_id;
private double total_amount;
private String adress;
private String card_number;
private int product_id;
public Orders createOrder(double totalAmount, int orderId, int cartId, String address, String creditCardId, String userId, String productImg, String productName, String sellerName, String quantity, String orderDate, double productPrice,int product_id) {
this.order_id = orderId;
this.cart_id = cartId;
this.adress = address;
this.credit_card_id = creditCardId;
this.user_id = userId;
this.product_img = productImg;
this.product_name = productName;
this.seller_name = sellerName;
this.quantity = quantity;
this.order_date = orderDate;
this.product_price = productPrice;
this.total_amount = totalAmount;
this.product_id=product_id;
return this;
}
public Orders createOrderWithMinimalData(double totalAmount,int orderId, String orderDate) {
this.total_amount = totalAmount;
this.order_id = orderId;
this.order_date = orderDate;
return this;
}
public Orders createOrderWithCardDetails(double totalAmount, String cardNumber, String address, String userId, String orderDate, int orderId) {
this.total_amount = totalAmount;
this.card_number = cardNumber;
this.adress = address;
this.user_id = userId;
this.order_date = orderDate;
this.order_id = orderId;
return this;
}
public String getUserId() {
return user_id;
}
public String getCard_number() {
return card_number;
}
public String getProductImg() {
return product_img;
}
public String getProductName() {
return product_name;
}
public String getSellerName() {
return seller_name;
}
public String getQuantity() {
return quantity;
}
public String getAdress() {
return adress;
}
public String getOrderDate() {
return order_date;
}
public String getCreditCardId() {
return credit_card_id;
}
public int getCartId() {
return cart_id;
}
public int getProductID() {
return product_id;
}
public double getProductPrice() {
return product_price;
}
public double getTotalAmount() {
return total_amount;
}
public int getOrderId() {
return order_id;
}}
| 2,896 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
Seller.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/models/Seller.java | package com.example.glass.arshopping.models;
public class Seller {
int id;
String name;
String image;
public Seller(int id, String name, String image) {
this.id = id;
this.name = name;
this.image = image;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
}
| 424 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
Cart.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/models/Cart.java | package com.example.glass.arshopping.models;
public class Cart {
String seller_id;
String product_name;
String quantity;
String date;
String product_img;
String id;
String cart_id2;
public Cart(String seller_id, String product_name, String quantity, String date, String cart_id, String product_img, String id) {
this.seller_id = seller_id;
this.product_name = product_name;
this.quantity = quantity;
this.date = date;
this.cart_id2=cart_id;
this.product_img=product_img;
this.id=id;
}
public String getId() { return id;}
public String getSellerID() {
return seller_id;
}
public String getProduct() {
return product_name;
}
public String getQuantity() {
return quantity;
}
public String getDate() {
return date;
}
public String getCartId() { return cart_id2;}
public String getProduct_img() {
return product_img;
}
}
| 1,010 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
Category.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/models/Category.java | package com.example.glass.arshopping.models;
public class Category {
int id;
String name;
String image;
public Category(int id, String name, String image) {
this.id = id;
this.name = name;
this.image = image;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
}
| 428 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
Product.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/models/Product.java | package com.example.glass.arshopping.models;
public class Product {
int id;
String name;
String image;
String description;
public Product(int id, String name, String image, String description) {
this.id = id;
this.name = name;
this.image = image;
this.description = description;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
public String getDescription() {
return description;
}
}
| 582 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
ProductSeller.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/models/ProductSeller.java | package com.example.glass.arshopping.models;
public class ProductSeller {
int product_id;
Seller seller;
double price;
public ProductSeller(int product_id, Seller seller, double price) {
this.product_id = product_id;
this.seller = seller;
this.price = price;
}
public int getProduct_id() {
return product_id;
}
public Seller getSeller() {
return seller;
}
public double getPrice() {
return price;
}
}
| 498 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
Global.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/utils/Global.java | package com.example.glass.arshopping.utils;
public class Global {
static public String url = "http://IP_ADDRESS:PORT";
}
| 126 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
SVG.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/utils/SVG.java | package com.example.glass.arshopping.utils;
import android.content.Context;
import android.widget.ImageView;
import com.pixplicity.sharp.Sharp;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class SVG {
private static OkHttpClient httpClient;
// this method is used to fetch svg and load it into
// target imageview.
public static void fetchSvg(Context context, String url,
final ImageView target)
{
if (httpClient == null) {
httpClient = new OkHttpClient.Builder()
.cache(new Cache(
context.getCacheDir(),
5 * 1024 * 1014))
.build();
}
// here we are making HTTP call to fetch data from
// URL.
Request request = new Request.Builder().url(url).build();
httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e)
{
// we are adding a default image if we gets
// any error.
//target.setImageResource(R.drawable.);
}
@Override
public void onResponse(Call call,
Response response)
throws IOException
{
// sharp is a library which will load stream
// which we generated from url in our target
// imageview.
InputStream stream
= response.body().byteStream();
try {
Sharp.loadInputStream(stream).into(target);
stream.close();
}catch (Exception e){}
}
});
}
} | 1,943 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
CustomerInfoAdapter.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/adapters/CustomerInfoAdapter.java | package com.example.glass.arshopping.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.glass.arshopping.R;
import com.example.glass.arshopping.models.Orders;
import java.util.List;
public class CustomerInfoAdapter extends ArrayAdapter<Orders> {
public CustomerInfoAdapter(@NonNull Context context, @NonNull List<Orders> objects) {
super(context, R.layout.customer_info, objects);
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.customer_info, parent, false
);
}
com.example.glass.arshopping.models.Orders orderItem = getItem(position);
TextView userID = listItemView.findViewById(R.id.p_user_id);
userID.setText(orderItem.getUserId());
TextView order_date = listItemView.findViewById(R.id.p_date);
order_date.setText(orderItem.getOrderDate());
TextView address = listItemView.findViewById(R.id.p_address);
address.setText(orderItem.getAdress());
TextView total_amount = listItemView.findViewById(R.id.p_total_amount);
total_amount.setText(String.valueOf(orderItem.getTotalAmount()));
TextView order_id = listItemView.findViewById(R.id.p_order_id);
order_id.setText(String.valueOf(orderItem.getOrderId()));
return listItemView;
}
}
| 1,759 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
OrdersAdapter.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/adapters/OrdersAdapter.java | package com.example.glass.arshopping.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.example.glass.arshopping.R;
import com.example.glass.arshopping.models.Orders;
import java.util.List;
public class OrdersAdapter extends ArrayAdapter<Orders> {
public OrdersAdapter(@NonNull Context context, @NonNull List<Orders> objects) {
super(context, R.layout.orders, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.orders, parent, false
);
}
Orders orderItem = getItem(position);
ImageView productImage = listItemView.findViewById(R.id.orders_product_img);
Glide.with(getContext()).load(orderItem.getProductImg()).into(productImage);
TextView productName = listItemView.findViewById(R.id.p_name);
productName.setText(orderItem.getProductName());
TextView sellerName = listItemView.findViewById(R.id.seller_name);
sellerName.setText(orderItem.getSellerName());
TextView quantity2 = listItemView.findViewById(R.id.p_quantity);
quantity2.setText(String.valueOf(orderItem.getQuantity()));
TextView price = listItemView.findViewById(R.id.product_price);
price.setText(String.valueOf(orderItem.getProductPrice()));
return listItemView;
}
} | 1,838 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
OrderListAdapter.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/adapters/OrderListAdapter.java | package com.example.glass.arshopping.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.glass.arshopping.models.Orders;
import com.example.glass.arshopping.R;
import java.util.List;
public class OrderListAdapter extends ArrayAdapter<com.example.glass.arshopping.models.Orders> {
public OrderListAdapter(@NonNull Context context, @NonNull List<com.example.glass.arshopping.models.Orders> objects) {
super(context, R.layout.order_list, objects);
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.order_list, parent, false
);
}
com.example.glass.arshopping.models.Orders orderItem = getItem(position);
TextView order_id = listItemView.findViewById(R.id.order_idd);
order_id.setText(""+orderItem.getOrderId());
TextView order_date = listItemView.findViewById(R.id.order_datee);
order_date.setText(orderItem.getOrderDate());
TextView total_amount = listItemView.findViewById(R.id.total_amountt);
total_amount.setText(String.valueOf(orderItem.getTotalAmount() +" TL"));
return listItemView;
}
}
| 1,577 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
ProductAdapter.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/adapters/ProductAdapter.java | package com.example.glass.arshopping.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.example.glass.arshopping.R;
import com.example.glass.arshopping.models.Product;
import java.util.List;
public class ProductAdapter extends ArrayAdapter<Product> {
public ProductAdapter(@NonNull Context context, @NonNull List<Product> objects) {
super(context, R.layout.product, objects);
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.product, parent, false
);
}
Product getPos = getItem(position);
ImageView Image = (ImageView) listItemView.findViewById(R.id.productimg);
try {
Glide.with(listItemView.getContext()).load(getPos.getImage()).into(Image);
} catch (Exception e){
Log.i("Exception", e.getMessage());
}
TextView id = (TextView) listItemView.findViewById(R.id.productid);
id.setText(getPos.getId()+"");
TextView name = (TextView) listItemView.findViewById(R.id.productname);
name.setText(getPos.getName());
TextView description = (TextView) listItemView.findViewById(R.id.description);
description.setText(getPos.getDescription());
return listItemView;
}
}
| 1,790 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
SellerAdapter.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/adapters/SellerAdapter.java | package com.example.glass.arshopping.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.glass.arshopping.R;
import com.example.glass.arshopping.models.Seller;
import java.util.List;
public class SellerAdapter extends ArrayAdapter<Seller> {
public SellerAdapter(@NonNull Context context, @NonNull List<Seller> objects) {
super(context, R.layout.seller, objects);
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.seller, parent, false
);
}
Seller getPos = getItem(position);
int resId = listItemView.getResources().getIdentifier(getPos.getImage() , "drawable", listItemView.getContext().getPackageName());
ImageView image = (ImageView) listItemView.findViewById(R.id.sellerimg);
image.setImageResource(resId);
TextView id = (TextView) listItemView.findViewById(R.id.sellerid);
id.setText(getPos.getId()+"");
TextView name = (TextView) listItemView.findViewById(R.id.sellername);
name.setText(getPos.getName());
return listItemView;
}
}
| 1,567 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
CartAdapter.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/adapters/CartAdapter.java | package com.example.glass.arshopping.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.example.glass.arshopping.R;
import com.example.glass.arshopping.models.Cart;
import java.util.List;
public class CartAdapter extends ArrayAdapter<Cart> {
public CartAdapter(@NonNull Context context, @NonNull List<Cart> objects) {
super(context, R.layout.cart, objects);
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.cart, parent, false
);
}
Cart getPos = getItem(position);
ImageView Image = (ImageView) listItemView.findViewById(R.id.product_img);
try {
Glide.with(listItemView.getContext()).load(getPos.getProduct_img()).into(Image);
} catch (Exception e){
Log.i("Exception", e.getMessage());
}
TextView product_name = (TextView) listItemView.findViewById(R.id.product_name);
product_name.setText(getPos.getProduct());
TextView seller_id = (TextView) listItemView.findViewById(R.id.seller_id);
seller_id.setText(getPos.getSellerID()+"");
TextView quantity = (TextView) listItemView.findViewById(R.id.quantity);
quantity.setText(getPos.getQuantity());
TextView date = (TextView) listItemView.findViewById(R.id.date);
date.setText(getPos.getDate());
TextView id = (TextView) listItemView.findViewById(R.id.c_id);
id.setText(getPos.getId());
TextView cidd = (TextView) listItemView.findViewById(R.id.cidd);
cidd.setText(getPos.getCartId());
return listItemView;
}
}
| 2,141 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
BestSellerAdapter.java | /FileExtraction/Java_unseen/7people_AR-Shopping/ARShopping/app/src/main/java/com/example/glass/arshopping/adapters/BestSellerAdapter.java | package com.example.glass.arshopping.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.glass.arshopping.R;
import com.example.glass.arshopping.models.ProductSeller;
import com.example.glass.arshopping.utils.SVG;
import java.util.List;
public class BestSellerAdapter extends ArrayAdapter<ProductSeller> {
public BestSellerAdapter(@NonNull Context context, @NonNull List<ProductSeller> objects) {
super(context, R.layout.bestseller, objects);
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.bestseller, parent, false
);
}
ProductSeller getPos = getItem(position);
ImageView Image = (ImageView) listItemView.findViewById(R.id.bestsellerimg);
try {
SVG.fetchSvg(listItemView.getContext(), getPos.getSeller().getImage(), Image);
} catch (Exception e){
Log.i("Exception", e.getMessage());
}
TextView seller = (TextView) listItemView.findViewById(R.id.seller);
seller.setText(getPos.getSeller().getName());
TextView ss = (TextView) listItemView.findViewById(R.id.seller_iddd);
ss.setText(getPos.getSeller().getId()+"");
TextView product = (TextView) listItemView.findViewById(R.id.product);
product.setText(""+getPos.getProduct_id());
TextView price = (TextView) listItemView.findViewById(R.id.price);
price.setText(getPos.getPrice()+" TL");
return listItemView;
}
}
| 1,986 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
BuildConfig.java | /FileExtraction/Java_unseen/7people_AR-Shopping/GestureLibrary/main/build/generated/source/buildConfig/debug/com/example/glass/ui/BuildConfig.java | /**
* Automatically generated file. DO NOT MODIFY
*/
package com.example.glass.ui;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String LIBRARY_PACKAGE_NAME = "com.example.glass.ui";
public static final String BUILD_TYPE = "debug";
}
| 316 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
MotionEventGenerator.java | /FileExtraction/Java_unseen/7people_AR-Shopping/GestureLibrary/main/src/test/java/com/example/glass/ui/MotionEventGenerator.java | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.glass.ui;
import android.view.MotionEvent;
import android.view.MotionEvent.PointerCoords;
import android.view.MotionEvent.PointerProperties;
import org.robolectric.Shadows;
import org.robolectric.shadows.ShadowMotionEvent;
public class MotionEventGenerator {
private static final int DOWN_EVENT_TIME = 100;
private static final int MOVE_EVENT_TIME = 200;
private static final int UP_EVENT_TIME = 300;
private static final int TWO_FINGER_POINTER_COUNT = 2;
private static final int FIRST_FINGER_POINTER_ID = 0;
private static final int SECOND_FINGER_POINTER_ID = 1;
private static final int SECOND_FINGER_SHIFT_PX = 100;
static final int INITIAL_X = 200;
static final int INITIAL_Y = 200;
static final int SECOND_FINGER_INITIAL_X = INITIAL_X + SECOND_FINGER_SHIFT_PX;
static final int SECOND_FINGER_INITIAL_Y = INITIAL_Y;
static final int DOWN_TIME = 10;
static final int META_STATE = 0;
public static MotionEvent getActionDown() {
return MotionEvent
.obtain(DOWN_TIME, DOWN_EVENT_TIME, MotionEvent.ACTION_DOWN, INITIAL_X, INITIAL_Y,
META_STATE);
}
public static MotionEvent getActionMove(float xPosition, float yPosition) {
return MotionEvent
.obtain(DOWN_TIME, MOVE_EVENT_TIME, MotionEvent.ACTION_MOVE, xPosition, yPosition,
META_STATE);
}
public static MotionEvent getActionUp(float xPosition, float yPosition) {
return MotionEvent
.obtain(DOWN_TIME, UP_EVENT_TIME, MotionEvent.ACTION_UP, xPosition, yPosition, META_STATE);
}
public static MotionEvent getActionCancel() {
return MotionEvent
.obtain(DOWN_TIME, MOVE_EVENT_TIME, MotionEvent.ACTION_CANCEL, INITIAL_X, INITIAL_Y,
META_STATE);
}
public static MotionEvent getSecondFingerActionDown() {
final MotionEvent motionEvent = MotionEvent
.obtain(DOWN_TIME, DOWN_EVENT_TIME, MotionEvent.ACTION_POINTER_DOWN,
TWO_FINGER_POINTER_COUNT, getPointerProperties(),
getPointerCoords(SECOND_FINGER_INITIAL_X, SECOND_FINGER_INITIAL_Y),
META_STATE, 0, 0, 0, 0, 0, 0, 0);
setMotionEventParameters(motionEvent, SECOND_FINGER_INITIAL_X, SECOND_FINGER_INITIAL_Y);
return motionEvent;
}
public static MotionEvent getSecondFingerActionMove(float xPosition, float yPosition) {
final MotionEvent motionEvent = MotionEvent
.obtain(DOWN_TIME, DOWN_EVENT_TIME, MotionEvent.ACTION_MOVE, TWO_FINGER_POINTER_COUNT,
getPointerProperties(), getPointerCoords(xPosition, yPosition), META_STATE, 0, 0, 0, 0,
0, 0, 0);
setMotionEventParameters(motionEvent, xPosition, yPosition);
return motionEvent;
}
public static MotionEvent getSecondFingerActionUp(float xPosition, float yPosition) {
final MotionEvent motionEvent = MotionEvent
.obtain(DOWN_TIME, DOWN_EVENT_TIME, MotionEvent.ACTION_POINTER_UP, TWO_FINGER_POINTER_COUNT,
getPointerProperties(), getPointerCoords(xPosition, yPosition), META_STATE, 0, 0, 0, 0,
0, 0, 0);
setMotionEventParameters(motionEvent, xPosition, yPosition);
return motionEvent;
}
private static PointerCoords[] getPointerCoords(float xPosition, float yPosition) {
final PointerCoords[] pointerCoords = new MotionEvent.PointerCoords[TWO_FINGER_POINTER_COUNT];
pointerCoords[0] = new MotionEvent.PointerCoords();
pointerCoords[0].x = xPosition - SECOND_FINGER_SHIFT_PX;
pointerCoords[0].y = yPosition;
pointerCoords[1] = new MotionEvent.PointerCoords();
pointerCoords[1].x = xPosition;
pointerCoords[1].y = yPosition;
return pointerCoords;
}
private static PointerProperties[] getPointerProperties() {
final PointerProperties[] pointerProperties = new MotionEvent.PointerProperties[TWO_FINGER_POINTER_COUNT];
pointerProperties[0] = new MotionEvent.PointerProperties();
pointerProperties[0].id = FIRST_FINGER_POINTER_ID;
pointerProperties[1] = new MotionEvent.PointerProperties();
pointerProperties[1].id = SECOND_FINGER_POINTER_ID;
return pointerProperties;
}
private static void setMotionEventParameters(MotionEvent motionEvent, float xPosition,
float yPosition) {
final ShadowMotionEvent shadowMotionEvent = Shadows.shadowOf(motionEvent);
shadowMotionEvent.setPointerIndex(SECOND_FINGER_POINTER_ID);
shadowMotionEvent.setPointerIds(FIRST_FINGER_POINTER_ID, SECOND_FINGER_POINTER_ID);
shadowMotionEvent.setPointer2(xPosition, yPosition);
}
}
| 5,132 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
GlassGestureDetectorTest.java | /FileExtraction/Java_unseen/7people_AR-Shopping/GestureLibrary/main/src/test/java/com/example/glass/ui/GlassGestureDetectorTest.java | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.glass.ui;
import android.content.Context;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import com.example.glass.ui.GlassGestureDetector.Gesture;
import com.example.glass.ui.GlassGestureDetector.OnGestureListener;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import static com.example.glass.ui.MotionEventGenerator.DOWN_TIME;
import static com.example.glass.ui.MotionEventGenerator.INITIAL_X;
import static com.example.glass.ui.MotionEventGenerator.INITIAL_Y;
import static com.example.glass.ui.MotionEventGenerator.META_STATE;
import static com.example.glass.ui.MotionEventGenerator.SECOND_FINGER_INITIAL_X;
import static com.example.glass.ui.MotionEventGenerator.SECOND_FINGER_INITIAL_Y;
import static com.example.glass.ui.MotionEventGenerator.getActionCancel;
import static com.example.glass.ui.MotionEventGenerator.getActionDown;
import static com.example.glass.ui.MotionEventGenerator.getActionMove;
import static com.example.glass.ui.MotionEventGenerator.getActionUp;
import static com.example.glass.ui.MotionEventGenerator.getSecondFingerActionDown;
import static com.example.glass.ui.MotionEventGenerator.getSecondFingerActionMove;
import static com.example.glass.ui.MotionEventGenerator.getSecondFingerActionUp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@RunWith(RobolectricTestRunner.class)
public class GlassGestureDetectorTest {
private static final int EVENT_TIME = 10;
private static final int ACTION = MotionEvent.ACTION_UP;
private static final int TWICE_SWIPE_DISTANCE_THRESHOLD_PX =
2 * GlassGestureDetector.SWIPE_DISTANCE_THRESHOLD_PX;
private static final int HALF_SWIPE_DISTANCE_THRESHOLD_PX =
GlassGestureDetector.SWIPE_DISTANCE_THRESHOLD_PX / 2;
private static final float ANGLE_EPSILON_DEGREES = 0.1F;
private static final float ANGLE_60_DEGREES = 60;
private static final float ANGLE_120_DEGREES = 120;
private static final double DELTA = 1e-15;
private GlassGestureDetector glassGestureDetector;
private MotionEvent motionEvent;
private Gesture detectedGesture;
private boolean isTouchEnded;
private boolean isScrolling;
private float scrollingDistanceX;
private float scrollingDistanceY;
private int touchSlop;
@Before
public void setUp() {
final Context context = RuntimeEnvironment.application;
glassGestureDetector = new GlassGestureDetector(context, new GestureListener());
motionEvent = MotionEvent
.obtain(DOWN_TIME, EVENT_TIME, ACTION, INITIAL_X, INITIAL_Y, META_STATE);
isTouchEnded = false;
isScrolling = false;
scrollingDistanceX = 0;
scrollingDistanceY = 0;
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Test
public void testOnTouchEvent() {
assertFalse(glassGestureDetector.onTouchEvent(motionEvent));
}
@Test
public void testScrolling() {
assertFalse(isScrolling);
glassGestureDetector.onTouchEvent(getActionDown());
assertFalse(isScrolling);
glassGestureDetector.onTouchEvent(
getActionMove(INITIAL_X, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX));
assertTrue(isScrolling);
assertEquals(0, scrollingDistanceX, DELTA);
assertEquals(TWICE_SWIPE_DISTANCE_THRESHOLD_PX, scrollingDistanceY, DELTA);
glassGestureDetector.onTouchEvent(
getActionUp(INITIAL_X, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX));
assertTrue(isScrolling);
assertEquals(0, scrollingDistanceX, DELTA);
assertEquals(TWICE_SWIPE_DISTANCE_THRESHOLD_PX, scrollingDistanceY, DELTA);
assertEquals(Gesture.SWIPE_UP, detectedGesture);
}
@Test
public void testScrollingSmallDistance() {
assertFalse(isScrolling);
glassGestureDetector.onTouchEvent(getActionDown());
assertFalse(isScrolling);
glassGestureDetector.onTouchEvent(
getActionMove(INITIAL_X, INITIAL_Y - HALF_SWIPE_DISTANCE_THRESHOLD_PX));
assertTrue(isScrolling);
assertEquals(0, scrollingDistanceX, DELTA);
assertEquals(HALF_SWIPE_DISTANCE_THRESHOLD_PX, scrollingDistanceY, DELTA);
glassGestureDetector.onTouchEvent(
getActionUp(INITIAL_X, INITIAL_Y - HALF_SWIPE_DISTANCE_THRESHOLD_PX));
assertTrue(isScrolling);
assertEquals(0, scrollingDistanceX, DELTA);
assertEquals(HALF_SWIPE_DISTANCE_THRESHOLD_PX, scrollingDistanceY, DELTA);
assertNull(detectedGesture);
}
@Test
public void testSwipeTooSmallDistance() {
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(INITIAL_X + HALF_SWIPE_DISTANCE_THRESHOLD_PX,
INITIAL_Y + HALF_SWIPE_DISTANCE_THRESHOLD_PX)));
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(
getActionUp(INITIAL_X + HALF_SWIPE_DISTANCE_THRESHOLD_PX,
INITIAL_Y + HALF_SWIPE_DISTANCE_THRESHOLD_PX)));
assertNull(detectedGesture);
}
@Test
public void testTapGesture() {
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionMove(INITIAL_X, INITIAL_Y)));
assertNull(detectedGesture);
assertTrue(glassGestureDetector.onTouchEvent(getActionUp(INITIAL_X, INITIAL_Y)));
assertEquals(Gesture.TAP, detectedGesture);
}
@Test
public void testTwoFingerTapGesture() {
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionMove(INITIAL_X, INITIAL_Y)));
assertFalse(glassGestureDetector
.onTouchEvent(getSecondFingerActionMove(SECOND_FINGER_INITIAL_X, SECOND_FINGER_INITIAL_Y)));
assertNull(detectedGesture);
assertFalse(glassGestureDetector
.onTouchEvent(getSecondFingerActionUp(SECOND_FINGER_INITIAL_X, SECOND_FINGER_INITIAL_Y)));
assertTrue(glassGestureDetector.onTouchEvent(getActionUp(INITIAL_X, INITIAL_Y)));
assertEquals(Gesture.TWO_FINGER_TAP, detectedGesture);
}
@Test
public void testOnTouchEnded() {
assertFalse(isTouchEnded);
glassGestureDetector.onTouchEvent(getActionDown());
assertFalse(isTouchEnded);
glassGestureDetector.onTouchEvent(getActionMove(INITIAL_X, INITIAL_Y));
assertFalse(isTouchEnded);
glassGestureDetector.onTouchEvent(getActionUp(INITIAL_X, INITIAL_Y));
assertTrue(isTouchEnded);
}
@Test
public void testInTapRegion() {
final int inTapRegionDistance = touchSlop - 1;
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertNull(detectedGesture);
assertFalse(glassGestureDetector
.onTouchEvent(getActionMove(INITIAL_X, INITIAL_Y - inTapRegionDistance)));
assertNull(detectedGesture);
assertTrue(
glassGestureDetector.onTouchEvent(getActionUp(INITIAL_X, INITIAL_Y - inTapRegionDistance)));
assertEquals(Gesture.TAP, detectedGesture);
}
@Test
public void testNotInTapRegion() {
final int notInTapRegionDistance = touchSlop + 1;
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertNull(detectedGesture);
assertFalse(glassGestureDetector
.onTouchEvent(getActionMove(INITIAL_X, INITIAL_Y - notInTapRegionDistance)));
assertNull(detectedGesture);
assertFalse(glassGestureDetector
.onTouchEvent(getActionUp(INITIAL_X, INITIAL_Y - notInTapRegionDistance)));
assertNull(detectedGesture);
}
@Test
public void testCancelledTapGesture() {
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getActionMove(INITIAL_X, INITIAL_Y)));
assertFalse(glassGestureDetector.onTouchEvent(getActionCancel()));
assertFalse(glassGestureDetector.onTouchEvent(getActionUp(INITIAL_X, INITIAL_Y)));
assertNull(detectedGesture);
}
@Test
public void testCancelledSwipeGesture() {
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getActionCancel()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(INITIAL_X, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(
getActionUp(INITIAL_X, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertNull(detectedGesture);
}
@Test
public void testAngleSwipeForward() {
final float endX = INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES));
// 120 degrees
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.SWIPE_FORWARD, detectedGesture);
// -120 degrees
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.SWIPE_FORWARD, detectedGesture);
}
@Test
public void testAngleTwoFingerSwipeForward() {
final float endX = INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES));
final float secondFingerEndX =
SECOND_FINGER_INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES));
// 120 degrees
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionMove(secondFingerEndX,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_FORWARD, detectedGesture);
// -120 degrees
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionMove(secondFingerEndX,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_FORWARD, detectedGesture);
}
@Test
public void testAngleSwipeBackward() {
final float endX = INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES));
// SWIPE_BACKWARD will be detected if movement angle is smaller or equal 60 degrees clockwise from X axis
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.SWIPE_BACKWARD, detectedGesture);
// SWIPE_BACKWARD will be detected if movement angle is smaller or equal -60 degrees counterclockwise from X axis
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX));
assertEquals(Gesture.SWIPE_BACKWARD, detectedGesture);
}
@Test
public void testAngleTwoFingerSwipeBackward() {
final float endX = INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES));
final float secondFingerEndX =
SECOND_FINGER_INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES));
// SWIPE_BACKWARD will be detected if movement angle is smaller or equal 60 degrees clockwise from X axis
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionMove(secondFingerEndX,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_BACKWARD, detectedGesture);
// SWIPE_BACKWARD will be detected if movement angle is smaller or equal -60 degrees counterclockwise from X axis
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionMove(secondFingerEndX,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_BACKWARD, detectedGesture);
}
@Test
public void testAngleSwipeUp() {
// SWIPE_UP gesture will be detected if movement angle is greater than 60 degrees clockwise from X axis
final float endX = INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES + ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.SWIPE_UP, detectedGesture);
// SWIPE_UP gesture will be detected if movement angle is smaller than 120 degrees clockwise from X axis
final float endX2 = INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES - ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX2, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX2, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.SWIPE_UP, detectedGesture);
}
@Test
public void testAngleTwoFingerSwipeUp() {
// SWIPE_UP gesture will be detected if movement angle is greater than 60 degrees clockwise from X axis
final float endX = INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES + ANGLE_EPSILON_DEGREES));
final float secondFingerEndX =
SECOND_FINGER_INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES + ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionMove(secondFingerEndX,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_UP, detectedGesture);
// SWIPE_UP gesture will be detected if movement angle is smaller than 120 degrees clockwise from X axis
final float endX2 = INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES - ANGLE_EPSILON_DEGREES));
final float secondFingerEndX2 =
SECOND_FINGER_INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES - ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX2, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionMove(secondFingerEndX2,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX2,
SECOND_FINGER_INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX2, INITIAL_Y - TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_UP, detectedGesture);
}
@Test
public void testAngleSwipeDown() {
// SWIPE_DOWN will be detected if movement angle is greater than 60 degrees counterclockwise from X axis
final float endX = INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES + ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.SWIPE_DOWN, detectedGesture);
// SWIPE_DOWN will be detected if movement angle is smaller than 120 degrees counterclockwise from X axis
final float endX2 = INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES - ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX2, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX2, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.SWIPE_DOWN, detectedGesture);
}
@Test
public void testAngleTwoFingerSwipeDown() {
// SWIPE_DOWN will be detected if movement angle is greater than 60 degrees counterclockwise from X axis
final float endX = INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES + ANGLE_EPSILON_DEGREES));
final float secondFingerEndX =
SECOND_FINGER_INITIAL_X - (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_60_DEGREES + ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionMove(secondFingerEndX,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_DOWN, detectedGesture);
// SWIPE_DOWN will be detected if movement angle is smaller than 120 degrees counterclockwise from X axis
final float endX2 = INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES - ANGLE_EPSILON_DEGREES));
final float secondFingerEndX2 =
SECOND_FINGER_INITIAL_X + (float) (TWICE_SWIPE_DISTANCE_THRESHOLD_PX / getAbsTanDegrees(
ANGLE_120_DEGREES - ANGLE_EPSILON_DEGREES));
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionDown()));
assertFalse(glassGestureDetector.onTouchEvent(
getActionMove(endX2, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(
getSecondFingerActionMove(secondFingerEndX2,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertFalse(glassGestureDetector.onTouchEvent(getSecondFingerActionUp(secondFingerEndX2,
SECOND_FINGER_INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertTrue(glassGestureDetector.onTouchEvent(
getActionUp(endX2, INITIAL_Y + TWICE_SWIPE_DISTANCE_THRESHOLD_PX)));
assertEquals(Gesture.TWO_FINGER_SWIPE_DOWN, detectedGesture);
}
@Test
public void testTapAndHold() {
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertNull(detectedGesture);
glassGestureDetector.tapAndHoldCountDownTimer.onFinish();
assertEquals(Gesture.TAP_AND_HOLD, detectedGesture);
}
@Test
public void testDetectTapAndHoldOnly() {
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionDown()));
assertNull(detectedGesture);
assertFalse(glassGestureDetector.onTouchEvent(getActionMove(INITIAL_X, INITIAL_Y)));
glassGestureDetector.tapAndHoldCountDownTimer.onFinish();
assertEquals(Gesture.TAP_AND_HOLD, detectedGesture);
detectedGesture = null;
assertFalse(glassGestureDetector.onTouchEvent(getActionUp(INITIAL_X, INITIAL_Y)));
assertNull(detectedGesture);
}
private MotionEvent getMotionEventForGesture(Gesture gesture) {
int X_CHANGE = 0;
int Y_CHANGE = 0;
switch (gesture) {
case SWIPE_UP:
Y_CHANGE -= TWICE_SWIPE_DISTANCE_THRESHOLD_PX;
break;
case SWIPE_DOWN:
Y_CHANGE += TWICE_SWIPE_DISTANCE_THRESHOLD_PX;
break;
case SWIPE_FORWARD:
X_CHANGE -= TWICE_SWIPE_DISTANCE_THRESHOLD_PX;
break;
case SWIPE_BACKWARD:
X_CHANGE += TWICE_SWIPE_DISTANCE_THRESHOLD_PX;
break;
default:
}
return MotionEvent
.obtain(DOWN_TIME, EVENT_TIME, ACTION, INITIAL_X + X_CHANGE, INITIAL_Y + Y_CHANGE,
META_STATE);
}
private double getAbsTanDegrees(float degrees) {
return Math.abs(Math.tan(Math.toRadians(degrees)));
}
class GestureListener implements OnGestureListener {
@Override
public boolean onGesture(Gesture gesture) {
detectedGesture = gesture;
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
isScrolling = true;
scrollingDistanceX = distanceX;
scrollingDistanceY = distanceY;
return false;
}
@Override
public void onTouchEnded() {
isTouchEnded = true;
}
}
} | 25,716 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
GlassGestureDetector.java | /FileExtraction/Java_unseen/7people_AR-Shopping/GestureLibrary/main/src/main/java/com/example/glass/ui/GlassGestureDetector.java | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.glass.ui;
import android.content.Context;
import android.os.CountDownTimer;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
/**
* Gesture detector for Google Glass usage purposes.
*
* It detects one and two finger gestures like:
* <ul>
* <li>TAP</li>
* <li>TAP_AND_HOLD</li>
* <li>TWO_FINGER_TAP</li>
* <li>SWIPE_FORWARD</li>
* <li>TWO_FINGER_SWIPE_FORWARD</li>
* <li>SWIPE_BACKWARD</li>
* <li>TWO_FINGER_SWIPE_BACKWARD</li>
* <li>SWIPE_UP</li>
* <li>TWO_FINGER_SWIPE_UP</li>
* <li>SWIPE_DOWN</li>
* <li>TWO_FINGER_SWIPE_DOWN</li>
* </ul>
*
* Swipe detection depends on the:
* <ul>
* <li>movement tan value</li>
* <li>movement distance</li>
* <li>movement velocity</li>
* </ul>
*
* To prevent unintentional SWIPE_DOWN, TWO_FINGER_SWIPE_DOWN, SWIPE_UP and TWO_FINGER_SWIPE_UP
* gestures, they are detected if movement angle is only between 60 and 120 degrees to the
* Glass touchpad horizontal axis.
* Any other detected swipes, will be considered as SWIPE_FORWARD and SWIPE_BACKWARD gestures,
* depends on the sign of the axis x movement value.
*
* ______________________________________________________________
* | \ UP / |
* | \ / |
* | 60 120 |
* | \ / |
* | \ / |
* | BACKWARD <------- 0 ------------ 180 ------> FORWARD |
* | / \ |
* | / \ |
* | 60 120 |
* | / \ |
* | / DOWN \ |
* --------------------------------------------------------------
*/
public class GlassGestureDetector {
/**
* Currently handled gestures.
*/
public enum Gesture {
TAP,
TAP_AND_HOLD,
TWO_FINGER_TAP,
SWIPE_FORWARD,
TWO_FINGER_SWIPE_FORWARD,
SWIPE_BACKWARD,
TWO_FINGER_SWIPE_BACKWARD,
SWIPE_UP,
TWO_FINGER_SWIPE_UP,
SWIPE_DOWN,
TWO_FINGER_SWIPE_DOWN
}
/**
* Listens for the gestures.
*/
public interface OnGestureListener {
/**
* Should notify about detected gesture.
*
* @param gesture is a detected gesture.
* @return TRUE if gesture is handled by the method. FALSE otherwise.
*/
boolean onGesture(Gesture gesture);
/**
* Notifies when a scroll occurs with the initial on down {@link MotionEvent} and the current
* move {@link MotionEvent}. The distance in x and y is also supplied for convenience.
*
* @param e1 The first down motion event that started the scrolling.
* @param e2 The move motion event that triggered the current onScroll.
* @param distanceX The distance along the X axis that has been scrolled since the last call to
* onScroll. This is NOT the distance between {@code e1} and {@code e2}.
* @param distanceY The distance along the Y axis that has been scrolled since the last call to
* onScroll. This is NOT the distance between {@code e1} and {@code e2}.
* @return true if the event is consumed, else false
*/
default boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
/**
* Notifies when touch is ended.
*/
default void onTouchEnded() {
}
}
private static final int VELOCITY_UNIT = 1000;
private static final int FIRST_FINGER_POINTER_INDEX = 0;
private static final int SECOND_FINGER_POINTER_INDEX = 1;
private static final int TAP_AND_HOLD_THRESHOLD_MS = ViewConfiguration.getLongPressTimeout();
private static final double TAN_ANGLE_DEGREES = Math.tan(Math.toRadians(60));
static final int SWIPE_DISTANCE_THRESHOLD_PX = 100;
static final int SWIPE_VELOCITY_THRESHOLD_PX = 100;
private final int touchSlopSquare;
final CountDownTimer tapAndHoldCountDownTimer = new CountDownTimer(TAP_AND_HOLD_THRESHOLD_MS,
TAP_AND_HOLD_THRESHOLD_MS) {
@Override
public void onTick(long millisUntilFinished) {}
@Override
public void onFinish() {
isTapAndHoldPerformed = true;
onGestureListener.onGesture(Gesture.TAP_AND_HOLD);
}
};
/**
* This flag is set to true each time the {@link MotionEvent#ACTION_DOWN} action appears
* and it remains true until the finger moves out of the tap region.
* Checking of the finger movement takes place each time the {@link MotionEvent#ACTION_MOVE}
* action appears, until finger moves out of the tap region.
* If this flag is set to false, {@link Gesture#TAP} and {@link Gesture#TWO_FINGER_TAP}
* gestures won't be notified as detected.
*
* Tap region is calculated from the {@link ViewConfiguration#getScaledTouchSlop()} value.
* It prevents from detecting {@link Gesture#TAP} and {@link Gesture#TWO_FINGER_TAP} gestures
* during the scrolling on the touchpad.
*/
private boolean isInTapRegion;
private boolean isTwoFingerGesture = false;
private boolean isActionDownPerformed = false;
private boolean isTapAndHoldPerformed = false;
private float firstFingerDownX;
private float firstFingerDownY;
private float firstFingerLastFocusX;
private float firstFingerLastFocusY;
private float firstFingerVelocityX;
private float firstFingerVelocityY;
private float firstFingerDistanceX;
private float firstFingerDistanceY;
private float secondFingerDownX;
private float secondFingerDownY;
private float secondFingerDistanceX;
private float secondFingerDistanceY;
private VelocityTracker velocityTracker;
private MotionEvent currentDownEvent;
private OnGestureListener onGestureListener;
/**
* {@link GlassGestureDetector} object is constructed by usage of this method.
*
* @param context is a context of the application.
* @param onGestureListener is a listener for the gestures.
*/
public GlassGestureDetector(Context context, OnGestureListener onGestureListener) {
final int touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
touchSlopSquare = touchSlop * touchSlop;
this.onGestureListener = onGestureListener;
}
/**
* Passes the {@link MotionEvent} object from the activity to the Android {@link
* GestureDetector}.
*
* @param motionEvent is a detected {@link MotionEvent} object.
* @return TRUE if event is handled by the Android {@link GestureDetector}. FALSE otherwise.
*/
public boolean onTouchEvent(MotionEvent motionEvent) {
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
}
velocityTracker.addMovement(motionEvent);
boolean handled = false;
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
tapAndHoldCountDownTimer.start();
firstFingerDownX = firstFingerLastFocusX = motionEvent.getX();
firstFingerDownY = firstFingerLastFocusY = motionEvent.getY();
isActionDownPerformed = true;
isInTapRegion = true;
if (currentDownEvent != null) {
currentDownEvent.recycle();
}
currentDownEvent = MotionEvent.obtain(motionEvent);
break;
case MotionEvent.ACTION_POINTER_DOWN:
tapAndHoldCountDownTimer.cancel();
isTwoFingerGesture = true;
secondFingerDownX = motionEvent.getX(motionEvent.getActionIndex());
secondFingerDownY = motionEvent.getY(motionEvent.getActionIndex());
break;
case MotionEvent.ACTION_MOVE:
final float firstFingerFocusX = motionEvent.getX(FIRST_FINGER_POINTER_INDEX);
final float firstFingerFocusY = motionEvent.getY(FIRST_FINGER_POINTER_INDEX);
final float scrollX = firstFingerLastFocusX - firstFingerFocusX;
final float scrollY = firstFingerLastFocusY - firstFingerFocusY;
firstFingerDistanceX = firstFingerFocusX - firstFingerDownX;
firstFingerDistanceY = firstFingerFocusY - firstFingerDownY;
if (motionEvent.getPointerCount() > 1) {
secondFingerDistanceX =
motionEvent.getX(SECOND_FINGER_POINTER_INDEX) - secondFingerDownX;
secondFingerDistanceY =
motionEvent.getY(SECOND_FINGER_POINTER_INDEX) - secondFingerDownY;
}
if (isInTapRegion) {
final float distance = (firstFingerDistanceX * firstFingerDistanceX)
+ (firstFingerDistanceY * firstFingerDistanceY);
float distanceSecondFinger = 0;
if (motionEvent.getPointerCount() > 1) {
distanceSecondFinger = (secondFingerDistanceX * secondFingerDistanceX)
+ (secondFingerDistanceY * secondFingerDistanceY);
}
if (distance > touchSlopSquare || distanceSecondFinger > touchSlopSquare) {
tapAndHoldCountDownTimer.cancel();
isInTapRegion = false;
}
}
if ((Math.abs(scrollX) >= 1) || (Math.abs(scrollY) >= 1)) {
handled = onGestureListener
.onScroll(currentDownEvent, motionEvent, scrollX, scrollY);
firstFingerLastFocusX = firstFingerFocusX;
firstFingerLastFocusY = firstFingerFocusY;
}
break;
case MotionEvent.ACTION_UP:
tapAndHoldCountDownTimer.cancel();
velocityTracker.computeCurrentVelocity(VELOCITY_UNIT);
firstFingerVelocityX = velocityTracker
.getXVelocity(motionEvent.getPointerId(motionEvent.getActionIndex()));
firstFingerVelocityY = velocityTracker
.getYVelocity(motionEvent.getPointerId(motionEvent.getActionIndex()));
handled = detectGesture();
onTouchEnded();
break;
case MotionEvent.ACTION_CANCEL:
tapAndHoldCountDownTimer.cancel();
velocityTracker.recycle();
velocityTracker = null;
isInTapRegion = false;
isTapAndHoldPerformed = false;
break;
}
return handled;
}
private boolean detectGesture() {
if (!isActionDownPerformed) {
return false;
}
if (isTapAndHoldPerformed) {
return false;
}
final double tan =
firstFingerDistanceX != 0 ? Math.abs(firstFingerDistanceY / firstFingerDistanceX)
: Double.MAX_VALUE;
if (isTwoFingerGesture) {
final double tanSecondFinger =
secondFingerDistanceX != 0 ? Math.abs(secondFingerDistanceY / secondFingerDistanceX)
: Double.MAX_VALUE;
return detectTwoFingerGesture(tan, tanSecondFinger);
} else {
return detectOneFingerGesture(tan);
}
}
private boolean detectOneFingerGesture(double tan) {
if (tan > TAN_ANGLE_DEGREES) {
if (Math.abs(firstFingerDistanceY) < SWIPE_DISTANCE_THRESHOLD_PX
|| Math.abs(firstFingerVelocityY) < SWIPE_VELOCITY_THRESHOLD_PX) {
if (isInTapRegion) {
return onGestureListener.onGesture(Gesture.TAP);
}
} else if (firstFingerDistanceY < 0) {
return onGestureListener.onGesture(Gesture.SWIPE_UP);
} else if (firstFingerDistanceY > 0) {
return onGestureListener.onGesture(Gesture.SWIPE_DOWN);
}
} else {
if (Math.abs(firstFingerDistanceX) < SWIPE_DISTANCE_THRESHOLD_PX
|| Math.abs(firstFingerVelocityX) < SWIPE_VELOCITY_THRESHOLD_PX) {
if (isInTapRegion) {
return onGestureListener.onGesture(Gesture.TAP);
}
} else if (firstFingerDistanceX < 0) {
return onGestureListener.onGesture(Gesture.SWIPE_FORWARD);
} else if (firstFingerDistanceX > 0) {
return onGestureListener.onGesture(Gesture.SWIPE_BACKWARD);
}
}
return false;
}
private boolean detectTwoFingerGesture(double tan, double tanSecondFinger) {
if (tan > TAN_ANGLE_DEGREES && tanSecondFinger > TAN_ANGLE_DEGREES) {
if (Math.abs(firstFingerDistanceY) < SWIPE_DISTANCE_THRESHOLD_PX
|| Math.abs(firstFingerVelocityY) < SWIPE_VELOCITY_THRESHOLD_PX) {
if (isInTapRegion) {
return onGestureListener.onGesture(Gesture.TWO_FINGER_TAP);
}
} else if (firstFingerDistanceY < 0 && secondFingerDistanceY < 0) {
return onGestureListener.onGesture(Gesture.TWO_FINGER_SWIPE_UP);
} else if (firstFingerDistanceY > 0 && secondFingerDistanceY > 0) {
return onGestureListener.onGesture(Gesture.TWO_FINGER_SWIPE_DOWN);
}
} else {
if (Math.abs(firstFingerDistanceX) < SWIPE_DISTANCE_THRESHOLD_PX
|| Math.abs(firstFingerVelocityX) < SWIPE_VELOCITY_THRESHOLD_PX) {
if (isInTapRegion) {
return onGestureListener.onGesture(Gesture.TWO_FINGER_TAP);
}
} else if (firstFingerDistanceX < 0 && secondFingerDistanceX < 0) {
return onGestureListener.onGesture(Gesture.TWO_FINGER_SWIPE_FORWARD);
} else if (firstFingerDistanceX > 0 && secondFingerDistanceX > 0) {
return onGestureListener.onGesture(Gesture.TWO_FINGER_SWIPE_BACKWARD);
}
}
return false;
}
private void onTouchEnded() {
isTwoFingerGesture = false;
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
isActionDownPerformed = false;
isTapAndHoldPerformed = false;
onGestureListener.onTouchEnded();
}
}
| 14,306 | Java | .java | 7people/AR-Shopping | 9 | 2 | 0 | 2023-06-12T14:01:53Z | 2023-07-26T07:06:06Z |
IssueServiceFacadeTest.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/test/java/com/aprey/jira/plugin/openpoker/IssueServiceFacadeTest.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
import com.atlassian.jira.bc.issue.IssueService;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueInputParameters;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.user.ApplicationUser;
import java.util.Collections;
import org.junit.Ignore;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class IssueServiceFacadeTest {
private static final String ISSUE_ID = "TEST-1";
private static final String ESTIMATE = "8";
private static final long FIELD_ID = 1L;
private static final long ISSUE_ID_LONG = 1L;
private final Issue issue = mock(Issue.class);
private final MutableIssue mutableIssue = mock(MutableIssue.class);
private final ApplicationUser applicationUser = mock(ApplicationUser.class);
private final IssueInputParameters issueInputParameters = mock(IssueInputParameters.class);
private final IssueService.UpdateValidationResult updateValidationResult = mock(
IssueService.UpdateValidationResult.class);
private final CustomFieldManager customFieldManager = mock(CustomFieldManager.class);
private final IssueService issueService = mock(IssueService.class);
private final IssueManager issueManager = mock(IssueManager.class);
private final IssueServiceFacade issueServiceFacade = new IssueServiceFacade(customFieldManager, issueService,
issueManager);
@Test
public void doesNothingIfStoryPointFieldDoesNotExist() {
when(issueManager.getIssueObject(ISSUE_ID)).thenReturn(mutableIssue);
when(customFieldManager.getCustomFieldObjects(mutableIssue)).thenReturn(Collections.emptyList());
issueServiceFacade.applyEstimate(ESTIMATE, applicationUser, ISSUE_ID);
verifyZeroInteractions(issueService);
}
@Test
@Ignore // Can't mock CustomField cause it fails with 'NoClassDefFound' exception. TODO: find the way to fix it.
public void doesNothingIfUpdateValidationResultHasErrors() {
final CustomField customField = mock(CustomField.class);
when(issueManager.getIssueObject(ISSUE_ID)).thenReturn(mutableIssue);
when(mutableIssue.getId()).thenReturn(ISSUE_ID_LONG);
when(customField.getFieldName()).thenReturn("Story Points");
when(customFieldManager.getCustomFieldObjects(mutableIssue)).thenReturn(Collections.singletonList(customField));
when(issueService.newIssueInputParameters()).thenReturn(issueInputParameters);
when(issueService.validateUpdate(applicationUser, ISSUE_ID_LONG, issueInputParameters)).thenReturn(
updateValidationResult);
when(updateValidationResult.isValid()).thenReturn(false);
issueServiceFacade.applyEstimate(ESTIMATE, applicationUser, ISSUE_ID);
verify(issueInputParameters, times(1)).addCustomFieldValue(FIELD_ID,
String.valueOf(ESTIMATE));
verify(issueInputParameters, times(1)).setSkipScreenCheck(true);
verify(issueInputParameters, times(1)).setRetainExistingValuesWhenParameterNotProvided(true, true);
verify(issueService, times(0)).update(applicationUser, updateValidationResult);
}
} | 4,409 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PersistenceServiceTest.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/test/java/com/aprey/jira/plugin/openpoker/persistence/PersistenceServiceTest.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationUnit;
import com.aprey.jira.plugin.openpoker.IssueServiceFacade;
import com.aprey.jira.plugin.openpoker.PokerSession;
import com.aprey.jira.plugin.openpoker.SessionStatus;
import com.atlassian.activeobjects.external.ActiveObjects;
import java.util.Optional;
import net.java.ao.Query;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class PersistenceServiceTest {
private static final String ISSUE_ID = "ID";
private static final long USER_ID = 1;
private static final long ESTIMATOR_ID = 2;
private static final int GRADE_ID = 10;
private final PokerSessionEntity sessionEntity = mock(PokerSessionEntity.class);
private final EstimateEntity estimateEntity = mock(EstimateEntity.class);
private final ActiveObjects ao = mock(ActiveObjects.class);
private final IssueServiceFacade issueServiceFacade = mock(IssueServiceFacade.class);
private final QueryBuilderService queryBuilder = mock(QueryBuilderService.class);
private final Query sessionQuery = mock(Query.class);
private final Query estimateQuery = mock(Query.class);
private final EntityToObjConverter converter = mock(EntityToObjConverter.class);
private final EstimationDeckService deckService = mock(EstimationDeckService.class);
private final PersistenceService service = new PersistenceService(ao, converter, queryBuilder, issueServiceFacade,
deckService);
@Test
public void sessionIsStarted() {
when(queryBuilder.sessionWhereIssueIdAndStatus(ISSUE_ID, SessionStatus.IN_PROGRESS)).thenReturn(sessionQuery);
when(ao.find(eq(PokerSessionEntity.class), eq(sessionQuery))).thenReturn(new PokerSessionEntity[]{});
when(ao.create(eq(PokerSessionEntity.class))).thenReturn(sessionEntity);
service.startSession(ISSUE_ID, USER_ID, EstimationUnit.FIBONACCI);
verify(sessionEntity, times(1)).setIssueId(eq(ISSUE_ID));
verify(sessionEntity, times(1)).setModeratorId(eq(USER_ID));
verify(sessionEntity, times(1)).setSessionStatus(eq(SessionStatus.IN_PROGRESS));
verify(sessionEntity, times(1)).setUnitOfMeasure(eq(EstimationUnit.FIBONACCI));
verify(sessionEntity, times(1)).save();
}
@Test
public void sessionIsAlreadyStarted() {
when(queryBuilder.sessionWhereIssueIdAndStatus(ISSUE_ID, SessionStatus.IN_PROGRESS)).thenReturn(sessionQuery);
when(ao.find(eq(PokerSessionEntity.class), eq(sessionQuery))).thenReturn(
new PokerSessionEntity[]{sessionEntity});
service.startSession(ISSUE_ID, USER_ID, EstimationUnit.FIBONACCI);
verifyZeroInteractions(sessionEntity);
verify(ao, times(0)).create(eq(PokerSessionEntity.class));
}
@Test
public void newEstimateIsAdded() {
// TODO: replace any() with concrete equal
when(ao.find(eq(PokerSessionEntity.class), any())).thenReturn(
new PokerSessionEntity[]{sessionEntity});
when(ao.find(eq(EstimateEntity.class), any())).thenReturn(new EstimateEntity[]{});
when(ao.create(EstimateEntity.class)).thenReturn(estimateEntity);
service.addEstimate("TEST-1", 12L, 12);
verify(estimateEntity, times(1)).setEstimatorId(12L);
verify(estimateEntity, times(1)).setGradeId(12);
verify(estimateEntity, times(1)).setPokerSession(sessionEntity);
verify(estimateEntity, times(1)).save();
}
@Test
public void existingEstimateIsUpdated() {
// TODO: replace any() with concrete equal
when(ao.find(eq(PokerSessionEntity.class), any())).thenReturn(
new PokerSessionEntity[]{sessionEntity});
when(ao.find(eq(EstimateEntity.class), any())).thenReturn(new EstimateEntity[]{estimateEntity});
service.addEstimate("TEST-1", 12L, 12);
verify(ao, times(0)).create(eq(EstimateEntity.class));
verify(estimateEntity, times(1)).setEstimatorId(12L);
verify(estimateEntity, times(1)).setGradeId(12);
verify(estimateEntity, times(1)).setPokerSession(sessionEntity);
verify(estimateEntity, times(1)).save();
}
@Test
public void sessionIsStopped() {
when(queryBuilder.sessionWhereIssueIdAndStatus(ISSUE_ID, SessionStatus.IN_PROGRESS)).thenReturn(sessionQuery);
when(ao.find(eq(PokerSessionEntity.class), eq(sessionQuery))).thenReturn(
new PokerSessionEntity[]{sessionEntity});
when(sessionEntity.getEstimates()).thenReturn(new EstimateEntity[]{estimateEntity});
service.stopSession(ISSUE_ID);
verify(sessionEntity, times(1)).setSessionStatus(SessionStatus.FINISHED);
verify(sessionEntity, times(1)).setCompletionDate(anyLong());
verify(sessionEntity, times(1)).save();
}
@Test
public void sessionIsStoppedAndDeleted() {
when(queryBuilder.sessionWhereIssueIdAndStatus(ISSUE_ID, SessionStatus.IN_PROGRESS)).thenReturn(sessionQuery);
when(ao.find(PokerSessionEntity.class, sessionQuery)).thenReturn(new PokerSessionEntity[]{sessionEntity});
when(sessionEntity.getEstimates()).thenReturn(new EstimateEntity[]{});
final Query allSessionsQuery = mock(Query.class);
when(queryBuilder.whereIssuerId(ISSUE_ID)).thenReturn(allSessionsQuery);
when(ao.find(PokerSessionEntity.class, allSessionsQuery)).thenReturn(new PokerSessionEntity[]{sessionEntity});
service.stopSession(ISSUE_ID);
verify(ao, times(1)).delete(sessionEntity);
verify(sessionEntity, times(0)).setSessionStatus(SessionStatus.FINISHED);
verify(sessionEntity, times(0)).setCompletionDate(anyLong());
verify(sessionEntity, times(0)).save();
}
@Test
public void allSessionsAreWithEstimatesDeleted() {
final Query allSessionsQuery = mock(Query.class);
final PokerSessionEntity sessionEntity2 = mock(PokerSessionEntity.class);
when(sessionEntity2.getEstimates()).thenReturn(new EstimateEntity[]{estimateEntity});
when(queryBuilder.whereIssuerId(ISSUE_ID)).thenReturn(allSessionsQuery);
when(ao.find(PokerSessionEntity.class, allSessionsQuery)).thenReturn(
new PokerSessionEntity[]{sessionEntity, sessionEntity2});
service.deleteSessions(ISSUE_ID);
verify(ao, times(1)).delete(sessionEntity);
verify(ao, times(1)).delete(sessionEntity2);
verify(ao, times(1)).delete(estimateEntity);
}
@Test
public void doesNothingIfThereIsNoSessionInProgress() {
when(queryBuilder.sessionWhereIssueIdAndStatus(ISSUE_ID, SessionStatus.IN_PROGRESS)).thenReturn(sessionQuery);
when(ao.find(eq(PokerSessionEntity.class), eq(sessionQuery))).thenReturn(
new PokerSessionEntity[]{});
service.stopSession(ISSUE_ID);
verifyZeroInteractions(sessionEntity);
}
@Test
public void findsActiveSession() {
PokerSession pokerSession = PokerSession.builder().build();
when(queryBuilder.sessionWhereIssueIdAndStatus(ISSUE_ID, SessionStatus.IN_PROGRESS)).thenReturn(sessionQuery);
when(ao.find(eq(PokerSessionEntity.class), eq(sessionQuery))).thenReturn(
new PokerSessionEntity[]{sessionEntity});
when(converter.toObj(sessionEntity)).thenReturn(pokerSession);
Optional<PokerSession> actual = service.getActiveSession(ISSUE_ID);
assertTrue(actual.isPresent());
assertEquals(pokerSession, actual.get());
}
} | 8,812 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PokerConfigPageTest.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/test/java/com/aprey/jira/plugin/openpoker/config/PokerConfigPageTest.java | package com.aprey.jira.plugin.openpoker.config;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import com.aprey.jira.plugin.openpoker.api.config.ConfigurationManager;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.mock.component.MockComponentWorker;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.web.action.JiraWebActionSupport;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import webwork.action.ServletActionContext;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PokerConfigPageTest {
private PokerConfigPage pokerConfigPage;
private HttpServletRequest request;
private Project project1;
private Project project2;
private Project project3;
@InjectMocks
private ProjectManager projectManager = mock(ProjectManager.class);
@InjectMocks
private PluginSettingsFactory pluginSettingsFactory = mock(PluginSettingsFactory.class);
@InjectMocks
private PluginSettings pluginSettings = mock(PluginSettings.class);
@InjectMocks
public static final ComponentAccessor componentAccessor = mock(ComponentAccessor.class);
@Before
public void setUp() {
final MockComponentWorker mockComponentWorker = new MockComponentWorker();
mockComponentWorker.addMock(ProjectManager.class, projectManager);
mockComponentWorker.addMock(PluginSettings.class, pluginSettings);
mockComponentWorker.addMock(PluginSettingsFactory.class, pluginSettingsFactory);
mockComponentWorker.addMock(ComponentAccessor.class, componentAccessor);
mockComponentWorker.init();
when(pluginSettingsFactory.createSettingsForKey(anyString())).thenReturn(pluginSettings);
pokerConfigPage = new PokerConfigPage();
request = mock(HttpServletRequest.class);
project1 = mock(Project.class);
project2 = mock(Project.class);
project3 = mock(Project.class);
ServletActionContext.setRequest(request);
when(request.getParameter("allowedProjects")).thenReturn("project1,project2");
when(project1.getKey()).thenReturn("project1");
when(project2.getKey()).thenReturn("project2");
when(project3.getKey()).thenReturn("project3");
when(projectManager.getProjects()).thenReturn(Arrays.asList(project1, project2, project3));
}
@Test
public void testDoDefault() throws Exception {
when(pluginSettings.get("allowedProjects")).thenReturn("project1,project2");
assertEquals(JiraWebActionSupport.INPUT, pokerConfigPage.doDefault());
assertEquals(Arrays.asList("project1", "project2"), pokerConfigPage.getAllowedProjects());
}
@Test
public void testGetAllowedProjects() throws Exception {
when(pluginSettings.get("allowedProjects")).thenReturn("project1,project2");
ConfigurationManager.storeAllowedProjects("project1,project2");
pokerConfigPage.doDefault();
assertEquals(Arrays.asList("project1", "project2"), pokerConfigPage.getAllowedProjects());
}
@Test
public void testGetAllowedProjectsValue() throws Exception {
when(pluginSettings.get("allowedProjects")).thenReturn("project1,project2");
ConfigurationManager.storeAllowedProjects("project1,project2");
pokerConfigPage.doDefault();
assertEquals("project1,project2", pokerConfigPage.getAllowedProjectsValue());
}
@Test
public void testGetProjects() {
List<Project> projects = pokerConfigPage.getProjects();
assertEquals(3, projects.size());
assertEquals("project1", projects.get(0).getKey());
assertEquals("project2", projects.get(1).getKey());
assertEquals("project3", projects.get(2).getKey());
}
@Test
public void testGetURL() {
assertEquals("openPokerConfig.jspa", pokerConfigPage.getURL());
}
}
| 3,962 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
ApplyVoteProcessorTest.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/test/java/com/aprey/jira/plugin/openpoker/api/ApplyVoteProcessorTest.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.jira.user.util.UserManager;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class ApplyVoteProcessorTest {
private static final String ISSUE_ID = "TEST-1";
private static final long USER_ID = 1;
private static final int ESTIMATE_ID = 2;
private final PersistenceService persistenceService = mock(PersistenceService.class);
private final UserManager userManager = mock(UserManager.class);
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final ApplicationUser applicationUser = mock(ApplicationUser.class);
private final ApplyVoteProcessor applyVoteProcessor = new ApplyVoteProcessor(userManager);
@Test
public void estimateIsAppliedAndSessionIsDeleted() {
when(request.getParameter("userId")).thenReturn(String.valueOf(USER_ID));
when(request.getParameter("finalEstimateId")).thenReturn(String.valueOf(ESTIMATE_ID));
when(userManager.getUserById(USER_ID)).thenReturn(Optional.of(applicationUser));
applyVoteProcessor.process(persistenceService, request, ISSUE_ID);
verify(persistenceService, times(1)).applyFinalEstimate(ISSUE_ID, ESTIMATE_ID,
applicationUser);
}
@Test
public void estimateIsNotAppliedIfUserIsNotFound() {
when(request.getParameter("userId")).thenReturn(String.valueOf(USER_ID));
when(request.getParameter("finalEstimateId")).thenReturn(String.valueOf(ESTIMATE_ID));
when(userManager.getUserById(USER_ID)).thenReturn(Optional.empty());
applyVoteProcessor.process(persistenceService, request, ISSUE_ID);
verifyZeroInteractions(persistenceService);
}
} | 2,922 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
StopSessionProcessorTest.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/test/java/com/aprey/jira/plugin/openpoker/api/StopSessionProcessorTest.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class StopSessionProcessorTest {
private static final String ISSUE_ID = "TEST-1";
private final PersistenceService persistenceService = mock(PersistenceService.class);
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final StopSessionProcessor processor = new StopSessionProcessor();
@Test
public void sessionIsSToppedAndNewEstimateIsAdded() {
when(request.getParameter("estimationGradeId")).thenReturn("1");
when(request.getParameter("userId")).thenReturn("12");
processor.process(persistenceService, request, ISSUE_ID);
verify(persistenceService, times(1)).addEstimate(ISSUE_ID, 12, 1);
verify(persistenceService, times(1)).stopSession(ISSUE_ID);
}
@Test
public void sessionIsStoppedAndNewEstimateIsNotAddedWhenParamIsNull() {
when(request.getParameter("estimationGradeId")).thenReturn(null);
processor.process(persistenceService, request, ISSUE_ID);
verify(persistenceService, times(1)).stopSession(ISSUE_ID);
verify(persistenceService, times(0)).addEstimate(eq(ISSUE_ID), anyLong(), anyInt());
}
@Test
public void sessionIsStoppedAndNewEstimateIsNotAddedWhenParamIsEmpty() {
when(request.getParameter("estimationGradeId")).thenReturn("");
processor.process(persistenceService, request, ISSUE_ID);
verify(persistenceService, times(1)).stopSession(ISSUE_ID);
verify(persistenceService, times(0)).addEstimate(eq(ISSUE_ID), anyLong(), anyInt());
}
@Test
public void sessionIsStoppedAndNewEstimateIsNotAddedWhenParamIsNotInt() {
when(request.getParameter("estimationGradeId")).thenReturn("test");
processor.process(persistenceService, request, ISSUE_ID);
verify(persistenceService, times(1)).stopSession(ISSUE_ID);
verify(persistenceService, times(0)).addEstimate(eq(ISSUE_ID), anyLong(), anyInt());
}
} | 3,179 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
AllowedProjectsConditionTest.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/test/java/com/aprey/jira/plugin/openpoker/api/config/AllowedProjectsConditionTest.java | package com.aprey.jira.plugin.openpoker.api.config;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.mock.component.MockComponentWorker;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AllowedProjectsConditionTest {
@InjectMocks
private PluginSettingsFactory pluginSettingsFactory = mock(PluginSettingsFactory.class);
@InjectMocks
private PluginSettings pluginSettings = mock(PluginSettings.class);
@InjectMocks
public static final ComponentAccessor componentAccessor = mock(ComponentAccessor.class);
private AllowedProjectsCondition condition;
private ApplicationUser applicationUser;
private JiraHelper jiraHelper;
private Project project;
@Before
public void setUp() {
final MockComponentWorker mockComponentWorker = new MockComponentWorker();
mockComponentWorker.addMock(PluginSettings.class, pluginSettings);
mockComponentWorker.addMock(PluginSettingsFactory.class, pluginSettingsFactory);
mockComponentWorker.addMock(ComponentAccessor.class, componentAccessor);
mockComponentWorker.init();
condition = new AllowedProjectsCondition();
applicationUser = mock(ApplicationUser.class);
jiraHelper = mock(JiraHelper.class);
project = mock(Project.class);
when(pluginSettingsFactory.createSettingsForKey(anyString())).thenReturn(pluginSettings);
}
@Test
public void testShouldDisplay_AllowedProjectsIsEmpty() {
ConfigurationManager.storeAllowedProjects("");
when(pluginSettings.get("allowedProjects")).thenReturn("");
assertTrue(condition.shouldDisplay(applicationUser, jiraHelper));
}
@Test
public void testShouldDisplay_CurrentProjectIsAllowed() {
when(jiraHelper.getProject()).thenReturn(project);
when(project.getKey()).thenReturn("TEST");
ConfigurationManager.storeAllowedProjects("TEST,ANOTHER");
when(pluginSettings.get("allowedProjects")).thenReturn("TEST,ANOTHER");
assertTrue(condition.shouldDisplay(applicationUser, jiraHelper));
}
@Test
public void testShouldDisplay_CurrentProjectIsNotAllowed() {
when(jiraHelper.getProject()).thenReturn(project);
when(project.getKey()).thenReturn("NOT_ALLOWED");
ConfigurationManager.storeAllowedProjects("TEST,ANOTHER");
when(pluginSettings.get("allowedProjects")).thenReturn("TEST,ANOTHER");
assertFalse(condition.shouldDisplay(applicationUser, jiraHelper));
}
@Test
public void testShouldDisplay_NoCurrentProject() {
when(jiraHelper.getProject()).thenReturn(null);
assertTrue(condition.shouldDisplay(applicationUser, jiraHelper));
}
}
| 3,055 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
ConfigurationManagerTest.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/test/java/com/aprey/jira/plugin/openpoker/api/config/ConfigurationManagerTest.java | package com.aprey.jira.plugin.openpoker.api.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.mock.component.MockComponentWorker;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class ConfigurationManagerTest {
@InjectMocks
private PluginSettingsFactory pluginSettingsFactory = mock(PluginSettingsFactory.class);
@InjectMocks
private PluginSettings pluginSettings = mock(PluginSettings.class);
@InjectMocks
public static final ComponentAccessor componentAccessor = mock(ComponentAccessor.class);
@Before
public void setUp() {
final MockComponentWorker mockComponentWorker = new MockComponentWorker();
mockComponentWorker.addMock(PluginSettings.class, pluginSettings);
mockComponentWorker.addMock(PluginSettingsFactory.class, pluginSettingsFactory);
mockComponentWorker.addMock(ComponentAccessor.class, componentAccessor);
mockComponentWorker.init();
when(pluginSettingsFactory.createSettingsForKey(anyString())).thenReturn(pluginSettings);
}
@Test
public void testGetStoredAllowedProjects() {
// Test with stored projects
when(pluginSettings.get("allowedProjects")).thenReturn("project1,project2,project3");
List<String> expected = Arrays.asList("project1", "project2", "project3");
List<String> result = ConfigurationManager.getStoredAllowedProjects();
assertEquals(expected, result);
// Test with no stored projects
when(pluginSettings.get("allowedProjects")).thenReturn(null);
expected = new ArrayList<>();
result = ConfigurationManager.getStoredAllowedProjects();
assertEquals(expected, result);
}
@Test
public void testStoreAllowedProjects() {
// Test storing allowed projects
String updatedAllowedProjects = "project1,project2,project3";
ConfigurationManager.storeAllowedProjects(updatedAllowedProjects);
verify(pluginSettings).put("allowedProjects", updatedAllowedProjects);
}
}
| 2,216 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EstimationUnit.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/EstimationUnit.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
public enum EstimationUnit {
FIBONACCI, CLASSIC_PLANNING, T_SHIRT_SIZE, LINEAR, FIST_TO_FIVE;
}
| 890 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
UserNotFoundException.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/UserNotFoundException.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
public class UserNotFoundException extends RuntimeException {
private static final long serialVersionUID = -4708997251674385306L;
public UserNotFoundException(String message) {
super(message);
}
}
| 1,009 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EstimationGrade.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/EstimationGrade.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
public interface EstimationGrade {
int getId();
String getValue();
boolean isApplicable();
}
| 898 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EstimationScale.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/EstimationScale.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.Getter;
@Getter
public enum EstimationScale {
CLASSIC_PLANNING("Planning Cards", EstimationUnit.CLASSIC_PLANNING),
FIBONACCI("Fibonacci", EstimationUnit.FIBONACCI),
LINEAR("Linear", EstimationUnit.LINEAR),
T_SHIRT_SIZE("T-shirt size", EstimationUnit.T_SHIRT_SIZE),
FIST_TO_FIVE("Fist to Five", EstimationUnit.FIST_TO_FIVE);
private final String name;
private EstimationUnit estimationUnit;
EstimationScale(String name, EstimationUnit estimationUnit) {
this.name = name;
this.estimationUnit = estimationUnit;
}
public static Optional<EstimationUnit> findByName(String name) {
return Arrays.stream(values())
.filter(e -> e.name.equals(name))
.map(EstimationScale::getEstimationUnit)
.findFirst();
}
public static Optional<EstimationScale> findByUnit(EstimationUnit unit) {
return Arrays.stream(values())
.filter(e -> e.estimationUnit.equals(unit))
.findFirst();
}
public static List<EstimationScale> getValues() {
return Arrays.stream(values()).collect(Collectors.toList());
}
}
| 2,103 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
Deck.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/Deck.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
import java.util.List;
public interface Deck {
List<EstimationGrade> getGrades();
EstimationGrade getGrade(int gradeId);
}
| 924 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
User.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/User.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class User {
private final long id;
private final String username;
private final String fullName;
}
| 970 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PokerSession.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/PokerSession.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
import com.atlassian.jira.user.ApplicationUser;
import java.util.List;
import lombok.Builder;
import lombok.Value;
@Builder
@Value
public class PokerSession {
private final ApplicationUser moderator;
private final String issueId;
private final SessionStatus status;
private final long completionDate;
private final List<EstimationGrade> estimationGrades;
private final List<Estimate> estimates;
private final EstimationUnit estimationUnit;
}
| 1,261 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
Estimate.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/Estimate.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
import com.atlassian.jira.user.ApplicationUser;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class Estimate {
private final ApplicationUser estimator;
private final String grade;
private final int gradeId;
}
| 1,033 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
IssueServiceFacade.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/IssueServiceFacade.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
import com.atlassian.jira.bc.issue.IssueService;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueInputParameters;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Scanned
@Named
public class IssueServiceFacade {
private static final String STORY_POINT_FILED_NAME = "Story Points";
@ComponentImport
private final CustomFieldManager customFieldManager;
@ComponentImport
private final IssueService issueService;
@ComponentImport
private final IssueManager issueManager;
@Inject
public IssueServiceFacade(CustomFieldManager customFieldManager, IssueService issueService,
IssueManager issueManager) {
this.customFieldManager = customFieldManager;
this.issueService = issueService;
this.issueManager = issueManager;
}
public void applyEstimate(String estimate, ApplicationUser user, String issueId) {
Issue issue = issueManager.getIssueObject(issueId);
Optional<CustomField> field = getField(issue);
if (!field.isPresent()) {
log.error("'Story Point' custom field does not exist");
return;
}
IssueInputParameters inputParameters = buildInputParams(field.get().getIdAsLong(), estimate);
IssueService.UpdateValidationResult updateValidationResult = issueService
.validateUpdate(user, issue.getId(), inputParameters);
if (!updateValidationResult.isValid()) {
log.error("Validation for updating story point is failed, errors: {}", updateValidationResult
.getErrorCollection().toString());
return;
}
IssueService.IssueResult updateResult = issueService.update(user, updateValidationResult);
if (!updateResult.isValid()) {
log.error("ISSUE has NOT been updated. Errors: {}\n" + updateResult.getErrorCollection().toString());
return;
}
log.info("The issue {} has been updated with a new story point value", issueId);
}
private IssueInputParameters buildInputParams(long fieldId, String estimate) {
IssueInputParameters issueInputParameters = issueService.newIssueInputParameters();
issueInputParameters.addCustomFieldValue(fieldId, estimate);
issueInputParameters.setSkipScreenCheck(true);
issueInputParameters.setRetainExistingValuesWhenParameterNotProvided(true, true);
return issueInputParameters;
}
private Optional<CustomField> getField(Issue issue) {
return customFieldManager.getCustomFieldObjects(issue)
.stream()
.filter(f -> f.getFieldName().equals(STORY_POINT_FILED_NAME))
.findFirst();
}
public Optional<String> getStoryPoints(String issueId) {
Issue issue = issueManager.getIssueObject(issueId);
Optional<Object> value = customFieldManager.getCustomFieldObjects(issue)
.stream()
.filter(f -> f.getFieldName().equals(STORY_POINT_FILED_NAME))
.map(f -> f.getValue(issue))
.filter(Objects::nonNull)
.findAny();
if (!value.isPresent()) {
return Optional.empty();
}
return format(value.get());
}
private Optional<String> format(Object value) {
if (value instanceof Double) {
DecimalFormat format = new DecimalFormat("0.#");
return Optional.of(format.format(value));
}
if (value instanceof Integer) {
return Optional.of(value.toString());
}
return Optional.empty();
}
}
| 5,149 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
SessionStatus.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/SessionStatus.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker;
public enum SessionStatus {
IN_PROGRESS("In Progress"),
FINISHED("Finished");
SessionStatus(String name) {
this.name = name;
}
private final String name;
public String getName() {
return name;
}
}
| 1,034 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
FistToFive.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/FistToFive.java | /*
* Copyright (C) 2022 Public Domain
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
public enum FistToFive implements EstimationGrade {
FIST(1, "Fist", false),
ONE(2, "1", true),
TWO(3, "2", true),
THREE(4, "3", true),
FOUR(5, "4", true),
FIVE(6, "5", true);
private final int id;
private final String value;
private final boolean applicable;
private static final Map<Integer, FistToFive> ID_TO_INSTANCE_MAP = Stream.of(FistToFive.values())
.collect(toMap(
FistToFive::getId,
Function.identity())
);
FistToFive(int id, String value, boolean applicable) {
this.id = id;
this.value = value;
this.applicable = applicable;
}
@Override
public int getId() {
return id;
}
@Override
public String getValue() {
return value;
}
@Override
public boolean isApplicable() {
return applicable;
}
public static EstimationGrade findById(int id) {
return ID_TO_INSTANCE_MAP.get(id);
}
public static List<EstimationGrade> getValuesList() {
return Stream.of(FistToFive.values()).collect(toList());
}
}
| 2,491 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
ClassicPlanning.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/ClassicPlanning.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
public enum ClassicPlanning implements EstimationGrade {
ZERO(1, "0", true),
ONE(2, "1", true),
TWO(3, "2", true),
THREE(4, "3", true),
FIVE(5, "5", true),
EIGHT(6, "8", true),
THIRTEEN(7, "13", true),
TWENTY(8, "20", true),
FORTY(9, "40", true),
HUNDRED(10, "100", true),
INFINITE(11, "Infinite", false),
COFFEE(12, "Coffee", false),
QUESTION(13, "?", false);
private final int id;
private final String value;
private final boolean applicable;
private static final Map<Integer, ClassicPlanning> ID_TO_INSTANCE_MAP = Stream.of(ClassicPlanning.values())
.collect(toMap(
ClassicPlanning::getId,
Function.identity())
);
ClassicPlanning(int id, String value, boolean applicable) {
this.id = id;
this.value = value;
this.applicable = applicable;
}
@Override
public int getId() {
return id;
}
@Override
public String getValue() {
return value;
}
@Override
public boolean isApplicable() {
return applicable;
}
public static EstimationGrade findById(int id) {
return ID_TO_INSTANCE_MAP.get(id);
}
public static List<EstimationGrade> getValuesList() {
return Stream.of(ClassicPlanning.values()).collect(toList());
}
}
| 2,733 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
FinalEstEntity.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/FinalEstEntity.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import net.java.ao.Entity;
import net.java.ao.schema.Index;
import net.java.ao.schema.Indexes;
@Indexes(@Index(name = "issueId", methodNames = {"getIssueId"}))
public interface FinalEstEntity extends Entity {
String getIssueId();
void setIssueId(String issueId);
String getEstimateValue();
void setEstimateValue(String estimate);
}
| 1,155 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PokerSessionEntity.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/PokerSessionEntity.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationUnit;
import com.aprey.jira.plugin.openpoker.SessionStatus;
import net.java.ao.Entity;
import net.java.ao.OneToMany;
import net.java.ao.schema.Index;
import net.java.ao.schema.Indexes;
@Indexes(@Index(name = "issueId", methodNames = {"getIssueId"}))
public interface PokerSessionEntity extends Entity {
String getIssueId();
void setIssueId(String issueId);
Long getModeratorId();
void setModeratorId(Long moderatorId);
SessionStatus getSessionStatus();
void setSessionStatus(SessionStatus status);
void setUnitOfMeasure(EstimationUnit estimationUnit);
EstimationUnit getUnitOfMeasure();
void setCompletionDate(long timestamp);
long getCompletionDate();
@OneToMany
EstimateEntity[] getEstimates();
}
| 1,610 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
FibonacciDeck.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/FibonacciDeck.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import com.aprey.jira.plugin.openpoker.Deck;
import java.util.List;
public class FibonacciDeck implements Deck {
@Override
public List<EstimationGrade> getGrades() {
return FibonacciNumber.getValuesList();
}
@Override
public EstimationGrade getGrade(int gradeId) {
return FibonacciNumber.findById(gradeId);
}
}
| 1,212 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
FibonacciNumber.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/FibonacciNumber.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
public enum FibonacciNumber implements EstimationGrade {
ONE(1, "1", true),
TWO(2, "2", true),
THREE(3, "3", true),
FIVE(4, "5", true),
EIGHT(5, "8", true),
THIRTEEN(6, "13", true),
TWENTY_ONE(7, "21", true),
THIRTY_FOUR(11, "34", true),
FIFTY_FIVE(12, "55", true),
EIGHTY_NINE(13, "89", true),
INFINITE(8, "Infinite", false),
COFFEE(9, "Coffee", false),
QUESTION(10, "?", false);
private final int id;
private final String value;
private final boolean applicable;
private static final Map<Integer, FibonacciNumber> ID_TO_INSTANCE_MAP = Stream.of(FibonacciNumber.values())
.collect(toMap(
FibonacciNumber::getId,
Function.identity())
);
FibonacciNumber(int id, String value, boolean applicable) {
this.id = id;
this.value = value;
this.applicable = applicable;
}
@Override
public int getId() {
return id;
}
@Override
public String getValue() {
return value;
}
@Override
public boolean isApplicable() {
return applicable;
}
public static EstimationGrade findById(int id) {
return ID_TO_INSTANCE_MAP.get(id);
}
public static List<EstimationGrade> getValuesList() {
return Stream.of(FibonacciNumber.values()).collect(toList());
}
}
| 2,771 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
LinearSequence.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/LinearSequence.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
public enum LinearSequence implements EstimationGrade {
ONE(1, "1", true),
TWO(2, "2", true),
THREE(3, "3", true),
FOUR(4, "4", true),
FIVE(5, "5", true),
SIX(6, "6", true),
EIGHT(7, "7", true),
NINE(8, "8", true),
TEN(9, "9", true),
ELEVEN(10, "10", true),
TWELFTH(11, "11", true),
THIRTEEN(12, "12", true);
private final int id;
private final String value;
private final boolean applicable;
private static final Map<Integer, LinearSequence> ID_TO_INSTANCE_MAP = Stream.of(LinearSequence.values())
.collect(toMap(
LinearSequence::getId,
Function.identity())
);
LinearSequence(int id, String value, boolean applicable) {
this.id = id;
this.value = value;
this.applicable = applicable;
}
@Override
public int getId() {
return id;
}
@Override
public String getValue() {
return value;
}
@Override
public boolean isApplicable() {
return applicable;
}
public static EstimationGrade findById(int id) {
return ID_TO_INSTANCE_MAP.get(id);
}
public static List<EstimationGrade> getValuesList() {
return Stream.of(LinearSequence.values()).collect(toList());
}
}
| 2,668 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
QueryBuilderService.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/QueryBuilderService.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.SessionStatus;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import javax.inject.Named;
import net.java.ao.Query;
@Scanned
@Named
public class QueryBuilderService {
Query sessionWhereIssueIdAndStatus(String issueId, SessionStatus status) {
return Query.select().where("ISSUE_ID = ? AND SESSION_STATUS = ?", issueId, status);
}
Query estimateWhereEstimatorIdAndSessionId(Long estimatorId, PokerSessionEntity session) {
return Query.select().where("POKER_SESSION_ID = ? AND ESTIMATOR_ID = ?", session, estimatorId);
}
Query whereIssuerId(String issueId) {
return Query.select().where("ISSUE_ID = ?", issueId);
}
}
| 1,532 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EntityToObjConverter.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/EntityToObjConverter.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.Estimate;
import com.aprey.jira.plugin.openpoker.EstimationUnit;
import com.aprey.jira.plugin.openpoker.PokerSession;
import com.aprey.jira.plugin.openpoker.UserNotFoundException;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.jira.user.util.UserManager;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
@Named
@Scanned
class EntityToObjConverter {
@ComponentImport
private final UserManager userManager;
private final EstimationDeckService estimationDeckService;
@Inject
public EntityToObjConverter(UserManager userManager, EstimationDeckService estimationDeckService) {
this.userManager = userManager;
this.estimationDeckService = estimationDeckService;
}
public Estimate toObj(EstimateEntity entity, EstimationUnit estimationUnit) {
return Estimate.builder()
.estimator(getUser(entity.getEstimatorId()))
.grade(estimationDeckService.getDeck(estimationUnit).getGrade(entity.getGradeId()).getValue())
.gradeId(entity.getGradeId())
.build();
}
public PokerSession toObj(PokerSessionEntity entity) {
return PokerSession.builder()
.status(entity.getSessionStatus())
.issueId(entity.getIssueId())
.moderator(getUser(entity.getModeratorId()))
.completionDate(entity.getCompletionDate())
.estimates(buildEstimates(entity.getEstimates(), entity.getUnitOfMeasure()))
.estimationGrades(estimationDeckService.getDeck(entity.getUnitOfMeasure()).getGrades())
.estimationUnit(entity.getUnitOfMeasure())
.build();
}
private List<Estimate> buildEstimates(EstimateEntity[] entities, EstimationUnit estimationUnit) {
return Arrays.stream(entities).map(e -> toObj(e, estimationUnit)).collect(Collectors.toList());
}
private ApplicationUser getUser(long userId) {
return userManager.getUserById(userId).orElseThrow(() -> new UserNotFoundException(
"User with id " + userId + " is not found"));
}
}
| 3,320 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PersistenceService.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/PersistenceService.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import com.aprey.jira.plugin.openpoker.EstimationUnit;
import com.aprey.jira.plugin.openpoker.IssueServiceFacade;
import com.aprey.jira.plugin.openpoker.PokerSession;
import com.aprey.jira.plugin.openpoker.SessionStatus;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
@Transactional
@Scanned
@Named
@Slf4j
public class PersistenceService {
@ComponentImport
private final ActiveObjects ao;
private final EntityToObjConverter converter;
private final QueryBuilderService queryBuilder;
private final IssueServiceFacade issueServiceFacade;
private final EstimationDeckService deckService;
@Inject
public PersistenceService(ActiveObjects ao, EntityToObjConverter converter,
QueryBuilderService queryBuilderService,
IssueServiceFacade issueServiceFacade,
EstimationDeckService estimationDeckService) {
this.ao = ao;
this.converter = converter;
this.queryBuilder = queryBuilderService;
this.issueServiceFacade = issueServiceFacade;
this.deckService = estimationDeckService;
}
public void startSession(String issueId, long userId, EstimationUnit estimationUnit) {
if (getActiveSessionEntity(issueId).isPresent()) {
return;
}
final PokerSessionEntity session = ao.create(PokerSessionEntity.class);
session.setIssueId(issueId);
session.setModeratorId(userId);
session.setSessionStatus(SessionStatus.IN_PROGRESS);
session.setUnitOfMeasure(estimationUnit);
session.save();
}
public void addEstimate(String issueId, long estimatorId, int gradeId) {
final Optional<PokerSessionEntity> sessionOpt = getActiveSessionEntity(issueId);
if (!sessionOpt.isPresent()) {
return;
}
Optional<EstimateEntity> existingEstimationOpt = findEstimate(estimatorId, sessionOpt.get());
final EstimateEntity estimate = existingEstimationOpt.orElseGet(() -> ao.create(EstimateEntity.class));
estimate.setEstimatorId(estimatorId);
estimate.setGradeId(gradeId);
estimate.setPokerSession(sessionOpt.get());
estimate.save();
}
public void stopSession(String issueId) {
final Optional<PokerSessionEntity> sessionOpt = getActiveSessionEntity(issueId);
if (!sessionOpt.isPresent()) {
return;
}
PokerSessionEntity session = sessionOpt.get();
if (session.getEstimates().length == 0) {
deleteSessions(issueId);
return;
}
session.setSessionStatus(SessionStatus.FINISHED);
session.setCompletionDate(System.currentTimeMillis());
session.save();
}
public Optional<String> getFinaleEstimate(String issueId) {
return findFinalEstimateEntity(issueId).map(e -> Optional.ofNullable(e.getEstimateValue()))
.orElse(issueServiceFacade.getStoryPoints(issueId));
}
public void applyFinalEstimate(String issueId, int estimateId, ApplicationUser applicationUser) {
List<PokerSessionEntity> orderedSessions = getAllSessions(issueId);
if (orderedSessions.isEmpty()) {
log.error("No completed sessions for issue with id {}", issueId);
return;
}
PokerSessionEntity latestSession = orderedSessions.get(0);
EstimationGrade estimationGrade = getEstimationGrade(estimateId, latestSession.getUnitOfMeasure());
if (estimationGrade.isApplicable()) {
issueServiceFacade.applyEstimate(estimationGrade.getValue(), applicationUser, issueId);
}
saveFinalEstimate(estimationGrade.getValue(), issueId);
deleteSessions(orderedSessions);
}
private EstimationGrade getEstimationGrade(int estimationId, EstimationUnit estimationUnit) {
return deckService.getDeck(estimationUnit).getGrade(estimationId);
}
private void saveFinalEstimate(String estimate, String issueId) {
FinalEstEntity estimateEntity = getFinalEstimateEntity(issueId);
estimateEntity.setEstimateValue(estimate);
estimateEntity.setIssueId(issueId);
estimateEntity.save();
}
private Optional<FinalEstEntity> findFinalEstimateEntity(String issueId) {
FinalEstEntity[] estimates = ao.find(FinalEstEntity.class, queryBuilder.whereIssuerId(issueId));
if (estimates.length == 0) {
return Optional.empty();
}
return Optional.of(estimates[0]);
}
private FinalEstEntity getFinalEstimateEntity(String issueId) {
return findFinalEstimateEntity(issueId).orElse(ao.create(FinalEstEntity.class));
}
private void deleteSessionAndEstimates(PokerSessionEntity session) {
if (session.getEstimates() != null) {
Arrays.stream(session.getEstimates()).forEach(ao::delete);
}
ao.delete(session);
}
public void deleteSessions(String issueId) {
PokerSessionEntity[] sessions = ao.find(PokerSessionEntity.class,
queryBuilder.whereIssuerId(issueId));
if (sessions == null) {
return;
}
deleteSessions(Arrays.stream(sessions).collect(Collectors.toList()));
}
private void deleteSessions(List<PokerSessionEntity> sessions) {
sessions.forEach(this::deleteSessionAndEstimates);
}
private Optional<EstimateEntity> findEstimate(final long estimatorId, final PokerSessionEntity session) {
EstimateEntity[] estimates = ao.find(EstimateEntity.class,
queryBuilder.estimateWhereEstimatorIdAndSessionId(estimatorId, session));
if (estimates.length == 0) {
return Optional.empty();
}
return Optional.of(estimates[0]);
}
private Optional<PokerSessionEntity> getActiveSessionEntity(String issueId) {
PokerSessionEntity[] sessions = ao.find(PokerSessionEntity.class,
queryBuilder.sessionWhereIssueIdAndStatus(issueId,
SessionStatus.IN_PROGRESS));
if (sessions.length == 0) {
return Optional.empty();
}
return Optional.of(sessions[0]);
}
public Optional<PokerSession> getActiveSession(String issueId) {
return getActiveSessionEntity(issueId).map(converter::toObj);
}
public Optional<PokerSession> getLatestCompletedSession(String issueId) {
Function<List<PokerSessionEntity>, Optional<PokerSessionEntity>> theLatestSessionFinder = sessionList ->
reverseOrderSessions(sessionList.stream())
.limit(1)
.findAny();
return findSessionByIssueIdAndStatus(issueId, SessionStatus.FINISHED, theLatestSessionFinder).map(
converter::toObj);
}
private List<PokerSessionEntity> getAllSessions(String issueId) {
PokerSessionEntity[] sessions = ao.find(PokerSessionEntity.class,
queryBuilder.whereIssuerId(issueId));
return reverseOrderSessions(Arrays.stream(sessions)).collect(Collectors.toList());
}
private Stream<PokerSessionEntity> reverseOrderSessions(Stream<PokerSessionEntity> sessions) {
return sessions.sorted(Comparator.comparingLong(PokerSessionEntity::getCompletionDate).reversed());
}
private Optional<PokerSessionEntity> findSessionByIssueIdAndStatus(String issueId, SessionStatus status,
Function<List<PokerSessionEntity>,
Optional<PokerSessionEntity>> sessionFinder) {
PokerSessionEntity[] sessions = ao.find(PokerSessionEntity.class,
queryBuilder.sessionWhereIssueIdAndStatus(issueId, status));
if (sessions.length == 0) {
return Optional.empty();
}
return sessionFinder.apply(Arrays.asList(sessions));
}
}
| 9,660 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
ClassicPlanningDeck.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/ClassicPlanningDeck.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import com.aprey.jira.plugin.openpoker.Deck;
import java.util.List;
public class ClassicPlanningDeck implements Deck {
@Override
public List<EstimationGrade> getGrades() {
return ClassicPlanning.getValuesList();
}
@Override
public EstimationGrade getGrade(int gradeId) {
return ClassicPlanning.findById(gradeId);
}
}
| 1,218 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EstimateEntity.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/EstimateEntity.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import net.java.ao.Entity;
import net.java.ao.schema.Index;
import net.java.ao.schema.Indexes;
@Indexes(@Index(name = "pokerSession", methodNames = {"getPokerSession"}))
public interface EstimateEntity extends Entity {
PokerSessionEntity getPokerSession();
void setPokerSession(PokerSessionEntity pokerSession);
long getEstimatorId();
void setEstimatorId(long estimatorId);
int getGradeId();
void setGradeId(int gradeId);
}
| 1,257 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
TshirtSizeDeck.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/TshirtSizeDeck.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import com.aprey.jira.plugin.openpoker.Deck;
import java.util.List;
public class TshirtSizeDeck implements Deck {
@Override
public List<EstimationGrade> getGrades() {
return TshirtSize.getValuesList();
}
@Override
public EstimationGrade getGrade(int gradeId) {
return TshirtSize.findById(gradeId);
}
}
| 1,203 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
TshirtSize.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/TshirtSize.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
public enum TshirtSize implements EstimationGrade {
XS(1, "XS", false),
S(2, "S", false),
M(3, "M", false),
L(4, "L", false),
XL(5, "XL", false),
XXL(6, "XXL", false),
XXXL(7, "XXXL", false),
COFFEE(8, "Coffee", false),
QUESTION(9, "?", false);
private final int id;
private final String value;
private final boolean applicable;
private static final Map<Integer, TshirtSize> ID_TO_INSTANCE_MAP = Stream.of(TshirtSize.values())
.collect(toMap(
TshirtSize::getId,
Function.identity()));
TshirtSize(int id, String value, boolean applicable) {
this.id = id;
this.value = value;
this.applicable = applicable;
}
@Override
public int getId() {
return id;
}
@Override
public String getValue() {
return value;
}
@Override
public boolean isApplicable() {
return applicable;
}
public static EstimationGrade findById(int id) {
return ID_TO_INSTANCE_MAP.get(id);
}
public static List<EstimationGrade> getValuesList() {
return Stream.of(TshirtSize.values()).collect(toList());
}
}
| 2,470 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
FistToFiveDeck.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/FistToFiveDeck.java | /*
* Copyright (C) 2022 Public Domain
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import com.aprey.jira.plugin.openpoker.Deck;
import java.util.List;
public class FistToFiveDeck implements Deck {
@Override
public List<EstimationGrade> getGrades() {
return FistToFive.getValuesList();
}
@Override
public EstimationGrade getGrade(int gradeId) {
return FistToFive.findById(gradeId);
}
}
| 1,201 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
LinearDeck.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/LinearDeck.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.Deck;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import java.util.List;
public class LinearDeck implements Deck {
@Override
public List<EstimationGrade> getGrades() {
return LinearSequence.getValuesList();
}
@Override
public EstimationGrade getGrade(int gradeId) {
return LinearSequence.findById(gradeId);
}
}
| 1,207 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EstimationDeckService.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/persistence/EstimationDeckService.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.persistence;
import com.aprey.jira.plugin.openpoker.Deck;
import com.aprey.jira.plugin.openpoker.EstimationUnit;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.google.common.collect.ImmutableMap;
import javax.inject.Named;
@Scanned
@Named
public class EstimationDeckService {
private final ImmutableMap<EstimationUnit, Deck> unitToDeckMap
= ImmutableMap.<EstimationUnit, Deck>builder()
.put(EstimationUnit.FIBONACCI, new FibonacciDeck())
.put(EstimationUnit.CLASSIC_PLANNING, new ClassicPlanningDeck())
.put(EstimationUnit.T_SHIRT_SIZE, new TshirtSizeDeck())
.put(EstimationUnit.LINEAR, new LinearDeck())
.put(EstimationUnit.FIST_TO_FIVE, new FistToFiveDeck())
.build();
public Deck getDeck(EstimationUnit estimationUnit) {
return unitToDeckMap.get(estimationUnit);
}
}
| 1,702 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PokerConfigPage.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/config/PokerConfigPage.java | package com.aprey.jira.plugin.openpoker.config;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.security.request.RequestMethod;
import com.atlassian.jira.security.request.SupportedMethods;
import com.atlassian.jira.web.action.JiraWebActionSupport;
import webwork.action.Action;
import webwork.action.ServletActionContext;
import static com.aprey.jira.plugin.openpoker.api.config.ConfigurationManager.getStoredAllowedProjects;
import static com.aprey.jira.plugin.openpoker.api.config.ConfigurationManager.storeAllowedProjects;
@SupportedMethods({ RequestMethod.GET })
public class PokerConfigPage extends JiraWebActionSupport {
//List of allowed projects
private List<String> allowedProjects = new ArrayList<>();
/**
* Method is called when the page is first loaded
*/
@Override
public String doDefault() throws Exception {
allowedProjects.addAll(getStoredAllowedProjects());
return Action.INPUT;
}
/**
* Method is called when the form is submitted
*/
@Override
@SupportedMethods({ RequestMethod.POST })
protected String doExecute() throws Exception {
String updatedAllowedProjects = getUpdatedAllowedProjects();
storeAllowedProjects(updatedAllowedProjects);
if ( !getHasErrorMessages() ) {
return returnComplete("openPokerConfig!default.jspa");
}
return Action.INPUT;
}
/**
* Method to get the updated allowed projects from the form
*
* @return String of allowed projects
*/
private static String getUpdatedAllowedProjects() {
HttpServletRequest request = ServletActionContext.getRequest();
String updatedAllowedProjects = request.getParameter("allowedProjects");
return updatedAllowedProjects;
}
public List<String> getAllowedProjects() {
return allowedProjects;
}
public String getAllowedProjectsValue() {
return String.join(",", allowedProjects);
}
public void setAllowedProjects(List<String> allowedProjects) {
this.allowedProjects = allowedProjects;
}
public List<Project> getProjects() {
return ComponentAccessor.getProjectManager().getProjects();
}
public String getURL() {
return "openPokerConfig.jspa";
}
}
| 2,276 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
ActionProcessor.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/ActionProcessor.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
public interface ActionProcessor {
default Optional<Integer> getParam(HttpServletRequest request, String paramName) {
String param = request.getParameter(paramName);
if (param == null || param.isEmpty()) {
return Optional.empty();
}
try {
return Optional.of(Integer.parseInt(param));
} catch (NumberFormatException ignore) {
return Optional.empty();
}
}
//TODO: persistanceService should be injected to prcossors instead of passing as parameter
void process(PersistenceService persistenceService, HttpServletRequest request, String issueId);
}
| 1,586 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
StartSessionProcessor.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/StartSessionProcessor.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.EstimationScale;
import com.aprey.jira.plugin.openpoker.EstimationUnit;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import javax.servlet.http.HttpServletRequest;
public class StartSessionProcessor implements ActionProcessor {
@Override
public void process(PersistenceService persistenceService, HttpServletRequest request, String issueId) {
final long userId = Long.parseLong(request.getParameter("userId"));
final String estimationScale = request.getParameter("estimationScale");
EstimationUnit estimationUnit = EstimationScale.findByName(estimationScale)
.orElse(EstimationUnit.CLASSIC_PLANNING);
persistenceService.startSession(issueId, userId, estimationUnit);
}
}
| 1,631 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PokerSessionServlet.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/PokerSessionServlet.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.google.common.base.Preconditions.checkNotNull;
public class PokerSessionServlet extends HttpServlet {
private final PersistenceService persistenceService;
private final ImmutableMap<SessionAction, ActionProcessor> actionProcessorMap;
@Inject
public PokerSessionServlet(PersistenceService persistenceService, ApplyVoteProcessor applyVoteProcessor) {
this.persistenceService = checkNotNull(persistenceService);
this.actionProcessorMap = ImmutableMap.<SessionAction, ActionProcessor>builder()
.put(SessionAction.START_SESSION, new StartSessionProcessor())
.put(SessionAction.STOP_SESSION, new StopSessionProcessor())
.put(SessionAction.VOTE, new VoteProcessor())
.put(SessionAction.RE_ESTIMATE, new StartSessionProcessor())
.put(SessionAction.CANCEL, new DeleteSessionProcessor())
.put(SessionAction.APPLY_ESTIMATE, applyVoteProcessor)
.build();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
final String issueId = req.getParameter("issueId");
final SessionAction action = getAction(req.getParameter("action"));
actionProcessorMap.get(action).process(persistenceService, req, issueId);
resp.sendRedirect(req.getContextPath() + "/browse/" + issueId);
}
private SessionAction getAction(String actionStr) {
return SessionAction.getAction(actionStr)
.orElseThrow(() -> new RuntimeException("Unknown action " + actionStr));
}
}
| 2,741 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
SessionViewDTO.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/SessionViewDTO.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.EstimationScale;
import com.aprey.jira.plugin.openpoker.PokerSession;
import lombok.Builder;
import lombok.Value;
@Builder
@Value
public class SessionViewDTO {
private final PokerSession session;
private final UserDTO moderator;
private final EstimationViewDTO estimation;
private final EstimationScale currentScale;
}
| 1,169 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PokerSessionResource.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/PokerSessionResource.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.PokerSession;
import com.aprey.jira.plugin.openpoker.UserNotFoundException;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.jira.user.util.UserManager;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/session/")
@Scanned
public class PokerSessionResource {
private final PersistenceService sessionService;
@ComponentImport
private final UserManager userManager;
private final UserConverter userConverter;
@Inject
public PokerSessionResource(PersistenceService sessionService, UserManager userManager,
UserConverter userConverter) {
this.sessionService = sessionService;
this.userManager = userManager;
this.userConverter = userConverter;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get(@Context HttpServletRequest request) {
final String issueId = request.getParameter("issueId");
final ApplicationUser user = getUser(request);
Optional<PokerSession> activeSessionOpt = sessionService.getActiveSession(issueId);
if (!activeSessionOpt.isPresent()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
PokerSession activeSession = activeSessionOpt.get();
SessionDTO sessionDTO = new SessionDTO();
sessionDTO.setStatus(activeSession.getStatus());
sessionDTO.setEstimators(activeSession.getEstimates().stream()
.map(e -> userConverter.buildUserDto(e.getEstimator(), user))
.collect(Collectors.toList()));
return Response.ok(sessionDTO).build();
}
private ApplicationUser getUser(HttpServletRequest request) {
final Long userId = Long.parseLong(request.getParameter("userId"));
return getUser(userId);
}
private ApplicationUser getUser(Long userId) {
return userManager.getUserById(userId).orElseThrow(() -> new UserNotFoundException(
"User with id " + userId + " is not found"));
}
}
| 3,409 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
StopSessionProcessor.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/StopSessionProcessor.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
public class StopSessionProcessor implements ActionProcessor {
@Override
public void process(PersistenceService persistenceService, HttpServletRequest request, String issueId) {
addEstimateIfExist(request, persistenceService, issueId);
persistenceService.stopSession(issueId);
}
private void addEstimateIfExist(HttpServletRequest request, PersistenceService persistenceService, String issueId) {
final Optional<Integer> gradeId = getParam(request, "estimationGradeId");
if (!gradeId.isPresent()) {
return;
}
final long userId = Long.parseLong(request.getParameter("userId"));
persistenceService.addEstimate(issueId, userId, gradeId.get());
}
}
| 1,674 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
UserConverter.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/UserConverter.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.atlassian.jira.avatar.Avatar;
import com.atlassian.jira.avatar.AvatarService;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import javax.inject.Inject;
import javax.inject.Named;
@Scanned
@Named
public class UserConverter {
@ComponentImport
private final AvatarService avatarService;
@Inject
public UserConverter(AvatarService avatarService) {
this.avatarService = avatarService;
}
public UserDTO buildUserDto(ApplicationUser targetUser, ApplicationUser currentUser) {
UserDTO dto = new UserDTO();
dto.setUsername(targetUser.getUsername());
dto.setDisplayName(targetUser.getDisplayName());
dto.setAvatarUrl(avatarService.getAvatarURL(currentUser, targetUser, Avatar.Size.SMALL).toString());
return dto;
}
}
| 1,747 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
ApplyVoteProcessor.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/ApplyVoteProcessor.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.jira.user.util.UserManager;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
@Named
@Scanned
@Slf4j
public class ApplyVoteProcessor implements ActionProcessor {
private static final String ESTIMATE_FILED = "finalEstimateId";
private static final String USER_ID_FIELD = "userId";
@ComponentImport
private final UserManager userManager;
@Inject
public ApplyVoteProcessor(UserManager userManager) {
this.userManager = userManager;
}
@Override
public void process(PersistenceService persistenceService, HttpServletRequest request, String issueId) {
final long userId = Long.parseLong(request.getParameter(USER_ID_FIELD));
final int estimateId = Integer.parseInt(request.getParameter(ESTIMATE_FILED));
Optional<ApplicationUser> applicationUser = userManager.getUserById(userId);
if (!applicationUser.isPresent()) {
log.error("Application user is not found by {} id", userId);
return;
}
persistenceService.applyFinalEstimate(issueId, estimateId, applicationUser.get());
}
}
| 2,293 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
UserDTO.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/UserDTO.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class UserDTO {
@XmlElement
private String username;
@XmlElement
private String displayName;
@XmlElement
private String avatarUrl;
public String getUsername() {
return username;
}
public String getDisplayName() {
return displayName;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setUsername(String username) {
this.username = username;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
}
| 1,691 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
DeleteSessionProcessor.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/DeleteSessionProcessor.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import javax.servlet.http.HttpServletRequest;
public class DeleteSessionProcessor implements ActionProcessor {
@Override
public void process(PersistenceService persistenceService, HttpServletRequest request, String issueId) {
persistenceService.deleteSessions(issueId);
}
}
| 1,161 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EstimationViewDTO.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/EstimationViewDTO.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.EstimationGrade;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import lombok.Builder;
import lombok.Value;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
@Value
@Builder
public class EstimationViewDTO {
private final List<EstimateDTO> estimates;
private final List<EstimationGrade> estimationGrades;
private final boolean alreadyVoted;
private final boolean applicableGrades;
public int getAverageEstimateId() {
return estimates.stream().map(EstimateDTO::getGradeId)
.collect(groupingBy(Function.identity(), counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey).orElse(1);
}
}
| 1,699 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
PlanningPokerWebPanelProvider.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/PlanningPokerWebPanelProvider.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.Estimate;
import com.aprey.jira.plugin.openpoker.EstimationScale;
import com.aprey.jira.plugin.openpoker.PokerSession;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.plugin.webfragment.contextproviders.AbstractJiraContextProvider;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Scanned
public class PlanningPokerWebPanelProvider extends AbstractJiraContextProvider {
private static final Logger log = LoggerFactory.getLogger(PlanningPokerWebPanelProvider.class);
private static final String ISSUE_ID_KEY = "issue";
private final PersistenceService sessionService;
private final UserConverter userConverter;
@Inject
public PlanningPokerWebPanelProvider(PersistenceService sessionService,
UserConverter userConverter) {
this.sessionService = sessionService;
this.userConverter = userConverter;
}
@Override
public Map<String, Object> getContextMap(ApplicationUser applicationUser, JiraHelper jiraHelper) {
final String issueId = ((Issue) jiraHelper.getContextParams().get(ISSUE_ID_KEY)).getKey();
final Map<String, Object> contextMap = new HashMap<>();
Optional<PokerSession> sessionOpt = findSession(issueId);
sessionOpt.ifPresent(pokerSession -> buildSessionView(pokerSession, contextMap, applicationUser));
contextMap.put("contextPath", jiraHelper.getRequest().getContextPath());
contextMap.put("issueId", issueId);
contextMap.put("userId", applicationUser.getId());
contextMap.put("estimationUnits", EstimationScale.getValues());
sessionService.getFinaleEstimate(issueId).ifPresent(v -> contextMap.put("currentEstimate", v));
return contextMap;
}
private void buildSessionView(PokerSession session, Map<String, Object> contextMap, ApplicationUser currentUser) {
SessionViewDTO viewDTO = SessionViewDTO.builder()
.session(session)
.estimation(buildEstimationView(session, currentUser))
.currentScale(EstimationScale.findByUnit(session.getEstimationUnit())
.orElse(EstimationScale.CLASSIC_PLANNING))
.moderator(
userConverter.buildUserDto(session.getModerator(), currentUser))
.build();
contextMap.put("viewDTO", viewDTO);
}
private EstimationViewDTO buildEstimationView(PokerSession session, ApplicationUser currentUser) {
boolean alreadyVoted = (session.getEstimates()
.stream()
.anyMatch(e -> e.getEstimator().equals(currentUser)));
List<EstimateDTO> estimates = session.getEstimates()
.stream()
.map(e -> toEstimateDto(currentUser, e))
.collect(Collectors.toList());
return EstimationViewDTO.builder()
.alreadyVoted(alreadyVoted)
.estimationGrades(session.getEstimationGrades())
.estimates(estimates)
.build();
}
private EstimateDTO toEstimateDto(ApplicationUser currentUser, Estimate estimate) {
return EstimateDTO.builder()
.grade(estimate.getGrade())
.gradeId(estimate.getGradeId())
.estimator(userConverter.buildUserDto(estimate.getEstimator(), currentUser))
.build();
}
private Optional<PokerSession> findSession(String issueId) {
Optional<PokerSession> sessionOpt = sessionService.getActiveSession(issueId);
if (sessionOpt.isPresent()) {
return sessionOpt;
}
return sessionService.getLatestCompletedSession(issueId);
}
}
| 5,435 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
EstimateDTO.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/EstimateDTO.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import lombok.Builder;
import lombok.Value;
@Builder
@Value
public class EstimateDTO {
private final UserDTO estimator;
private final String grade;
private final int gradeId;
}
| 984 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
SessionAction.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/SessionAction.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import java.util.Optional;
import java.util.stream.Stream;
public enum SessionAction {
START_SESSION("Start Estimation"),
VOTE("Vote"),
STOP_SESSION("Stop Estimation"),
RE_ESTIMATE("Re-estimate"),
APPLY_ESTIMATE("Apply"),
CANCEL("Terminate");
private final String actionName;
private SessionAction(String actionName) {
this.actionName = actionName;
}
public String getActionName() {
return actionName;
}
public static Optional<SessionAction> getAction(String actionName) {
return Stream.of(SessionAction.values())
.filter(a -> a.getActionName().equals(actionName))
.findAny();
}
}
| 1,498 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
SessionDTO.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/SessionDTO.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.SessionStatus;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class SessionDTO {
@XmlElement
private SessionStatus status;
@XmlElement
private List<UserDTO> estimators;
public SessionStatus getStatus() {
return status;
}
public List<UserDTO> getEstimators() {
return estimators;
}
public void setStatus(SessionStatus status) {
this.status = status;
}
public void setEstimators(List<UserDTO> estimators) {
this.estimators = estimators;
}
}
| 1,587 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
VoteProcessor.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/VoteProcessor.java | /*
* Copyright (C) 2021 Andriy Preizner
*
* This file is a part of Open Poker jira plugin
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.aprey.jira.plugin.openpoker.api;
import com.aprey.jira.plugin.openpoker.persistence.PersistenceService;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
//TODO: cover with unit tests
public class VoteProcessor implements ActionProcessor {
@Override
public void process(PersistenceService persistenceService, HttpServletRequest request, String issueId) {
final long userId = Long.parseLong(request.getParameter("userId"));
final Optional<Integer> gradeId = getParam(request, "estimationGradeId");
if (!gradeId.isPresent()) {
return;
}
persistenceService.addEstimate(issueId, userId, gradeId.get());
}
}
| 1,455 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
ConfigurationManager.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/config/ConfigurationManager.java | package com.aprey.jira.plugin.openpoker.api.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
public abstract class ConfigurationManager {
//Key for plugin settings
private static String OPEN_POKER_KEY = "com.aprey.jira.plugin.openpoker";
/**
* Method to get the plugin settings
*
* @return pluginSettings instance
*/
public static PluginSettings getPluginSettings() {
PluginSettingsFactory pluginSettingsFactory = ComponentAccessor.getOSGiComponentInstanceOfType(PluginSettingsFactory.class);
PluginSettings pluginSettings = pluginSettingsFactory.createSettingsForKey(OPEN_POKER_KEY);
return pluginSettings;
}
/**
* Method to get the stored allowed projects from plugin settings
*
* @return ArrayList of allowed projects
*/
public static ArrayList<String> getStoredAllowedProjects() {
PluginSettings pluginSettings = getPluginSettings();
String storedProjects = ((String) pluginSettings.get("allowedProjects"));
if ( storedProjects != null && !storedProjects.isEmpty() ) {
return Arrays.stream(storedProjects.split(",")).collect(Collectors.toCollection(ArrayList::new));
}
return new ArrayList<>();
}
/**
* Method to store the updated allowed projects in plugin settings
*
* @param updatedAllowedProjects String of allowed projects
*/
public static void storeAllowedProjects(String updatedAllowedProjects) {
PluginSettings pluginSettings = getPluginSettings();
pluginSettings.put("allowedProjects", updatedAllowedProjects);
}
}
| 1,722 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
AllowedProjectsCondition.java | /FileExtraction/Java_unseen/aprey10_open-poker/src/main/java/com/aprey/jira/plugin/openpoker/api/config/AllowedProjectsCondition.java | package com.aprey.jira.plugin.openpoker.api.config;
import java.util.List;
import com.atlassian.jira.plugin.webfragment.conditions.AbstractWebCondition;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.user.ApplicationUser;
/**
* Class that defines a condition for the web fragment visibility
*/
public class AllowedProjectsCondition extends AbstractWebCondition {
/**
* Method to determine whether the web fragment should be displayed or not
* @param applicationUser The user currently viewing the page
* @param jiraHelper The JiraHelper that provides access to various Jira-related objects
* @return boolean value indicating whether the web fragment should be displayed or not
*/
@Override
public boolean shouldDisplay(ApplicationUser applicationUser, JiraHelper jiraHelper) {
List<String> allowedProjects = ConfigurationManager.getStoredAllowedProjects();
if ( allowedProjects.isEmpty() ) {
return true;
}
if ( jiraHelper.getProject() != null ) {
return allowedProjects.contains(jiraHelper.getProject().getKey());
}
return true;
}
}
| 1,114 | Java | .java | aprey10/open-poker | 17 | 11 | 14 | 2020-11-15T00:10:51Z | 2023-01-29T20:26:25Z |
SmppMessageHandlerTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/test/java/org/restcomm/connect/sms/smpp/SmppMessageHandlerTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms.smpp;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.japi.Creator;
import akka.testkit.JavaTestKit;
import akka.testkit.TestKit;
import com.cloudhopper.smpp.PduAsyncResponse;
import com.cloudhopper.smpp.impl.DefaultPduAsyncResponse;
import com.cloudhopper.smpp.pdu.PduRequest;
import com.cloudhopper.smpp.pdu.SubmitSmResp;
import org.apache.commons.configuration.Configuration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.core.service.api.NumberSelectorService;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.SmsMessagesDao;
import org.restcomm.connect.dao.entities.IncomingPhoneNumber;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.monitoringservice.MonitoringService;
import org.restcomm.connect.sms.smpp.dlr.spi.DLRPayload;
import javax.servlet.ServletContext;
import javax.servlet.sip.SipFactory;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.restcomm.connect.sms.SmsService;
import org.restcomm.connect.sms.api.SmsStatusUpdated;
import scala.concurrent.duration.FiniteDuration;
/**
* @author Henrique Rosa ([email protected])
*/
public class SmppMessageHandlerTest {
private static ActorSystem system;
@BeforeClass
public static void beforeAll() {
system = ActorSystem.create();
}
@AfterClass
public static void afterAll() {
system.shutdown();
}
@Test
public void testRemover() {
List<IncomingPhoneNumber> numbers = new ArrayList();
IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder();
builder.setPhoneNumber("123.");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertTrue(numbers.isEmpty());
builder.setPhoneNumber("123*");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertTrue(numbers.isEmpty());
builder.setPhoneNumber("^123");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertTrue(numbers.isEmpty());
builder.setPhoneNumber(".");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertTrue(numbers.isEmpty());
builder.setPhoneNumber("[5]");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertTrue(numbers.isEmpty());
builder.setPhoneNumber("1|2");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertTrue(numbers.isEmpty());
builder.setPhoneNumber("\\d");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertTrue(numbers.isEmpty());
builder.setPhoneNumber("+1234");
numbers.add(builder.build());
builder.setPhoneNumber("+1234*");
numbers.add(builder.build());
builder.setPhoneNumber("+1234.*");
numbers.add(builder.build());
builder.setPhoneNumber("9887");
numbers.add(builder.build());
builder.setPhoneNumber("+");
numbers.add(builder.build());
RegexRemover.removeRegexes(numbers);
assertEquals(3, numbers.size());
}
@Test
public void testOnReceiveDlrPayload() throws ParseException {
new JavaTestKit(system) {
{
// given
final ServletContext servletContext = mock(ServletContext.class);
final DaoManager daoManager = mock(DaoManager.class);
final DLRPayload dlrPayload = new DLRPayload();
dlrPayload.setId("12345");
dlrPayload.setStat(SmsMessage.Status.UNDELIVERED);
final SmsMessagesDao smsMessagesDao = mock(SmsMessagesDao.class);
final SmsMessage message = SmsMessage.builder().setSid(Sid.generate(Sid.Type.SMS_MESSAGE)).setSmppMessageId(dlrPayload.getId()).setStatus(SmsMessage.Status.SENT).build();
when(servletContext.getAttribute(DaoManager.class.getName())).thenReturn(daoManager);
when(servletContext.getAttribute(Configuration.class.getName())).thenReturn(mock(Configuration.class));
when(servletContext.getAttribute(SipFactory.class.getName())).thenReturn(mock(SipFactory.class));
when(servletContext.getAttribute(MonitoringService.class.getName())).thenReturn(mock(ActorRef.class));
when(servletContext.getAttribute(NumberSelectorService.class.getName())).thenReturn(mock(NumberSelectorService.class));
when(servletContext.getAttribute(SmsService.class.getName())).thenReturn(getRef());
when(daoManager.getSmsMessagesDao()).thenReturn(smsMessagesDao);
when(smsMessagesDao.getSmsMessageBySmppMessageId(dlrPayload.getId())).thenReturn(message);
final ActorRef messageHandler = system.actorOf(Props.apply(new Creator<Actor>() {
@Override
public Actor create() throws Exception {
return new SmppMessageHandler(servletContext);
}
}));
// when
messageHandler.tell(dlrPayload, getRef());
// then
verify(smsMessagesDao, timeout(100)).getSmsMessageBySmppMessageId(dlrPayload.getId());
SmsStatusUpdated expectMsgClass = expectMsgClass(FiniteDuration.create(100, TimeUnit.MILLISECONDS),
SmsStatusUpdated.class);
SmsMessage msg = (SmsMessage) expectMsgClass.getInfo().attributes().get("record");
assertEquals(SmsMessage.Status.UNDELIVERED, msg.getStatus());
}
};
}
@Test
public void testOnReceiveDlrPayloadForUnknownSms() throws ParseException {
new JavaTestKit(system) {
{
// given
final ServletContext servletContext = mock(ServletContext.class);
final DaoManager daoManager = mock(DaoManager.class);
final SmsMessagesDao smsMessagesDao = mock(SmsMessagesDao.class);
final DLRPayload dlrPayload = new DLRPayload();
dlrPayload.setId("12345");
when(servletContext.getAttribute(DaoManager.class.getName())).thenReturn(daoManager);
when(servletContext.getAttribute(Configuration.class.getName())).thenReturn(mock(Configuration.class));
when(servletContext.getAttribute(SipFactory.class.getName())).thenReturn(mock(SipFactory.class));
when(servletContext.getAttribute(MonitoringService.class.getName())).thenReturn(mock(ActorRef.class));
when(servletContext.getAttribute(NumberSelectorService.class.getName())).thenReturn(mock(NumberSelectorService.class));
when(servletContext.getAttribute(SmsService.class.getName())).thenReturn(getRef());
when(daoManager.getSmsMessagesDao()).thenReturn(smsMessagesDao);
when(smsMessagesDao.getSmsMessageBySmppMessageId(dlrPayload.getId())).thenReturn(null);
final ActorRef messageHandler = system.actorOf(Props.apply(new Creator<Actor>() {
@Override
public Actor create() throws Exception {
return new SmppMessageHandler(servletContext);
}
}));
// when
messageHandler.tell(dlrPayload, getRef());
// then
verify(smsMessagesDao, timeout(100)).getSmsMessageBySmppMessageId(dlrPayload.getId());
expectNoMsg();
}
};
}
@Test
public void testOnReceivePduAsyncResponseWithExistingSmppMessageCorrelation() {
new JavaTestKit(system) {
{
// given
final ServletContext servletContext = mock(ServletContext.class);
final DaoManager daoManager = mock(DaoManager.class);
when(servletContext.getAttribute(DaoManager.class.getName())).thenReturn(daoManager);
when(servletContext.getAttribute(Configuration.class.getName())).thenReturn(mock(Configuration.class));
when(servletContext.getAttribute(SipFactory.class.getName())).thenReturn(mock(SipFactory.class));
when(servletContext.getAttribute(MonitoringService.class.getName())).thenReturn(mock(ActorRef.class));
when(servletContext.getAttribute(NumberSelectorService.class.getName())).thenReturn(mock(NumberSelectorService.class));
when(servletContext.getAttribute(SmsService.class.getName())).thenReturn(getRef());
final String smppMessageId = "12345";
final SmsMessagesDao smsMessagesDao = mock(SmsMessagesDao.class);
final SmsMessage existingSmsMessage = SmsMessage.builder().setSid(Sid.generate(Sid.Type.SMS_MESSAGE)).setSmppMessageId(smppMessageId).setStatus(SmsMessage.Status.QUEUED).build();
final SmsMessage smsMessage = SmsMessage.builder().setSid(Sid.generate(Sid.Type.SMS_MESSAGE)).setSmppMessageId(null).setStatus(SmsMessage.Status.SENDING).build();
final SubmitSmResp submitSmResp = mock(SubmitSmResp.class);
final PduRequest pduRequest = mock(PduRequest.class);
final PduAsyncResponse pduResponse = mock(DefaultPduAsyncResponse.class);
when(pduResponse.getRequest()).thenReturn(pduRequest);
when(pduResponse.getResponse()).thenReturn(submitSmResp);
when(pduRequest.getReferenceObject()).thenReturn(smsMessage.getSid());
when(submitSmResp.getMessageId()).thenReturn(smppMessageId);
when(submitSmResp.getCommandStatus()).thenReturn(0);
when(daoManager.getSmsMessagesDao()).thenReturn(smsMessagesDao);
when(smsMessagesDao.getSmsMessageBySmppMessageId(smppMessageId)).thenReturn(existingSmsMessage);
when(smsMessagesDao.getSmsMessage(smsMessage.getSid())).thenReturn(smsMessage);
final SmsMessage smsMessageWithSmppMessageId1 = SmsMessage.builder().setSid(Sid.generate(Sid.Type.SMS_MESSAGE)).setSmppMessageId(smppMessageId).setStatus(SmsMessage.Status.SENT).build();
final SmsMessage smsMessageWithSmppMessageId2 = SmsMessage.builder().setSid(Sid.generate(Sid.Type.SMS_MESSAGE)).setSmppMessageId(smppMessageId).setStatus(SmsMessage.Status.SENT).build();
final SmsMessage smsMessageWithSmppMessageId3 = SmsMessage.builder().setSid(Sid.generate(Sid.Type.SMS_MESSAGE)).setSmppMessageId(smppMessageId).setStatus(SmsMessage.Status.SENT).build();
final List<SmsMessage> messages = Arrays.asList(smsMessageWithSmppMessageId1, smsMessageWithSmppMessageId2, smsMessageWithSmppMessageId3);
when(smsMessagesDao.findBySmppMessageId(smppMessageId)).thenReturn(messages);
final ActorRef messageHandler = system.actorOf(Props.apply(new Creator<Actor>() {
@Override
public Actor create() throws Exception {
return new SmppMessageHandler(servletContext);
}
}));
// when
messageHandler.tell(pduResponse, getRef());
// then
final ArgumentCaptor<SmsMessage> smsCaptor = ArgumentCaptor.forClass(SmsMessage.class);
SmsStatusUpdated expectMsgClass = expectMsgClass(FiniteDuration.create(100, TimeUnit.MILLISECONDS),
SmsStatusUpdated.class);
SmsMessage msg = (SmsMessage) expectMsgClass.getInfo().attributes().get("record");
assertEquals(SmsMessage.Status.SENT, msg.getStatus());
}
};
}
}
| 13,109 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
TelestaxDlrParserTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/test/java/org/restcomm/connect/sms/smpp/dlr/provider/TelestaxDlrParserTest.java | package org.restcomm.connect.sms.smpp.dlr.provider;
import org.junit.Assert;
import org.junit.Test;
import org.restcomm.connect.dao.entities.SmsMessage.Status;
import org.restcomm.connect.sms.smpp.dlr.spi.DLRPayload;
import org.restcomm.connect.sms.smpp.dlr.spi.DlrParser;
import org.restcomm.connect.commons.dao.MessageError;
/**
* @author mariafarooq
*
*/
public class TelestaxDlrParserTest {
@Test
public void parseInvalidDLR() {
final String pduMessage = "submit date:invaliddate stat:invalidStat";
DlrParser parser = new TelestaxDlrParser();
DLRPayload dlrMap = parser.parseMessage(pduMessage);
Assert.assertNull(dlrMap.getId());
}
@Test
public void parseDLRMessageTest() {
final String pduMessage = "id:0000058049 sub:001 dlvrd:001 submit date:1805170144 done date:1805170144 stat:DELIVRD err:000 text:none ";
DlrParser parser = new TelestaxDlrParser();
DLRPayload dlrMap = parser.parseMessage(pduMessage);
Assert.assertEquals("0000058049", dlrMap.getId());
Assert.assertEquals("001", dlrMap.getSub());
Assert.assertEquals("001", dlrMap.getDlvrd());
Assert.assertNull(dlrMap.getErr());
Assert.assertEquals(Status.DELIVERED, dlrMap.getStat());
Assert.assertEquals(2018, dlrMap.getDoneDate().getYear());
Assert.assertEquals(2018, dlrMap.getSubmitDate().getYear());
}
}
| 1,433 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsSession.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/SmsSession.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import javax.servlet.sip.SipURI;
import akka.actor.ActorSystem;
import org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.patterns.Observe;
import org.restcomm.connect.commons.patterns.Observing;
import org.restcomm.connect.commons.patterns.StopObserving;
import org.restcomm.connect.commons.push.PushNotificationServerHelper;
import org.restcomm.connect.dao.ClientsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.RegistrationsDao;
import org.restcomm.connect.dao.entities.Client;
import org.restcomm.connect.dao.entities.Registration;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.sms.api.GetLastSmsRequest;
import org.restcomm.connect.sms.api.SmsSessionAttribute;
import org.restcomm.connect.sms.api.SmsSessionInfo;
import org.restcomm.connect.sms.api.SmsSessionRequest;
import org.restcomm.connect.sms.api.SmsSessionResponse;
import org.restcomm.connect.sms.smpp.SmppClientOpsThread;
import org.restcomm.connect.sms.smpp.SmppInboundMessageEntity;
import org.restcomm.connect.sms.smpp.SmppMessageHandler;
import org.restcomm.connect.sms.smpp.SmppOutboundMessageEntity;
import org.restcomm.connect.telephony.api.TextMessage;
import org.restcomm.smpp.parameter.TlvSet;
import com.cloudhopper.commons.charset.Charset;
import com.cloudhopper.commons.charset.CharsetUtil;
import com.cloudhopper.commons.util.ByteArrayUtil;
import com.cloudhopper.smpp.SmppConstants;
import com.cloudhopper.smpp.tlv.Tlv;
import com.google.common.collect.ImmutableMap;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import scala.concurrent.duration.Duration;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Maria Farooq)
*/
public final class SmsSession extends RestcommUntypedActor {
private static final String SMS_RECORD = "record";
// Logger
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Runtime stuff.
private final ActorSystem system;
private final Configuration smsConfiguration;
private final Configuration configuration;
private final SipFactory factory;
private final List<ActorRef> observers;
private final SipURI transport;
private final Map<String, Object> attributes;
// Push notification server
private final PushNotificationServerHelper pushNotificationServerHelper;
// Map for custom headers from inbound SIP MESSAGE
private ConcurrentHashMap<String, String> customRequestHeaderMap = new ConcurrentHashMap<String, String>();
private TlvSet tlvSet;
private final DaoManager storage;
private SmsSessionRequest initial;
private SmsSessionRequest last;
private final boolean smppActivated;
private String externalIP;
private final ServletContext servletContext;
private ActorRef smppMessageHandler;
private final ActorRef monitoringService;
private final Sid fromOrganizationSid;
public SmsSession(final Configuration configuration, final SipFactory factory, final SipURI transport,
final DaoManager storage, final ActorRef monitoringService, final ServletContext servletContext, final Sid fromOrganizationSid) {
super();
this.system = getContext().system();
this.configuration = configuration;
this.smsConfiguration = configuration.subset("sms-aggregator");
this.factory = factory;
this.observers = new ArrayList<ActorRef>();
this.transport = transport;
this.attributes = new HashMap<String, Object>();
this.storage = storage;
this.monitoringService = monitoringService;
this.servletContext = servletContext;
this.smppActivated = Boolean.parseBoolean(this.configuration.subset("smpp").getString("[@activateSmppConnection]", "false"));
if (smppActivated) {
smppMessageHandler = (ActorRef) servletContext.getAttribute(SmppMessageHandler.class.getName());
}
String defaultHost = transport.getHost();
this.externalIP = this.configuration.subset("runtime-settings").getString("external-ip");
if (externalIP == null || externalIP.isEmpty() || externalIP.equals(""))
externalIP = defaultHost;
this.fromOrganizationSid = fromOrganizationSid;
this.tlvSet = new TlvSet();
if(!this.configuration.subset("outbound-sms").isEmpty()) {
//TODO: handle arbitrary keys instead of just TAG_DEST_NETWORK_ID
try {
String valStr = this.configuration.subset("outbound-sms").getString("destination_network_id");
this.tlvSet.addOptionalParameter(new Tlv(SmppConstants.TAG_DEST_NETWORK_ID,ByteArrayUtil.toByteArray(Integer.parseInt(valStr))));
} catch (Exception e) {
logger.error("Error while parsing tlv configuration " + e);
}
}
this.pushNotificationServerHelper = new PushNotificationServerHelper(system, configuration);
}
private void inbound(final Object message) throws IOException {
if (message instanceof SipServletRequest) {
final SipServletRequest request = (SipServletRequest) message;
// Handle the SMS.
SipURI uri = (SipURI) request.getFrom().getURI();
final String from = uri.getUser();
uri = (SipURI) request.getTo().getURI();
final String to = uri.getUser();
String body = null;
if (request.getContentLength() > 0) {
body = new String(request.getRawContent());
}
Iterator<String> headerIt = request.getHeaderNames();
while (headerIt.hasNext()) {
String headerName = headerIt.next();
if (headerName.startsWith("X-")) {
customRequestHeaderMap.put(headerName, request.getHeader(headerName));
}
}
// Store the last sms event.
last = new SmsSessionRequest(from, to, body, this.tlvSet, customRequestHeaderMap);
if (initial == null) {
initial = last;
}
// Notify the observers.
final ActorRef self = self();
for (final ActorRef observer : observers) {
observer.tell(last, self);
}
} else if (message instanceof SmppInboundMessageEntity) {
final SmppInboundMessageEntity request = (SmppInboundMessageEntity) message;
final SmsSessionRequest.Encoding encoding;
if(request.getSmppEncoding().equals(CharsetUtil.CHARSET_UCS_2)) {
encoding = SmsSessionRequest.Encoding.UCS_2;
} else {
encoding = SmsSessionRequest.Encoding.GSM;
}
// Store the last sms event.
last = new SmsSessionRequest (request.getSmppFrom(), request.getSmppTo(), request.getSmppContent(), encoding, request.getTlvSet(), null);
if (initial == null) {
initial = last;
}
// Notify the observers.
for (final ActorRef observer : observers) {
observer.tell(last, self());
}
}
}
private SmsSessionInfo info() {
final String from = initial.from();
final String to = initial.to();
final Map<String, Object> attributes = ImmutableMap.copyOf(this.attributes);
return new SmsSessionInfo(from, to, attributes);
}
private void observe(final Object message) {
final ActorRef self = self();
final Observe request = (Observe) message;
final ActorRef observer = request.observer();
if (observer != null) {
observers.add(observer);
observer.tell(new Observing(self), self);
}
}
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
if (Observe.class.equals(klass)) {
observe(message);
} else if (StopObserving.class.equals(klass)) {
stopObserving(message);
} else if (GetLastSmsRequest.class.equals(klass)) {
sender.tell(last, self);
} else if (SmsSessionAttribute.class.equals(klass)) {
final SmsSessionAttribute attribute = (SmsSessionAttribute) message;
attributes.put(attribute.name(), attribute.value());
Object record = attributes.get(SMS_RECORD);
if (record != null) {
system.eventStream().publish(record);
}
} else if (SmsSessionRequest.class.equals(klass)) {
outbound(message);
} else if (message instanceof SipServletRequest) {
inbound(message);
} else if (message instanceof SipServletResponse) {
response(message);
} else if (message instanceof SmppInboundMessageEntity) {
inbound(message);
}
}
@Override
public void postStop() {
super.postStop();
Object record = attributes.get(SMS_RECORD);
if (record != null) {
system.eventStream().publish(record);
}
}
private void response(final Object message) {
final SipServletResponse response = (SipServletResponse) message;
final int status = response.getStatus();
SmsSessionInfo info = info();
SmsSessionResponse result = null;
Object record = info.attributes().get(SMS_RECORD);
if (SipServletResponse.SC_ACCEPTED == status || SipServletResponse.SC_OK == status) {
if (record != null) {
SmsMessage toBeUpdated = ((SmsMessage)record);
SmsMessage.Builder builder = SmsMessage.builder();
builder.copyMessage(toBeUpdated);
builder.setDateSent(DateTime.now());
builder.setStatus(SmsMessage.Status.SENT);
this.attributes.put(SMS_RECORD, builder.build());
info = info();
}
result = new SmsSessionResponse(info, true);
} else {
if (record != null) {
SmsMessage toBeUpdated = ((SmsMessage)record);
SmsMessage.Builder builder = SmsMessage.builder();
builder.copyMessage(toBeUpdated);
builder.setStatus(SmsMessage.Status.FAILED);
this.attributes.put(SMS_RECORD, builder.build());
info = info();
}
result = new SmsSessionResponse(info, false);
}
// Notify the observers.
final ActorRef self = self();
for (final ActorRef observer : observers) {
observer.tell(result, self);
}
}
private void outbound(final Object message) {
last = (SmsSessionRequest) message;
if (initial == null) {
initial = last;
}
final Charset charset;
if(logger.isInfoEnabled()) {
logger.info("SMS encoding: " + last.encoding() );
}
switch(last.encoding()) {
case GSM:
charset = CharsetUtil.CHARSET_GSM;
break;
case UCS_2:
charset = CharsetUtil.CHARSET_UCS_2;
break;
case UTF_8:
charset = CharsetUtil.CHARSET_UTF_8;
break;
default:
charset = CharsetUtil.CHARSET_GSM;
}
monitoringService.tell(new TextMessage(last.from(), last.to(), TextMessage.SmsState.OUTBOUND), self());
final ClientsDao clients = storage.getClientsDao();
String to;
if (last.to().toLowerCase().startsWith("client")) {
to = last.to().replaceAll("client:","");
} else {
to = last.to();
}
final Client toClient = clients.getClient(to, fromOrganizationSid);
long delay = 0;
if (toClient == null) {
//We will send using the SMPP link only if:
// 1. This SMS is not for a registered client
// 2, SMPP is activated
if (smppActivated) {
if(logger.isInfoEnabled()) {
logger.info("Destination is not a local registered client, therefore, sending through SMPP to: " + last.to() );
}
if (sendUsingSmpp(last.from(), last.to(), last.body(), tlvSet, charset))
return;
}
} else {
delay = pushNotificationServerHelper.sendPushNotificationIfNeeded(toClient.getPushClientIdentity());
}
system.scheduler().scheduleOnce(Duration.create(delay, TimeUnit.MILLISECONDS), new Runnable() {
@Override
public void run() {
sendUsingSip(toClient, (SmsSessionRequest) message);
}
}, system.dispatcher());
}
private boolean sendUsingSmpp(String from, String to, String body, Charset encoding) {
return sendUsingSmpp(from, to, body, null, encoding);
}
private boolean sendUsingSmpp(String from, String to, String body, TlvSet tlvSet, Charset encoding) {
if ((SmppClientOpsThread.getSmppSession() != null && SmppClientOpsThread.getSmppSession().isBound()) && smppMessageHandler != null) {
if(logger.isInfoEnabled()) {
logger.info("SMPP session is available and connected, outbound message will be forwarded to : " + to );
logger.info("Encoding: " + encoding );
}
SmsMessage record = (SmsMessage)this.attributes.get(SMS_RECORD);
Sid sid = null;
if(record!=null) {
sid = record.getSid();
if(logger.isInfoEnabled()) {
logger.info("record sid = "+sid.toString());
}
}else{
logger.error("record is null");
}
try {
final SmppOutboundMessageEntity sms = new SmppOutboundMessageEntity(to, from, body, encoding, tlvSet, sid);
smppMessageHandler.tell(sms, null);
}catch (final Exception exception) {
// Log the exception.
logger.error("There was an error sending SMS to SMPP endpoint : " + exception);
}
return true;
}
return false;
}
private void sendUsingSip(Client toClient, SmsSessionRequest request) {
Registration toClientRegistration = null;
if (toClient != null) {
final RegistrationsDao registrations = storage.getRegistrationsDao();
toClientRegistration = registrations.getRegistration(toClient.getLogin(), fromOrganizationSid);
}
final SipApplicationSession application = factory.createApplicationSession();
StringBuilder buffer = new StringBuilder();
//buffer.append("sip:").append(from).append("@").append(transport.getHost() + ":" + transport.getPort());
buffer.append("sip:").append(request.from()).append("@").append(externalIP + ":" + transport.getPort());
final String sender = buffer.toString();
buffer = new StringBuilder();
if (toClientRegistration != null) {
buffer.append(toClientRegistration.getLocation());
} else {
final String service = smsConfiguration.getString("outbound-endpoint");
if (service == null) {
return;
}
buffer.append("sip:");
final String prefix = smsConfiguration.getString("outbound-prefix");
if (prefix != null) {
buffer.append(prefix);
}
buffer.append(request.to()).append("@").append(service);
}
final String recipient = buffer.toString();
try {
application.setAttribute(SmsSession.class.getName(), self());
if (request.getOrigRequest() != null) {
application.setAttribute(SipServletRequest.class.getName(), request.getOrigRequest());
}
final SipServletRequest sms = factory.createRequest(application, "MESSAGE", sender, recipient);
final SipURI uri = (SipURI) factory.createURI(recipient);
sms.pushRoute(uri);
sms.setRequestURI(uri);
sms.setContent(request.body(), "text/plain");
final SipSession session = sms.getSession();
session.setHandler("SmsService");
Map<String, String> headers = request.headers();
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
sms.setHeader(header.getKey(), header.getValue());
}
}
sms.send();
} catch (final Exception exception) {
// Notify the observers.
SmsSessionInfo info = info();
Object record = info.attributes().get(SMS_RECORD);
if (record != null) {
SmsMessage toBeUpdated = ((SmsMessage)record);
SmsMessage.Builder builder = SmsMessage.builder();
builder.copyMessage(toBeUpdated);
builder.setStatus(SmsMessage.Status.FAILED);
this.attributes.put(SMS_RECORD, builder.build());
info = info();
}
final SmsSessionResponse error = new SmsSessionResponse(info, false);
for (final ActorRef observer : observers) {
observer.tell(error, self());
}
// Log the exception.
logger.error(exception.getMessage(), exception);
}
}
private void stopObserving(final Object message) {
final StopObserving request = (StopObserving) message;
final ActorRef observer = request.observer();
if (observer != null) {
observers.remove(observer);
}
}
}
| 19,481 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsStatusNotifier.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/SmsStatusNotifier.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.restcomm.connect.dao.entities.SmsMessage;
public class SmsStatusNotifier {
private static final String MSG_STATUS_PARAM = "MessageStatus";
private static final String MSG_ID_PARAM = "MessageSid";
private static final String ERROR_CODE_PARAM = "ErrorCode";
private static final String ACCOUT_SID_PARAM = "AccountSid";
private static final String FROM_PARAM = "From";
private static final String TO_PARAM = "To";
private static final String BODY_PARAM = "Body";
static List<NameValuePair> populateReqParams(SmsMessage message) {
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair(FROM_PARAM, message.getSender()));
parameters.add(new BasicNameValuePair(TO_PARAM, message.getRecipient()));
parameters.add(new BasicNameValuePair(BODY_PARAM, message.getBody()));
parameters.add(new BasicNameValuePair(ACCOUT_SID_PARAM, message.getAccountSid().toString()));
if (message.getError() != null ) {
parameters.add(new BasicNameValuePair(ERROR_CODE_PARAM, message.getError().toString()));
}
parameters.add(new BasicNameValuePair(MSG_ID_PARAM, message.getSid().toString()));
parameters.add(new BasicNameValuePair(MSG_STATUS_PARAM, message.getStatus().toString()));
parameters.add(new BasicNameValuePair(BODY_PARAM, message.getBody()));
return parameters;
}
}
| 2,421 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsServiceException.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/SmsServiceException.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class SmsServiceException extends Exception {
private static final long serialVersionUID = 1L;
public SmsServiceException() {
super();
}
public SmsServiceException(final String message) {
super(message);
}
public SmsServiceException(final Throwable cause) {
super(cause);
}
public SmsServiceException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,369 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsServiceProxy.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/SmsServiceProxy.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.sms.smpp.SmppMessageHandler;
import org.restcomm.connect.sms.smpp.SmppService;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletContextEvent;
import javax.servlet.sip.SipServletListener;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import java.io.IOException;
/**
* @author [email protected] (Thomas Quintana)
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
public final class SmsServiceProxy extends SipServlet implements SipServletListener {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(SmsServiceProxy.class);
private ActorSystem system;
private ActorRef service;
private ActorRef smppService;
private ActorRef smppMessageHandler;
private ServletContext context;
public SmsServiceProxy() {
super();
}
@Override
protected void doRequest(final SipServletRequest request) throws ServletException, IOException {
service.tell(request, null);
}
@Override
protected void doResponse(final SipServletResponse response) throws ServletException, IOException {
service.tell(response, null);
}
private ActorRef service(final Configuration configuration, final SipFactory factory, final DaoManager storage) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new SmsService(configuration, factory, storage, context);
}
});
return system.actorOf(props);
}
private ActorRef smppService(final Configuration configuration, final SipFactory factory, final DaoManager storage,
final ServletContext context, final ActorRef smppMessageHandler) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new SmppService(configuration, factory, storage, context, smppMessageHandler);
}
});
return system.actorOf(props);
}
private ActorRef smppMessageHandler () {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new SmppMessageHandler(context);
}
});
return system.actorOf(props);
}
@Override
public void servletInitialized(SipServletContextEvent event) {
if (event.getSipServlet().getClass().equals(SmsServiceProxy.class)) {
context = event.getServletContext();
final SipFactory factory = (SipFactory) context.getAttribute(SIP_FACTORY);
Configuration configuration = (Configuration) context.getAttribute(Configuration.class.getName());
final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName());
system = (ActorSystem) context.getAttribute(ActorSystem.class.getName());
service = service(configuration, factory, storage);
context.setAttribute(SmsService.class.getName(), service);
if (configuration.subset("smpp").getString("[@activateSmppConnection]", "false").equalsIgnoreCase("true")) {
if(logger.isInfoEnabled()) {
logger.info("Will initialize SMPP");
}
smppMessageHandler = smppMessageHandler();
smppService = smppService(configuration,factory,storage,context, smppMessageHandler);
context.setAttribute(SmppService.class.getName(), smppService);
context.setAttribute(SmppMessageHandler.class.getName(), smppMessageHandler);
}
}
}
}
| 5,292 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsService.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/SmsService.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms;
import static javax.servlet.sip.SipServletResponse.SC_FORBIDDEN;
import static javax.servlet.sip.SipServletResponse.SC_NOT_FOUND;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Currency;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipURI;
import org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.push.PushNotificationServerHelper;
import org.restcomm.connect.core.service.RestcommConnectServiceProvider;
import org.restcomm.connect.core.service.util.UriUtils;
import org.restcomm.connect.core.service.api.NumberSelectorService;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.ApplicationsDao;
import org.restcomm.connect.dao.ClientsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.SmsMessagesDao;
import org.restcomm.connect.dao.common.OrganizationUtil;
import org.restcomm.connect.dao.entities.Account;
import org.restcomm.connect.dao.entities.Application;
import org.restcomm.connect.dao.entities.Client;
import org.restcomm.connect.dao.entities.IncomingPhoneNumber;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.dao.entities.SmsMessage.Direction;
import org.restcomm.connect.dao.entities.SmsMessage.Status;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionCreateSmsSessionRequest;
import org.restcomm.connect.extension.api.IExtensionFeatureAccessRequest;
import org.restcomm.connect.extension.api.RestcommExtensionException;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
import org.restcomm.connect.extension.controller.ExtensionController;
import org.restcomm.connect.http.client.rcmlserver.resolver.RcmlserverResolver;
import org.restcomm.connect.interpreter.SIPOrganizationUtil;
import org.restcomm.connect.interpreter.SmsInterpreter;
import org.restcomm.connect.interpreter.SmsInterpreterParams;
import org.restcomm.connect.interpreter.StartInterpreter;
import org.restcomm.connect.monitoringservice.MonitoringService;
import org.restcomm.connect.sms.api.CreateSmsSession;
import org.restcomm.connect.sms.api.DestroySmsSession;
import org.restcomm.connect.sms.api.SmsServiceResponse;
import org.restcomm.connect.sms.api.SmsSessionAttribute;
import org.restcomm.connect.sms.api.SmsSessionRequest;
import org.restcomm.connect.telephony.api.FeatureAccessRequest;
import org.restcomm.connect.telephony.api.TextMessage;
import org.restcomm.connect.telephony.api.util.B2BUAHelper;
import org.restcomm.connect.telephony.api.util.CallControlHelper;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorContext;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.apache.http.NameValuePair;
import org.restcomm.connect.http.client.Downloader;
import org.restcomm.connect.http.client.HttpRequestDescriptor;
import static org.restcomm.connect.sms.SmsStatusNotifier.populateReqParams;
import org.restcomm.connect.sms.api.SmsStatusUpdated;
import scala.concurrent.duration.Duration;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected]
* @author [email protected] (Maria Farooq)
*/
public final class SmsService extends RestcommUntypedActor {
private static final String RECORD_ATT="record";
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
static final int ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE = SC_FORBIDDEN;
private final ActorSystem system;
private final Configuration configuration;
private boolean authenticateUsers = true;
private final ServletConfig servletConfig;
private final SipFactory sipFactory;
private final DaoManager storage;
private final ServletContext servletContext;
static final int ERROR_NOTIFICATION = 0;
static final int WARNING_NOTIFICATION = 1;
private final ActorRef monitoringService;
// Push notification server
private final PushNotificationServerHelper pushNotificationServerHelper;
// configurable switch whether to use the To field in a SIP header to determine the callee address
// alternatively the Request URI can be used
private boolean useTo = true;
//Control whether Restcomm will patch SDP for B2BUA calls
private boolean patchForNatB2BUASessions;
//List of extensions for SmsService
List<RestcommExtensionGeneric> extensions;
private final NumberSelectorService numberSelector;
private UriUtils uriUtils;
public SmsService(final Configuration configuration, final SipFactory factory,
final DaoManager storage, final ServletContext servletContext) {
super();
this.system = context().system();
this.configuration = configuration;
final Configuration runtime = configuration.subset("runtime-settings");
this.authenticateUsers = runtime.getBoolean("authenticate");
this.servletConfig = (ServletConfig) configuration.getProperty(ServletConfig.class.getName());
this.sipFactory = factory;
this.storage = storage;
this.servletContext = servletContext;
monitoringService = (ActorRef) servletContext.getAttribute(MonitoringService.class.getName());
numberSelector = (NumberSelectorService) servletContext.getAttribute(NumberSelectorService.class.getName());
this.pushNotificationServerHelper = new PushNotificationServerHelper(system, configuration);
// final Configuration runtime = configuration.subset("runtime-settings");
// TODO this.useTo = runtime.getBoolean("use-to");
patchForNatB2BUASessions = runtime.getBoolean("patch-for-nat-b2bua-sessions", true);
boolean useSbc = runtime.getBoolean("use-sbc", false);
if (useSbc) {
if (logger.isDebugEnabled()) {
logger.debug("SmsService: use-sbc is true, overriding patch-for-nat-b2bua-sessions to false");
}
patchForNatB2BUASessions = false;
}
extensions = ExtensionController.getInstance().getExtensions(ExtensionType.SmsService);
if (logger.isInfoEnabled()) {
logger.info("SmsService extensions: " + (extensions != null ? extensions.size() : "0"));
}
this.uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils();
}
private void message(final Object message) throws IOException {
final ActorRef self = self();
final SipServletRequest request = (SipServletRequest) message;
// ignore composing messages and accept content type including text only
// https://github.com/Mobicents/RestComm/issues/494
if (request.getContentLength() == 0 || !request.getContentType().contains("text/plain")) {
SipServletResponse reject = request.createResponse(SipServletResponse.SC_NOT_ACCEPTABLE);
reject.addHeader("Reason", "Content Type is not text plain");
reject.send();
return;
}
final SipURI fromURI = (SipURI) request.getFrom().getURI();
final String fromUser = fromURI.getUser();
final ClientsDao clients = storage.getClientsDao();
final SipURI ruri = (SipURI) request.getRequestURI();
final String to = ruri.getUser();
Sid destinationOrganizationSid = SIPOrganizationUtil.searchOrganizationBySIPRequest(storage.getOrganizationsDao(), request);
final Sid sourceOrganizationSid = OrganizationUtil.getOrganizationSidBySipURIHost(storage, fromURI);
if (logger.isDebugEnabled()) {
logger.debug("sourceOrganizationSid: " + sourceOrganizationSid);
logger.debug("destinationOrganizationSid: " + destinationOrganizationSid);
}
if (sourceOrganizationSid == null) {
logger.error("Null Organization: fromUri: " + fromURI);
}
final Client client = clients.getClient(fromUser, sourceOrganizationSid);
final String toUser = CallControlHelper.getUserSipId(request, useTo);
final Client toClient = clients.getClient(toUser, destinationOrganizationSid);
final AccountsDao accounts = storage.getAccountsDao();
final ApplicationsDao applications = storage.getApplicationsDao();
IncomingPhoneNumber number = getIncomingPhoneNumber(to, sourceOrganizationSid, destinationOrganizationSid);
if (number != null) {
Account numAccount = accounts.getAccount(number.getAccountSid());
if (!numAccount.getStatus().equals(Account.Status.ACTIVE)) {
//reject SMS since the Number belongs to an an account which is not ACTIVE
final SipServletResponse response = request.createResponse(ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE, "Account is not ACTIVE");
response.send();
String msg = String.format("Restcomm rejects this SMS because number's %s account %s is not ACTIVE, current state %s", number.getPhoneNumber(), numAccount.getSid(), numAccount.getStatus());
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
sendNotification(msg, 11005, "error", true);
return;
}
}
// Make sure we force clients to authenticate.
if (client != null) {
Account clientAccount = accounts.getAccount(client.getAccountSid());
if (!clientAccount.getStatus().equals(Account.Status.ACTIVE)) {
//reject SMS since the Number belongs to an an account which is not ACTIVE
final SipServletResponse response = request.createResponse(ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE, "Account is not ACTIVE");
response.send();
String msg = String.format("Restcomm rejects this SMS because client's %s account %s is not ACTIVE, current state %s", client.getFriendlyName(), clientAccount.getSid(), clientAccount.getStatus());
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
sendNotification(msg, 11005, "error", true);
return;
}
// Make sure we force clients to authenticate.
if (authenticateUsers // https://github.com/Mobicents/RestComm/issues/29 Allow disabling of SIP authentication
&& !CallControlHelper.checkAuthentication(request, storage, sourceOrganizationSid)) {
if (logger.isInfoEnabled()) {
logger.info("Client " + client.getLogin() + " failed to authenticate");
}
// Since the client failed to authenticate, we will ignore the message and not process further
return;
}
}
if (toClient != null) {
Account toAccount = accounts.getAccount(toClient.getAccountSid());
if (!toAccount.getStatus().equals(Account.Status.ACTIVE)) {
//reject SMS since the Number belongs to an an account which is not ACTIVE
final SipServletResponse response = request.createResponse(ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE, "Account is not ACTIVE");
response.send();
String msg = String.format("Restcomm rejects this SMS because client's %s account %s is not ACTIVE, current state %s", client.getFriendlyName(), toAccount.getSid(), toAccount.getStatus());
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
sendNotification(msg, 11005, "error", true);
return;
}
}
// Try to see if the request is destined for an application we are hosting.
if (redirectToHostedSmsApp(request, applications, number)) {
// Tell the sender we received the message okay.
if (logger.isInfoEnabled()) {
logger.info("Message to :" + toUser + " matched to one of the hosted applications");
}
//this is used to send a reply back to SIP client when a Restcomm App forwards inbound sms to a Restcomm client ex. Alice
final SipServletResponse messageAccepted = request.createResponse(SipServletResponse.SC_ACCEPTED);
messageAccepted.send();
monitoringService.tell(new TextMessage(((SipURI) request.getFrom().getURI()).getUser(), ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.INBOUND_TO_APP), self);
return;
}
if (client != null) {
// try to see if the request is destined to another registered client
// if (client != null) { // make sure the caller is a registered client and not some external SIP agent that we
// have little control over
if (toClient != null) { // looks like its a p2p attempt between two valid registered clients, lets redirect
long delay = pushNotificationServerHelper.sendPushNotificationIfNeeded(toClient.getPushClientIdentity());
// workaround for only clients with push_client_identity after long discussion about current SIP Message flow processing
// https://telestax.atlassian.net/browse/RESTCOMM-1159
if (delay > 0) {
final SipServletResponse trying = request.createResponse(SipServletResponse.SC_TRYING);
trying.send();
}
system.scheduler().scheduleOnce(Duration.create(delay, TimeUnit.MILLISECONDS), new Runnable() {
@Override
public void run() {
try {
// to the b2bua
if (B2BUAHelper.redirectToB2BUA(system, request, client, toClient, storage, sipFactory, patchForNatB2BUASessions)) {
// if all goes well with proxying the SIP MESSAGE on to the target client
// then we can end further processing of this request and send response to sender
if (logger.isInfoEnabled()) {
logger.info("P2P, Message from: " + client.getLogin() + " redirected to registered client: "
+ toClient.getLogin());
}
monitoringService.tell(new TextMessage(((SipURI) request.getFrom().getURI()).getUser(), ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.INBOUND_TO_CLIENT), self);
return;
} else {
String errMsg = "Cannot Connect to Client: " + toClient.getFriendlyName()
+ " : Make sure the Client exist or is registered with Restcomm";
sendNotification(errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_NOT_FOUND, "Cannot complete P2P messages");
resp.send();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, system.dispatcher());
} else {
// Since toUser is null, try to route the message outside using the SMS Aggregator
if (logger.isInfoEnabled()) {
logger.info("Restcomm will route this SMS to an external aggregator: " + client.getLogin() + " to: " + toUser);
}
ExtensionController ec = ExtensionController.getInstance();
final IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.OUTBOUND_SMS, client.getAccountSid());
ExtensionResponse er = ec.executePreOutboundAction(far, this.extensions);
if (er.isAllowed()) {
final SipServletResponse trying = request.createResponse(SipServletResponse.SC_TRYING);
trying.send();
//TODO:do extensions check here too?
ActorRef session = session(this.configuration, sourceOrganizationSid);
// Create an SMS detail record.
final Sid sid = Sid.generate(Sid.Type.SMS_MESSAGE);
final SmsMessage.Builder builder = SmsMessage.builder();
builder.setSid(sid);
builder.setAccountSid(client.getAccountSid());
builder.setApiVersion(client.getApiVersion());
builder.setRecipient(toUser);
builder.setSender(client.getLogin());
builder.setBody(new String(request.getRawContent()));
builder.setDirection(Direction.OUTBOUND_CALL);
builder.setStatus(Status.SENDING);
builder.setPrice(new BigDecimal("0.00"));
// TODO implement currency property to be read from Configuration
builder.setPriceUnit(Currency.getInstance("USD"));
final StringBuilder buffer = new StringBuilder();
buffer.append("/").append(client.getApiVersion()).append("/Accounts/");
buffer.append(client.getAccountSid().toString()).append("/SMS/Messages/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
final SmsMessage record = builder.build();
final SmsMessagesDao messages = storage.getSmsMessagesDao();
messages.addSmsMessage(record);
// Store the sms record in the sms session.
session.tell(new SmsSessionAttribute("record", record), self());
// Send the SMS.
final SmsSessionRequest sms = new SmsSessionRequest(client.getLogin(), toUser, new String(request.getRawContent()), request, null);
monitoringService.tell(new TextMessage(((SipURI) request.getFrom().getURI()).getUser(), ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.INBOUND_TO_PROXY_OUT), self);
session.tell(sms, self());
} else {
if (logger.isDebugEnabled()) {
final String errMsg = "Outbound SMS from Client " + client.getFriendlyName() + " not Allowed";
logger.debug(errMsg);
}
String errMsg = "Outbound SMS from Client: " + client.getFriendlyName()
+ " is not Allowed";
sendNotification(errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_FORBIDDEN, "Call not allowed");
resp.send();
}
ec.executePostOutboundAction(far, extensions);
}
} else {
final SipServletResponse response = request.createResponse(SC_NOT_FOUND);
response.send();
// We didn't find anyway to handle the SMS.
String errMsg = "Restcomm cannot process this SMS because the destination number is not hosted locally. To: " + toUser;
sendNotification(errMsg, 11005, "error", true);
monitoringService.tell(new TextMessage(((SipURI) request.getFrom().getURI()).getUser(), ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.NOT_FOUND), self);
}
}
private IncomingPhoneNumber getIncomingPhoneNumber(String phone, Sid sourceOrganizationSid, Sid destinationOrganization) {
IncomingPhoneNumber number = numberSelector.searchNumber(phone, sourceOrganizationSid, destinationOrganization);
return number;
}
/**
*
* Try to locate a hosted sms app corresponding to the callee/To address. If
* one is found, begin execution, otherwise return false;
*
* @param request
* @param applications
* @param number
*/
private boolean redirectToHostedSmsApp(final SipServletRequest request,
final ApplicationsDao applications, IncomingPhoneNumber number) {
boolean isFoundHostedApp = false;
// Handle the SMS message.
// final SipURI uri = (SipURI) request.getRequestURI();
// final String to = uri.getUser();
// Sid destOrg = SIPOrganizationUtil.searchOrganizationBySIPRequest(storage.getOrganizationsDao(), request);
// IncomingPhoneNumber number = numberSelector.searchNumber(to, sourceOrganizationSid, destOrg);
try {
if (number != null) {
ExtensionController ec = ExtensionController.getInstance();
IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.INBOUND_SMS, number.getAccountSid());
ExtensionResponse er = ec.executePreInboundAction(far, extensions);
if (er.isAllowed()) {
URI appUri = number.getSmsUrl();
ActorRef interpreter = null;
if (appUri != null || number.getSmsApplicationSid() != null) {
final SmsInterpreterParams.Builder builder = new SmsInterpreterParams.Builder();
builder.setSmsService(self());
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setAccountId(number.getAccountSid());
builder.setVersion(number.getApiVersion());
final Sid sid = number.getSmsApplicationSid();
if (sid != null) {
final Application application = applications.getApplication(sid);
RcmlserverConfigurationSet rcmlserverConfig = RestcommConfiguration.getInstance().getRcmlserver();
RcmlserverResolver resolver = RcmlserverResolver.getInstance(rcmlserverConfig.getBaseUrl(), rcmlserverConfig.getApiPath());
builder.setUrl(uriUtils.resolve(resolver.resolveRelative(application.getRcmlUrl()), number.getAccountSid()));
} else {
builder.setUrl(uriUtils.resolve(appUri, number.getAccountSid()));
}
final String smsMethod = number.getSmsMethod();
if (smsMethod == null || smsMethod.isEmpty()) {
builder.setMethod("POST");
} else {
builder.setMethod(smsMethod);
}
URI appFallbackUrl = number.getSmsFallbackUrl();
if (appFallbackUrl != null) {
builder.setFallbackUrl(uriUtils.resolve(number.getSmsFallbackUrl(), number.getAccountSid()));
builder.setFallbackMethod(number.getSmsFallbackMethod());
}
final Props props = SmsInterpreter.props(builder.build());
interpreter = getContext().actorOf(props);
}
Sid organizationSid = storage.getOrganizationsDao().getOrganization(storage.getAccountsDao().getAccount(number.getAccountSid()).getOrganizationSid()).getSid();
if (logger.isDebugEnabled()) {
logger.debug("redirectToHostedSmsApp organizationSid = " + organizationSid);
}
//TODO:do extensions check here too?
final ActorRef session = session(this.configuration, organizationSid);
session.tell(request, self());
final StartInterpreter start = new StartInterpreter(session);
interpreter.tell(start, self());
isFoundHostedApp = true;
ec.executePostInboundAction(far, extensions);
} else {
if (logger.isDebugEnabled()) {
final String errMsg = "Inbound SMS is not Allowed";
logger.debug(errMsg);
}
String errMsg = "Inbound SMS to Number: " + number.getPhoneNumber()
+ " is not allowed";
sendNotification(errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_FORBIDDEN, "SMS not allowed");
resp.send();
ec.executePostInboundAction(far, extensions);
return false;
}
}
} catch (Exception e) {
String msg = String.format("There is no valid Restcomm SMS Request URL configured for this number : %s", ((SipURI) request.getRequestURI()).getUser());
sendNotification(msg, 12003, "warning", true);
}
return isFoundHostedApp;
}
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
if (logger.isDebugEnabled()) {
logger.debug(" ********** Onreceive: " + self().path() + ", Processing Message: " + klass.getName()
+ " Sender is: " + sender().path() + " Message is: " + message);
}
if (CreateSmsSession.class.equals(klass)) {
onCreateSession(message);
} else if (DestroySmsSession.class.equals(klass)) {
onDestroySession(message);
} else if (message instanceof SipServletRequest) {
onServletRequest(message);
} else if (message instanceof SipServletResponse) {
onServletResponse(message);
} else if (message instanceof SmsStatusUpdated) {
onStatusUpdated((SmsStatusUpdated) message);
}
}
private void onServletResponse(Object message) throws Exception {
final SipServletResponse response = (SipServletResponse) message;
final SipServletRequest request = response.getRequest();
final String method = request.getMethod();
if ("MESSAGE".equalsIgnoreCase(method)) {
response(message);
}
}
private void onServletRequest(Object message) throws IOException {
final SipServletRequest request = (SipServletRequest) message;
final String method = request.getMethod();
if ("MESSAGE".equalsIgnoreCase(method)) {
message(message);
}
}
private void onDestroySession(Object message) {
final UntypedActorContext context = getContext();
final DestroySmsSession request = (DestroySmsSession) message;
final ActorRef session = request.session();
context.stop(session);
}
private void onCreateSession(Object message) {
ExtensionController ec = ExtensionController.getInstance();
final ActorRef self = self();
final ActorRef sender = sender();
IExtensionCreateSmsSessionRequest ier = (CreateSmsSession) message;
ier.setConfiguration(this.configuration);
ExtensionResponse executePreOutboundAction = ec.executePreOutboundAction(ier, this.extensions);
if (executePreOutboundAction.isAllowed()) {
CreateSmsSession createSmsSession = (CreateSmsSession) message;
final ActorRef session = session(ier.getConfiguration(), OrganizationUtil.getOrganizationSidByAccountSid(storage, new Sid(createSmsSession.getAccountSid())));
final SmsServiceResponse<ActorRef> response = new SmsServiceResponse<ActorRef>(session);
sender.tell(response, self);
} else {
final SmsServiceResponse<ActorRef> response = new SmsServiceResponse(new RestcommExtensionException("Now allowed to create SmsSession"));
sender.tell(response, self());
}
ec.executePostOutboundAction(ier, this.extensions);
}
private void response(final Object message) throws Exception {
final ActorRef self = self();
final SipServletResponse response = (SipServletResponse) message;
// https://bitbucket.org/telestax/telscale-restcomm/issue/144/send-p2p-chat-works-but-gives-npe
if (B2BUAHelper.isB2BUASession(response)) {
B2BUAHelper.forwardResponse(system, response, patchForNatB2BUASessions);
return;
}
final SipApplicationSession application = response.getApplicationSession();
//handle SIP application session and make sure it has not being invalidated
if (logger.isInfoEnabled()) {
logger.info("Is SipApplicationSession valid: " + application.isValid());
}
if (application != null) {
final ActorRef session = (ActorRef) application.getAttribute(SmsSession.class.getName());
//P2P messaging doesnt include session, check if necessary
if (session != null) {
session.tell(response, self);
}
final SipServletRequest origRequest = (SipServletRequest) application.getAttribute(SipServletRequest.class.getName());
if (origRequest != null && origRequest.getSession().isValid()) {
SipServletResponse responseToOriginator = origRequest.createResponse(response.getStatus(), response.getReasonPhrase());
responseToOriginator.send();
}
}
}
@SuppressWarnings("unchecked")
private SipURI outboundInterface() {
SipURI result = null;
final List<SipURI> uris = (List<SipURI>) servletContext.getAttribute(SipServlet.OUTBOUND_INTERFACES);
for (final SipURI uri : uris) {
final String transport = uri.getTransportParam();
if ("udp".equalsIgnoreCase(transport)) {
result = uri;
}
}
return result;
}
private ActorRef session(final Configuration p_configuration, final Sid organizationSid) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new SmsSession(p_configuration, sipFactory, outboundInterface(), storage, monitoringService, servletContext, organizationSid);
}
});
return getContext().actorOf(props);
}
// used for sending warning and error logs to notification engine and to the console
private void sendNotification(String errMessage, int errCode, String errType, boolean createNotification) {
NotificationsDao notifications = storage.getNotificationsDao();
Notification notification;
if (errType == "warning") {
logger.warning(errMessage); // send message to console
if (createNotification) {
notification = notification(WARNING_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "error") {
logger.error(errMessage); // send message to console
if (createNotification) {
notification = notification(ERROR_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "info") {
if (logger.isInfoEnabled()) {
logger.info(errMessage); // send message to console
}
}
}
private Notification notification(final int log, final int error, final String message) {
String version = configuration.subset("runtime-settings").getString("api-version");
Sid accountId = new Sid("ACae6e420f425248d6a26948c17a9e2acf");
// Sid callSid = new Sid("CA00000000000000000000000000000000");
final Notification.Builder builder = Notification.builder();
final Sid sid = Sid.generate(Sid.Type.NOTIFICATION);
builder.setSid(sid);
// builder.setAccountSid(accountId);
builder.setAccountSid(accountId);
// builder.setCallSid(callSid);
builder.setApiVersion(version);
builder.setLog(log);
builder.setErrorCode(error);
final String base = configuration.subset("runtime-settings").getString("error-dictionary-uri");
StringBuilder buffer = new StringBuilder();
buffer.append(base);
if (!base.endsWith("/")) {
buffer.append("/");
}
buffer.append(error).append(".html");
final URI info = URI.create(buffer.toString());
builder.setMoreInfo(info);
builder.setMessageText(message);
final DateTime now = DateTime.now();
builder.setMessageDate(now);
try {
builder.setRequestUrl(new URI(""));
} catch (URISyntaxException e) {
e.printStackTrace();
}
/**
* if (response != null) { builder.setRequestUrl(request.getUri());
* builder.setRequestMethod(request.getMethod());
* builder.setRequestVariables(request.getParametersAsString()); }
*
*/
builder.setRequestMethod("");
builder.setRequestVariables("");
buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Notifications/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
return builder.build();
}
private void onStatusUpdated(SmsStatusUpdated event) {
SmsMessage msg = (SmsMessage) event.getInfo().attributes().get(RECORD_ATT);
storage.getSmsMessagesDao().updateSmsMessage(msg);
notifyStatus(msg);
}
// The storage engine.
private void notifyStatus(SmsMessage message) {
URI callback = message.getStatusCallback();
if (callback != null) {
String method = message.getStatusCallbackMethod();
if (method != null && !method.isEmpty()) {
if (!org.apache.http.client.methods.HttpGet.METHOD_NAME.equalsIgnoreCase(method)
&& !org.apache.http.client.methods.HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
final Notification notification = notification(WARNING_NOTIFICATION, 14104, method
+ " is not a valid HTTP method for <Sms>");
storage.getNotificationsDao().addNotification(notification);
method = org.apache.http.client.methods.HttpPost.METHOD_NAME;
}
} else {
method = org.apache.http.client.methods.HttpPost.METHOD_NAME;
}
List<NameValuePair> parameters = populateReqParams(message);
HttpRequestDescriptor request = new HttpRequestDescriptor(callback, method, parameters);
downloader().tell(request, self());
}
}
protected ActorRef downloader() {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Downloader();
}
});
return getContext().actorOf(props);
}
}
| 37,434 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsSessionException.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/SmsSessionException.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class SmsSessionException extends Exception {
private static final long serialVersionUID = 1L;
public SmsSessionException(final String message) {
super(message);
}
public SmsSessionException(final Throwable cause) {
super(cause);
}
public SmsSessionException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,310 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmppInboundMessageEntity.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/SmppInboundMessageEntity.java | package org.restcomm.connect.sms.smpp;
import org.restcomm.smpp.parameter.TlvSet;
import com.cloudhopper.commons.charset.Charset;
public class SmppInboundMessageEntity {
private final String smppTo;
private final String smppFrom;
private final String smppContent;
private final Charset smppEncoding;
private final TlvSet tlvSet;
private final boolean isDeliveryReceipt;
public SmppInboundMessageEntity(String smppTo, String smppFrom, String smppContent, Charset smppEncoding){
this(smppTo, smppFrom, smppContent, smppEncoding, null, false);
}
public SmppInboundMessageEntity(String smppTo, String smppFrom, String smppContent, Charset smppEncoding,
boolean isDeliveryReceipt) {
this(smppTo, smppFrom, smppContent, smppEncoding, null, isDeliveryReceipt);
}
public SmppInboundMessageEntity(String smppTo, String smppFrom, String smppContent, Charset smppEncoding, TlvSet tlvSet){
this(smppTo, smppFrom, smppContent, smppEncoding, tlvSet, false);
}
public SmppInboundMessageEntity(String smppTo, String smppFrom, String smppContent, Charset smppEncoding, TlvSet tlvSet,
boolean isDeliveryReceipt) {
this.smppTo = smppTo;
this.smppFrom = smppFrom;
this.smppContent = smppContent;
this.smppEncoding = smppEncoding;
this.tlvSet = tlvSet;
this.isDeliveryReceipt = isDeliveryReceipt;
}
public final TlvSet getTlvSet(){
return tlvSet;
}
public final String getSmppTo(){
return smppTo;
}
public final String getSmppFrom(){
return smppFrom;
}
public final String getSmppContent(){
return smppContent;
}
public final Charset getSmppEncoding(){
return smppEncoding;
}
public final boolean getIsDeliveryReceipt() {
return isDeliveryReceipt;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SMPPInboundMessage[From=")
.append(smppFrom)
.append(",To")
.append(smppTo)
.append(",Content=")
.append(smppContent)
.append(",Encoding=")
.append(smppEncoding)
.append("isDeliveryReceipt=")
.append(isDeliveryReceipt);
return builder.toString();
}
}
| 2,388 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmppInterpreter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/SmppInterpreter.java | package org.restcomm.connect.sms.smpp;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorContext;
import akka.actor.UntypedActorFactory;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import org.apache.commons.configuration.Configuration;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.fsm.Action;
import org.restcomm.connect.commons.fsm.FiniteStateMachine;
import org.restcomm.connect.commons.fsm.State;
import org.restcomm.connect.commons.fsm.Transition;
import org.restcomm.connect.commons.patterns.Observe;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.SmsMessagesDao;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.dao.entities.SmsMessage.Direction;
import org.restcomm.connect.dao.entities.SmsMessage.Status;
import org.restcomm.connect.email.EmailService;
import org.restcomm.connect.email.api.EmailRequest;
import org.restcomm.connect.email.api.EmailResponse;
import org.restcomm.connect.email.api.Mail;
import org.restcomm.connect.http.client.Downloader;
import org.restcomm.connect.http.client.DownloaderResponse;
import org.restcomm.connect.http.client.HttpRequestDescriptor;
import org.restcomm.connect.http.client.HttpResponseDescriptor;
import org.restcomm.connect.interpreter.StartInterpreter;
import org.restcomm.connect.interpreter.StopInterpreter;
import org.restcomm.connect.interpreter.rcml.Attribute;
import org.restcomm.connect.interpreter.rcml.GetNextVerb;
import org.restcomm.connect.interpreter.rcml.Parser;
import org.restcomm.connect.interpreter.rcml.Tag;
import org.restcomm.connect.sms.api.CreateSmsSession;
import org.restcomm.connect.sms.api.DestroySmsSession;
import org.restcomm.connect.sms.api.GetLastSmsRequest;
import org.restcomm.connect.sms.api.SmsServiceResponse;
import org.restcomm.connect.sms.api.SmsSessionAttribute;
import org.restcomm.connect.sms.api.SmsSessionInfo;
import org.restcomm.connect.sms.api.SmsSessionRequest;
import org.restcomm.connect.sms.api.SmsSessionResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Currency;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.restcomm.connect.interpreter.rcml.SmsVerb;
import static org.restcomm.connect.interpreter.rcml.Verbs.*;
public class SmppInterpreter extends RestcommUntypedActor {
private static final int ERROR_NOTIFICATION = 0;
private static final int WARNING_NOTIFICATION = 1;
static String EMAIL_SENDER;
// Logger
private static final Logger logger = Logger.getLogger(SmppInterpreter.class);
// private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// States for the FSM.
private final State uninitialized;
private final State acquiringLastSmsRequest;
private final State downloadingRcml;
private final State downloadingFallbackRcml;
private final State ready;
private final State redirecting;
private final State creatingSmsSession;
private final State sendingEmail;
private final State sendingSms;
private final State waitingForSmsResponses;
private final State finished;
// FSM.
private final FiniteStateMachine fsm;
// SMS Stuff.
private final ActorRef smsService;
private final Map<Sid, ActorRef> sessions;
private Sid initialSessionSid;
private ActorRef initialSession;
private ActorRef mailerService;
private SmsSessionRequest initialSessionRequest;
// HTTP Stuff.
private final ActorRef downloader;
// The storage engine.
private final DaoManager storage;
//Runtime configuration
private final Configuration runtime;
// User specific configuration.
private final Configuration configuration;
//Email configuration
private final Configuration emailconfiguration;
// Information to reach the application that will be executed
// by this interpreter.
private final Sid accountId;
private final String version;
private final URI url;
private final String method;
private final URI fallbackUrl;
private final String fallbackMethod;
// application data.
private HttpRequestDescriptor request;
private HttpResponseDescriptor response;
// The RCML parser.
private ActorRef parser;
private Tag verb;
private boolean normalizeNumber;
private ConcurrentHashMap<String, String> customHttpHeaderMap = new ConcurrentHashMap<String, String>();
private ConcurrentHashMap<String, String> customRequestHeaderMap;
public SmppInterpreter(final SmppInterpreterParams params) {
super();
final ActorRef source = self();
uninitialized = new State("uninitialized", null, null);
acquiringLastSmsRequest = new State("acquiring last sms event", new AcquiringLastSmsEvent(source), null);
downloadingRcml = new State("downloading rcml", new DownloadingRcml(source), null);
downloadingFallbackRcml = new State("downloading fallback rcml", new DownloadingFallbackRcml(source), null);
ready = new State("ready", new Ready(source), null);
redirecting = new State("redirecting", new Redirecting(source), null);
creatingSmsSession = new State("creating sms session", new CreatingSmsSession(source), null);
sendingSms = new State("sending sms", new SendingSms(source), null);
waitingForSmsResponses = new State("waiting for sms responses", new WaitingForSmsResponses(source), null);
sendingEmail = new State("sending Email", new SendingEmail(source), null);
finished = new State("finished", new Finished(source), null);
// Initialize the transitions for the FSM.
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(uninitialized, acquiringLastSmsRequest));
transitions.add(new Transition(acquiringLastSmsRequest, downloadingRcml));
transitions.add(new Transition(acquiringLastSmsRequest, finished));
transitions.add(new Transition(acquiringLastSmsRequest, sendingEmail));
transitions.add(new Transition(downloadingRcml, ready));
transitions.add(new Transition(downloadingRcml, downloadingFallbackRcml));
transitions.add(new Transition(downloadingRcml, finished));
transitions.add(new Transition(downloadingRcml, sendingEmail));
transitions.add(new Transition(downloadingFallbackRcml, ready));
transitions.add(new Transition(downloadingFallbackRcml, finished));
transitions.add(new Transition(downloadingFallbackRcml, sendingEmail));
transitions.add(new Transition(ready, redirecting));
transitions.add(new Transition(ready, creatingSmsSession));
transitions.add(new Transition(ready, waitingForSmsResponses));
transitions.add(new Transition(ready, sendingEmail));
transitions.add(new Transition(ready, finished));
transitions.add(new Transition(redirecting, ready));
transitions.add(new Transition(redirecting, creatingSmsSession));
transitions.add(new Transition(redirecting, finished));
transitions.add(new Transition(redirecting, sendingEmail));
transitions.add(new Transition(redirecting, waitingForSmsResponses));
transitions.add(new Transition(creatingSmsSession, sendingSms));
transitions.add(new Transition(creatingSmsSession, waitingForSmsResponses));
transitions.add(new Transition(creatingSmsSession, sendingEmail));
transitions.add(new Transition(creatingSmsSession, finished));
transitions.add(new Transition(sendingSms, ready));
transitions.add(new Transition(sendingSms, redirecting));
transitions.add(new Transition(sendingSms, creatingSmsSession));
transitions.add(new Transition(sendingSms, waitingForSmsResponses));
transitions.add(new Transition(sendingSms, sendingEmail));
transitions.add(new Transition(sendingSms, finished));
transitions.add(new Transition(waitingForSmsResponses, waitingForSmsResponses));
transitions.add(new Transition(waitingForSmsResponses, sendingEmail));
transitions.add(new Transition(waitingForSmsResponses, finished));
transitions.add(new Transition(sendingEmail, ready));
transitions.add(new Transition(sendingEmail, redirecting));
transitions.add(new Transition(sendingEmail, creatingSmsSession));
transitions.add(new Transition(sendingEmail, waitingForSmsResponses));
transitions.add(new Transition(sendingEmail, finished));
// Initialize the FSM.
this.fsm = new FiniteStateMachine(uninitialized, transitions);
// Initialize the runtime stuff.
this.smsService = params.getSmsService();
this.downloader = downloader();
this.storage = params.getStorage();
this.runtime = params.getConfiguration().subset("runtime-settings");
this.configuration = params.getConfiguration().subset("sms-aggregator");
this.emailconfiguration = params.getConfiguration().subset("smtp-service");
this.accountId = params.getAccountId();
this.version = params.getVersion();
this.url = params.getUrl();
this.method = params.getMethod();
this.fallbackUrl = params.getFallbackUrl();
this.fallbackMethod = params.getFallbackMethod();
this.sessions = new HashMap<Sid, ActorRef>();
this.normalizeNumber = runtime.getBoolean("normalize-numbers-for-outbound-calls");
}
public static Props props(final SmppInterpreterParams params) {
return new Props(new UntypedActorFactory() {
@Override
public Actor create() throws Exception {
return new SmppInterpreter(params);
}
});
}
private ActorRef downloader() {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Downloader();
}
});
return getContext().actorOf(props);
}
ActorRef mailer(final Configuration configuration) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public Actor create() throws Exception {
return new EmailService(configuration);
}
});
return getContext().actorOf(props);
}
protected String format(final String number) {
if(normalizeNumber) {
final PhoneNumberUtil numbersUtil = PhoneNumberUtil.getInstance();
try {
final PhoneNumber result = numbersUtil.parse(number, "US");
return numbersUtil.format(result, PhoneNumberFormat.E164);
} catch (final NumberParseException ignored) {
return null;
}
} else {
return number;
}
}
protected void invalidVerb(final Tag verb) {
final ActorRef self = self();
final Notification notification = notification(WARNING_NOTIFICATION, 14110, "Invalid Verb for SMS Reply");
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
// Get the next verb.
final GetNextVerb next = new GetNextVerb();
parser.tell(next, self);
}
protected Notification notification(final int log, final int error, final String message) {
final Notification.Builder builder = Notification.builder();
final Sid sid = Sid.generate(Sid.Type.NOTIFICATION);
builder.setSid(sid);
builder.setAccountSid(accountId);
builder.setApiVersion(version);
builder.setLog(log);
builder.setErrorCode(error);
final String base = runtime.getString("error-dictionary-uri");
StringBuilder buffer = new StringBuilder();
buffer.append(base);
if (!base.endsWith("/")) {
buffer.append("/");
}
buffer.append(error).append(".html");
final URI info = URI.create(buffer.toString());
builder.setMoreInfo(info);
builder.setMessageText(message);
final DateTime now = DateTime.now();
builder.setMessageDate(now);
if (request != null) {
builder.setRequestUrl(request.getUri());
builder.setRequestMethod(request.getMethod());
builder.setRequestVariables(request.getParametersAsString());
}
if (response != null) {
builder.setResponseHeaders(response.getHeadersAsString());
final String type = response.getContentType();
if (type != null && (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html"))) {
try {
builder.setResponseBody(response.getContentAsString());
} catch (final IOException exception) {
logger.error(
"There was an error while reading the contents of the resource " + "located @ " + url.toString(),
exception);
}
}
}
buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Notifications/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
return builder.build();
}
@SuppressWarnings("unchecked")
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
final State state = fsm.state();
if (StartInterpreter.class.equals(klass)) {
fsm.transition(message, acquiringLastSmsRequest);
} else if (SmsSessionRequest.class.equals(klass)) {
customRequestHeaderMap = ((SmsSessionRequest)message).headers();
if(!state.equals(sendingSms)){
fsm.transition(message, downloadingRcml);
}
} else if (DownloaderResponse.class.equals(klass)) {
final DownloaderResponse response = (DownloaderResponse) message;
if (response.succeeded()) {
final HttpResponseDescriptor descriptor = response.get();
if (HttpStatus.SC_OK == descriptor.getStatusCode()) {
fsm.transition(message, ready);
} else {
if (downloadingRcml.equals(state)) {
if (fallbackUrl != null) {
fsm.transition(message, downloadingFallbackRcml);
}
} else {
if (sessions.size() > 0) {
fsm.transition(message, waitingForSmsResponses);
} else {
fsm.transition(message, finished);
}
}
}
} else {
if (downloadingRcml.equals(state)) {
if (fallbackUrl != null) {
fsm.transition(message, downloadingFallbackRcml);
}
} else {
if (sessions.size() > 0) {
fsm.transition(message, waitingForSmsResponses);
} else {
fsm.transition(message, finished);
}
}
}
} else if (Tag.class.equals(klass)) {
final Tag verb = (Tag) message;
if (redirect.equals(verb.name())) {
fsm.transition(message, redirecting);
} else if (sms.equals(verb.name())) {
fsm.transition(message, creatingSmsSession);
} else if (email.equals(verb.name())) {
fsm.transition(message, sendingEmail);
} else {
invalidVerb(verb);
}
} else if (SmsServiceResponse.class.equals(klass)) {
final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message;
if (response.succeeded()) {
if (creatingSmsSession.equals(state)) {
fsm.transition(message, sendingSms);
}
} else {
if (sessions.size() > 0) {
fsm.transition(message, waitingForSmsResponses);
} else {
fsm.transition(message, finished);
}
}
} else if (SmsSessionResponse.class.equals(klass)) {
response(message);
} else if (StopInterpreter.class.equals(klass)) {
if (sessions.size() > 0) {
fsm.transition(message, waitingForSmsResponses);
} else {
fsm.transition(message, finished);
}
} else if (EmailResponse.class.equals(klass)) {
final EmailResponse response = (EmailResponse) message;
if (!response.succeeded()) {
logger.error(
"There was an error while sending an email :" + response.error(),
response.cause());
}
fsm.transition(message, ready);
}
}
protected List<NameValuePair> parameters() {
final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
final String smsSessionSid = initialSessionSid.toString();
parameters.add(new BasicNameValuePair("SmsSid", smsSessionSid));
final String accountSid = accountId.toString();
parameters.add(new BasicNameValuePair("AccountSid", accountSid));
final String from = format(initialSessionRequest.from());
parameters.add(new BasicNameValuePair("From", from));
final String to = format(initialSessionRequest.to());
parameters.add(new BasicNameValuePair("To", to));
final String body = initialSessionRequest.body();
parameters.add(new BasicNameValuePair("Body", body));
//Issue https://telestax.atlassian.net/browse/RESTCOMM-517. If Request contains custom headers pass them to the HTTP server.
if(customRequestHeaderMap != null && !customRequestHeaderMap.isEmpty()){
Iterator<String> iter = customRequestHeaderMap.keySet().iterator();
while(iter.hasNext()){
String headerName = iter.next();
parameters.add(new BasicNameValuePair("SipHeader_" + headerName, customRequestHeaderMap.remove(headerName)));
}
}
return parameters;
}
private ActorRef parser(final String xml) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Parser(xml, self());
}
});
return getContext().actorOf(props);
}
private void response(final Object message) {
final Class<?> klass = message.getClass();
final ActorRef self = self();
if (SmsSessionResponse.class.equals(klass)) {
final SmsSessionResponse response = (SmsSessionResponse) message;
final SmsSessionInfo info = response.info();
SmsMessage record = (SmsMessage) info.attributes().get("record");
final SmsMessagesDao messages = storage.getSmsMessagesDao();
messages.updateSmsMessage(record);
// Destroy the sms session.
final ActorRef session = sessions.remove(record.getSid());
final DestroySmsSession destroy = new DestroySmsSession(session);
smsService.tell(destroy, self);
// Try to stop the interpreter.
final State state = fsm.state();
if (waitingForSmsResponses.equals(state)) {
final StopInterpreter stop = new StopInterpreter();
self.tell(stop, self);
}
}
}
protected URI resolve(final URI base, final URI uri) {
if (base.equals(uri)) {
return uri;
} else {
if (!uri.isAbsolute()) {
return base.resolve(uri);
} else {
return uri;
}
}
}
private abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
private final class AcquiringLastSmsEvent extends AbstractAction {
public AcquiringLastSmsEvent(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final StartInterpreter request = (StartInterpreter) message;
initialSession = request.resource();
initialSession.tell(new Observe(source), source);
initialSession.tell(new GetLastSmsRequest(), source);
}
}
private final class DownloadingRcml extends AbstractAction {
public DownloadingRcml(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
initialSessionRequest = (SmsSessionRequest) message;
initialSessionSid = Sid.generate(Sid.Type.SMS_MESSAGE);
final SmsMessage.Builder builder = SmsMessage.builder();
builder.setSid(initialSessionSid);
builder.setAccountSid(accountId);
builder.setApiVersion(version);
builder.setRecipient(initialSessionRequest.to());
builder.setSender(initialSessionRequest.from());
builder.setBody(initialSessionRequest.body());
builder.setDirection(Direction.INBOUND);
builder.setStatus(Status.RECEIVED);
builder.setPrice(new BigDecimal("0.00"));
// TODO implement currency property to be read from Configuration
builder.setPriceUnit(Currency.getInstance("USD"));
final StringBuilder buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/SMS/Messages/");
buffer.append(initialSessionSid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
final SmsMessage record = builder.build();
final SmsMessagesDao messages = storage.getSmsMessagesDao();
messages.addSmsMessage(record);
getContext().system().eventStream().publish(record);
// Destroy the initial session.
smsService.tell(new DestroySmsSession(initialSession), source);
initialSession = null;
// Ask the downloader to get us the application that will be executed.
final List<NameValuePair> parameters = parameters();
request = new HttpRequestDescriptor(url, method, parameters);
downloader.tell(request, source);
}
}
private final class DownloadingFallbackRcml extends AbstractAction {
public DownloadingFallbackRcml(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final Class<?> klass = message.getClass();
// Notify the account of the issue.
if (DownloaderResponse.class.equals(klass)) {
final DownloaderResponse result = (DownloaderResponse) message;
final Throwable cause = result.cause();
Notification notification = null;
if (cause instanceof ClientProtocolException) {
notification = notification(ERROR_NOTIFICATION, 11206, cause.getMessage());
} else if (cause instanceof IOException) {
notification = notification(ERROR_NOTIFICATION, 11205, cause.getMessage());
} else if (cause instanceof URISyntaxException) {
notification = notification(ERROR_NOTIFICATION, 11100, cause.getMessage());
}
if (notification != null) {
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
}
}
// Try to use the fall back url and method.
final List<NameValuePair> parameters = parameters();
request = new HttpRequestDescriptor(fallbackUrl, fallbackMethod, parameters);
downloader.tell(request, source);
}
}
private final class Ready extends AbstractAction {
public Ready(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final UntypedActorContext context = getContext();
final State state = fsm.state();
// Make sure we create a new parser if necessary.
if (downloadingRcml.equals(state) || downloadingFallbackRcml.equals(state) || redirecting.equals(state)
|| sendingSms.equals(state)) {
response = ((DownloaderResponse) message).get();
if (parser != null) {
context.stop(parser);
parser = null;
}
try{
final String type = response.getContentType();
final String content = response.getContentAsString();
if ((type != null && content != null) && (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html"))) {
parser = parser(content);
} else {
if(logger.isInfoEnabled()) {
logger.info("DownloaderResponse getContentType is null: "+response);
}
final NotificationsDao notifications = storage.getNotificationsDao();
final Notification notification = notification(WARNING_NOTIFICATION, 12300, "Invalide content-type.");
notifications.addNotification(notification);
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
}
} catch (Exception e) {
final NotificationsDao notifications = storage.getNotificationsDao();
final Notification notification = notification(WARNING_NOTIFICATION, 12300, "Invalide content-type.");
notifications.addNotification(notification);
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
}
}
// Ask the parser for the next action to take.
Header[] headers = response.getHeaders();
for(Header header: headers) {
if (header.getName().startsWith("X-")) {
customHttpHeaderMap.put(header.getName(), header.getValue());
}
}
final GetNextVerb next = new GetNextVerb();
parser.tell(next, source);
}
}
private final class Redirecting extends AbstractAction {
public Redirecting(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
verb = (Tag) message;
final NotificationsDao notifications = storage.getNotificationsDao();
String method = "POST";
Attribute attribute = verb.attribute("method");
if (attribute != null) {
method = attribute.value();
if (method != null && !method.isEmpty()) {
if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) {
final Notification notification = notification(WARNING_NOTIFICATION, 13710, method
+ " is not a valid HTTP method for <Redirect>");
notifications.addNotification(notification);
method = "POST";
}
} else {
method = "POST";
}
}
final String text = verb.text();
if (text != null && !text.isEmpty()) {
// Try to redirect.
URI target = null;
try {
target = URI.create(text);
} catch (final Exception exception) {
final Notification notification = notification(ERROR_NOTIFICATION, 11100, text + " is an invalid URI.");
notifications.addNotification(notification);
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
}
final URI base = request.getUri();
final URI uri = resolve(base, target);
final List<NameValuePair> parameters = parameters();
request = new HttpRequestDescriptor(uri, method, parameters);
downloader.tell(request, source);
} else {
// Ask the parser for the next action to take.
final GetNextVerb next = new GetNextVerb();
parser.tell(next, source);
}
}
}
private final class CreatingSmsSession extends AbstractAction {
public CreatingSmsSession(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
// Save <Sms> verb.
verb = (Tag) message;
// Create a new sms session to handle the <Sms> verb.
smsService.tell(new CreateSmsSession(initialSessionRequest.from(), initialSessionRequest.to(), accountId.toString(), false), source);
}
}
private final class SendingSms extends AbstractAction {
public SendingSms(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(final Object message) throws Exception {
final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message;
final ActorRef session = response.get();
final NotificationsDao notifications = storage.getNotificationsDao();
SmsSessionRequest.Encoding encoding = initialSessionRequest.encoding();
// Parse "from".
String from = initialSessionRequest.to();
Attribute attribute = verb.attribute("from");
if (attribute != null) {
from = attribute.value();
if (from != null && !from.isEmpty()) {
from = format(from);
if (from == null) {
from = verb.attribute("from").value();
final Notification notification = notification(ERROR_NOTIFICATION, 14102, from
+ " is an invalid 'from' phone number.");
notifications.addNotification(notification);
smsService.tell(new DestroySmsSession(session), source);
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
}
} else {
from = initialSessionRequest.to();
}
}
// Parse "to".
String to = initialSessionRequest.from();
attribute = verb.attribute("to");
if (attribute != null) {
to = attribute.value();
if (to == null) {
to = initialSessionRequest.from();
}
}
// Parse <Sms> text.
String body = verb.text();
if (body == null || body.isEmpty()) {
final Notification notification = notification(ERROR_NOTIFICATION, 14103, body + " is an invalid SMS body.");
notifications.addNotification(notification);
smsService.tell(new DestroySmsSession(session), source);
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
} else {
// Start observing events from the sms session.
session.tell(new Observe(source), source);
// Create an SMS detail record.
final Sid sid = Sid.generate(Sid.Type.SMS_MESSAGE);
final SmsMessage.Builder builder = SmsMessage.builder();
builder.setSid(sid);
builder.setAccountSid(accountId);
builder.setApiVersion(version);
builder.setRecipient(to);
builder.setSender(from);
builder.setBody(body);
builder.setDirection(Direction.OUTBOUND_REPLY);
builder.setStatus(Status.SENDING);
builder.setPrice(new BigDecimal("0.00"));
// TODO implement currency property to be read from Configuration
builder.setPriceUnit(Currency.getInstance("USD"));
final StringBuilder buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/SMS/Messages/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
SmsVerb.populateAttributes(verb, builder);
final SmsMessage record = builder.build();
final SmsMessagesDao messages = storage.getSmsMessagesDao();
messages.addSmsMessage(record);
// Store the sms record in the sms session.
session.tell(new SmsSessionAttribute("record", record), source);
// Send the SMS.
final SmsSessionRequest sms = new SmsSessionRequest(from, to, body, encoding, customHttpHeaderMap);
session.tell(sms, source);
sessions.put(sid, session);
}
// Parses "action".
attribute = verb.attribute("action");
if (attribute != null) {
String action = attribute.value();
if (action != null && !action.isEmpty()) {
URI target = null;
try {
target = URI.create(action);
} catch (final Exception exception) {
final Notification notification = notification(ERROR_NOTIFICATION, 11100, action
+ " is an invalid URI.");
notifications.addNotification(notification);
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
}
final URI base = request.getUri();
final URI uri = resolve(base, target);
// Parse "method".
String method = "POST";
attribute = verb.attribute("method");
if (attribute != null) {
method = attribute.value();
if (method != null && !method.isEmpty()) {
if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) {
final Notification notification = notification(WARNING_NOTIFICATION, 14104, method
+ " is not a valid HTTP method for <Sms>");
notifications.addNotification(notification);
method = "POST";
}
} else {
method = "POST";
}
}
// Redirect to the action url.
final List<NameValuePair> parameters = parameters();
final String status = Status.SENDING.toString();
parameters.add(new BasicNameValuePair("SmsStatus", status));
request = new HttpRequestDescriptor(uri, method, parameters);
downloader.tell(request, source);
return;
}
}
// Ask the parser for the next action to take.
final GetNextVerb next = new GetNextVerb();
parser.tell(next, source);
}
}
private final class WaitingForSmsResponses extends AbstractAction {
public WaitingForSmsResponses(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
response(message);
}
}
private final class Finished extends AbstractAction {
public Finished(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final UntypedActorContext context = getContext();
context.stop(source);
}
}
private final class SendingEmail extends AbstractAction {
public SendingEmail(final ActorRef source){
super(source);
}
@Override
public void execute( final Object message) throws Exception {
final Tag verb = (Tag)message;
// Parse "from".
String from;
Attribute attribute = verb.attribute("from");
if (attribute != null) {
from = attribute.value();
}else{
Exception error = new Exception("From attribute was not defined");
source.tell(new EmailResponse(error,error.getMessage()), source);
return;
}
// Parse "to".
String to;
attribute = verb.attribute("to");
if (attribute != null) {
to = attribute.value();
}else{
Exception error = new Exception("To attribute was not defined");
source.tell(new EmailResponse(error,error.getMessage()), source);
return;
}
// Parse "cc".
String cc="";
attribute = verb.attribute("cc");
if (attribute != null) {
cc = attribute.value();
}
// Parse "bcc".
String bcc="";
attribute = verb.attribute("bcc");
if (attribute != null) {
bcc = attribute.value();
}
// Parse "subject"
String subject;
attribute = verb.attribute("subject");
if (attribute != null) {
subject = attribute.value();
}else{
subject="Restcomm Email Service";
}
// Send the email.
final Mail emailMsg = new Mail(from, to, subject, verb.text(),cc,bcc);
if (mailerService == null){
mailerService = mailer(emailconfiguration);
}
mailerService.tell(new EmailRequest(emailMsg), self());
}
}
}
| 41,006 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmppOutboundMessageEntity.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/SmppOutboundMessageEntity.java | package org.restcomm.connect.sms.smpp;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.smpp.parameter.TlvSet;
import com.cloudhopper.commons.charset.Charset;
public class SmppOutboundMessageEntity {
private final String smppTo;
private final String smppFrom;
private final String smppContent;
private final Charset smppEncoding;
private final TlvSet tlvSet;
private final Sid msgSid;
public SmppOutboundMessageEntity(String smppTo, String smppFrom, String smppContent, Charset smppEncoding){
this(smppTo, smppFrom, smppContent, smppEncoding, null, Sid.generate(Sid.Type.INVALID));
}
public SmppOutboundMessageEntity(String smppTo, String smppFrom, String smppContent, Charset smppEncoding, TlvSet tlvSet, Sid smsSid){
this.smppTo = smppTo;
this.smppFrom = smppFrom;
this.smppContent = smppContent;
this.smppEncoding = smppEncoding;
this.tlvSet = tlvSet;
this.msgSid = smsSid;
}
public final TlvSet getTlvSet(){
return tlvSet;
}
public final String getSmppTo(){
return smppTo;
}
public final String getSmppFrom(){
return smppFrom;
}
public final String getSmppContent(){
return smppContent;
}
public final Charset getSmppEncoding(){
return smppEncoding;
}
public Sid getMessageSid() {
return msgSid;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SMPPOutboundMessage[From=")
.append(smppFrom)
.append(",To")
.append(smppTo)
.append(",Content=")
.append(smppContent)
.append(",Encoding=")
.append(smppEncoding);
if(tlvSet!=null){
builder.append(",TlvSet=")
.append(tlvSet.toString());
}
if(msgSid!=null){
builder.append(",msgSid=")
.append(msgSid.toString());
}
builder.append("]");
return super.toString();
}
}
| 2,089 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmppInterpreterParams.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/SmppInterpreterParams.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms.smpp;
import akka.actor.ActorRef;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoManager;
import java.net.URI;
/**
* @author [email protected] (Oleg Agafonov)
*/
public final class SmppInterpreterParams {
private Configuration configuration;
private ActorRef smsService;
private DaoManager storage;
private Sid accountId;
private String version;
private URI url;
private String method;
private URI fallbackUrl;
private String fallbackMethod;
private SmppInterpreterParams(Configuration configuration, ActorRef smsService, DaoManager storage, Sid accountId, String version, URI url, String method, URI fallbackUrl, String fallbackMethod) {
this.configuration = configuration;
this.smsService = smsService;
this.storage = storage;
this.accountId = accountId;
this.version = version;
this.url = url;
this.method = method;
this.fallbackUrl = fallbackUrl;
this.fallbackMethod = fallbackMethod;
}
public Configuration getConfiguration() {
return configuration;
}
public ActorRef getSmsService() {
return smsService;
}
public DaoManager getStorage() {
return storage;
}
public Sid getAccountId() {
return accountId;
}
public String getVersion() {
return version;
}
public URI getUrl() {
return url;
}
public String getMethod() {
return method;
}
public URI getFallbackUrl() {
return fallbackUrl;
}
public String getFallbackMethod() {
return fallbackMethod;
}
public static final class Builder {
private Configuration configuration;
private ActorRef smsService;
private DaoManager storage;
private Sid accountId;
private String version;
private URI url;
private String method;
private URI fallbackUrl;
private String fallbackMethod;
public Builder setConfiguration(Configuration configuration) {
this.configuration = configuration;
return this;
}
public Builder setSmsService(ActorRef smsService) {
this.smsService = smsService;
return this;
}
public Builder setStorage(DaoManager storage) {
this.storage = storage;
return this;
}
public Builder setAccountId(Sid accountId) {
this.accountId = accountId;
return this;
}
public Builder setVersion(String version) {
this.version = version;
return this;
}
public Builder setUrl(URI url) {
this.url = url;
return this;
}
public Builder setMethod(String method) {
this.method = method;
return this;
}
public Builder setFallbackUrl(URI fallbackUrl) {
this.fallbackUrl = fallbackUrl;
return this;
}
public Builder setFallbackMethod(String fallbackMethod) {
this.fallbackMethod = fallbackMethod;
return this;
}
public SmppInterpreterParams build() {
return new SmppInterpreterParams(configuration, smsService, storage, accountId, version, url, method, fallbackUrl, fallbackMethod);
}
}
}
| 4,318 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmppService.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/SmppService.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms.smpp;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.impl.DefaultSmppClient;
import com.cloudhopper.smpp.type.Address;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.dao.DaoManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipURI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import static javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES;
/**
*
* @author amit bhayani
* @author [email protected]
*
*/
public final class SmppService extends RestcommUntypedActor {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private final ActorRef smppMessageHandler;
private final Configuration configuration;
private boolean authenticateUsers = true;
private final ServletConfig servletConfig;
private final SipFactory sipFactory;
private final DaoManager storage;
private final ServletContext servletContext;
private static String smppActivated;
static final int ERROR_NOTIFICATION = 0;
static final int WARNING_NOTIFICATION = 1;
private static String smppSourceAddressMap;
private static String smppDestinationAddressMap;
private static String smppTonNpiValue;
private ThreadPoolExecutor executor;
private ScheduledThreadPoolExecutor monitorExecutor;
private DefaultSmppClient clientBootstrap = null;
private SmppClientOpsThread smppClientOpsThread = null;
private ArrayList<Smpp> smppList = new ArrayList<Smpp>();
public SmppService(final Configuration configuration, final SipFactory factory,
final DaoManager storage, final ServletContext servletContext, final ActorRef smppMessageHandler) {
super();
this.smppMessageHandler = smppMessageHandler;
this.configuration = configuration;
final Configuration runtime = configuration.subset("runtime-settings");
this.authenticateUsers = runtime.getBoolean("authenticate");
this.servletConfig = (ServletConfig) configuration.getProperty(ServletConfig.class.getName());
this.sipFactory = factory;
this.storage = storage;
this.servletContext = servletContext;
Configuration config = this.configuration.subset("smpp");
smppActivated = config.getString("[@activateSmppConnection]");
//get smpp address map from restcomm.xml file
this.smppSourceAddressMap = config.getString("connections.connection[@sourceAddressMap]");
this.smppDestinationAddressMap = config.getString("connections.connection[@destinationAddressMap]");
this.smppTonNpiValue = config.getString("connections.connection[@tonNpiValue]");
this.initializeSmppConnections();
}
public static String getSmppTonNpiValue(){
return smppTonNpiValue;
}
@Override
public void onReceive(Object message) throws Exception {}
private void initializeSmppConnections() {
Configuration smppConfiguration = this.configuration.subset("smpp");
List<Object> smppConnections = smppConfiguration.getList("connections.connection.name");
int smppConnecsSize = smppConnections.size();
if (smppConnecsSize == 0) {
logger.warning("No SMPP Connections defined!");
return;
}
for (int count = 0; count < smppConnecsSize; count++) {
String name = smppConfiguration.getString("connections.connection(" + count + ").name");
String systemId = smppConfiguration.getString("connections.connection(" + count + ").systemid");
String peerIp = smppConfiguration.getString("connections.connection(" + count + ").peerip");
int peerPort = smppConfiguration.getInt("connections.connection(" + count + ").peerport");
SmppBindType bindtype = SmppBindType.valueOf(smppConfiguration.getString("connections.connection(" + count
+ ").bindtype"));
if (bindtype == null) {
logger.warning("Bindtype for SMPP name=" + name + " is not specified. Using default TRANSCEIVER");
}
String password = smppConfiguration.getString("connections.connection(" + count + ").password");
String systemType = smppConfiguration.getString("connections.connection(" + count + ").systemtype");
byte interfaceVersion = smppConfiguration.getByte("connections.connection(" + count + ").interfaceversion");
byte ton = smppConfiguration.getByte("connections.connection(" + count + ").ton");
byte npi = smppConfiguration.getByte("connections.connection(" + count + ").npi");
String range = smppConfiguration.getString("connections.connection(" + count + ").range");
Address address = null;
if (ton != -1 && npi != -1 && range != null) {
address = new Address(ton, npi, range);
}
int windowSize = smppConfiguration.getInt("connections.connection(" + count + ").windowsize");
long windowWaitTimeout = smppConfiguration.getLong("connections.connection(" + count + ").windowwaittimeout");
long connectTimeout = smppConfiguration.getLong("connections.connection(" + count + ").connecttimeout");
long requestExpiryTimeout = smppConfiguration.getLong("connections.connection(" + count + ").requestexpirytimeout");
long windowMonitorInterval = smppConfiguration.getLong("connections.connection(" + count
+ ").windowmonitorinterval");
boolean logBytes = smppConfiguration.getBoolean("connections.connection(" + count + ").logbytes");
boolean countersEnabled = smppConfiguration.getBoolean("connections.connection(" + count + ").countersenabled");
long enquireLinkDelay = smppConfiguration.getLong("connections.connection(" + count + ").enquirelinkdelay");
String inboundCharacterEncoding = smppConfiguration.getString("connections.connection(" + count + ").inboundencoding");
String outboundCharacterEncoding = smppConfiguration.getString("connections.connection(" + count + ").outboundencoding");
boolean messagePayloadFlag = smppConfiguration.getBoolean("connections.connection(" + count + ").messagepayloadflag");
boolean autoDetectDcsFlag = smppConfiguration.getBoolean("connections.connection(" + count + ").autodetectdcsflag");
Smpp smpp = new Smpp(name, systemId, peerIp, peerPort, bindtype, password, systemType, interfaceVersion, address,
connectTimeout, windowSize, windowWaitTimeout, requestExpiryTimeout, windowMonitorInterval,
countersEnabled, logBytes, enquireLinkDelay, inboundCharacterEncoding, outboundCharacterEncoding, messagePayloadFlag, autoDetectDcsFlag);
this.smppList.add(smpp);
if(logger.isInfoEnabled()) {
logger.info("creating new SMPP connection " + smpp);
}
}
// for monitoring thread use, it's preferable to create your own
// instance of an executor and cast it to a ThreadPoolExecutor from
// Executors.newCachedThreadPool() this permits exposing thinks like
// executor.getActiveCount() via JMX possible no point renaming the
// threads in a factory since underlying Netty framework does not easily
// allow you to customize your thread names
this.executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
// to enable automatic expiration of requests, a second scheduled
// executor is required which is what a monitor task will be executed
// with - this is probably a thread pool that can be shared with between
// all client bootstraps
this.monitorExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1, new ThreadFactory() {
private AtomicInteger sequence = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("SmppServer-SessionWindowMonitorPool-" + sequence.getAndIncrement());
return t;
}
});
// a single instance of a client bootstrap can technically be shared
// between any sessions that are created (a session can go to any
// different number of SMSCs) - each session created under a client
// bootstrap will use the executor and monitorExecutor set in its
// constructor - just be *very* careful with the "expectedSessions"
// value to make sure it matches the actual number of total concurrent
// open sessions you plan on handling - the underlying netty library
// used for NIO sockets essentially uses this value as the max number of
// threads it will ever use, despite the "max pool size", etc. set on
// the executor passed in here
// Setting expected session to be 25. May be this should be
// configurable?
this.clientBootstrap = new DefaultSmppClient(this.executor, 25, monitorExecutor);
this.smppClientOpsThread = new SmppClientOpsThread(this.clientBootstrap, outboundInterface("udp").getPort(), smppMessageHandler);
(new Thread(this.smppClientOpsThread)).start();
for(Smpp smpp : this.smppList){
this.smppClientOpsThread.scheduleConnect(smpp);
}
if(logger.isInfoEnabled()) {
logger.info("SMPP Service started");
}
}
private SipURI outboundInterface(String transport) {
SipURI result = null;
@SuppressWarnings("unchecked")
final List<SipURI> uris = (List<SipURI>) this.servletContext.getAttribute(OUTBOUND_INTERFACES);
for (final SipURI uri : uris) {
final String interfaceTransport = uri.getTransportParam();
if (transport.equalsIgnoreCase(interfaceTransport)) {
result = uri;
}
}
return result;
}
}
| 11,385 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RegexRemover.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/RegexRemover.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.sms.smpp;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.restcomm.connect.dao.entities.IncomingPhoneNumber;
public class RegexRemover {
public static final char[] REGEX_SPECIAL_CHARS = {'*', '#', '^', '|', '.', '\\', '$', '[', ']'};
/**
* SMPP is not supporting organizations at the moment, disable regexes to
* prevent an organization to capture all cloud traffic with a single regex.
*
* @param numbers
*/
static void removeRegexes(List<IncomingPhoneNumber> numbers) {
//use a list to prevent conc access during iteration
List<IncomingPhoneNumber> toBeRemoved = new ArrayList();
if (numbers != null) {
for (IncomingPhoneNumber nAux : numbers) {
if (StringUtils.containsAny(nAux.getPhoneNumber(), REGEX_SPECIAL_CHARS)) {
//mark this as to be removed later
toBeRemoved.add(nAux);
}
}
//finally remove regexes
for (IncomingPhoneNumber nAux : toBeRemoved) {
//this is relying on Java default equals IncomingPhoneNumber
numbers.remove(nAux);
}
}
}
}
| 2,087 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.