file_id
stringlengths 4
10
| content
stringlengths 91
42.8k
| repo
stringlengths 7
108
| path
stringlengths 7
251
| token_length
int64 34
8.19k
| original_comment
stringlengths 11
11.5k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 34
42.8k
|
---|---|---|---|---|---|---|---|---|
202603_6 | /*
*
* .::::.
* .::::::::.
* ::::::::::: by [email protected]
* ..:::::::::::'
* '::::::::::::'
* .::::::::::
* '::::::::::::::..
* ..::::::::::::.
* ``::::::::::::::::
* ::::``:::::::::' .:::.
* ::::' ':::::' .::::::::.
* .::::' :::: .:::::::'::::.
* .:::' ::::: .:::::::::' ':::::.
* .::' :::::.:::::::::' ':::::.
* .::' ::::::::::::::' ``::::.
* ...::: ::::::::::::' ``::.
* ```` ':. ':::::::::' ::::..
* '.:::::' ':'````..
*
*/
package cn.qssq666.robot.ui;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* Created by 情随事迁([email protected]) on 2017/3/7. 虽然能解决左右平均分配问题但是不能解决4个item 中每一个item 宽度一致问题。
* 因此开发者还需要 写一个东西就是
* jingxuanHeadBinding.recyclerviewSinger.setPadding(spacingInPixels/2, 0, spacingInPixels/2, spacingInPixels/2);
*/
public class EqualDivierDecoration extends SpacesItemDecoration {
private boolean needTop;
/**
* 不包括顶部
* @param recyclerView
* @param space
*/
public EqualDivierDecoration(RecyclerView recyclerView, int space) {
super(space);
/**
* 顶部 下面实现了
*/
recyclerView.setPadding(getSpace() / 2, 0, getSpace() / 2, getSpace() / 2);
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight) {
this(recyclerView, space, needLeft, needRight, true);
/**
* 顶部 下面实现了
*/
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight, boolean isneddTop) {
super(space);
/**
* 顶部 下面实现了
*/
this.needTop = isneddTop;
recyclerView.setPadding(needLeft ? getSpace() / 2 : 0, isneddTop ? getSpace() / 2 : 0, needRight ? getSpace() / 2 : 0, getSpace() / 2);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// int itemCount = parent.getLayoutManager().getItemCount();
// int childAdapterPosition = parent.getChildAdapterPosition(view);
// GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
// int spanCount = layoutManager.getSpanCount();
// int result = childAdapterPosition % spanCount;
//左右必须等分 上下没关系。
if (needTop) {
outRect.top = getSpace() / 2;
}
outRect.left = getSpace() / 2;
outRect.right = getSpace() / 2;
outRect.bottom = getSpace() / 2;//底部的diy不给提供,只负责顶部
}
}
| lozn00/robot | app/src/main/java/cn/qssq666/robot/ui/EqualDivierDecoration.java | 824 | // int itemCount = parent.getLayoutManager().getItemCount(); | line_comment | nl | /*
*
* .::::.
* .::::::::.
* ::::::::::: by [email protected]
* ..:::::::::::'
* '::::::::::::'
* .::::::::::
* '::::::::::::::..
* ..::::::::::::.
* ``::::::::::::::::
* ::::``:::::::::' .:::.
* ::::' ':::::' .::::::::.
* .::::' :::: .:::::::'::::.
* .:::' ::::: .:::::::::' ':::::.
* .::' :::::.:::::::::' ':::::.
* .::' ::::::::::::::' ``::::.
* ...::: ::::::::::::' ``::.
* ```` ':. ':::::::::' ::::..
* '.:::::' ':'````..
*
*/
package cn.qssq666.robot.ui;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* Created by 情随事迁([email protected]) on 2017/3/7. 虽然能解决左右平均分配问题但是不能解决4个item 中每一个item 宽度一致问题。
* 因此开发者还需要 写一个东西就是
* jingxuanHeadBinding.recyclerviewSinger.setPadding(spacingInPixels/2, 0, spacingInPixels/2, spacingInPixels/2);
*/
public class EqualDivierDecoration extends SpacesItemDecoration {
private boolean needTop;
/**
* 不包括顶部
* @param recyclerView
* @param space
*/
public EqualDivierDecoration(RecyclerView recyclerView, int space) {
super(space);
/**
* 顶部 下面实现了
*/
recyclerView.setPadding(getSpace() / 2, 0, getSpace() / 2, getSpace() / 2);
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight) {
this(recyclerView, space, needLeft, needRight, true);
/**
* 顶部 下面实现了
*/
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight, boolean isneddTop) {
super(space);
/**
* 顶部 下面实现了
*/
this.needTop = isneddTop;
recyclerView.setPadding(needLeft ? getSpace() / 2 : 0, isneddTop ? getSpace() / 2 : 0, needRight ? getSpace() / 2 : 0, getSpace() / 2);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// int itemCount<SUF>
// int childAdapterPosition = parent.getChildAdapterPosition(view);
// GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
// int spanCount = layoutManager.getSpanCount();
// int result = childAdapterPosition % spanCount;
//左右必须等分 上下没关系。
if (needTop) {
outRect.top = getSpace() / 2;
}
outRect.left = getSpace() / 2;
outRect.right = getSpace() / 2;
outRect.bottom = getSpace() / 2;//底部的diy不给提供,只负责顶部
}
}
|
202629_0 | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
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.google.firebase.auth.FirebaseAuth;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LeaderboardActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
RequestQueue requestQueue;
JsonObjectRequest JsonRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
// getSupportActionBar().setTitle("Leaderboard");
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Leaderboard </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
//De button wordt ge-enabled op de Action Bar
nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.navView);
nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
mAuth = FirebaseAuth.getInstance();
String URL = "hhttp://capilgrim.azurewebsites.net/api/pilgrimages";
final List<Pilgrimage> pilgrimagesList = new ArrayList<Pilgrimage>();
requestQueue = Volley.newRequestQueue(this);
Log.d("GETTER", "onCreate: ");
JsonRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject Leaderboard = response;
JSONArray pilgrimages = Leaderboard.getJSONArray("pilgrimages");
Log.d("GETTER", "onResponse: " + pilgrimages.length());
for (int i = 0; i < pilgrimages.length(); i++) {
Log.d("GETTER", "onResponse: TEST");
final JSONObject temp = pilgrimages.getJSONObject(i);
Pilgrimage pilgrimagetemp = new Pilgrimage(){{
id = temp.getInt("id");
FireBaseID = temp.getString("fireBaseID");
username = temp.getString("username");
startTime = temp.getInt("startTime");
Time = temp.getInt("time");
}};
pilgrimagesList.add(pilgrimagetemp);
}
Pilgrimage[] pilgrimagesarray = new Pilgrimage[pilgrimagesList.size()];
pilgrimagesarray = pilgrimagesList.toArray(pilgrimagesarray);
//String[] pilgrimages = {"Eerste", "Tweede", "Derde", "Vierde"};
ListAdapter Adapter = new LeaderboardAdapter(getBaseContext(),pilgrimagesarray);
ListView leaderboardList = (ListView) findViewById(R.id.LeaderBoardListView);
leaderboardList.setAdapter(Adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST response", error.toString());
}
}
);
requestQueue.add(JsonRequest);
}
//Nu kan er op de button gedrukt worden
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item){
switch (item.getItemId()){
case R.id.nav_collections:
Intent intentCollection = new Intent(LeaderboardActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(LeaderboardActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(LeaderboardActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(LeaderboardActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(LeaderboardActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(LeaderboardActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(LeaderboardActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(LeaderboardActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
| AP-IT-GH/CA1819-Pilgrim | src/AndroidApp/app/src/main/java/com/example/midasvg/pilgrim/LeaderboardActivity.java | 1,535 | //De button wordt ge-enabled op de Action Bar | line_comment | nl | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
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.google.firebase.auth.FirebaseAuth;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LeaderboardActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
RequestQueue requestQueue;
JsonObjectRequest JsonRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
// getSupportActionBar().setTitle("Leaderboard");
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Leaderboard </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
//De button<SUF>
nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.navView);
nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
mAuth = FirebaseAuth.getInstance();
String URL = "hhttp://capilgrim.azurewebsites.net/api/pilgrimages";
final List<Pilgrimage> pilgrimagesList = new ArrayList<Pilgrimage>();
requestQueue = Volley.newRequestQueue(this);
Log.d("GETTER", "onCreate: ");
JsonRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject Leaderboard = response;
JSONArray pilgrimages = Leaderboard.getJSONArray("pilgrimages");
Log.d("GETTER", "onResponse: " + pilgrimages.length());
for (int i = 0; i < pilgrimages.length(); i++) {
Log.d("GETTER", "onResponse: TEST");
final JSONObject temp = pilgrimages.getJSONObject(i);
Pilgrimage pilgrimagetemp = new Pilgrimage(){{
id = temp.getInt("id");
FireBaseID = temp.getString("fireBaseID");
username = temp.getString("username");
startTime = temp.getInt("startTime");
Time = temp.getInt("time");
}};
pilgrimagesList.add(pilgrimagetemp);
}
Pilgrimage[] pilgrimagesarray = new Pilgrimage[pilgrimagesList.size()];
pilgrimagesarray = pilgrimagesList.toArray(pilgrimagesarray);
//String[] pilgrimages = {"Eerste", "Tweede", "Derde", "Vierde"};
ListAdapter Adapter = new LeaderboardAdapter(getBaseContext(),pilgrimagesarray);
ListView leaderboardList = (ListView) findViewById(R.id.LeaderBoardListView);
leaderboardList.setAdapter(Adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST response", error.toString());
}
}
);
requestQueue.add(JsonRequest);
}
//Nu kan er op de button gedrukt worden
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item){
switch (item.getItemId()){
case R.id.nav_collections:
Intent intentCollection = new Intent(LeaderboardActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(LeaderboardActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(LeaderboardActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(LeaderboardActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(LeaderboardActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(LeaderboardActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(LeaderboardActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(LeaderboardActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
|
202629_1 | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
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.google.firebase.auth.FirebaseAuth;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LeaderboardActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
RequestQueue requestQueue;
JsonObjectRequest JsonRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
// getSupportActionBar().setTitle("Leaderboard");
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Leaderboard </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
//De button wordt ge-enabled op de Action Bar
nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.navView);
nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
mAuth = FirebaseAuth.getInstance();
String URL = "hhttp://capilgrim.azurewebsites.net/api/pilgrimages";
final List<Pilgrimage> pilgrimagesList = new ArrayList<Pilgrimage>();
requestQueue = Volley.newRequestQueue(this);
Log.d("GETTER", "onCreate: ");
JsonRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject Leaderboard = response;
JSONArray pilgrimages = Leaderboard.getJSONArray("pilgrimages");
Log.d("GETTER", "onResponse: " + pilgrimages.length());
for (int i = 0; i < pilgrimages.length(); i++) {
Log.d("GETTER", "onResponse: TEST");
final JSONObject temp = pilgrimages.getJSONObject(i);
Pilgrimage pilgrimagetemp = new Pilgrimage(){{
id = temp.getInt("id");
FireBaseID = temp.getString("fireBaseID");
username = temp.getString("username");
startTime = temp.getInt("startTime");
Time = temp.getInt("time");
}};
pilgrimagesList.add(pilgrimagetemp);
}
Pilgrimage[] pilgrimagesarray = new Pilgrimage[pilgrimagesList.size()];
pilgrimagesarray = pilgrimagesList.toArray(pilgrimagesarray);
//String[] pilgrimages = {"Eerste", "Tweede", "Derde", "Vierde"};
ListAdapter Adapter = new LeaderboardAdapter(getBaseContext(),pilgrimagesarray);
ListView leaderboardList = (ListView) findViewById(R.id.LeaderBoardListView);
leaderboardList.setAdapter(Adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST response", error.toString());
}
}
);
requestQueue.add(JsonRequest);
}
//Nu kan er op de button gedrukt worden
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item){
switch (item.getItemId()){
case R.id.nav_collections:
Intent intentCollection = new Intent(LeaderboardActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(LeaderboardActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(LeaderboardActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(LeaderboardActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(LeaderboardActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(LeaderboardActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(LeaderboardActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(LeaderboardActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
| AP-IT-GH/CA1819-Pilgrim | src/AndroidApp/app/src/main/java/com/example/midasvg/pilgrim/LeaderboardActivity.java | 1,535 | //String[] pilgrimages = {"Eerste", "Tweede", "Derde", "Vierde"}; | line_comment | nl | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
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.google.firebase.auth.FirebaseAuth;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LeaderboardActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
RequestQueue requestQueue;
JsonObjectRequest JsonRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
// getSupportActionBar().setTitle("Leaderboard");
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Leaderboard </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
//De button wordt ge-enabled op de Action Bar
nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.navView);
nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
mAuth = FirebaseAuth.getInstance();
String URL = "hhttp://capilgrim.azurewebsites.net/api/pilgrimages";
final List<Pilgrimage> pilgrimagesList = new ArrayList<Pilgrimage>();
requestQueue = Volley.newRequestQueue(this);
Log.d("GETTER", "onCreate: ");
JsonRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject Leaderboard = response;
JSONArray pilgrimages = Leaderboard.getJSONArray("pilgrimages");
Log.d("GETTER", "onResponse: " + pilgrimages.length());
for (int i = 0; i < pilgrimages.length(); i++) {
Log.d("GETTER", "onResponse: TEST");
final JSONObject temp = pilgrimages.getJSONObject(i);
Pilgrimage pilgrimagetemp = new Pilgrimage(){{
id = temp.getInt("id");
FireBaseID = temp.getString("fireBaseID");
username = temp.getString("username");
startTime = temp.getInt("startTime");
Time = temp.getInt("time");
}};
pilgrimagesList.add(pilgrimagetemp);
}
Pilgrimage[] pilgrimagesarray = new Pilgrimage[pilgrimagesList.size()];
pilgrimagesarray = pilgrimagesList.toArray(pilgrimagesarray);
//String[] pilgrimages<SUF>
ListAdapter Adapter = new LeaderboardAdapter(getBaseContext(),pilgrimagesarray);
ListView leaderboardList = (ListView) findViewById(R.id.LeaderBoardListView);
leaderboardList.setAdapter(Adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST response", error.toString());
}
}
);
requestQueue.add(JsonRequest);
}
//Nu kan er op de button gedrukt worden
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item){
switch (item.getItemId()){
case R.id.nav_collections:
Intent intentCollection = new Intent(LeaderboardActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(LeaderboardActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(LeaderboardActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(LeaderboardActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(LeaderboardActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(LeaderboardActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(LeaderboardActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(LeaderboardActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
|
202629_2 | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
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.google.firebase.auth.FirebaseAuth;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LeaderboardActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
RequestQueue requestQueue;
JsonObjectRequest JsonRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
// getSupportActionBar().setTitle("Leaderboard");
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Leaderboard </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
//De button wordt ge-enabled op de Action Bar
nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.navView);
nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
mAuth = FirebaseAuth.getInstance();
String URL = "hhttp://capilgrim.azurewebsites.net/api/pilgrimages";
final List<Pilgrimage> pilgrimagesList = new ArrayList<Pilgrimage>();
requestQueue = Volley.newRequestQueue(this);
Log.d("GETTER", "onCreate: ");
JsonRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject Leaderboard = response;
JSONArray pilgrimages = Leaderboard.getJSONArray("pilgrimages");
Log.d("GETTER", "onResponse: " + pilgrimages.length());
for (int i = 0; i < pilgrimages.length(); i++) {
Log.d("GETTER", "onResponse: TEST");
final JSONObject temp = pilgrimages.getJSONObject(i);
Pilgrimage pilgrimagetemp = new Pilgrimage(){{
id = temp.getInt("id");
FireBaseID = temp.getString("fireBaseID");
username = temp.getString("username");
startTime = temp.getInt("startTime");
Time = temp.getInt("time");
}};
pilgrimagesList.add(pilgrimagetemp);
}
Pilgrimage[] pilgrimagesarray = new Pilgrimage[pilgrimagesList.size()];
pilgrimagesarray = pilgrimagesList.toArray(pilgrimagesarray);
//String[] pilgrimages = {"Eerste", "Tweede", "Derde", "Vierde"};
ListAdapter Adapter = new LeaderboardAdapter(getBaseContext(),pilgrimagesarray);
ListView leaderboardList = (ListView) findViewById(R.id.LeaderBoardListView);
leaderboardList.setAdapter(Adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST response", error.toString());
}
}
);
requestQueue.add(JsonRequest);
}
//Nu kan er op de button gedrukt worden
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item){
switch (item.getItemId()){
case R.id.nav_collections:
Intent intentCollection = new Intent(LeaderboardActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(LeaderboardActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(LeaderboardActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(LeaderboardActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(LeaderboardActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(LeaderboardActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(LeaderboardActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(LeaderboardActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
| AP-IT-GH/CA1819-Pilgrim | src/AndroidApp/app/src/main/java/com/example/midasvg/pilgrim/LeaderboardActivity.java | 1,535 | //Nu kan er op de button gedrukt worden | line_comment | nl | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
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.google.firebase.auth.FirebaseAuth;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LeaderboardActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
RequestQueue requestQueue;
JsonObjectRequest JsonRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
// getSupportActionBar().setTitle("Leaderboard");
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Leaderboard </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
//De button wordt ge-enabled op de Action Bar
nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
navigationView = (NavigationView) findViewById(R.id.navView);
nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
mAuth = FirebaseAuth.getInstance();
String URL = "hhttp://capilgrim.azurewebsites.net/api/pilgrimages";
final List<Pilgrimage> pilgrimagesList = new ArrayList<Pilgrimage>();
requestQueue = Volley.newRequestQueue(this);
Log.d("GETTER", "onCreate: ");
JsonRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject Leaderboard = response;
JSONArray pilgrimages = Leaderboard.getJSONArray("pilgrimages");
Log.d("GETTER", "onResponse: " + pilgrimages.length());
for (int i = 0; i < pilgrimages.length(); i++) {
Log.d("GETTER", "onResponse: TEST");
final JSONObject temp = pilgrimages.getJSONObject(i);
Pilgrimage pilgrimagetemp = new Pilgrimage(){{
id = temp.getInt("id");
FireBaseID = temp.getString("fireBaseID");
username = temp.getString("username");
startTime = temp.getInt("startTime");
Time = temp.getInt("time");
}};
pilgrimagesList.add(pilgrimagetemp);
}
Pilgrimage[] pilgrimagesarray = new Pilgrimage[pilgrimagesList.size()];
pilgrimagesarray = pilgrimagesList.toArray(pilgrimagesarray);
//String[] pilgrimages = {"Eerste", "Tweede", "Derde", "Vierde"};
ListAdapter Adapter = new LeaderboardAdapter(getBaseContext(),pilgrimagesarray);
ListView leaderboardList = (ListView) findViewById(R.id.LeaderBoardListView);
leaderboardList.setAdapter(Adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST response", error.toString());
}
}
);
requestQueue.add(JsonRequest);
}
//Nu kan<SUF>
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item){
switch (item.getItemId()){
case R.id.nav_collections:
Intent intentCollection = new Intent(LeaderboardActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(LeaderboardActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(LeaderboardActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(LeaderboardActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(LeaderboardActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(LeaderboardActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(LeaderboardActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(LeaderboardActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
|
202681_6 | /*
*
* .::::.
* .::::::::.
* ::::::::::: by [email protected]
* ..:::::::::::'
* '::::::::::::'
* .::::::::::
* '::::::::::::::..
* ..::::::::::::.
* ``::::::::::::::::
* ::::``:::::::::' .:::.
* ::::' ':::::' .::::::::.
* .::::' :::: .:::::::'::::.
* .:::' ::::: .:::::::::' ':::::.
* .::' :::::.:::::::::' ':::::.
* .::' ::::::::::::::' ``::::.
* ...::: ::::::::::::' ``::.
* ```` ':. ':::::::::' ::::..
* '.:::::' ':'````..
*
*/
package cn.qssq666.rapiddevelopframe.view;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by 情随事迁([email protected]) on 2017/3/7. 虽然能解决左右平均分配问题但是不能解决4个item 中每一个item 宽度一致问题。
* 因此开发者还需要 写一个东西就是
* jingxuanHeadBinding.recyclerviewSinger.setPadding(spacingInPixels/2, 0, spacingInPixels/2, spacingInPixels/2);
*/
public class EqualDivierDecoration extends SpacesItemDecoration {
private boolean needTop;
/**
* 不包括顶部
* @param recyclerView
* @param space
*/
public EqualDivierDecoration(RecyclerView recyclerView, int space) {
super(space);
/**
* 顶部 下面实现了
*/
recyclerView.setPadding(getSpace() / 2, 0, getSpace() / 2, getSpace() / 2);
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight) {
this(recyclerView, space, needLeft, needRight, true);
/**
* 顶部 下面实现了
*/
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight, boolean isneddTop) {
super(space);
/**
* 顶部 下面实现了
*/
this.needTop = isneddTop;
recyclerView.setPadding(needLeft ? getSpace() / 2 : 0, isneddTop ? getSpace() / 2 : 0, needRight ? getSpace() / 2 : 0, getSpace() / 2);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// int itemCount = parent.getLayoutManager().getItemCount();
// int childAdapterPosition = parent.getChildAdapterPosition(view);
// GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
// int spanCount = layoutManager.getSpanCount();
// int result = childAdapterPosition % spanCount;
//左右必须等分 上下没关系。
if (needTop) {
outRect.top = getSpace() / 2;
}
outRect.left = getSpace() / 2;
outRect.right = getSpace() / 2;
outRect.bottom = getSpace() / 2;//底部的diy不给提供,只负责顶部
}
}
| lozn00/QuickDevelopFrame | appx/src/main/java/cn/qssq666/rapiddevelopframe/view/EqualDivierDecoration.java | 829 | // int itemCount = parent.getLayoutManager().getItemCount(); | line_comment | nl | /*
*
* .::::.
* .::::::::.
* ::::::::::: by [email protected]
* ..:::::::::::'
* '::::::::::::'
* .::::::::::
* '::::::::::::::..
* ..::::::::::::.
* ``::::::::::::::::
* ::::``:::::::::' .:::.
* ::::' ':::::' .::::::::.
* .::::' :::: .:::::::'::::.
* .:::' ::::: .:::::::::' ':::::.
* .::' :::::.:::::::::' ':::::.
* .::' ::::::::::::::' ``::::.
* ...::: ::::::::::::' ``::.
* ```` ':. ':::::::::' ::::..
* '.:::::' ':'````..
*
*/
package cn.qssq666.rapiddevelopframe.view;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by 情随事迁([email protected]) on 2017/3/7. 虽然能解决左右平均分配问题但是不能解决4个item 中每一个item 宽度一致问题。
* 因此开发者还需要 写一个东西就是
* jingxuanHeadBinding.recyclerviewSinger.setPadding(spacingInPixels/2, 0, spacingInPixels/2, spacingInPixels/2);
*/
public class EqualDivierDecoration extends SpacesItemDecoration {
private boolean needTop;
/**
* 不包括顶部
* @param recyclerView
* @param space
*/
public EqualDivierDecoration(RecyclerView recyclerView, int space) {
super(space);
/**
* 顶部 下面实现了
*/
recyclerView.setPadding(getSpace() / 2, 0, getSpace() / 2, getSpace() / 2);
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight) {
this(recyclerView, space, needLeft, needRight, true);
/**
* 顶部 下面实现了
*/
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight, boolean isneddTop) {
super(space);
/**
* 顶部 下面实现了
*/
this.needTop = isneddTop;
recyclerView.setPadding(needLeft ? getSpace() / 2 : 0, isneddTop ? getSpace() / 2 : 0, needRight ? getSpace() / 2 : 0, getSpace() / 2);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// int itemCount<SUF>
// int childAdapterPosition = parent.getChildAdapterPosition(view);
// GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
// int spanCount = layoutManager.getSpanCount();
// int result = childAdapterPosition % spanCount;
//左右必须等分 上下没关系。
if (needTop) {
outRect.top = getSpace() / 2;
}
outRect.left = getSpace() / 2;
outRect.right = getSpace() / 2;
outRect.bottom = getSpace() / 2;//底部的diy不给提供,只负责顶部
}
}
|
202684_2 |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here you can try out the combined functionality of your classes
TodoList list = new TodoList();
Scanner scanner = new Scanner(System.in);
UserInterface ui = new UserInterface(list, scanner);
ui.start();
// list.add("iets doen");
// list.add("nog iets doen");
// list.add("andermaal iets doen");
// list.add("een vierde taak");
// list.print();
// list.remove(3);
// System.out.println("");
// list.print();
}
}
| Thibault-be/MOOC-Helsinki-Java-2 | part08-Part08_05.TodoList/src/main/java/Main.java | 165 | // list.add("andermaal iets doen"); | line_comment | nl |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here you can try out the combined functionality of your classes
TodoList list = new TodoList();
Scanner scanner = new Scanner(System.in);
UserInterface ui = new UserInterface(list, scanner);
ui.start();
// list.add("iets doen");
// list.add("nog iets doen");
// list.add("andermaal iets<SUF>
// list.add("een vierde taak");
// list.print();
// list.remove(3);
// System.out.println("");
// list.print();
}
}
|
202684_3 |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here you can try out the combined functionality of your classes
TodoList list = new TodoList();
Scanner scanner = new Scanner(System.in);
UserInterface ui = new UserInterface(list, scanner);
ui.start();
// list.add("iets doen");
// list.add("nog iets doen");
// list.add("andermaal iets doen");
// list.add("een vierde taak");
// list.print();
// list.remove(3);
// System.out.println("");
// list.print();
}
}
| Thibault-be/MOOC-Helsinki-Java-2 | part08-Part08_05.TodoList/src/main/java/Main.java | 165 | // list.add("een vierde taak"); | line_comment | nl |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here you can try out the combined functionality of your classes
TodoList list = new TodoList();
Scanner scanner = new Scanner(System.in);
UserInterface ui = new UserInterface(list, scanner);
ui.start();
// list.add("iets doen");
// list.add("nog iets doen");
// list.add("andermaal iets doen");
// list.add("een vierde<SUF>
// list.print();
// list.remove(3);
// System.out.println("");
// list.print();
}
}
|
202701_6 | /**
* Copyright (c) 2008-2023, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved.
* This work is provided under a BSD-style open-source license, see project
* <a href="https://savage.nps.edu/opendis7-java/license.html" target="_blank">license.html</a> and <a href="https://savage.nps.edu/opendis7-java/license.txt" target="_blank">license.txt</a>
*/
// header autogenerated using string template dis7javalicense.txt
// autogenerated using string template entitytypecommon.txt
package edu.nps.moves.dis7.entities.deu.platform.surface;
import edu.nps.moves.dis7.pdus.*;
import edu.nps.moves.dis7.enumerations.*;
/**
* <p> Entity class <b><code>KoosexDelphin</code></b> collects multiple enumeration values together to uniquely define this entity. </p>
* <p> <i>Usage:</i> create an instance of this class with <code>KoosexDelphin.createInstance()</code> or <code>new KoosexDelphin()</code>. </p>
* <ul>
* <li> Country: Germany (DEU) = <code>78</code>; </li>
* <li> Entity kind: PlatformDomain = <code>SURFACE</code>; </li>
* <li> Domain: Platform = <code>1</code>; </li>
* <li> Category: Auxiliary, Merchant Marine = <code>17</code>; </li>
* <li> SubCategory: Harbortugstype414 = <code>3</code>; </li>
* <li> Specific: KoosexDelphin = <code>1</code>; </li>
* <li> Entity type uid: 16676; </li>
* <li> Online document reference: <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/blob/master/specifications/README.md" target="_blank">SISO-REF-010-v33-DRAFT-20231217-d10 (2023-12-17)</a>. </li>
* </ul>
* <p> Full name: edu.nps.moves.dis7.source.generator.entityTypes.GenerateEntityTypes$SpecificElem@2313052e. </p>
* @see Country#GERMANY_DEU
* @see EntityKind#PLATFORM
* @see Domain
* @see PlatformDomain
* @see Category
* @see AuxiliaryMerchantMarine
* @see SubCategory
*/
public final class KoosexDelphin extends EntityType
{
/** Default constructor */
public KoosexDelphin()
{
setCountry(Country.GERMANY_DEU);
setEntityKind(EntityKind.PLATFORM);
setDomain(Domain.inst(PlatformDomain.SURFACE));
setCategory((byte)17); // uid 16659, Auxiliary, Merchant Marine
setSubCategory((byte)3); // uid 16675, Harbor tugs (type 414)
setSpecific((byte)1); // uid 16676, Koos (ex-Delphin)
}
/** Create a new instance of this final (unmodifiable) class
* @return copy of class for use as data */
public static KoosexDelphin createInstance()
{
return new KoosexDelphin();
}
}
| open-dis/opendis7-java | src-generated/edu/nps/moves/dis7/entities/deu/platform/surface/KoosexDelphin.java | 824 | // uid 16676, Koos (ex-Delphin) | line_comment | nl | /**
* Copyright (c) 2008-2023, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved.
* This work is provided under a BSD-style open-source license, see project
* <a href="https://savage.nps.edu/opendis7-java/license.html" target="_blank">license.html</a> and <a href="https://savage.nps.edu/opendis7-java/license.txt" target="_blank">license.txt</a>
*/
// header autogenerated using string template dis7javalicense.txt
// autogenerated using string template entitytypecommon.txt
package edu.nps.moves.dis7.entities.deu.platform.surface;
import edu.nps.moves.dis7.pdus.*;
import edu.nps.moves.dis7.enumerations.*;
/**
* <p> Entity class <b><code>KoosexDelphin</code></b> collects multiple enumeration values together to uniquely define this entity. </p>
* <p> <i>Usage:</i> create an instance of this class with <code>KoosexDelphin.createInstance()</code> or <code>new KoosexDelphin()</code>. </p>
* <ul>
* <li> Country: Germany (DEU) = <code>78</code>; </li>
* <li> Entity kind: PlatformDomain = <code>SURFACE</code>; </li>
* <li> Domain: Platform = <code>1</code>; </li>
* <li> Category: Auxiliary, Merchant Marine = <code>17</code>; </li>
* <li> SubCategory: Harbortugstype414 = <code>3</code>; </li>
* <li> Specific: KoosexDelphin = <code>1</code>; </li>
* <li> Entity type uid: 16676; </li>
* <li> Online document reference: <a href="https://gitlab.nps.edu/Savage/NetworkedGraphicsMV3500/-/blob/master/specifications/README.md" target="_blank">SISO-REF-010-v33-DRAFT-20231217-d10 (2023-12-17)</a>. </li>
* </ul>
* <p> Full name: edu.nps.moves.dis7.source.generator.entityTypes.GenerateEntityTypes$SpecificElem@2313052e. </p>
* @see Country#GERMANY_DEU
* @see EntityKind#PLATFORM
* @see Domain
* @see PlatformDomain
* @see Category
* @see AuxiliaryMerchantMarine
* @see SubCategory
*/
public final class KoosexDelphin extends EntityType
{
/** Default constructor */
public KoosexDelphin()
{
setCountry(Country.GERMANY_DEU);
setEntityKind(EntityKind.PLATFORM);
setDomain(Domain.inst(PlatformDomain.SURFACE));
setCategory((byte)17); // uid 16659, Auxiliary, Merchant Marine
setSubCategory((byte)3); // uid 16675, Harbor tugs (type 414)
setSpecific((byte)1); // uid 16676,<SUF>
}
/** Create a new instance of this final (unmodifiable) class
* @return copy of class for use as data */
public static KoosexDelphin createInstance()
{
return new KoosexDelphin();
}
}
|
202729_8 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;
import java.util.stream.Collectors;
import jdk.jshell.spi.ExecutionControl;
import org.json.*;
// Võimaldab trennide andmebaasi laadida ning salvestada, samuti muuta selle andmeid mingil moel (trenni lisamine, kustutamine jne)
// Mõte oli, et niimoodi lahutab backendi ja frontendi rohkem ära. Ehk siis andmete töötlemise ja salvestamisega tegeleb mingi class, ning graafikaliides ei pea
// midagi teadma, kuidas neid andmeid töödeldakse.
public class Andmebaas {
public static final String ANDMEBAASI_FAIL = "andmebaas.json";
private HashMap<String, List<Trenn>> trenniAndmed;
public Andmebaas() {
this.trenniAndmed = new HashMap<>();
}
public boolean lisaTrenn(String kuupäev, String nimi, String kestvus) {
if(!this.trenniAndmed.containsKey(kuupäev))
return false;
//loome uue random ID et seda trenniga koos kasutada (panin kolmekohalise sest siis on vast piisavalt palju trenne võimalik lisada)
int id = (int) (Math.random() * 1000);
//loome juba kasutusel olevate IDde listi
ArrayList<Integer> trennideIDd = new ArrayList<>();
//ma pole kindel kas see töötab nii nagu ma plaanisin
//aga see peaks iga trenni id panema listi:
this.trenniAndmed.forEach((key, value) -> {
if (value.isEmpty()) ;
else {
for (Trenn mingiTrenn : value) {
trennideIDd.add(Integer.parseInt(mingiTrenn.getId()));
}
}
});
//kontrollime et seda IDd ei oleks seal listis
while (trennideIDd.contains(id)) id = (int) (Math.random() * 1000);
//teeme uue trenni isendi
Trenn uusTrenn = new Trenn(String.valueOf(id), kestvus, nimi);
//lisame selle selle kuupäeva trennide listi
this.trenniAndmed.get(kuupäev).add(uusTrenn);
return true;
}
//kustutab trenni kindla IDga mingilt kuupäevalt, kontrollides kas selline ID on olemas
public boolean kustutaTrenn(String kuupäev, String id) {
if(!this.trenniAndmed.containsKey(kuupäev))
return false;
boolean eemaldati = this.trenniAndmed.get(kuupäev).removeIf(trenn -> trenn.getId().equals(id));
return eemaldati;
}
public List<Trenn> tagastaTrennidKuupäeval(String kuupäev) {
return this.trenniAndmed.get(kuupäev);
}
public boolean looUusKuupäev(String kuupäev) {
if(this.trenniAndmed.containsKey(kuupäev)) // vana kuupäev kirjutatakse üle ilma selleta
return false;
ArrayList<Trenn> mingidTrennid = new ArrayList<>();
this.trenniAndmed.put(kuupäev, mingidTrennid);
return true;
}
public boolean kustutaKuupäev(String kuupäev) {
return this.trenniAndmed.remove(kuupäev) != null;
}
public void lisaKuupäev(String kuupäev) {
this.trenniAndmed.put(kuupäev, new ArrayList<>());
}
public List<String> tagastaKõikKuupäevad() {
//kõik kuupäevad uude listi
List<String> kõikKuupäevad=new ArrayList<>();
if (this.trenniAndmed.isEmpty()) return kõikKuupäevad;
this.trenniAndmed.forEach((key, value) -> {
kõikKuupäevad.add(key);
});
return kõikKuupäevad;
}
//tagastab mingi välja sisemiste andmeväljade info rekursiivselt
private List<Andmeväli> loeAndmeväljadRekursiivselt(JSONObject praeguseVäljaInfo) {
ArrayList<Andmeväli> andmeväljad = new ArrayList<>();
JSONArray andmeväljadJson = praeguseVäljaInfo.getJSONArray("väljad");
Iterator<Object> it = andmeväljadJson.iterator();
while (it.hasNext()) {
JSONObject väljaInfo = (JSONObject) it.next();
String id = väljaInfo.getString("id");
String väljaNimi = väljaInfo.getString("nimi");
String väärtus = väljaInfo.getString("väärtus");
// rekursiivselt paneme kirja sisemised väljad
List<Andmeväli> sisemisedVäljad = new ArrayList<>();
if (!väljaInfo.getJSONArray("väljad").isEmpty())
sisemisedVäljad = this.loeAndmeväljadRekursiivselt(väljaInfo);
Andmeväli väli = new Andmeväli(id, väljaNimi, väärtus, sisemisedVäljad);
andmeväljad.add(väli);
}
return andmeväljad;
}
//laeb andmebaasi faili info
public void laeAndmebaas() throws FileNotFoundException {
JSONTokener jsonFail = new JSONTokener(new FileReader(ANDMEBAASI_FAIL));
// vaatame kõik kuupäevad andmebaasis läbi
JSONObject kuupäevadKoosTrennidega = new JSONObject(jsonFail);
for (String kuupäev : kuupäevadKoosTrennidega.keySet()) {
this.trenniAndmed.put(kuupäev, new ArrayList<>());
// vaatame läbi kõik trennid, mis sel kuupäeval tegime
JSONArray treeningud = kuupäevadKoosTrennidega.getJSONArray(kuupäev);
for (Object o : treeningud) {
JSONObject trennJson = (JSONObject) o;
String trenniNimi = trennJson.getString("nimi");
String trenniKestvus = trennJson.getString("kestvus");
String id = trennJson.getString("id");
// lisame trenni kindlasse kuupäeva
Trenn trenn = new Trenn(id, trenniKestvus, trenniNimi);
List<Trenn> trennidKuupäeval = this.trenniAndmed.get(kuupäev);
trennidKuupäeval.add(trenn);
// loeme trenni andmeväljad eraldi objekti, siis uuendame trenni infot
List<Andmeväli> andmeväljad = this.loeAndmeväljadRekursiivselt(trennJson);
trenn.setPeamisedVäljad(andmeväljad);
}
}
}
//tagastab väljaobjektide JSONArray, mida andmebaas kasutab
private JSONArray väljaObjektidJsoniks(List<Andmeväli> väljad) {
JSONArray väljadJson = new JSONArray();
for (Andmeväli andmed : väljad) {
JSONObject andmedJson = new JSONObject();
andmedJson.put("id", andmed.getId());
andmedJson.put("nimi", andmed.getNimi());
andmedJson.put("väärtus", andmed.getVäärtus());
if (andmed.getSisemisedVäljad().size() != 0)
andmedJson.put("väljad", this.väljaObjektidJsoniks(andmed.getSisemisedVäljad()));
else
andmedJson.put("väljad", new JSONArray());
// lisame andmete Jsoni listi
väljadJson.put(andmedJson);
}
return väljadJson;
}
//tagastab trenniobjektide JSONArray, mida andmebaas kasutab
private JSONArray trenniObjektidJsoniks(List<Trenn> trennid) {
JSONArray trennidJson = new JSONArray();
for (Trenn trenn : trennid) {
JSONObject trenniJson = new JSONObject();
trenniJson.put("id", trenn.getId());
trenniJson.put("nimi", trenn.getNimi());
trenniJson.put("kestvus", trenn.getKestvus());
trenniJson.put("väljad", this.väljaObjektidJsoniks(trenn.getPeamisedVäljad()));
trennidJson.put(trenniJson);
}
return trennidJson;
}
public void salvestaAndmebaas() throws java.io.IOException {
// Java objektide muundamine JSONiks
JSONObject uusAndmebaas = new JSONObject();
for (String kuupäev : this.trenniAndmed.keySet()) {
List<Trenn> trennid = this.trenniAndmed.get(kuupäev);
uusAndmebaas.put(kuupäev, this.trenniObjektidJsoniks(trennid));
}
// faili salvestamine
File andmebaasiFail = new File(ANDMEBAASI_FAIL);
try (FileWriter salvestus = new FileWriter(andmebaasiFail)) {
salvestus.write(uusAndmebaas.toString());
salvestus.flush();
}
}
// testimise meetod
public static void main(String[] args) throws Exception {
Andmebaas andmed = new Andmebaas();
andmed.laeAndmebaas();
//need andmed on nüüd andmebaasis:
//andmed.looUusKuupäev("2023-03-18");
//andmed.lisaTrenn("2023-03-18", "Jalutamine", "80min");
//andmed.looUusKuupäev("2023-02-28");
//andmed.lisaTrenn("2023-02-28", "Jõutrenn", "60min");
//andmed.lisaTrenn("2023-04-05", "Jooks", "30min");
System.out.println(andmed.tagastaKõikKuupäevad());
andmed.salvestaAndmebaas();
}
}
| madiskoivopuu/treeningpaevik | src/Andmebaas.java | 2,639 | //teeme uue trenni isendi | line_comment | nl | import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;
import java.util.stream.Collectors;
import jdk.jshell.spi.ExecutionControl;
import org.json.*;
// Võimaldab trennide andmebaasi laadida ning salvestada, samuti muuta selle andmeid mingil moel (trenni lisamine, kustutamine jne)
// Mõte oli, et niimoodi lahutab backendi ja frontendi rohkem ära. Ehk siis andmete töötlemise ja salvestamisega tegeleb mingi class, ning graafikaliides ei pea
// midagi teadma, kuidas neid andmeid töödeldakse.
public class Andmebaas {
public static final String ANDMEBAASI_FAIL = "andmebaas.json";
private HashMap<String, List<Trenn>> trenniAndmed;
public Andmebaas() {
this.trenniAndmed = new HashMap<>();
}
public boolean lisaTrenn(String kuupäev, String nimi, String kestvus) {
if(!this.trenniAndmed.containsKey(kuupäev))
return false;
//loome uue random ID et seda trenniga koos kasutada (panin kolmekohalise sest siis on vast piisavalt palju trenne võimalik lisada)
int id = (int) (Math.random() * 1000);
//loome juba kasutusel olevate IDde listi
ArrayList<Integer> trennideIDd = new ArrayList<>();
//ma pole kindel kas see töötab nii nagu ma plaanisin
//aga see peaks iga trenni id panema listi:
this.trenniAndmed.forEach((key, value) -> {
if (value.isEmpty()) ;
else {
for (Trenn mingiTrenn : value) {
trennideIDd.add(Integer.parseInt(mingiTrenn.getId()));
}
}
});
//kontrollime et seda IDd ei oleks seal listis
while (trennideIDd.contains(id)) id = (int) (Math.random() * 1000);
//teeme uue<SUF>
Trenn uusTrenn = new Trenn(String.valueOf(id), kestvus, nimi);
//lisame selle selle kuupäeva trennide listi
this.trenniAndmed.get(kuupäev).add(uusTrenn);
return true;
}
//kustutab trenni kindla IDga mingilt kuupäevalt, kontrollides kas selline ID on olemas
public boolean kustutaTrenn(String kuupäev, String id) {
if(!this.trenniAndmed.containsKey(kuupäev))
return false;
boolean eemaldati = this.trenniAndmed.get(kuupäev).removeIf(trenn -> trenn.getId().equals(id));
return eemaldati;
}
public List<Trenn> tagastaTrennidKuupäeval(String kuupäev) {
return this.trenniAndmed.get(kuupäev);
}
public boolean looUusKuupäev(String kuupäev) {
if(this.trenniAndmed.containsKey(kuupäev)) // vana kuupäev kirjutatakse üle ilma selleta
return false;
ArrayList<Trenn> mingidTrennid = new ArrayList<>();
this.trenniAndmed.put(kuupäev, mingidTrennid);
return true;
}
public boolean kustutaKuupäev(String kuupäev) {
return this.trenniAndmed.remove(kuupäev) != null;
}
public void lisaKuupäev(String kuupäev) {
this.trenniAndmed.put(kuupäev, new ArrayList<>());
}
public List<String> tagastaKõikKuupäevad() {
//kõik kuupäevad uude listi
List<String> kõikKuupäevad=new ArrayList<>();
if (this.trenniAndmed.isEmpty()) return kõikKuupäevad;
this.trenniAndmed.forEach((key, value) -> {
kõikKuupäevad.add(key);
});
return kõikKuupäevad;
}
//tagastab mingi välja sisemiste andmeväljade info rekursiivselt
private List<Andmeväli> loeAndmeväljadRekursiivselt(JSONObject praeguseVäljaInfo) {
ArrayList<Andmeväli> andmeväljad = new ArrayList<>();
JSONArray andmeväljadJson = praeguseVäljaInfo.getJSONArray("väljad");
Iterator<Object> it = andmeväljadJson.iterator();
while (it.hasNext()) {
JSONObject väljaInfo = (JSONObject) it.next();
String id = väljaInfo.getString("id");
String väljaNimi = väljaInfo.getString("nimi");
String väärtus = väljaInfo.getString("väärtus");
// rekursiivselt paneme kirja sisemised väljad
List<Andmeväli> sisemisedVäljad = new ArrayList<>();
if (!väljaInfo.getJSONArray("väljad").isEmpty())
sisemisedVäljad = this.loeAndmeväljadRekursiivselt(väljaInfo);
Andmeväli väli = new Andmeväli(id, väljaNimi, väärtus, sisemisedVäljad);
andmeväljad.add(väli);
}
return andmeväljad;
}
//laeb andmebaasi faili info
public void laeAndmebaas() throws FileNotFoundException {
JSONTokener jsonFail = new JSONTokener(new FileReader(ANDMEBAASI_FAIL));
// vaatame kõik kuupäevad andmebaasis läbi
JSONObject kuupäevadKoosTrennidega = new JSONObject(jsonFail);
for (String kuupäev : kuupäevadKoosTrennidega.keySet()) {
this.trenniAndmed.put(kuupäev, new ArrayList<>());
// vaatame läbi kõik trennid, mis sel kuupäeval tegime
JSONArray treeningud = kuupäevadKoosTrennidega.getJSONArray(kuupäev);
for (Object o : treeningud) {
JSONObject trennJson = (JSONObject) o;
String trenniNimi = trennJson.getString("nimi");
String trenniKestvus = trennJson.getString("kestvus");
String id = trennJson.getString("id");
// lisame trenni kindlasse kuupäeva
Trenn trenn = new Trenn(id, trenniKestvus, trenniNimi);
List<Trenn> trennidKuupäeval = this.trenniAndmed.get(kuupäev);
trennidKuupäeval.add(trenn);
// loeme trenni andmeväljad eraldi objekti, siis uuendame trenni infot
List<Andmeväli> andmeväljad = this.loeAndmeväljadRekursiivselt(trennJson);
trenn.setPeamisedVäljad(andmeväljad);
}
}
}
//tagastab väljaobjektide JSONArray, mida andmebaas kasutab
private JSONArray väljaObjektidJsoniks(List<Andmeväli> väljad) {
JSONArray väljadJson = new JSONArray();
for (Andmeväli andmed : väljad) {
JSONObject andmedJson = new JSONObject();
andmedJson.put("id", andmed.getId());
andmedJson.put("nimi", andmed.getNimi());
andmedJson.put("väärtus", andmed.getVäärtus());
if (andmed.getSisemisedVäljad().size() != 0)
andmedJson.put("väljad", this.väljaObjektidJsoniks(andmed.getSisemisedVäljad()));
else
andmedJson.put("väljad", new JSONArray());
// lisame andmete Jsoni listi
väljadJson.put(andmedJson);
}
return väljadJson;
}
//tagastab trenniobjektide JSONArray, mida andmebaas kasutab
private JSONArray trenniObjektidJsoniks(List<Trenn> trennid) {
JSONArray trennidJson = new JSONArray();
for (Trenn trenn : trennid) {
JSONObject trenniJson = new JSONObject();
trenniJson.put("id", trenn.getId());
trenniJson.put("nimi", trenn.getNimi());
trenniJson.put("kestvus", trenn.getKestvus());
trenniJson.put("väljad", this.väljaObjektidJsoniks(trenn.getPeamisedVäljad()));
trennidJson.put(trenniJson);
}
return trennidJson;
}
public void salvestaAndmebaas() throws java.io.IOException {
// Java objektide muundamine JSONiks
JSONObject uusAndmebaas = new JSONObject();
for (String kuupäev : this.trenniAndmed.keySet()) {
List<Trenn> trennid = this.trenniAndmed.get(kuupäev);
uusAndmebaas.put(kuupäev, this.trenniObjektidJsoniks(trennid));
}
// faili salvestamine
File andmebaasiFail = new File(ANDMEBAASI_FAIL);
try (FileWriter salvestus = new FileWriter(andmebaasiFail)) {
salvestus.write(uusAndmebaas.toString());
salvestus.flush();
}
}
// testimise meetod
public static void main(String[] args) throws Exception {
Andmebaas andmed = new Andmebaas();
andmed.laeAndmebaas();
//need andmed on nüüd andmebaasis:
//andmed.looUusKuupäev("2023-03-18");
//andmed.lisaTrenn("2023-03-18", "Jalutamine", "80min");
//andmed.looUusKuupäev("2023-02-28");
//andmed.lisaTrenn("2023-02-28", "Jõutrenn", "60min");
//andmed.lisaTrenn("2023-04-05", "Jooks", "30min");
System.out.println(andmed.tagastaKõikKuupäevad());
andmed.salvestaAndmebaas();
}
}
|
202733_33 | package com.nortal.jroad.client.dhl;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.AadressType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DhlDokumentType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DokumentDocument;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.EdastusDocument.Edastus;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.MetainfoDocument.Metainfo;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.TagasisideType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlIdDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaabumisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNrDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaEpostDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatmisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_manual.impl.KoostajaFailinimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.GetSendStatusResponseTypeUnencoded.Item;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.OccupationType;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.SendDocumentsV2RequestType;
import com.nortal.jroad.client.dhl.types.ee.sk.digiDoc.v13.SignedDocType;
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException;
/**
* @author ats.uiboupin
*/
public interface DhlXTeeService {
public enum SendStatus {
/** Document is sent to DVK, but some recipients have not received it(marked this document as read) */
SENT("saatmisel"),
/** Document is sent to DVK and all recipients have received it(marked it read) */
RECEIVED("saadetud"),
/** Document is cancelled (deleteOldDocuments service has been called by the DVK administrator) */
CANCELLED("katkestatud");
String statusCode;
SendStatus(String statusCode) {
this.statusCode = statusCode;
}
public static SendStatus get(String parameterName) {
final SendStatus[] values = SendStatus.values();
for (SendStatus parameter : values) {
if (parameter.statusCode.equals(parameterName)) {
return parameter;
}
}
throw new IllegalArgumentException("Unknown status: " + parameterName);
}
/**
* @param staatus - string based enum generated from schema
* @return SendStatus Enum from string based "Enum"
*/
public static SendStatus get(Edastus.Staatus.Enum staatus) {
return get(staatus.toString());
}
@Override
public String toString() {
return statusCode;
}
}
/**
* @return organizations(regNr, name) that are capable of communicating with DVK
*/
Map<String/* regNr */, String/* name */> getSendingOptions();
/**
* @see {@link #sendDocuments(Collection, AadressType[], AadressType, SendDocumentsDokumentCallback)}
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender);
/**
* Composes and sends document to given recipients.
*
* @param contentsToSend - wrapper containing input stream of data with file name and mimeType to be assigned to the DVK document to be sent.
* @param recipients
* @param sender
* @param callback - optional callBack implementation to be called by the service method when the document is composed, allowing to change content of
* <i>"dokument"</i> as desired.
* @return dhl_Id's of the sent document
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender, SendDocumentsDokumentCallback callback,
SendDocumentsRequestCallback requestCallback);
/**
* @param ids - set of id's to be used to query statuses for.
* @return list of items containing single document status information.
*/
List<Item> getSendStatuses(Set<String> ids);
/**
* @param maxNrOfDocuments maximum number of documents that will be returned with the service call
* @return
*/
ReceivedDocumentsWrapper receiveDocuments(int maxNrOfDocuments);
/**
* @param receivedDocumentIds -
*/
void markDocumentsReceived(Collection<String> receivedDocumentIds);
/**
* Allows to mark documents received lik {@link #markDocumentsReceived(Collection)}, but also enables to add some additional information.<br>
* For example when you discover a virus or fail to process the DVK dokument
*
* @param receivedDocsInfos
*/
void markDocumentsReceivedV2(Collection<TagasisideType> receivedDocsInfos);
// void runSystemCheck();
List<OccupationType> getOccupationList(List<String> institutionRegNrs);
/**
* Callback interface, that can be used to alter <i>"dokument"</i> element after it has been composed <br>
* (just before attaching it to request body and making the service call)
*/
interface SendDocumentsDokumentCallback {
void doWithDocument(DokumentDocument dokumentDocument);
}
/**
* Callback interface, that can be used to alter request body just before making the service call
*/
interface SendDocumentsRequestCallback {
void doWithRequest(SendDocumentsV2RequestType request);
}
interface GetDvkOrganizationsHelper {
String getOrganizationName(String regnr);
Map<String, String> getDvkOrganizationsCache();
/**
* makes service call to retrieve up-to-date organisations list
*/
void updateDvkCapableOrganisationsCache();
/**
* @param organizationsCache to be used
*/
void setDvkOrganizationsCache(Map<String, String> organizationsCache);
DvkOrganizationsUpdateStrategy getUpdateStrategy();
void setUpdateStrategy(DvkOrganizationsUpdateStrategy updateStrategy);
}
/**
* @author ats.uiboupin
* Strategy pattern implementation for deciding whether or not to update DVK capable organizations list
*/
interface DvkOrganizationsUpdateStrategy {
/**
* @param cachedOrganisationName - name(or <code>null</code>) fetched from the cache based on organization registry number.
* @return true if updating cache should be done when such organization name(or null) is fetched from the cached list, false otherwise
*/
boolean update4getOrganizationName(String cachedOrganisationName);
/**
* @param dvkCapableOrganizations
* @return
*/
boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations);
/**
* Concrete strategy implementation might do decisions based on time when cache was last updated.
*
* @param lastUpdate - time when the cache was last successfully updated.
*/
void setLastUpdated(Calendar lastUpdate);
}
/**
* @author ats.uiboupin
* Simple strategy implementation, see #update4getRecipientName() and #update4getDvkOrganizationsCache
*/
class DvkOrganizationsCacheingUpdateStrategy implements DvkOrganizationsUpdateStrategy {
private static org.apache.commons.logging.Log log //
= org.apache.commons.logging.LogFactory.getLog(DhlXTeeService.DvkOrganizationsCacheingUpdateStrategy.class);
private Calendar lastUpdated;
private int maxUpdateInterval = 24 * 60; // 24h
private int timeUnit = Calendar.HOUR;
/**
* Update only if given <code>cachedOrganisationName</code> is not empty.
*/
public boolean update4getOrganizationName(String cachedOrganisationName) {
return StringUtils.isBlank(cachedOrganisationName); // only update when organisation name not found
}
/**
* asks to update cache when asking if last update was more than <code>maxUpdateInterval</code> minutes ago.
*/
public boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations) {
Calendar cal = Calendar.getInstance();
cal.add(timeUnit, -maxUpdateInterval);
return dvkCapableOrganizations == null || dvkCapableOrganizations.isEmpty() || lastUpdated == null || lastUpdated.before(cal);
}
// START: Getters / setters
public int getMaxUpdateInterval() {
return maxUpdateInterval;
}
public DvkOrganizationsCacheingUpdateStrategy setMaxUpdateInterval(int maxUpdateInterval) {
this.maxUpdateInterval = maxUpdateInterval;
return this;
}
public int getTimeUnit() {
return timeUnit;
}
/**
* @param timeUnit must be Calendar field(i.e. Calendar.MINUTE)
* @return
*/
public DvkOrganizationsCacheingUpdateStrategy setTimeUnit(int timeUnit) {
this.timeUnit = timeUnit;
return this;
}
public void setLastUpdated(Calendar date) {
if (log.isDebugEnabled()) {
log.debug("cache updated at: " + (new SimpleDateFormat().format(date.getTime())));
}
this.lastUpdated = date;
}
// END: Getters / setters
}
public interface ReceivedDocumentsWrapper extends Map<String, ReceivedDocumentsWrapper.ReceivedDocument>, Iterable<String> {
public Iterator<String> iterator();
public Set<Entry<String, ReceivedDocument>> entrySet();
public Map<String, ReceivedDocument> getDhlDocumentsMap();
public List<DhlDokumentType> getReceivedDocuments();
public interface ReceivedDocument {
public DhlDokumentType getDhlDocument();
public SignedDocType getSignedDoc();
public MetainfoHelper getMetaInfoHelper();
}
/**
* @return file that contains response (dhl:dokument elements from response attachment) if saving documents is enabled, null otherwise
*/
File getResponseDocumentsXml();
}
class ContentToSend {
private String fileName;
private String mimeType;
private InputStream inputStream;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
/**
* Helper class to work around parsing AnyType. <br>
* Convenience methods could be created to the subclasses as follows:
*
* <pre>
* public String getDhlId() {
* // DhlIdDocumentImpl.class is class for representing "dhl_id" xml-element.
* return getObject(DhlIdDocumentImpl.class).getDhlId();
* }
* </pre>
*
* @author ats.uiboupin
* @see http://www.ws-i.org/Profiles/BasicProfile-1.2.html#soapenc_Array
*/
class AnyTypeHelper {
private static Log log = LogFactory.getLog(AnyTypeHelper.class);
private final Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList;
public AnyTypeHelper(XmlObject xmlObject) {
subElementsList = parse(xmlObject); // NOPMD
}
protected Map<Class<? extends XmlObject>, List<? extends XmlObject>> parse(XmlObject xmlObject) {
if (log.isTraceEnabled()) {
log.trace("starting to parse xmlObject:\n" + xmlObject + "\n\n");
}
XmlCursor cursor = xmlObject.newCursor();
cursor.toFirstChild();// move before the root element
cursor.toFirstChild();// move to the first child of the root
Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList = new HashMap<Class<? extends XmlObject>, List<? extends XmlObject>>();
try {
do {
XmlObject object = XmlObject.Factory.parse(cursor.getDomNode());
@SuppressWarnings("unchecked")
// to be able to add object that is in fact a subclass of XmlObject, but referenced using XmlObject
List<XmlObject> list = (List<XmlObject>) subElementsList.get(object.getClass());
if (list == null) {
list = new ArrayList<XmlObject>();
}
list.add(object);
subElementsList.put(object.getClass(), list);
log.debug("adding node: '" + cursor.getDomNode().getLocalName() + "' (" + cursor.getDomNode().getNamespaceURI()
+ "),\nclass: " + object.getClass() + ", cursor: \n" + object);
} while (cursor.toNextSibling());
} catch (XmlException e) {
throw new RuntimeException("Failed to parse xmlObject:\n" + xmlObject, e);
}
return subElementsList;
}
/**
* Low-level method to retrieve any subelement by class
*
* @param <T>
* @param clazz - class of the subelement
* @return subelement according to given class, null otherwise
*/
public <T> T getObject(Class<T> clazz) {
@SuppressWarnings("unchecked")
List<T> objects = (List<T>) subElementsList.get(clazz);
if (objects != null) {
return objects.get(0);
}
return null;
}
@SuppressWarnings("unchecked")
public <T> List<T> getObjects(Class<T> clazz) {
return (List<T>) subElementsList.get(clazz);
}
}
class MetainfoHelper extends AnyTypeHelper {
public MetainfoHelper(Metainfo metainfo) {
super(metainfo);
}
// START: Convenience methods to get values of subelements
// START: methods for the fields created AUTOMATICALLY by DVK
public String getDhlId() {
return getObject(DhlIdDocumentImpl.class).getDhlId();
}
public String getDhlSaatjaAsutuseNr() {
return getObject(DhlSaatjaAsutuseNrDocumentImpl.class).getDhlSaatjaAsutuseNr();
}
public String getDhlSaatjaAsutuseNimi() {
return getObject(DhlSaatjaAsutuseNimiDocumentImpl.class).getDhlSaatjaAsutuseNimi();
}
/**
* @return the time when DVK received the document
*/
public Calendar getDhlSaabumisAeg() {
return getObject(DhlSaabumisaegDocumentImpl.class).getDhlSaabumisaeg();
}
/**
* @return the time when DVK sent out the document
*/
public Calendar getDhlSaatmisAeg() {
return getObject(DhlSaatmisaegDocumentImpl.class).getDhlSaatmisaeg();
}
public String getDhlSaatjaEpost() {
final DhlSaatjaEpostDocumentImpl object = getObject(DhlSaatjaEpostDocumentImpl.class);
return object == null ? null : object.getDhlSaatjaEpost();
}
/**
* XXX: sarnaselt eelnevatele on võimalik kätte saada(automaatselt lisatavatest andmetest) veel näiteks:
* dhl_saabumisviis, dhl_saatmisviis, dhl_saatja_asutuse_nimi, dhl_saatja_isikukood, dhl_saaja_asutuse_nr, dhl_saaja_asutuse_nimi, dhl_saaja_isikukood,
* dhl_saaja_epost, dhl_kaust
*/
// END: methods for the fields created AUTOMATICALLY by DVK
// START: methods for the fields created MANUALLY by DVK
public String getKoostajaFailinimi() {
final KoostajaFailinimiDocumentImpl kfDoc = getObject(KoostajaFailinimiDocumentImpl.class);
if (null != kfDoc) {
return kfDoc.getKoostajaFailinimi().xmlText();
}
return null;
}
// END: methods for the fields created MANUALLY by DVK
// END: Convenience methods to get values of subelements
}
/**
* Wrapper(unchecked exception) for checked exception XRoadServiceConsumptionException
*
* @author Ats Uiboupin
*/
public class WrappedXRoadServiceConsumptionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WrappedXRoadServiceConsumptionException(XRoadServiceConsumptionException cause) {
super(resolveMessage(cause), cause);
}
@Override
public XRoadServiceConsumptionException getCause() {
return (XRoadServiceConsumptionException) super.getCause();
}
private static String resolveMessage(XRoadServiceConsumptionException e) {
return "Failed to execute xtee query " + e.getFullServiceName() + ". Fault(" + e.getFaultCode() + "): '" + e.getFaultString() + "'";
}
}
// START: getters/setters
GetDvkOrganizationsHelper getDvkOrganizationsHelper();
void setDvkOrganizationsHelper(GetDvkOrganizationsHelper dvkOrganizationsHelper);
// END: getters/setters
}
| nortal/j-road | client-service/dhl/src/main/java/com/nortal/jroad/client/dhl/DhlXTeeService.java | 4,683 | // START: Convenience methods to get values of subelements | line_comment | nl | package com.nortal.jroad.client.dhl;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.AadressType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DhlDokumentType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DokumentDocument;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.EdastusDocument.Edastus;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.MetainfoDocument.Metainfo;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.TagasisideType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlIdDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaabumisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNrDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaEpostDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatmisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_manual.impl.KoostajaFailinimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.GetSendStatusResponseTypeUnencoded.Item;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.OccupationType;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.SendDocumentsV2RequestType;
import com.nortal.jroad.client.dhl.types.ee.sk.digiDoc.v13.SignedDocType;
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException;
/**
* @author ats.uiboupin
*/
public interface DhlXTeeService {
public enum SendStatus {
/** Document is sent to DVK, but some recipients have not received it(marked this document as read) */
SENT("saatmisel"),
/** Document is sent to DVK and all recipients have received it(marked it read) */
RECEIVED("saadetud"),
/** Document is cancelled (deleteOldDocuments service has been called by the DVK administrator) */
CANCELLED("katkestatud");
String statusCode;
SendStatus(String statusCode) {
this.statusCode = statusCode;
}
public static SendStatus get(String parameterName) {
final SendStatus[] values = SendStatus.values();
for (SendStatus parameter : values) {
if (parameter.statusCode.equals(parameterName)) {
return parameter;
}
}
throw new IllegalArgumentException("Unknown status: " + parameterName);
}
/**
* @param staatus - string based enum generated from schema
* @return SendStatus Enum from string based "Enum"
*/
public static SendStatus get(Edastus.Staatus.Enum staatus) {
return get(staatus.toString());
}
@Override
public String toString() {
return statusCode;
}
}
/**
* @return organizations(regNr, name) that are capable of communicating with DVK
*/
Map<String/* regNr */, String/* name */> getSendingOptions();
/**
* @see {@link #sendDocuments(Collection, AadressType[], AadressType, SendDocumentsDokumentCallback)}
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender);
/**
* Composes and sends document to given recipients.
*
* @param contentsToSend - wrapper containing input stream of data with file name and mimeType to be assigned to the DVK document to be sent.
* @param recipients
* @param sender
* @param callback - optional callBack implementation to be called by the service method when the document is composed, allowing to change content of
* <i>"dokument"</i> as desired.
* @return dhl_Id's of the sent document
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender, SendDocumentsDokumentCallback callback,
SendDocumentsRequestCallback requestCallback);
/**
* @param ids - set of id's to be used to query statuses for.
* @return list of items containing single document status information.
*/
List<Item> getSendStatuses(Set<String> ids);
/**
* @param maxNrOfDocuments maximum number of documents that will be returned with the service call
* @return
*/
ReceivedDocumentsWrapper receiveDocuments(int maxNrOfDocuments);
/**
* @param receivedDocumentIds -
*/
void markDocumentsReceived(Collection<String> receivedDocumentIds);
/**
* Allows to mark documents received lik {@link #markDocumentsReceived(Collection)}, but also enables to add some additional information.<br>
* For example when you discover a virus or fail to process the DVK dokument
*
* @param receivedDocsInfos
*/
void markDocumentsReceivedV2(Collection<TagasisideType> receivedDocsInfos);
// void runSystemCheck();
List<OccupationType> getOccupationList(List<String> institutionRegNrs);
/**
* Callback interface, that can be used to alter <i>"dokument"</i> element after it has been composed <br>
* (just before attaching it to request body and making the service call)
*/
interface SendDocumentsDokumentCallback {
void doWithDocument(DokumentDocument dokumentDocument);
}
/**
* Callback interface, that can be used to alter request body just before making the service call
*/
interface SendDocumentsRequestCallback {
void doWithRequest(SendDocumentsV2RequestType request);
}
interface GetDvkOrganizationsHelper {
String getOrganizationName(String regnr);
Map<String, String> getDvkOrganizationsCache();
/**
* makes service call to retrieve up-to-date organisations list
*/
void updateDvkCapableOrganisationsCache();
/**
* @param organizationsCache to be used
*/
void setDvkOrganizationsCache(Map<String, String> organizationsCache);
DvkOrganizationsUpdateStrategy getUpdateStrategy();
void setUpdateStrategy(DvkOrganizationsUpdateStrategy updateStrategy);
}
/**
* @author ats.uiboupin
* Strategy pattern implementation for deciding whether or not to update DVK capable organizations list
*/
interface DvkOrganizationsUpdateStrategy {
/**
* @param cachedOrganisationName - name(or <code>null</code>) fetched from the cache based on organization registry number.
* @return true if updating cache should be done when such organization name(or null) is fetched from the cached list, false otherwise
*/
boolean update4getOrganizationName(String cachedOrganisationName);
/**
* @param dvkCapableOrganizations
* @return
*/
boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations);
/**
* Concrete strategy implementation might do decisions based on time when cache was last updated.
*
* @param lastUpdate - time when the cache was last successfully updated.
*/
void setLastUpdated(Calendar lastUpdate);
}
/**
* @author ats.uiboupin
* Simple strategy implementation, see #update4getRecipientName() and #update4getDvkOrganizationsCache
*/
class DvkOrganizationsCacheingUpdateStrategy implements DvkOrganizationsUpdateStrategy {
private static org.apache.commons.logging.Log log //
= org.apache.commons.logging.LogFactory.getLog(DhlXTeeService.DvkOrganizationsCacheingUpdateStrategy.class);
private Calendar lastUpdated;
private int maxUpdateInterval = 24 * 60; // 24h
private int timeUnit = Calendar.HOUR;
/**
* Update only if given <code>cachedOrganisationName</code> is not empty.
*/
public boolean update4getOrganizationName(String cachedOrganisationName) {
return StringUtils.isBlank(cachedOrganisationName); // only update when organisation name not found
}
/**
* asks to update cache when asking if last update was more than <code>maxUpdateInterval</code> minutes ago.
*/
public boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations) {
Calendar cal = Calendar.getInstance();
cal.add(timeUnit, -maxUpdateInterval);
return dvkCapableOrganizations == null || dvkCapableOrganizations.isEmpty() || lastUpdated == null || lastUpdated.before(cal);
}
// START: Getters / setters
public int getMaxUpdateInterval() {
return maxUpdateInterval;
}
public DvkOrganizationsCacheingUpdateStrategy setMaxUpdateInterval(int maxUpdateInterval) {
this.maxUpdateInterval = maxUpdateInterval;
return this;
}
public int getTimeUnit() {
return timeUnit;
}
/**
* @param timeUnit must be Calendar field(i.e. Calendar.MINUTE)
* @return
*/
public DvkOrganizationsCacheingUpdateStrategy setTimeUnit(int timeUnit) {
this.timeUnit = timeUnit;
return this;
}
public void setLastUpdated(Calendar date) {
if (log.isDebugEnabled()) {
log.debug("cache updated at: " + (new SimpleDateFormat().format(date.getTime())));
}
this.lastUpdated = date;
}
// END: Getters / setters
}
public interface ReceivedDocumentsWrapper extends Map<String, ReceivedDocumentsWrapper.ReceivedDocument>, Iterable<String> {
public Iterator<String> iterator();
public Set<Entry<String, ReceivedDocument>> entrySet();
public Map<String, ReceivedDocument> getDhlDocumentsMap();
public List<DhlDokumentType> getReceivedDocuments();
public interface ReceivedDocument {
public DhlDokumentType getDhlDocument();
public SignedDocType getSignedDoc();
public MetainfoHelper getMetaInfoHelper();
}
/**
* @return file that contains response (dhl:dokument elements from response attachment) if saving documents is enabled, null otherwise
*/
File getResponseDocumentsXml();
}
class ContentToSend {
private String fileName;
private String mimeType;
private InputStream inputStream;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
/**
* Helper class to work around parsing AnyType. <br>
* Convenience methods could be created to the subclasses as follows:
*
* <pre>
* public String getDhlId() {
* // DhlIdDocumentImpl.class is class for representing "dhl_id" xml-element.
* return getObject(DhlIdDocumentImpl.class).getDhlId();
* }
* </pre>
*
* @author ats.uiboupin
* @see http://www.ws-i.org/Profiles/BasicProfile-1.2.html#soapenc_Array
*/
class AnyTypeHelper {
private static Log log = LogFactory.getLog(AnyTypeHelper.class);
private final Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList;
public AnyTypeHelper(XmlObject xmlObject) {
subElementsList = parse(xmlObject); // NOPMD
}
protected Map<Class<? extends XmlObject>, List<? extends XmlObject>> parse(XmlObject xmlObject) {
if (log.isTraceEnabled()) {
log.trace("starting to parse xmlObject:\n" + xmlObject + "\n\n");
}
XmlCursor cursor = xmlObject.newCursor();
cursor.toFirstChild();// move before the root element
cursor.toFirstChild();// move to the first child of the root
Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList = new HashMap<Class<? extends XmlObject>, List<? extends XmlObject>>();
try {
do {
XmlObject object = XmlObject.Factory.parse(cursor.getDomNode());
@SuppressWarnings("unchecked")
// to be able to add object that is in fact a subclass of XmlObject, but referenced using XmlObject
List<XmlObject> list = (List<XmlObject>) subElementsList.get(object.getClass());
if (list == null) {
list = new ArrayList<XmlObject>();
}
list.add(object);
subElementsList.put(object.getClass(), list);
log.debug("adding node: '" + cursor.getDomNode().getLocalName() + "' (" + cursor.getDomNode().getNamespaceURI()
+ "),\nclass: " + object.getClass() + ", cursor: \n" + object);
} while (cursor.toNextSibling());
} catch (XmlException e) {
throw new RuntimeException("Failed to parse xmlObject:\n" + xmlObject, e);
}
return subElementsList;
}
/**
* Low-level method to retrieve any subelement by class
*
* @param <T>
* @param clazz - class of the subelement
* @return subelement according to given class, null otherwise
*/
public <T> T getObject(Class<T> clazz) {
@SuppressWarnings("unchecked")
List<T> objects = (List<T>) subElementsList.get(clazz);
if (objects != null) {
return objects.get(0);
}
return null;
}
@SuppressWarnings("unchecked")
public <T> List<T> getObjects(Class<T> clazz) {
return (List<T>) subElementsList.get(clazz);
}
}
class MetainfoHelper extends AnyTypeHelper {
public MetainfoHelper(Metainfo metainfo) {
super(metainfo);
}
// START: Convenience<SUF>
// START: methods for the fields created AUTOMATICALLY by DVK
public String getDhlId() {
return getObject(DhlIdDocumentImpl.class).getDhlId();
}
public String getDhlSaatjaAsutuseNr() {
return getObject(DhlSaatjaAsutuseNrDocumentImpl.class).getDhlSaatjaAsutuseNr();
}
public String getDhlSaatjaAsutuseNimi() {
return getObject(DhlSaatjaAsutuseNimiDocumentImpl.class).getDhlSaatjaAsutuseNimi();
}
/**
* @return the time when DVK received the document
*/
public Calendar getDhlSaabumisAeg() {
return getObject(DhlSaabumisaegDocumentImpl.class).getDhlSaabumisaeg();
}
/**
* @return the time when DVK sent out the document
*/
public Calendar getDhlSaatmisAeg() {
return getObject(DhlSaatmisaegDocumentImpl.class).getDhlSaatmisaeg();
}
public String getDhlSaatjaEpost() {
final DhlSaatjaEpostDocumentImpl object = getObject(DhlSaatjaEpostDocumentImpl.class);
return object == null ? null : object.getDhlSaatjaEpost();
}
/**
* XXX: sarnaselt eelnevatele on võimalik kätte saada(automaatselt lisatavatest andmetest) veel näiteks:
* dhl_saabumisviis, dhl_saatmisviis, dhl_saatja_asutuse_nimi, dhl_saatja_isikukood, dhl_saaja_asutuse_nr, dhl_saaja_asutuse_nimi, dhl_saaja_isikukood,
* dhl_saaja_epost, dhl_kaust
*/
// END: methods for the fields created AUTOMATICALLY by DVK
// START: methods for the fields created MANUALLY by DVK
public String getKoostajaFailinimi() {
final KoostajaFailinimiDocumentImpl kfDoc = getObject(KoostajaFailinimiDocumentImpl.class);
if (null != kfDoc) {
return kfDoc.getKoostajaFailinimi().xmlText();
}
return null;
}
// END: methods for the fields created MANUALLY by DVK
// END: Convenience methods to get values of subelements
}
/**
* Wrapper(unchecked exception) for checked exception XRoadServiceConsumptionException
*
* @author Ats Uiboupin
*/
public class WrappedXRoadServiceConsumptionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WrappedXRoadServiceConsumptionException(XRoadServiceConsumptionException cause) {
super(resolveMessage(cause), cause);
}
@Override
public XRoadServiceConsumptionException getCause() {
return (XRoadServiceConsumptionException) super.getCause();
}
private static String resolveMessage(XRoadServiceConsumptionException e) {
return "Failed to execute xtee query " + e.getFullServiceName() + ". Fault(" + e.getFaultCode() + "): '" + e.getFaultString() + "'";
}
}
// START: getters/setters
GetDvkOrganizationsHelper getDvkOrganizationsHelper();
void setDvkOrganizationsHelper(GetDvkOrganizationsHelper dvkOrganizationsHelper);
// END: getters/setters
}
|
202733_41 | package com.nortal.jroad.client.dhl;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.AadressType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DhlDokumentType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DokumentDocument;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.EdastusDocument.Edastus;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.MetainfoDocument.Metainfo;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.TagasisideType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlIdDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaabumisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNrDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaEpostDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatmisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_manual.impl.KoostajaFailinimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.GetSendStatusResponseTypeUnencoded.Item;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.OccupationType;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.SendDocumentsV2RequestType;
import com.nortal.jroad.client.dhl.types.ee.sk.digiDoc.v13.SignedDocType;
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException;
/**
* @author ats.uiboupin
*/
public interface DhlXTeeService {
public enum SendStatus {
/** Document is sent to DVK, but some recipients have not received it(marked this document as read) */
SENT("saatmisel"),
/** Document is sent to DVK and all recipients have received it(marked it read) */
RECEIVED("saadetud"),
/** Document is cancelled (deleteOldDocuments service has been called by the DVK administrator) */
CANCELLED("katkestatud");
String statusCode;
SendStatus(String statusCode) {
this.statusCode = statusCode;
}
public static SendStatus get(String parameterName) {
final SendStatus[] values = SendStatus.values();
for (SendStatus parameter : values) {
if (parameter.statusCode.equals(parameterName)) {
return parameter;
}
}
throw new IllegalArgumentException("Unknown status: " + parameterName);
}
/**
* @param staatus - string based enum generated from schema
* @return SendStatus Enum from string based "Enum"
*/
public static SendStatus get(Edastus.Staatus.Enum staatus) {
return get(staatus.toString());
}
@Override
public String toString() {
return statusCode;
}
}
/**
* @return organizations(regNr, name) that are capable of communicating with DVK
*/
Map<String/* regNr */, String/* name */> getSendingOptions();
/**
* @see {@link #sendDocuments(Collection, AadressType[], AadressType, SendDocumentsDokumentCallback)}
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender);
/**
* Composes and sends document to given recipients.
*
* @param contentsToSend - wrapper containing input stream of data with file name and mimeType to be assigned to the DVK document to be sent.
* @param recipients
* @param sender
* @param callback - optional callBack implementation to be called by the service method when the document is composed, allowing to change content of
* <i>"dokument"</i> as desired.
* @return dhl_Id's of the sent document
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender, SendDocumentsDokumentCallback callback,
SendDocumentsRequestCallback requestCallback);
/**
* @param ids - set of id's to be used to query statuses for.
* @return list of items containing single document status information.
*/
List<Item> getSendStatuses(Set<String> ids);
/**
* @param maxNrOfDocuments maximum number of documents that will be returned with the service call
* @return
*/
ReceivedDocumentsWrapper receiveDocuments(int maxNrOfDocuments);
/**
* @param receivedDocumentIds -
*/
void markDocumentsReceived(Collection<String> receivedDocumentIds);
/**
* Allows to mark documents received lik {@link #markDocumentsReceived(Collection)}, but also enables to add some additional information.<br>
* For example when you discover a virus or fail to process the DVK dokument
*
* @param receivedDocsInfos
*/
void markDocumentsReceivedV2(Collection<TagasisideType> receivedDocsInfos);
// void runSystemCheck();
List<OccupationType> getOccupationList(List<String> institutionRegNrs);
/**
* Callback interface, that can be used to alter <i>"dokument"</i> element after it has been composed <br>
* (just before attaching it to request body and making the service call)
*/
interface SendDocumentsDokumentCallback {
void doWithDocument(DokumentDocument dokumentDocument);
}
/**
* Callback interface, that can be used to alter request body just before making the service call
*/
interface SendDocumentsRequestCallback {
void doWithRequest(SendDocumentsV2RequestType request);
}
interface GetDvkOrganizationsHelper {
String getOrganizationName(String regnr);
Map<String, String> getDvkOrganizationsCache();
/**
* makes service call to retrieve up-to-date organisations list
*/
void updateDvkCapableOrganisationsCache();
/**
* @param organizationsCache to be used
*/
void setDvkOrganizationsCache(Map<String, String> organizationsCache);
DvkOrganizationsUpdateStrategy getUpdateStrategy();
void setUpdateStrategy(DvkOrganizationsUpdateStrategy updateStrategy);
}
/**
* @author ats.uiboupin
* Strategy pattern implementation for deciding whether or not to update DVK capable organizations list
*/
interface DvkOrganizationsUpdateStrategy {
/**
* @param cachedOrganisationName - name(or <code>null</code>) fetched from the cache based on organization registry number.
* @return true if updating cache should be done when such organization name(or null) is fetched from the cached list, false otherwise
*/
boolean update4getOrganizationName(String cachedOrganisationName);
/**
* @param dvkCapableOrganizations
* @return
*/
boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations);
/**
* Concrete strategy implementation might do decisions based on time when cache was last updated.
*
* @param lastUpdate - time when the cache was last successfully updated.
*/
void setLastUpdated(Calendar lastUpdate);
}
/**
* @author ats.uiboupin
* Simple strategy implementation, see #update4getRecipientName() and #update4getDvkOrganizationsCache
*/
class DvkOrganizationsCacheingUpdateStrategy implements DvkOrganizationsUpdateStrategy {
private static org.apache.commons.logging.Log log //
= org.apache.commons.logging.LogFactory.getLog(DhlXTeeService.DvkOrganizationsCacheingUpdateStrategy.class);
private Calendar lastUpdated;
private int maxUpdateInterval = 24 * 60; // 24h
private int timeUnit = Calendar.HOUR;
/**
* Update only if given <code>cachedOrganisationName</code> is not empty.
*/
public boolean update4getOrganizationName(String cachedOrganisationName) {
return StringUtils.isBlank(cachedOrganisationName); // only update when organisation name not found
}
/**
* asks to update cache when asking if last update was more than <code>maxUpdateInterval</code> minutes ago.
*/
public boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations) {
Calendar cal = Calendar.getInstance();
cal.add(timeUnit, -maxUpdateInterval);
return dvkCapableOrganizations == null || dvkCapableOrganizations.isEmpty() || lastUpdated == null || lastUpdated.before(cal);
}
// START: Getters / setters
public int getMaxUpdateInterval() {
return maxUpdateInterval;
}
public DvkOrganizationsCacheingUpdateStrategy setMaxUpdateInterval(int maxUpdateInterval) {
this.maxUpdateInterval = maxUpdateInterval;
return this;
}
public int getTimeUnit() {
return timeUnit;
}
/**
* @param timeUnit must be Calendar field(i.e. Calendar.MINUTE)
* @return
*/
public DvkOrganizationsCacheingUpdateStrategy setTimeUnit(int timeUnit) {
this.timeUnit = timeUnit;
return this;
}
public void setLastUpdated(Calendar date) {
if (log.isDebugEnabled()) {
log.debug("cache updated at: " + (new SimpleDateFormat().format(date.getTime())));
}
this.lastUpdated = date;
}
// END: Getters / setters
}
public interface ReceivedDocumentsWrapper extends Map<String, ReceivedDocumentsWrapper.ReceivedDocument>, Iterable<String> {
public Iterator<String> iterator();
public Set<Entry<String, ReceivedDocument>> entrySet();
public Map<String, ReceivedDocument> getDhlDocumentsMap();
public List<DhlDokumentType> getReceivedDocuments();
public interface ReceivedDocument {
public DhlDokumentType getDhlDocument();
public SignedDocType getSignedDoc();
public MetainfoHelper getMetaInfoHelper();
}
/**
* @return file that contains response (dhl:dokument elements from response attachment) if saving documents is enabled, null otherwise
*/
File getResponseDocumentsXml();
}
class ContentToSend {
private String fileName;
private String mimeType;
private InputStream inputStream;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
/**
* Helper class to work around parsing AnyType. <br>
* Convenience methods could be created to the subclasses as follows:
*
* <pre>
* public String getDhlId() {
* // DhlIdDocumentImpl.class is class for representing "dhl_id" xml-element.
* return getObject(DhlIdDocumentImpl.class).getDhlId();
* }
* </pre>
*
* @author ats.uiboupin
* @see http://www.ws-i.org/Profiles/BasicProfile-1.2.html#soapenc_Array
*/
class AnyTypeHelper {
private static Log log = LogFactory.getLog(AnyTypeHelper.class);
private final Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList;
public AnyTypeHelper(XmlObject xmlObject) {
subElementsList = parse(xmlObject); // NOPMD
}
protected Map<Class<? extends XmlObject>, List<? extends XmlObject>> parse(XmlObject xmlObject) {
if (log.isTraceEnabled()) {
log.trace("starting to parse xmlObject:\n" + xmlObject + "\n\n");
}
XmlCursor cursor = xmlObject.newCursor();
cursor.toFirstChild();// move before the root element
cursor.toFirstChild();// move to the first child of the root
Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList = new HashMap<Class<? extends XmlObject>, List<? extends XmlObject>>();
try {
do {
XmlObject object = XmlObject.Factory.parse(cursor.getDomNode());
@SuppressWarnings("unchecked")
// to be able to add object that is in fact a subclass of XmlObject, but referenced using XmlObject
List<XmlObject> list = (List<XmlObject>) subElementsList.get(object.getClass());
if (list == null) {
list = new ArrayList<XmlObject>();
}
list.add(object);
subElementsList.put(object.getClass(), list);
log.debug("adding node: '" + cursor.getDomNode().getLocalName() + "' (" + cursor.getDomNode().getNamespaceURI()
+ "),\nclass: " + object.getClass() + ", cursor: \n" + object);
} while (cursor.toNextSibling());
} catch (XmlException e) {
throw new RuntimeException("Failed to parse xmlObject:\n" + xmlObject, e);
}
return subElementsList;
}
/**
* Low-level method to retrieve any subelement by class
*
* @param <T>
* @param clazz - class of the subelement
* @return subelement according to given class, null otherwise
*/
public <T> T getObject(Class<T> clazz) {
@SuppressWarnings("unchecked")
List<T> objects = (List<T>) subElementsList.get(clazz);
if (objects != null) {
return objects.get(0);
}
return null;
}
@SuppressWarnings("unchecked")
public <T> List<T> getObjects(Class<T> clazz) {
return (List<T>) subElementsList.get(clazz);
}
}
class MetainfoHelper extends AnyTypeHelper {
public MetainfoHelper(Metainfo metainfo) {
super(metainfo);
}
// START: Convenience methods to get values of subelements
// START: methods for the fields created AUTOMATICALLY by DVK
public String getDhlId() {
return getObject(DhlIdDocumentImpl.class).getDhlId();
}
public String getDhlSaatjaAsutuseNr() {
return getObject(DhlSaatjaAsutuseNrDocumentImpl.class).getDhlSaatjaAsutuseNr();
}
public String getDhlSaatjaAsutuseNimi() {
return getObject(DhlSaatjaAsutuseNimiDocumentImpl.class).getDhlSaatjaAsutuseNimi();
}
/**
* @return the time when DVK received the document
*/
public Calendar getDhlSaabumisAeg() {
return getObject(DhlSaabumisaegDocumentImpl.class).getDhlSaabumisaeg();
}
/**
* @return the time when DVK sent out the document
*/
public Calendar getDhlSaatmisAeg() {
return getObject(DhlSaatmisaegDocumentImpl.class).getDhlSaatmisaeg();
}
public String getDhlSaatjaEpost() {
final DhlSaatjaEpostDocumentImpl object = getObject(DhlSaatjaEpostDocumentImpl.class);
return object == null ? null : object.getDhlSaatjaEpost();
}
/**
* XXX: sarnaselt eelnevatele on võimalik kätte saada(automaatselt lisatavatest andmetest) veel näiteks:
* dhl_saabumisviis, dhl_saatmisviis, dhl_saatja_asutuse_nimi, dhl_saatja_isikukood, dhl_saaja_asutuse_nr, dhl_saaja_asutuse_nimi, dhl_saaja_isikukood,
* dhl_saaja_epost, dhl_kaust
*/
// END: methods for the fields created AUTOMATICALLY by DVK
// START: methods for the fields created MANUALLY by DVK
public String getKoostajaFailinimi() {
final KoostajaFailinimiDocumentImpl kfDoc = getObject(KoostajaFailinimiDocumentImpl.class);
if (null != kfDoc) {
return kfDoc.getKoostajaFailinimi().xmlText();
}
return null;
}
// END: methods for the fields created MANUALLY by DVK
// END: Convenience methods to get values of subelements
}
/**
* Wrapper(unchecked exception) for checked exception XRoadServiceConsumptionException
*
* @author Ats Uiboupin
*/
public class WrappedXRoadServiceConsumptionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WrappedXRoadServiceConsumptionException(XRoadServiceConsumptionException cause) {
super(resolveMessage(cause), cause);
}
@Override
public XRoadServiceConsumptionException getCause() {
return (XRoadServiceConsumptionException) super.getCause();
}
private static String resolveMessage(XRoadServiceConsumptionException e) {
return "Failed to execute xtee query " + e.getFullServiceName() + ". Fault(" + e.getFaultCode() + "): '" + e.getFaultString() + "'";
}
}
// START: getters/setters
GetDvkOrganizationsHelper getDvkOrganizationsHelper();
void setDvkOrganizationsHelper(GetDvkOrganizationsHelper dvkOrganizationsHelper);
// END: getters/setters
}
| nortal/j-road | client-service/dhl/src/main/java/com/nortal/jroad/client/dhl/DhlXTeeService.java | 4,683 | // END: Convenience methods to get values of subelements | line_comment | nl | package com.nortal.jroad.client.dhl;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.AadressType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DhlDokumentType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.DokumentDocument;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.EdastusDocument.Edastus;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.MetainfoDocument.Metainfo;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl.TagasisideType;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlIdDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaabumisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaAsutuseNrDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatjaEpostDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_automatic.impl.DhlSaatmisaegDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.schemas.dhl_meta_manual.impl.KoostajaFailinimiDocumentImpl;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.GetSendStatusResponseTypeUnencoded.Item;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.OccupationType;
import com.nortal.jroad.client.dhl.types.ee.riik.xtee.dhl.producers.producer.dhl.SendDocumentsV2RequestType;
import com.nortal.jroad.client.dhl.types.ee.sk.digiDoc.v13.SignedDocType;
import com.nortal.jroad.client.exception.XRoadServiceConsumptionException;
/**
* @author ats.uiboupin
*/
public interface DhlXTeeService {
public enum SendStatus {
/** Document is sent to DVK, but some recipients have not received it(marked this document as read) */
SENT("saatmisel"),
/** Document is sent to DVK and all recipients have received it(marked it read) */
RECEIVED("saadetud"),
/** Document is cancelled (deleteOldDocuments service has been called by the DVK administrator) */
CANCELLED("katkestatud");
String statusCode;
SendStatus(String statusCode) {
this.statusCode = statusCode;
}
public static SendStatus get(String parameterName) {
final SendStatus[] values = SendStatus.values();
for (SendStatus parameter : values) {
if (parameter.statusCode.equals(parameterName)) {
return parameter;
}
}
throw new IllegalArgumentException("Unknown status: " + parameterName);
}
/**
* @param staatus - string based enum generated from schema
* @return SendStatus Enum from string based "Enum"
*/
public static SendStatus get(Edastus.Staatus.Enum staatus) {
return get(staatus.toString());
}
@Override
public String toString() {
return statusCode;
}
}
/**
* @return organizations(regNr, name) that are capable of communicating with DVK
*/
Map<String/* regNr */, String/* name */> getSendingOptions();
/**
* @see {@link #sendDocuments(Collection, AadressType[], AadressType, SendDocumentsDokumentCallback)}
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender);
/**
* Composes and sends document to given recipients.
*
* @param contentsToSend - wrapper containing input stream of data with file name and mimeType to be assigned to the DVK document to be sent.
* @param recipients
* @param sender
* @param callback - optional callBack implementation to be called by the service method when the document is composed, allowing to change content of
* <i>"dokument"</i> as desired.
* @return dhl_Id's of the sent document
*/
Set<String> sendDocuments(Collection<ContentToSend> contentsToSend, AadressType[] recipients, AadressType sender, SendDocumentsDokumentCallback callback,
SendDocumentsRequestCallback requestCallback);
/**
* @param ids - set of id's to be used to query statuses for.
* @return list of items containing single document status information.
*/
List<Item> getSendStatuses(Set<String> ids);
/**
* @param maxNrOfDocuments maximum number of documents that will be returned with the service call
* @return
*/
ReceivedDocumentsWrapper receiveDocuments(int maxNrOfDocuments);
/**
* @param receivedDocumentIds -
*/
void markDocumentsReceived(Collection<String> receivedDocumentIds);
/**
* Allows to mark documents received lik {@link #markDocumentsReceived(Collection)}, but also enables to add some additional information.<br>
* For example when you discover a virus or fail to process the DVK dokument
*
* @param receivedDocsInfos
*/
void markDocumentsReceivedV2(Collection<TagasisideType> receivedDocsInfos);
// void runSystemCheck();
List<OccupationType> getOccupationList(List<String> institutionRegNrs);
/**
* Callback interface, that can be used to alter <i>"dokument"</i> element after it has been composed <br>
* (just before attaching it to request body and making the service call)
*/
interface SendDocumentsDokumentCallback {
void doWithDocument(DokumentDocument dokumentDocument);
}
/**
* Callback interface, that can be used to alter request body just before making the service call
*/
interface SendDocumentsRequestCallback {
void doWithRequest(SendDocumentsV2RequestType request);
}
interface GetDvkOrganizationsHelper {
String getOrganizationName(String regnr);
Map<String, String> getDvkOrganizationsCache();
/**
* makes service call to retrieve up-to-date organisations list
*/
void updateDvkCapableOrganisationsCache();
/**
* @param organizationsCache to be used
*/
void setDvkOrganizationsCache(Map<String, String> organizationsCache);
DvkOrganizationsUpdateStrategy getUpdateStrategy();
void setUpdateStrategy(DvkOrganizationsUpdateStrategy updateStrategy);
}
/**
* @author ats.uiboupin
* Strategy pattern implementation for deciding whether or not to update DVK capable organizations list
*/
interface DvkOrganizationsUpdateStrategy {
/**
* @param cachedOrganisationName - name(or <code>null</code>) fetched from the cache based on organization registry number.
* @return true if updating cache should be done when such organization name(or null) is fetched from the cached list, false otherwise
*/
boolean update4getOrganizationName(String cachedOrganisationName);
/**
* @param dvkCapableOrganizations
* @return
*/
boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations);
/**
* Concrete strategy implementation might do decisions based on time when cache was last updated.
*
* @param lastUpdate - time when the cache was last successfully updated.
*/
void setLastUpdated(Calendar lastUpdate);
}
/**
* @author ats.uiboupin
* Simple strategy implementation, see #update4getRecipientName() and #update4getDvkOrganizationsCache
*/
class DvkOrganizationsCacheingUpdateStrategy implements DvkOrganizationsUpdateStrategy {
private static org.apache.commons.logging.Log log //
= org.apache.commons.logging.LogFactory.getLog(DhlXTeeService.DvkOrganizationsCacheingUpdateStrategy.class);
private Calendar lastUpdated;
private int maxUpdateInterval = 24 * 60; // 24h
private int timeUnit = Calendar.HOUR;
/**
* Update only if given <code>cachedOrganisationName</code> is not empty.
*/
public boolean update4getOrganizationName(String cachedOrganisationName) {
return StringUtils.isBlank(cachedOrganisationName); // only update when organisation name not found
}
/**
* asks to update cache when asking if last update was more than <code>maxUpdateInterval</code> minutes ago.
*/
public boolean update4getDvkOrganizationsCache(Map<String, String> dvkCapableOrganizations) {
Calendar cal = Calendar.getInstance();
cal.add(timeUnit, -maxUpdateInterval);
return dvkCapableOrganizations == null || dvkCapableOrganizations.isEmpty() || lastUpdated == null || lastUpdated.before(cal);
}
// START: Getters / setters
public int getMaxUpdateInterval() {
return maxUpdateInterval;
}
public DvkOrganizationsCacheingUpdateStrategy setMaxUpdateInterval(int maxUpdateInterval) {
this.maxUpdateInterval = maxUpdateInterval;
return this;
}
public int getTimeUnit() {
return timeUnit;
}
/**
* @param timeUnit must be Calendar field(i.e. Calendar.MINUTE)
* @return
*/
public DvkOrganizationsCacheingUpdateStrategy setTimeUnit(int timeUnit) {
this.timeUnit = timeUnit;
return this;
}
public void setLastUpdated(Calendar date) {
if (log.isDebugEnabled()) {
log.debug("cache updated at: " + (new SimpleDateFormat().format(date.getTime())));
}
this.lastUpdated = date;
}
// END: Getters / setters
}
public interface ReceivedDocumentsWrapper extends Map<String, ReceivedDocumentsWrapper.ReceivedDocument>, Iterable<String> {
public Iterator<String> iterator();
public Set<Entry<String, ReceivedDocument>> entrySet();
public Map<String, ReceivedDocument> getDhlDocumentsMap();
public List<DhlDokumentType> getReceivedDocuments();
public interface ReceivedDocument {
public DhlDokumentType getDhlDocument();
public SignedDocType getSignedDoc();
public MetainfoHelper getMetaInfoHelper();
}
/**
* @return file that contains response (dhl:dokument elements from response attachment) if saving documents is enabled, null otherwise
*/
File getResponseDocumentsXml();
}
class ContentToSend {
private String fileName;
private String mimeType;
private InputStream inputStream;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
/**
* Helper class to work around parsing AnyType. <br>
* Convenience methods could be created to the subclasses as follows:
*
* <pre>
* public String getDhlId() {
* // DhlIdDocumentImpl.class is class for representing "dhl_id" xml-element.
* return getObject(DhlIdDocumentImpl.class).getDhlId();
* }
* </pre>
*
* @author ats.uiboupin
* @see http://www.ws-i.org/Profiles/BasicProfile-1.2.html#soapenc_Array
*/
class AnyTypeHelper {
private static Log log = LogFactory.getLog(AnyTypeHelper.class);
private final Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList;
public AnyTypeHelper(XmlObject xmlObject) {
subElementsList = parse(xmlObject); // NOPMD
}
protected Map<Class<? extends XmlObject>, List<? extends XmlObject>> parse(XmlObject xmlObject) {
if (log.isTraceEnabled()) {
log.trace("starting to parse xmlObject:\n" + xmlObject + "\n\n");
}
XmlCursor cursor = xmlObject.newCursor();
cursor.toFirstChild();// move before the root element
cursor.toFirstChild();// move to the first child of the root
Map<Class<? extends XmlObject>, List<? extends XmlObject>> subElementsList = new HashMap<Class<? extends XmlObject>, List<? extends XmlObject>>();
try {
do {
XmlObject object = XmlObject.Factory.parse(cursor.getDomNode());
@SuppressWarnings("unchecked")
// to be able to add object that is in fact a subclass of XmlObject, but referenced using XmlObject
List<XmlObject> list = (List<XmlObject>) subElementsList.get(object.getClass());
if (list == null) {
list = new ArrayList<XmlObject>();
}
list.add(object);
subElementsList.put(object.getClass(), list);
log.debug("adding node: '" + cursor.getDomNode().getLocalName() + "' (" + cursor.getDomNode().getNamespaceURI()
+ "),\nclass: " + object.getClass() + ", cursor: \n" + object);
} while (cursor.toNextSibling());
} catch (XmlException e) {
throw new RuntimeException("Failed to parse xmlObject:\n" + xmlObject, e);
}
return subElementsList;
}
/**
* Low-level method to retrieve any subelement by class
*
* @param <T>
* @param clazz - class of the subelement
* @return subelement according to given class, null otherwise
*/
public <T> T getObject(Class<T> clazz) {
@SuppressWarnings("unchecked")
List<T> objects = (List<T>) subElementsList.get(clazz);
if (objects != null) {
return objects.get(0);
}
return null;
}
@SuppressWarnings("unchecked")
public <T> List<T> getObjects(Class<T> clazz) {
return (List<T>) subElementsList.get(clazz);
}
}
class MetainfoHelper extends AnyTypeHelper {
public MetainfoHelper(Metainfo metainfo) {
super(metainfo);
}
// START: Convenience methods to get values of subelements
// START: methods for the fields created AUTOMATICALLY by DVK
public String getDhlId() {
return getObject(DhlIdDocumentImpl.class).getDhlId();
}
public String getDhlSaatjaAsutuseNr() {
return getObject(DhlSaatjaAsutuseNrDocumentImpl.class).getDhlSaatjaAsutuseNr();
}
public String getDhlSaatjaAsutuseNimi() {
return getObject(DhlSaatjaAsutuseNimiDocumentImpl.class).getDhlSaatjaAsutuseNimi();
}
/**
* @return the time when DVK received the document
*/
public Calendar getDhlSaabumisAeg() {
return getObject(DhlSaabumisaegDocumentImpl.class).getDhlSaabumisaeg();
}
/**
* @return the time when DVK sent out the document
*/
public Calendar getDhlSaatmisAeg() {
return getObject(DhlSaatmisaegDocumentImpl.class).getDhlSaatmisaeg();
}
public String getDhlSaatjaEpost() {
final DhlSaatjaEpostDocumentImpl object = getObject(DhlSaatjaEpostDocumentImpl.class);
return object == null ? null : object.getDhlSaatjaEpost();
}
/**
* XXX: sarnaselt eelnevatele on võimalik kätte saada(automaatselt lisatavatest andmetest) veel näiteks:
* dhl_saabumisviis, dhl_saatmisviis, dhl_saatja_asutuse_nimi, dhl_saatja_isikukood, dhl_saaja_asutuse_nr, dhl_saaja_asutuse_nimi, dhl_saaja_isikukood,
* dhl_saaja_epost, dhl_kaust
*/
// END: methods for the fields created AUTOMATICALLY by DVK
// START: methods for the fields created MANUALLY by DVK
public String getKoostajaFailinimi() {
final KoostajaFailinimiDocumentImpl kfDoc = getObject(KoostajaFailinimiDocumentImpl.class);
if (null != kfDoc) {
return kfDoc.getKoostajaFailinimi().xmlText();
}
return null;
}
// END: methods for the fields created MANUALLY by DVK
// END: Convenience<SUF>
}
/**
* Wrapper(unchecked exception) for checked exception XRoadServiceConsumptionException
*
* @author Ats Uiboupin
*/
public class WrappedXRoadServiceConsumptionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WrappedXRoadServiceConsumptionException(XRoadServiceConsumptionException cause) {
super(resolveMessage(cause), cause);
}
@Override
public XRoadServiceConsumptionException getCause() {
return (XRoadServiceConsumptionException) super.getCause();
}
private static String resolveMessage(XRoadServiceConsumptionException e) {
return "Failed to execute xtee query " + e.getFullServiceName() + ". Fault(" + e.getFaultCode() + "): '" + e.getFaultString() + "'";
}
}
// START: getters/setters
GetDvkOrganizationsHelper getDvkOrganizationsHelper();
void setDvkOrganizationsHelper(GetDvkOrganizationsHelper dvkOrganizationsHelper);
// END: getters/setters
}
|
202776_2 | package com.wjs.schedule.component.cuckoo;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.wjs.schedule.bean.JobInfoBean;
import com.wjs.schedule.component.quartz.QuartzManage;
import com.wjs.schedule.dao.exec.CuckooJobDetailMapper;
import com.wjs.schedule.dao.exec.CuckooJobExecLogMapper;
import com.wjs.schedule.domain.exec.CuckooJobDetail;
import com.wjs.schedule.domain.exec.CuckooJobExecLog;
import com.wjs.schedule.enums.CuckooBooleanFlag;
import com.wjs.schedule.enums.CuckooJobExecStatus;
import com.wjs.schedule.enums.CuckooJobExecType;
import com.wjs.schedule.enums.CuckooJobStatus;
import com.wjs.schedule.exception.JobCanNotRunningException;
import com.wjs.schedule.exception.JobRunningErrorException;
import com.wjs.schedule.service.job.CuckooJobDependencyService;
import com.wjs.schedule.service.job.CuckooJobLogService;
import com.wjs.schedule.service.job.CuckooJobService;
import com.wjs.schedule.service.net.CuckooNetService;
import com.wjs.schedule.vo.job.CuckooClientJobExecResult;
@Component("cuckooJobExecutor")
public class CuckooJobExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(CuckooJobExecutor.class);
@Autowired
CuckooJobDetailMapper cuckooJobDetailMapper;
@Autowired
CuckooJobExecLogMapper cuckooJobExecLogsMapper;
@Autowired
CuckooNetService cuckooServerService;
@Autowired
CuckooJobDependencyService cuckooJobDependencyService;
@Autowired
CuckooJobLogService cuckooJobLogService;
@Autowired
CuckooJobService cuckooJobService;
@Autowired
QuartzManage quartzExec;
@Autowired
CuckooJobCallBack cuckooJobCallBack;
/**
* quartz任务执行器
*
* @param jobId
* @param forceJob
* @param needTrigglerNext
* @param txdate
* @return 任务是否执行完成,如果是依赖关系没有结束(持续pending),返回false,否则不论成功失败,都返回true
* @throws JobCanNotRunningException
*/
@Transactional(propagation = Propagation.REQUIRED)
public boolean executeQuartzJob(CuckooJobExecLog jobLog) {
if (!CuckooJobExecStatus.PENDING.getValue().equals(jobLog.getExecJobStatus())) {
// 如果任务状态是非PENDING状态的,表示被用户修改过状态,此处记录ERROR日志。并且将当期Quartz丢弃(返回成功即可)
LOGGER.warn("invalid job exec status:{},jobLogInfo:{}", jobLog.getExecJobStatus(), jobLog);
return true;
}
if(checkJobCanRunning(jobLog)){
try {
executeJob(jobLog);
return true;
} catch (JobCanNotRunningException | JobRunningErrorException e) {
return false;
}
};
return false;
}
// 执行任务
private void executeJob(CuckooJobExecLog jobLog) throws JobCanNotRunningException, JobRunningErrorException {
LOGGER.info("job start execjob,jobLog:{}", jobLog);
String remark = "";
JobInfoBean jobBean = new JobInfoBean();
// 初始化执行日志
try {
// 查询远程执行器-- 考虑负载均衡 ,如果可执行客户端没有的话,放到数据库队列里面去。用于客户端重连等操作完成后操作
// CuckooNetClientInfo cuckooNetClientInfo = cuckooServerService.getExecNetClientInfo(jobLog.getJobId());
jobLog.setJobExecTime(System.currentTimeMillis());
// 调用日志执行单元(远程调用)
jobBean.setFlowCurrTime(jobLog.getFlowCurTime());
jobBean.setFlowLastTime(jobLog.getFlowLastTime());
jobBean.setJobId(jobLog.getJobId());
jobBean.setExecType(CuckooJobExecType.fromName(jobLog.getExecJobType()));
jobBean.setTypeDaily(CuckooBooleanFlag.YES.getValue().equals(jobLog.getTypeDaily()));
jobBean.setJobClassApplication(jobLog.getJobClassApplication());
jobBean.setJobName(jobLog.getJobName());
jobBean.setTxDate(jobLog.getTxDate());
jobBean.setJobLogId(jobLog.getId());
jobBean.setCuckooParallelJobArgs(jobLog.getCuckooParallelJobArgs());
jobBean.setNeedTrigglerNext(jobLog.getNeedTriggleNext());
jobLog.setExecJobStatus(CuckooJobExecStatus.RUNNING.getValue());
cuckooJobLogService.updateJobLogByPk(jobLog);
// cuckooJobExecLogsMapper.lockByPrimaryKey(jobLog.getId());
CuckooClientJobExecResult remoteExecutor = cuckooServerService.execRemoteJob(jobBean);
remark = remoteExecutor.getRemark();
LOGGER.info("job start running,remark:{},logInfo:{}", remark, jobLog);
// 插入执行日志
jobBean.setMessage(remark.length() > 490 ? remark.substring(0, 490) : remark);
// // 检查并触发下级任务
// cuckooJobCallBack.execJobSuccedCallBack(jobBean);
} catch (JobRunningErrorException e) {
// 未知异常,报错处理
remark = e.getMessage();
LOGGER.error("running err job exec,err:{},jobInfo:{}", e.getMessage(), jobLog);
// 插入执行日志
jobBean.setMessage(remark.length() > 490 ? remark.substring(0, 490) : remark);
cuckooJobCallBack.execJobFailedCallBack(jobBean);
} catch (JobCanNotRunningException e) {
remark = e.getMessage();
LOGGER.error("cannot running job exec,err:{},jobInfo:{}", e.getMessage(), jobLog);
// 插入执行日志
jobLog.setRemark(remark.length() > 490 ? remark.substring(0, 490) : remark);
jobLog.setExecJobStatus(CuckooJobExecStatus.PENDING.getValue());
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
throw e;
}catch (Exception e) {
remark = e.getMessage();
LOGGER.error("cannot running job exec,err:{},jobInfo:{}", e.getMessage(), jobLog, e);
// 插入执行日志
jobBean.setMessage(remark.length() > 490 ? remark.substring(0, 490) : remark);
throw e;
// cuckooJobCallBack.execJobFailedCallBack(jobBean);
}
}
// /**
// * 当前任务触发
// * @param jobInfoBean
// */
// public void executeCurJob(JobInfoBean jobInfoBean) {
//
// if(null == jobInfoBean){
// return;
// }
// // 根据jobInfoBean查询当前任务
// CuckooJobDetail jobInfoNext = cuckooJobService.getJobById(jobInfoBean.getJobId());
// JobDataMap data = new JobDataMap();
// data.put(CuckooJobConstant.DAILY_JOB_TXDATE, jobInfoBean.getTxDate());
// data.put(CuckooJobConstant.FLOW_JOB_END_TIME, jobInfoBean.getFlowCurrTime());
// data.put(CuckooJobConstant.FLOW_JOB_START_TIME, jobInfoBean.getFlowLastTime());
// data.put(CuckooJobConstant.NEED_TRIGGLE_NEXT, jobInfoBean.getNeedTrigglerNext());
// // 获取job性质
// if (checkJobDependency(jobInfoNext, data)) {
//
// executeJob(jobInfoNext, data);
// }
// }
/**
* 下级任务触发,调用任务执行功能
* @param jobInfo
*/
@Async
@Transactional(propagation = Propagation.REQUIRED)
public void executeNextJob(JobInfoBean jobInfoBean) {
CuckooJobExecLog jobLog = cuckooJobExecLogsMapper.selectByPrimaryKey(jobInfoBean.getJobLogId());
// 根据jobInfoBean查询下一个任务
List<CuckooJobDetail> jobInfoNexts = cuckooJobService.getNextJobById(jobLog.getJobId());
if(CollectionUtils.isNotEmpty(jobInfoNexts)){
for (CuckooJobDetail cuckooJobDetail : jobInfoNexts) {
LOGGER.info("trigger next job:{}, father joblog:{}", cuckooJobDetail , jobLog );
// 强制执行属性,不继承
jobLog.setForceTriggle(false);
// 判断任务类型,修改任务状态为PENDING,放入到PENDING任务队列中
if(cuckooJobDependencyService.checkDepedencyJobFinished(cuckooJobDetail,jobLog)){
cuckooJobService.pendingJob(cuckooJobDetail, jobLog);
}
}
}
}
private boolean checkJobCanRunning(CuckooJobExecLog jobLog){
// 查询任务信息
CuckooJobDetail jobInfo = cuckooJobDetailMapper.selectByPrimaryKey(jobLog.getJobId());
if(jobLog.getForceTriggle()){
// 强制执行的任务(手工调度),不需要校验
return true;
}else{
// 非强制执行的任务(手工调度),状态为暂停,等待下次调度
if (CuckooJobStatus.PAUSE.getValue().equals(jobInfo.getJobStatus())) {
LOGGER.debug("job is paush,triggle next time, jobInfo:{}", jobInfo);
jobLog.setRemark("job is paush,triggle next time");
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
return false;
}
// 检查日志中,上一次执行任务(txdate/latest_time倒叙)未执行成功,那么当前任务不能执行
if(!cuckooJobLogService.checkPreLogIsDone(jobLog)){
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
return false;
}
if(!cuckooJobDependencyService.checkDepedencyJobFinished(jobLog)){
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
return false;
}
// 校验任务依赖状态
return true;
}
}
}
| suyin58/cuckoo-schedule | schedule-admin/src/main/java/com/wjs/schedule/component/cuckoo/CuckooJobExecutor.java | 2,681 | // CuckooNetClientInfo cuckooNetClientInfo = cuckooServerService.getExecNetClientInfo(jobLog.getJobId()); | line_comment | nl | package com.wjs.schedule.component.cuckoo;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.wjs.schedule.bean.JobInfoBean;
import com.wjs.schedule.component.quartz.QuartzManage;
import com.wjs.schedule.dao.exec.CuckooJobDetailMapper;
import com.wjs.schedule.dao.exec.CuckooJobExecLogMapper;
import com.wjs.schedule.domain.exec.CuckooJobDetail;
import com.wjs.schedule.domain.exec.CuckooJobExecLog;
import com.wjs.schedule.enums.CuckooBooleanFlag;
import com.wjs.schedule.enums.CuckooJobExecStatus;
import com.wjs.schedule.enums.CuckooJobExecType;
import com.wjs.schedule.enums.CuckooJobStatus;
import com.wjs.schedule.exception.JobCanNotRunningException;
import com.wjs.schedule.exception.JobRunningErrorException;
import com.wjs.schedule.service.job.CuckooJobDependencyService;
import com.wjs.schedule.service.job.CuckooJobLogService;
import com.wjs.schedule.service.job.CuckooJobService;
import com.wjs.schedule.service.net.CuckooNetService;
import com.wjs.schedule.vo.job.CuckooClientJobExecResult;
@Component("cuckooJobExecutor")
public class CuckooJobExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(CuckooJobExecutor.class);
@Autowired
CuckooJobDetailMapper cuckooJobDetailMapper;
@Autowired
CuckooJobExecLogMapper cuckooJobExecLogsMapper;
@Autowired
CuckooNetService cuckooServerService;
@Autowired
CuckooJobDependencyService cuckooJobDependencyService;
@Autowired
CuckooJobLogService cuckooJobLogService;
@Autowired
CuckooJobService cuckooJobService;
@Autowired
QuartzManage quartzExec;
@Autowired
CuckooJobCallBack cuckooJobCallBack;
/**
* quartz任务执行器
*
* @param jobId
* @param forceJob
* @param needTrigglerNext
* @param txdate
* @return 任务是否执行完成,如果是依赖关系没有结束(持续pending),返回false,否则不论成功失败,都返回true
* @throws JobCanNotRunningException
*/
@Transactional(propagation = Propagation.REQUIRED)
public boolean executeQuartzJob(CuckooJobExecLog jobLog) {
if (!CuckooJobExecStatus.PENDING.getValue().equals(jobLog.getExecJobStatus())) {
// 如果任务状态是非PENDING状态的,表示被用户修改过状态,此处记录ERROR日志。并且将当期Quartz丢弃(返回成功即可)
LOGGER.warn("invalid job exec status:{},jobLogInfo:{}", jobLog.getExecJobStatus(), jobLog);
return true;
}
if(checkJobCanRunning(jobLog)){
try {
executeJob(jobLog);
return true;
} catch (JobCanNotRunningException | JobRunningErrorException e) {
return false;
}
};
return false;
}
// 执行任务
private void executeJob(CuckooJobExecLog jobLog) throws JobCanNotRunningException, JobRunningErrorException {
LOGGER.info("job start execjob,jobLog:{}", jobLog);
String remark = "";
JobInfoBean jobBean = new JobInfoBean();
// 初始化执行日志
try {
// 查询远程执行器-- 考虑负载均衡 ,如果可执行客户端没有的话,放到数据库队列里面去。用于客户端重连等操作完成后操作
// CuckooNetClientInfo cuckooNetClientInfo<SUF>
jobLog.setJobExecTime(System.currentTimeMillis());
// 调用日志执行单元(远程调用)
jobBean.setFlowCurrTime(jobLog.getFlowCurTime());
jobBean.setFlowLastTime(jobLog.getFlowLastTime());
jobBean.setJobId(jobLog.getJobId());
jobBean.setExecType(CuckooJobExecType.fromName(jobLog.getExecJobType()));
jobBean.setTypeDaily(CuckooBooleanFlag.YES.getValue().equals(jobLog.getTypeDaily()));
jobBean.setJobClassApplication(jobLog.getJobClassApplication());
jobBean.setJobName(jobLog.getJobName());
jobBean.setTxDate(jobLog.getTxDate());
jobBean.setJobLogId(jobLog.getId());
jobBean.setCuckooParallelJobArgs(jobLog.getCuckooParallelJobArgs());
jobBean.setNeedTrigglerNext(jobLog.getNeedTriggleNext());
jobLog.setExecJobStatus(CuckooJobExecStatus.RUNNING.getValue());
cuckooJobLogService.updateJobLogByPk(jobLog);
// cuckooJobExecLogsMapper.lockByPrimaryKey(jobLog.getId());
CuckooClientJobExecResult remoteExecutor = cuckooServerService.execRemoteJob(jobBean);
remark = remoteExecutor.getRemark();
LOGGER.info("job start running,remark:{},logInfo:{}", remark, jobLog);
// 插入执行日志
jobBean.setMessage(remark.length() > 490 ? remark.substring(0, 490) : remark);
// // 检查并触发下级任务
// cuckooJobCallBack.execJobSuccedCallBack(jobBean);
} catch (JobRunningErrorException e) {
// 未知异常,报错处理
remark = e.getMessage();
LOGGER.error("running err job exec,err:{},jobInfo:{}", e.getMessage(), jobLog);
// 插入执行日志
jobBean.setMessage(remark.length() > 490 ? remark.substring(0, 490) : remark);
cuckooJobCallBack.execJobFailedCallBack(jobBean);
} catch (JobCanNotRunningException e) {
remark = e.getMessage();
LOGGER.error("cannot running job exec,err:{},jobInfo:{}", e.getMessage(), jobLog);
// 插入执行日志
jobLog.setRemark(remark.length() > 490 ? remark.substring(0, 490) : remark);
jobLog.setExecJobStatus(CuckooJobExecStatus.PENDING.getValue());
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
throw e;
}catch (Exception e) {
remark = e.getMessage();
LOGGER.error("cannot running job exec,err:{},jobInfo:{}", e.getMessage(), jobLog, e);
// 插入执行日志
jobBean.setMessage(remark.length() > 490 ? remark.substring(0, 490) : remark);
throw e;
// cuckooJobCallBack.execJobFailedCallBack(jobBean);
}
}
// /**
// * 当前任务触发
// * @param jobInfoBean
// */
// public void executeCurJob(JobInfoBean jobInfoBean) {
//
// if(null == jobInfoBean){
// return;
// }
// // 根据jobInfoBean查询当前任务
// CuckooJobDetail jobInfoNext = cuckooJobService.getJobById(jobInfoBean.getJobId());
// JobDataMap data = new JobDataMap();
// data.put(CuckooJobConstant.DAILY_JOB_TXDATE, jobInfoBean.getTxDate());
// data.put(CuckooJobConstant.FLOW_JOB_END_TIME, jobInfoBean.getFlowCurrTime());
// data.put(CuckooJobConstant.FLOW_JOB_START_TIME, jobInfoBean.getFlowLastTime());
// data.put(CuckooJobConstant.NEED_TRIGGLE_NEXT, jobInfoBean.getNeedTrigglerNext());
// // 获取job性质
// if (checkJobDependency(jobInfoNext, data)) {
//
// executeJob(jobInfoNext, data);
// }
// }
/**
* 下级任务触发,调用任务执行功能
* @param jobInfo
*/
@Async
@Transactional(propagation = Propagation.REQUIRED)
public void executeNextJob(JobInfoBean jobInfoBean) {
CuckooJobExecLog jobLog = cuckooJobExecLogsMapper.selectByPrimaryKey(jobInfoBean.getJobLogId());
// 根据jobInfoBean查询下一个任务
List<CuckooJobDetail> jobInfoNexts = cuckooJobService.getNextJobById(jobLog.getJobId());
if(CollectionUtils.isNotEmpty(jobInfoNexts)){
for (CuckooJobDetail cuckooJobDetail : jobInfoNexts) {
LOGGER.info("trigger next job:{}, father joblog:{}", cuckooJobDetail , jobLog );
// 强制执行属性,不继承
jobLog.setForceTriggle(false);
// 判断任务类型,修改任务状态为PENDING,放入到PENDING任务队列中
if(cuckooJobDependencyService.checkDepedencyJobFinished(cuckooJobDetail,jobLog)){
cuckooJobService.pendingJob(cuckooJobDetail, jobLog);
}
}
}
}
private boolean checkJobCanRunning(CuckooJobExecLog jobLog){
// 查询任务信息
CuckooJobDetail jobInfo = cuckooJobDetailMapper.selectByPrimaryKey(jobLog.getJobId());
if(jobLog.getForceTriggle()){
// 强制执行的任务(手工调度),不需要校验
return true;
}else{
// 非强制执行的任务(手工调度),状态为暂停,等待下次调度
if (CuckooJobStatus.PAUSE.getValue().equals(jobInfo.getJobStatus())) {
LOGGER.debug("job is paush,triggle next time, jobInfo:{}", jobInfo);
jobLog.setRemark("job is paush,triggle next time");
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
return false;
}
// 检查日志中,上一次执行任务(txdate/latest_time倒叙)未执行成功,那么当前任务不能执行
if(!cuckooJobLogService.checkPreLogIsDone(jobLog)){
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
return false;
}
if(!cuckooJobDependencyService.checkDepedencyJobFinished(jobLog)){
cuckooJobExecLogsMapper.updateByPrimaryKeySelective(jobLog);
return false;
}
// 校验任务依赖状态
return true;
}
}
}
|
202793_45 | package TakistusjooksFX;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Maie on 29/10/2016.
*/
public class Katse2 extends Application {
public ArrayList<Rectangle> platvormid = new ArrayList(); // ArrayList, mis hoiab kõik mängulaua elemendid, v.a mängija
public Pane appRoot = new Pane(); // appRoot'is toimub kogu liikumine
public Pane gameRoot = new Pane(); // gameRootis' on kõik mängu elemendid (mängija+level)
public int manguLaius; // Teeb kindlaks ühe leveli laiuse
public int maxLaius;
public String rida;
public double grav; // Gravitatsioonikonstant
public boolean jumping = false; // Topelthüpe keelatud ehk mängija hüppab korra ja järgmine hüpe on lubatud pärast esimese hüppe lõppu
public Rectangle taust = new Rectangle(600, 400); // Taust ehk must ruut
private Rectangle tekitaRuut(int x, int y, int w, int h, Color color) { //Programmisisene meetod elementide loomiseks (kõik ruudud)
Rectangle ruut = new Rectangle(w, h);
ruut.setTranslateX(x); //Seab paika koordinaadid tekkinud ruudule
ruut.setTranslateY(y);
ruut.setFill(color); //Annab ruudule värvi
gameRoot.getChildren().addAll(ruut); //Tekkinud ruudud pannakse gameRoot'i ehk Pane'i, kus on kõik elemendid
return ruut;
}
public void manguSisu() { //Meetod, mis genereerib terve leveli ette antud andmetest (LevelData) (Almas Baimagambetov:
// https://github.com/AlmasB/FXTutorials/blob/master/src/com/almasb/tutorial14/Main.java)
manguLaius = LevelData.LVL1[0].length(); //Mängu laiuseks võta LevelData's oleva stringi ühe "sõna" pikkuse
maxLaius = LevelData.LVL1.length;
for (int i = 0; i < maxLaius; i++) { //Käi läbi iga rida
rida = LevelData.LVL1[i]; //Muuda iga "sõna" sees olev täht eraldi stringiks (muidu asi ei tööta)
for (int j = 0; j < rida.length(); j++) { //Käi läbi iga loodud string
switch (rida.charAt(j)) {
case '0': //Kui on "0", siis ära tee midagi.
break;
case '1': //Kui on "1", siis tekita ruut meetodi tekitaRuut abil
Rectangle platvorm = tekitaRuut(j * 50, i * 50, 50, 50, Color.BLUE);
platvormid.add(platvorm); //Lisa tekkinud platvorm ArrayListi platvormid
break;
}
}
}
appRoot.getChildren().addAll(taust, gameRoot); //Pane kogu krempel kõige peamisele Pane'ile ehk sellele, kus toimub liikumine (appRoot)
}
Rectangle mangija = tekitaRuut(100, 200, 30, 30, Color.WHITE); //Tekita mängija ruut
private void taustLiigub() { //Meetod, mis paneb tausta vasakult paremale liikuma (liigub gameRoot)
double scrollSpeed = -3; //Liikumise kiirus
double taustParemale = gameRoot.getLayoutX() + scrollSpeed; //Võta gameRoot X asukoha ja lisa juurde liikumine
gameRoot.setLayoutX(taustParemale); //Sea uueks gameRoot X-telje asukohaks tekkinud arv
}
public void gravity(boolean isHitting) { //Mängija kukub pidevalt allapoole (sõbra abi - Jason Parks)
if (isHitting && grav == 0) {
return;
}
double mangijaY = mangija.getTranslateY(); //Leia mängija asukoht Y-teljel
grav = grav + 0.1; //Gravity ehk mida kõrgemalt kukub, seda kõrgem väärtus
double uusMangijaY = mangijaY + grav; //Leia mängija asukoht Y-teljel koos gravitatsiooniga
mangija.setTranslateY(uusMangijaY); //Sea mängija uueks Y-koordinaadiks leitud asukoht
}
public void playerMove(boolean isHitting) { //Mängija liigutamine (sõbra abi - Jason Parks)
if (!isHitting) { //Kui kokkupõrget pole, siis liiguta mängijat edasi
mangija.setTranslateX(mangija.getTranslateX() + 3);
}
}
public boolean verticalHitDetection() { //Kukub platvormile ja jääb püsima (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getBoundsInParent().intersects(platvorm.getBoundsInParent())) { //Kui mängija asukoht ristub platvormiga...
if (grav != -4 && grav != 0) { //Kui gravitatsioon ei ole -4 (ehk ei toimu hüpet) ja see ei ole 0 (ehk mängija ei seisa platvormil,
grav = 0; //siis lülita gravitatsioon välja ja
jumping = false; //(Hüpe false ehk topelthüpet ei saa teha)
mangija.setTranslateY(platvorm.getTranslateY() - mangija.getHeight()); //sea mängija asukohaks platvorm + mängija kõrgus ehk platvormi kohale
}
return true; //Ülalnimetatud tegevuste tulemuseks määra meetodi tõeseks ehk kokkupõrge toimus
}
}
return false; //Kui kokkupõrget ei toimunud, siis määra meetod mittetõeseks
}
public boolean horizontalHitDetection() { //Läheb vastu platvormi ja ei sõida sisse (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getTranslateX() + mangija.getWidth() > platvorm.getTranslateX() //Kui mängija ei asu platvormi piires ehk mängija vasak külg + laius on suuremad
&& mangija.getTranslateX() + mangija.getWidth() < platvorm.getTranslateX() + platvorm.getWidth()) { //platvormi vasakust ja paremast küljest
//System.out.println("hit a platform " + platvorm.getTranslateX() + " " + platvorm.getTranslateY());
//System.out.println("" + mangija.getTranslateY() + " " + (platvorm.getTranslateY() - mangija.getHeight()));
if (mangija.getTranslateY() > platvorm.getTranslateY() - mangija.getHeight()) { //Kui samal ajal mängija Y-koordinaat on suurem platvormi Y-koordinaadist - mängija kõrgus
//System.out.println("ouch"); //ehk mängija on platvormi kohal,
return true; //siis määra meetodi tõeseks ehk kokkupõrge toimus (mööda X-telge)
}
}
}
return false; //Vastasel juhul on meetod mittetõene ehk kokkupõrget ei toimunud.
}
@Override
public void start(Stage primaryStage) throws Exception {
manguSisu(); //Genereeri mängu sisu ehk lae level.
Scene esimene = new Scene(appRoot); //Akna tegemine ja appRoot näitamine
primaryStage.setTitle("Napikas: The Game");
primaryStage.setScene(esimene);
primaryStage.show();
VBox akenEnd = new VBox(); //Death screen (Tehtud docs.oracle.com juhendi järgi)
Button uuesti = new Button("Uuesti?");
uuesti.setStyle("-fx-font-size: 21pt;"); //Nupu suurus (teksti suurus)
akenEnd.setStyle("-fx-background-color:RED");
akenEnd.getChildren().add(uuesti);
akenEnd.setAlignment(Pos.CENTER); //Seab nupu keskele
Scene teine = new Scene(akenEnd, 600, 400);
VBox congratsAken = new VBox(); //Lõpusõnum
Text congratsT = new Text("See oli küll napikas!!!");
congratsT.setStyle("-fx-font-size: 40pt;");
congratsAken.getChildren().addAll(congratsT);
congratsAken.setAlignment(Pos.CENTER);
Scene kolmas = new Scene(congratsAken, 600, 400);
AnimationTimer timer = new AnimationTimer() { //Kogu liikumine, mis mängus toimub.
@Override
public void handle(long now) {
boolean isHorizontalHitting = horizontalHitDetection();
playerMove(isHorizontalHitting);
boolean isHitting = verticalHitDetection();
gravity(isHitting);
taustLiigub();
if (mangija.getTranslateY() > appRoot.getTranslateY() + 400) { //Kui mängija kukub alla, siis näita Death Screen
primaryStage.setScene(teine);
}
if (mangija.getTranslateX() > (manguLaius + 5) * 50){ //kui mängija jõuab lõppu + 1 ruut, siis näita lõpusõnumit
primaryStage.setScene(kolmas);
}
}
};timer.start();
{
esimene.setOnKeyPressed(event -> { //Hüppamine (sõbra abi - Jason Parks)
if (event.getCode() == KeyCode.SPACE && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
} else if (event.getCode() == KeyCode.UP && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
}
});
uuesti.setOnAction(event -> { //Death screen nupp -> reset game
mangija.setTranslateX(100);
mangija.setTranslateY(100);
gameRoot.setLayoutX(0);
primaryStage.setScene(esimene);
});
}
}
} | mpalmeos/TakistusjooksFX | Katse2.java | 2,816 | //System.out.println("" + mangija.getTranslateY() + " " + (platvorm.getTranslateY() - mangija.getHeight())); | line_comment | nl | package TakistusjooksFX;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Maie on 29/10/2016.
*/
public class Katse2 extends Application {
public ArrayList<Rectangle> platvormid = new ArrayList(); // ArrayList, mis hoiab kõik mängulaua elemendid, v.a mängija
public Pane appRoot = new Pane(); // appRoot'is toimub kogu liikumine
public Pane gameRoot = new Pane(); // gameRootis' on kõik mängu elemendid (mängija+level)
public int manguLaius; // Teeb kindlaks ühe leveli laiuse
public int maxLaius;
public String rida;
public double grav; // Gravitatsioonikonstant
public boolean jumping = false; // Topelthüpe keelatud ehk mängija hüppab korra ja järgmine hüpe on lubatud pärast esimese hüppe lõppu
public Rectangle taust = new Rectangle(600, 400); // Taust ehk must ruut
private Rectangle tekitaRuut(int x, int y, int w, int h, Color color) { //Programmisisene meetod elementide loomiseks (kõik ruudud)
Rectangle ruut = new Rectangle(w, h);
ruut.setTranslateX(x); //Seab paika koordinaadid tekkinud ruudule
ruut.setTranslateY(y);
ruut.setFill(color); //Annab ruudule värvi
gameRoot.getChildren().addAll(ruut); //Tekkinud ruudud pannakse gameRoot'i ehk Pane'i, kus on kõik elemendid
return ruut;
}
public void manguSisu() { //Meetod, mis genereerib terve leveli ette antud andmetest (LevelData) (Almas Baimagambetov:
// https://github.com/AlmasB/FXTutorials/blob/master/src/com/almasb/tutorial14/Main.java)
manguLaius = LevelData.LVL1[0].length(); //Mängu laiuseks võta LevelData's oleva stringi ühe "sõna" pikkuse
maxLaius = LevelData.LVL1.length;
for (int i = 0; i < maxLaius; i++) { //Käi läbi iga rida
rida = LevelData.LVL1[i]; //Muuda iga "sõna" sees olev täht eraldi stringiks (muidu asi ei tööta)
for (int j = 0; j < rida.length(); j++) { //Käi läbi iga loodud string
switch (rida.charAt(j)) {
case '0': //Kui on "0", siis ära tee midagi.
break;
case '1': //Kui on "1", siis tekita ruut meetodi tekitaRuut abil
Rectangle platvorm = tekitaRuut(j * 50, i * 50, 50, 50, Color.BLUE);
platvormid.add(platvorm); //Lisa tekkinud platvorm ArrayListi platvormid
break;
}
}
}
appRoot.getChildren().addAll(taust, gameRoot); //Pane kogu krempel kõige peamisele Pane'ile ehk sellele, kus toimub liikumine (appRoot)
}
Rectangle mangija = tekitaRuut(100, 200, 30, 30, Color.WHITE); //Tekita mängija ruut
private void taustLiigub() { //Meetod, mis paneb tausta vasakult paremale liikuma (liigub gameRoot)
double scrollSpeed = -3; //Liikumise kiirus
double taustParemale = gameRoot.getLayoutX() + scrollSpeed; //Võta gameRoot X asukoha ja lisa juurde liikumine
gameRoot.setLayoutX(taustParemale); //Sea uueks gameRoot X-telje asukohaks tekkinud arv
}
public void gravity(boolean isHitting) { //Mängija kukub pidevalt allapoole (sõbra abi - Jason Parks)
if (isHitting && grav == 0) {
return;
}
double mangijaY = mangija.getTranslateY(); //Leia mängija asukoht Y-teljel
grav = grav + 0.1; //Gravity ehk mida kõrgemalt kukub, seda kõrgem väärtus
double uusMangijaY = mangijaY + grav; //Leia mängija asukoht Y-teljel koos gravitatsiooniga
mangija.setTranslateY(uusMangijaY); //Sea mängija uueks Y-koordinaadiks leitud asukoht
}
public void playerMove(boolean isHitting) { //Mängija liigutamine (sõbra abi - Jason Parks)
if (!isHitting) { //Kui kokkupõrget pole, siis liiguta mängijat edasi
mangija.setTranslateX(mangija.getTranslateX() + 3);
}
}
public boolean verticalHitDetection() { //Kukub platvormile ja jääb püsima (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getBoundsInParent().intersects(platvorm.getBoundsInParent())) { //Kui mängija asukoht ristub platvormiga...
if (grav != -4 && grav != 0) { //Kui gravitatsioon ei ole -4 (ehk ei toimu hüpet) ja see ei ole 0 (ehk mängija ei seisa platvormil,
grav = 0; //siis lülita gravitatsioon välja ja
jumping = false; //(Hüpe false ehk topelthüpet ei saa teha)
mangija.setTranslateY(platvorm.getTranslateY() - mangija.getHeight()); //sea mängija asukohaks platvorm + mängija kõrgus ehk platvormi kohale
}
return true; //Ülalnimetatud tegevuste tulemuseks määra meetodi tõeseks ehk kokkupõrge toimus
}
}
return false; //Kui kokkupõrget ei toimunud, siis määra meetod mittetõeseks
}
public boolean horizontalHitDetection() { //Läheb vastu platvormi ja ei sõida sisse (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getTranslateX() + mangija.getWidth() > platvorm.getTranslateX() //Kui mängija ei asu platvormi piires ehk mängija vasak külg + laius on suuremad
&& mangija.getTranslateX() + mangija.getWidth() < platvorm.getTranslateX() + platvorm.getWidth()) { //platvormi vasakust ja paremast küljest
//System.out.println("hit a platform " + platvorm.getTranslateX() + " " + platvorm.getTranslateY());
//System.out.println("" +<SUF>
if (mangija.getTranslateY() > platvorm.getTranslateY() - mangija.getHeight()) { //Kui samal ajal mängija Y-koordinaat on suurem platvormi Y-koordinaadist - mängija kõrgus
//System.out.println("ouch"); //ehk mängija on platvormi kohal,
return true; //siis määra meetodi tõeseks ehk kokkupõrge toimus (mööda X-telge)
}
}
}
return false; //Vastasel juhul on meetod mittetõene ehk kokkupõrget ei toimunud.
}
@Override
public void start(Stage primaryStage) throws Exception {
manguSisu(); //Genereeri mängu sisu ehk lae level.
Scene esimene = new Scene(appRoot); //Akna tegemine ja appRoot näitamine
primaryStage.setTitle("Napikas: The Game");
primaryStage.setScene(esimene);
primaryStage.show();
VBox akenEnd = new VBox(); //Death screen (Tehtud docs.oracle.com juhendi järgi)
Button uuesti = new Button("Uuesti?");
uuesti.setStyle("-fx-font-size: 21pt;"); //Nupu suurus (teksti suurus)
akenEnd.setStyle("-fx-background-color:RED");
akenEnd.getChildren().add(uuesti);
akenEnd.setAlignment(Pos.CENTER); //Seab nupu keskele
Scene teine = new Scene(akenEnd, 600, 400);
VBox congratsAken = new VBox(); //Lõpusõnum
Text congratsT = new Text("See oli küll napikas!!!");
congratsT.setStyle("-fx-font-size: 40pt;");
congratsAken.getChildren().addAll(congratsT);
congratsAken.setAlignment(Pos.CENTER);
Scene kolmas = new Scene(congratsAken, 600, 400);
AnimationTimer timer = new AnimationTimer() { //Kogu liikumine, mis mängus toimub.
@Override
public void handle(long now) {
boolean isHorizontalHitting = horizontalHitDetection();
playerMove(isHorizontalHitting);
boolean isHitting = verticalHitDetection();
gravity(isHitting);
taustLiigub();
if (mangija.getTranslateY() > appRoot.getTranslateY() + 400) { //Kui mängija kukub alla, siis näita Death Screen
primaryStage.setScene(teine);
}
if (mangija.getTranslateX() > (manguLaius + 5) * 50){ //kui mängija jõuab lõppu + 1 ruut, siis näita lõpusõnumit
primaryStage.setScene(kolmas);
}
}
};timer.start();
{
esimene.setOnKeyPressed(event -> { //Hüppamine (sõbra abi - Jason Parks)
if (event.getCode() == KeyCode.SPACE && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
} else if (event.getCode() == KeyCode.UP && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
}
});
uuesti.setOnAction(event -> { //Death screen nupp -> reset game
mangija.setTranslateX(100);
mangija.setTranslateY(100);
gameRoot.setLayoutX(0);
primaryStage.setScene(esimene);
});
}
}
} |
202872_33 | /*
* Copyright 2016 The gRPC Authors
*
* 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 io.grpc.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.MoreExecutors;
import io.grpc.Status;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
/**
* Manages keepalive pings.
*/
public class KeepAliveManager {
private static final long MIN_KEEPALIVE_TIME_NANOS = TimeUnit.SECONDS.toNanos(10);
private static final long MIN_KEEPALIVE_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(10L);
private final ScheduledExecutorService scheduler;
@GuardedBy("this")
private final Stopwatch stopwatch;
private final KeepAlivePinger keepAlivePinger;
private final boolean keepAliveDuringTransportIdle;
@GuardedBy("this")
private State state = State.IDLE;
@GuardedBy("this")
private ScheduledFuture<?> shutdownFuture;
@GuardedBy("this")
private ScheduledFuture<?> pingFuture;
private final Runnable shutdown = new LogExceptionRunnable(new Runnable() {
@Override
public void run() {
boolean shouldShutdown = false;
synchronized (KeepAliveManager.this) {
if (state != State.DISCONNECTED) {
// We haven't received a ping response within the timeout. The connection is likely gone
// already. Shutdown the transport and fail all existing rpcs.
state = State.DISCONNECTED;
shouldShutdown = true;
}
}
if (shouldShutdown) {
keepAlivePinger.onPingTimeout();
}
}
});
private final Runnable sendPing = new LogExceptionRunnable(new Runnable() {
@Override
public void run() {
boolean shouldSendPing = false;
synchronized (KeepAliveManager.this) {
pingFuture = null;
if (state == State.PING_SCHEDULED) {
shouldSendPing = true;
state = State.PING_SENT;
// Schedule a shutdown. It fires if we don't receive the ping response within the timeout.
shutdownFuture = scheduler.schedule(shutdown, keepAliveTimeoutInNanos,
TimeUnit.NANOSECONDS);
} else if (state == State.PING_DELAYED) {
// We have received some data. Reschedule the ping with the new time.
pingFuture = scheduler.schedule(
sendPing,
keepAliveTimeInNanos - stopwatch.elapsed(TimeUnit.NANOSECONDS),
TimeUnit.NANOSECONDS);
state = State.PING_SCHEDULED;
}
}
if (shouldSendPing) {
// Send the ping.
keepAlivePinger.ping();
}
}
});
private final long keepAliveTimeInNanos;
private final long keepAliveTimeoutInNanos;
private enum State {
/*
* We don't need to do any keepalives. This means the transport has no active rpcs and
* keepAliveDuringTransportIdle == false.
*/
IDLE,
/*
* We have scheduled a ping to be sent in the future. We may decide to delay it if we receive
* some data.
*/
PING_SCHEDULED,
/*
* We need to delay the scheduled keepalive ping.
*/
PING_DELAYED,
/*
* The ping has been sent out. Waiting for a ping response.
*/
PING_SENT,
/*
* Transport goes idle after ping has been sent.
*/
IDLE_AND_PING_SENT,
/*
* The transport has been disconnected. We won't do keepalives any more.
*/
DISCONNECTED,
}
/**
* Creates a KeepAliverManager.
*/
public KeepAliveManager(KeepAlivePinger keepAlivePinger, ScheduledExecutorService scheduler,
long keepAliveTimeInNanos, long keepAliveTimeoutInNanos,
boolean keepAliveDuringTransportIdle) {
this(keepAlivePinger, scheduler, Stopwatch.createUnstarted(), keepAliveTimeInNanos,
keepAliveTimeoutInNanos,
keepAliveDuringTransportIdle);
}
@VisibleForTesting
KeepAliveManager(KeepAlivePinger keepAlivePinger, ScheduledExecutorService scheduler,
Stopwatch stopwatch, long keepAliveTimeInNanos, long keepAliveTimeoutInNanos,
boolean keepAliveDuringTransportIdle) {
this.keepAlivePinger = checkNotNull(keepAlivePinger, "keepAlivePinger");
this.scheduler = checkNotNull(scheduler, "scheduler");
this.stopwatch = checkNotNull(stopwatch, "stopwatch");
this.keepAliveTimeInNanos = keepAliveTimeInNanos;
this.keepAliveTimeoutInNanos = keepAliveTimeoutInNanos;
this.keepAliveDuringTransportIdle = keepAliveDuringTransportIdle;
stopwatch.reset().start();
}
/** Start keepalive monitoring. */
public synchronized void onTransportStarted() {
if (keepAliveDuringTransportIdle) {
onTransportActive();
}
}
/**
* Transport has received some data so that we can delay sending keepalives.
*/
public synchronized void onDataReceived() {
stopwatch.reset().start();
// We do not cancel the ping future here. This avoids constantly scheduling and cancellation in
// a busy transport. Instead, we update the status here and reschedule later. So we actually
// keep one sendPing task always in flight when there're active rpcs.
if (state == State.PING_SCHEDULED) {
state = State.PING_DELAYED;
} else if (state == State.PING_SENT || state == State.IDLE_AND_PING_SENT) {
// Ping acked or effectively ping acked. Cancel shutdown, and then if not idle,
// schedule a new keep-alive ping.
if (shutdownFuture != null) {
shutdownFuture.cancel(false);
}
if (state == State.IDLE_AND_PING_SENT) {
// not to schedule new pings until onTransportActive
state = State.IDLE;
return;
}
// schedule a new ping
state = State.PING_SCHEDULED;
checkState(pingFuture == null, "There should be no outstanding pingFuture");
pingFuture = scheduler.schedule(sendPing, keepAliveTimeInNanos, TimeUnit.NANOSECONDS);
}
}
/**
* Transport has active streams. Start sending keepalives if necessary.
*/
public synchronized void onTransportActive() {
if (state == State.IDLE) {
// When the transport goes active, we do not reset the nextKeepaliveTime. This allows us to
// quickly check whether the connection is still working.
state = State.PING_SCHEDULED;
if (pingFuture == null) {
pingFuture = scheduler.schedule(
sendPing,
keepAliveTimeInNanos - stopwatch.elapsed(TimeUnit.NANOSECONDS),
TimeUnit.NANOSECONDS);
}
} else if (state == State.IDLE_AND_PING_SENT) {
state = State.PING_SENT;
} // Other states are possible when keepAliveDuringTransportIdle == true
}
/**
* Transport has finished all streams.
*/
public synchronized void onTransportIdle() {
if (keepAliveDuringTransportIdle) {
return;
}
if (state == State.PING_SCHEDULED || state == State.PING_DELAYED) {
state = State.IDLE;
}
if (state == State.PING_SENT) {
state = State.IDLE_AND_PING_SENT;
}
}
/**
* Transport is being terminated. We no longer need to do keepalives.
*/
public synchronized void onTransportTermination() {
if (state != State.DISCONNECTED) {
state = State.DISCONNECTED;
if (shutdownFuture != null) {
shutdownFuture.cancel(false);
}
if (pingFuture != null) {
pingFuture.cancel(false);
pingFuture = null;
}
}
}
/**
* Bumps keepalive time to 10 seconds if the specified value was smaller than that.
*/
public static long clampKeepAliveTimeInNanos(long keepAliveTimeInNanos) {
return Math.max(keepAliveTimeInNanos, MIN_KEEPALIVE_TIME_NANOS);
}
/**
* Bumps keepalive timeout to 10 milliseconds if the specified value was smaller than that.
*/
public static long clampKeepAliveTimeoutInNanos(long keepAliveTimeoutInNanos) {
return Math.max(keepAliveTimeoutInNanos, MIN_KEEPALIVE_TIMEOUT_NANOS);
}
public interface KeepAlivePinger {
/**
* Sends out a keep-alive ping.
*/
void ping();
/**
* Callback when Ping Ack was not received in KEEPALIVE_TIMEOUT. Should shutdown the transport.
*/
void onPingTimeout();
}
/**
* Default client side {@link KeepAlivePinger}.
*/
public static final class ClientKeepAlivePinger implements KeepAlivePinger {
private final ConnectionClientTransport transport;
public ClientKeepAlivePinger(ConnectionClientTransport transport) {
this.transport = transport;
}
@Override
public void ping() {
transport.ping(new ClientTransport.PingCallback() {
@Override
public void onSuccess(long roundTripTimeNanos) {}
@Override
public void onFailure(Throwable cause) {
transport.shutdownNow(Status.UNAVAILABLE.withDescription(
"Keepalive failed. The connection is likely gone"));
}
}, MoreExecutors.directExecutor());
}
@Override
public void onPingTimeout() {
transport.shutdownNow(Status.UNAVAILABLE.withDescription(
"Keepalive failed. The connection is likely gone"));
}
}
}
| grpc/grpc-java | core/src/main/java/io/grpc/internal/KeepAliveManager.java | 2,569 | /**
* Default client side {@link KeepAlivePinger}.
*/ | block_comment | nl | /*
* Copyright 2016 The gRPC Authors
*
* 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 io.grpc.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.MoreExecutors;
import io.grpc.Status;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
/**
* Manages keepalive pings.
*/
public class KeepAliveManager {
private static final long MIN_KEEPALIVE_TIME_NANOS = TimeUnit.SECONDS.toNanos(10);
private static final long MIN_KEEPALIVE_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(10L);
private final ScheduledExecutorService scheduler;
@GuardedBy("this")
private final Stopwatch stopwatch;
private final KeepAlivePinger keepAlivePinger;
private final boolean keepAliveDuringTransportIdle;
@GuardedBy("this")
private State state = State.IDLE;
@GuardedBy("this")
private ScheduledFuture<?> shutdownFuture;
@GuardedBy("this")
private ScheduledFuture<?> pingFuture;
private final Runnable shutdown = new LogExceptionRunnable(new Runnable() {
@Override
public void run() {
boolean shouldShutdown = false;
synchronized (KeepAliveManager.this) {
if (state != State.DISCONNECTED) {
// We haven't received a ping response within the timeout. The connection is likely gone
// already. Shutdown the transport and fail all existing rpcs.
state = State.DISCONNECTED;
shouldShutdown = true;
}
}
if (shouldShutdown) {
keepAlivePinger.onPingTimeout();
}
}
});
private final Runnable sendPing = new LogExceptionRunnable(new Runnable() {
@Override
public void run() {
boolean shouldSendPing = false;
synchronized (KeepAliveManager.this) {
pingFuture = null;
if (state == State.PING_SCHEDULED) {
shouldSendPing = true;
state = State.PING_SENT;
// Schedule a shutdown. It fires if we don't receive the ping response within the timeout.
shutdownFuture = scheduler.schedule(shutdown, keepAliveTimeoutInNanos,
TimeUnit.NANOSECONDS);
} else if (state == State.PING_DELAYED) {
// We have received some data. Reschedule the ping with the new time.
pingFuture = scheduler.schedule(
sendPing,
keepAliveTimeInNanos - stopwatch.elapsed(TimeUnit.NANOSECONDS),
TimeUnit.NANOSECONDS);
state = State.PING_SCHEDULED;
}
}
if (shouldSendPing) {
// Send the ping.
keepAlivePinger.ping();
}
}
});
private final long keepAliveTimeInNanos;
private final long keepAliveTimeoutInNanos;
private enum State {
/*
* We don't need to do any keepalives. This means the transport has no active rpcs and
* keepAliveDuringTransportIdle == false.
*/
IDLE,
/*
* We have scheduled a ping to be sent in the future. We may decide to delay it if we receive
* some data.
*/
PING_SCHEDULED,
/*
* We need to delay the scheduled keepalive ping.
*/
PING_DELAYED,
/*
* The ping has been sent out. Waiting for a ping response.
*/
PING_SENT,
/*
* Transport goes idle after ping has been sent.
*/
IDLE_AND_PING_SENT,
/*
* The transport has been disconnected. We won't do keepalives any more.
*/
DISCONNECTED,
}
/**
* Creates a KeepAliverManager.
*/
public KeepAliveManager(KeepAlivePinger keepAlivePinger, ScheduledExecutorService scheduler,
long keepAliveTimeInNanos, long keepAliveTimeoutInNanos,
boolean keepAliveDuringTransportIdle) {
this(keepAlivePinger, scheduler, Stopwatch.createUnstarted(), keepAliveTimeInNanos,
keepAliveTimeoutInNanos,
keepAliveDuringTransportIdle);
}
@VisibleForTesting
KeepAliveManager(KeepAlivePinger keepAlivePinger, ScheduledExecutorService scheduler,
Stopwatch stopwatch, long keepAliveTimeInNanos, long keepAliveTimeoutInNanos,
boolean keepAliveDuringTransportIdle) {
this.keepAlivePinger = checkNotNull(keepAlivePinger, "keepAlivePinger");
this.scheduler = checkNotNull(scheduler, "scheduler");
this.stopwatch = checkNotNull(stopwatch, "stopwatch");
this.keepAliveTimeInNanos = keepAliveTimeInNanos;
this.keepAliveTimeoutInNanos = keepAliveTimeoutInNanos;
this.keepAliveDuringTransportIdle = keepAliveDuringTransportIdle;
stopwatch.reset().start();
}
/** Start keepalive monitoring. */
public synchronized void onTransportStarted() {
if (keepAliveDuringTransportIdle) {
onTransportActive();
}
}
/**
* Transport has received some data so that we can delay sending keepalives.
*/
public synchronized void onDataReceived() {
stopwatch.reset().start();
// We do not cancel the ping future here. This avoids constantly scheduling and cancellation in
// a busy transport. Instead, we update the status here and reschedule later. So we actually
// keep one sendPing task always in flight when there're active rpcs.
if (state == State.PING_SCHEDULED) {
state = State.PING_DELAYED;
} else if (state == State.PING_SENT || state == State.IDLE_AND_PING_SENT) {
// Ping acked or effectively ping acked. Cancel shutdown, and then if not idle,
// schedule a new keep-alive ping.
if (shutdownFuture != null) {
shutdownFuture.cancel(false);
}
if (state == State.IDLE_AND_PING_SENT) {
// not to schedule new pings until onTransportActive
state = State.IDLE;
return;
}
// schedule a new ping
state = State.PING_SCHEDULED;
checkState(pingFuture == null, "There should be no outstanding pingFuture");
pingFuture = scheduler.schedule(sendPing, keepAliveTimeInNanos, TimeUnit.NANOSECONDS);
}
}
/**
* Transport has active streams. Start sending keepalives if necessary.
*/
public synchronized void onTransportActive() {
if (state == State.IDLE) {
// When the transport goes active, we do not reset the nextKeepaliveTime. This allows us to
// quickly check whether the connection is still working.
state = State.PING_SCHEDULED;
if (pingFuture == null) {
pingFuture = scheduler.schedule(
sendPing,
keepAliveTimeInNanos - stopwatch.elapsed(TimeUnit.NANOSECONDS),
TimeUnit.NANOSECONDS);
}
} else if (state == State.IDLE_AND_PING_SENT) {
state = State.PING_SENT;
} // Other states are possible when keepAliveDuringTransportIdle == true
}
/**
* Transport has finished all streams.
*/
public synchronized void onTransportIdle() {
if (keepAliveDuringTransportIdle) {
return;
}
if (state == State.PING_SCHEDULED || state == State.PING_DELAYED) {
state = State.IDLE;
}
if (state == State.PING_SENT) {
state = State.IDLE_AND_PING_SENT;
}
}
/**
* Transport is being terminated. We no longer need to do keepalives.
*/
public synchronized void onTransportTermination() {
if (state != State.DISCONNECTED) {
state = State.DISCONNECTED;
if (shutdownFuture != null) {
shutdownFuture.cancel(false);
}
if (pingFuture != null) {
pingFuture.cancel(false);
pingFuture = null;
}
}
}
/**
* Bumps keepalive time to 10 seconds if the specified value was smaller than that.
*/
public static long clampKeepAliveTimeInNanos(long keepAliveTimeInNanos) {
return Math.max(keepAliveTimeInNanos, MIN_KEEPALIVE_TIME_NANOS);
}
/**
* Bumps keepalive timeout to 10 milliseconds if the specified value was smaller than that.
*/
public static long clampKeepAliveTimeoutInNanos(long keepAliveTimeoutInNanos) {
return Math.max(keepAliveTimeoutInNanos, MIN_KEEPALIVE_TIMEOUT_NANOS);
}
public interface KeepAlivePinger {
/**
* Sends out a keep-alive ping.
*/
void ping();
/**
* Callback when Ping Ack was not received in KEEPALIVE_TIMEOUT. Should shutdown the transport.
*/
void onPingTimeout();
}
/**
* Default client side<SUF>*/
public static final class ClientKeepAlivePinger implements KeepAlivePinger {
private final ConnectionClientTransport transport;
public ClientKeepAlivePinger(ConnectionClientTransport transport) {
this.transport = transport;
}
@Override
public void ping() {
transport.ping(new ClientTransport.PingCallback() {
@Override
public void onSuccess(long roundTripTimeNanos) {}
@Override
public void onFailure(Throwable cause) {
transport.shutdownNow(Status.UNAVAILABLE.withDescription(
"Keepalive failed. The connection is likely gone"));
}
}, MoreExecutors.directExecutor());
}
@Override
public void onPingTimeout() {
transport.shutdownNow(Status.UNAVAILABLE.withDescription(
"Keepalive failed. The connection is likely gone"));
}
}
}
|
202873_4 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-19 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
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, version 2.
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, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app.ui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.GroupLayout.Group;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import processing.app.Language;
import processing.app.Platform;
import processing.app.Sketch;
/**
* Find & Replace window for the Processing editor.
*/
public class FindReplace extends JFrame {
Editor editor;
static final int BORDER = Platform.isMacOS() ? 20 : 13;
JTextField findField;
JTextField replaceField;
static String findString;
static String replaceString;
JButton replaceButton;
JButton replaceAllButton;
JButton replaceAndFindButton;
JButton previousButton;
JButton findButton;
JCheckBox ignoreCaseBox;
static boolean ignoreCase = true;
JCheckBox allTabsBox;
static boolean allTabs = false;
JCheckBox wrapAroundBox;
static boolean wrapAround = true;
public FindReplace(Editor editor) {
super(Language.text("find"));
this.editor = editor;
Container pain = getContentPane();
JLabel findLabel = new JLabel(Language.text("find.find"));
JLabel replaceLabel = new JLabel(Language.text("find.replace_with"));
findField = new JTextField();
replaceField = new JTextField();
if (findString != null) findField.setText(findString);
if (replaceString != null) replaceField.setText(replaceString);
ignoreCaseBox = new JCheckBox(Language.text("find.ignore_case"));
ignoreCaseBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ignoreCase = ignoreCaseBox.isSelected();
}
});
ignoreCaseBox.setSelected(ignoreCase);
allTabsBox = new JCheckBox(Language.text("find.all_tabs"));
allTabsBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
allTabs = allTabsBox.isSelected();
}
});
allTabsBox.setSelected(allTabs);
allTabsBox.setEnabled(true);
wrapAroundBox = new JCheckBox(Language.text("find.wrap_around"));
wrapAroundBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
wrapAround = wrapAroundBox.isSelected();
}
});
wrapAroundBox.setSelected(wrapAround);
GroupLayout layout = new GroupLayout(pain);
pain.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
// To hold the buttons in the specified order depending on the OS
Group buttonsHorizontalGroup = layout.createSequentialGroup();
replaceAllButton = new JButton(Language.text("find.btn.replace_all"));
replaceButton = new JButton(Language.text("find.btn.replace"));
replaceAndFindButton = new JButton(Language.text("find.btn.replace_and_find"));
previousButton = new JButton(Language.text("find.btn.previous"));
findButton = new JButton(Language.text("find.btn.find"));
// ordering is different on mac versus pc
if (Platform.isMacOS()) {
buttonsHorizontalGroup.addComponent(replaceAllButton)
.addComponent(replaceButton)
.addComponent(replaceAndFindButton)
.addComponent(previousButton)
.addComponent(findButton);
} else {
buttonsHorizontalGroup.addComponent(findButton)
.addComponent(previousButton)
.addComponent(replaceAndFindButton)
.addComponent(replaceButton)
.addComponent(replaceAllButton);
}
setFound(false);
Group buttonsVerticalGroup = layout.createParallelGroup(); // Creates group for arranging buttons vertically
buttonsVerticalGroup.addComponent(findButton)
.addComponent(previousButton)
.addComponent(replaceAndFindButton)
.addComponent(replaceButton)
.addComponent(replaceAllButton);
layout.setHorizontalGroup(layout
.createSequentialGroup()
.addGap(BORDER)
.addGroup(layout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, // TRAILING makes everything right alinged
layout.createSequentialGroup()
.addGap(replaceLabel.getPreferredSize().width
- findLabel.getPreferredSize().width)
.addComponent(findLabel)
.addComponent(findField))
.addGroup(GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(replaceLabel)
.addGroup(layout.createParallelGroup()
.addComponent(replaceField)
.addGroup(GroupLayout.Alignment.LEADING,
layout.createSequentialGroup()
.addComponent(ignoreCaseBox)
.addComponent(allTabsBox)
.addComponent(wrapAroundBox)
.addGap(0))))
.addGroup(GroupLayout.Alignment.CENTER,buttonsHorizontalGroup))
.addGap(BORDER)
);
// layout.linkSize(SwingConstants.HORIZONTAL, findButton, replaceButton, replaceAllButton, replaceAndFindButton, previousButton);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGap(BORDER)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(findLabel)
.addComponent(findField))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(replaceLabel)
.addComponent(replaceField))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(ignoreCaseBox)
.addComponent(allTabsBox)
.addComponent(wrapAroundBox))
.addGroup(buttonsVerticalGroup)
.addGap(BORDER)
);
setLocationRelativeTo(null); // center
Dimension size = layout.preferredLayoutSize(pain);
setSize(size.width, size.height);
Dimension screen = Toolkit.getScreenSize();
setLocation((screen.width - size.width) / 2,
(screen.height - size.height) / 2);
replaceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
replace();
}
});
replaceAllButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
replaceAll();
}
});
replaceAndFindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
replaceAndFindNext();
}
});
findButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findNext();
}
});
previousButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findPrevious();
}
});
// you mustn't replace what you haven't found, my son
// semantics of replace are "replace the current selection with the replace field"
// so whether we have found before or not is irrelevent
// replaceButton.setEnabled(false);
// replaceFindButton.setEnabled(false);
// make the find button the blinky default
getRootPane().setDefaultButton(findButton);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
handleClose();
}
});
Toolkit.registerWindowCloseKeys(getRootPane(), new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
handleClose();
}
});
Toolkit.setIcon(this);
// hack to to get first field to focus properly on osx
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
//System.out.println("activating");
/*boolean ok =*/ findField.requestFocusInWindow();
//System.out.println("got " + ok);
findField.selectAll();
}
});
pack();
setResizable(true);
setLocationRelativeTo(null);
}
public void handleClose() {
//System.out.println("handling close now");
findString = findField.getText();
replaceString = replaceField.getText();
// this object should eventually become dereferenced
setVisible(false);
}
// look for the next instance of the find string to be found
// once found, select it (and go to that line)
private boolean find(boolean wrap, boolean backwards) {
String searchTerm = findField.getText();
// this will catch "find next" being called when no search yet
if (searchTerm.length() != 0) {
String text = editor.getText();
// Started work on find/replace across tabs. These two variables store
// the original tab and selection position so that it knew when to stop
// rotating through.
Sketch sketch = editor.getSketch();
int tabIndex = sketch.getCurrentCodeIndex();
// int selIndex = backwards ?
// editor.getSelectionStart() : editor.getSelectionStop();
if (ignoreCase) {
searchTerm = searchTerm.toLowerCase();
text = text.toLowerCase();
}
int nextIndex;
if (!backwards) {
//int selectionStart = editor.textarea.getSelectionStart();
int selectionEnd = editor.getSelectionStop();
nextIndex = text.indexOf(searchTerm, selectionEnd);
if (nextIndex == -1 && wrap && !allTabs) {
// if wrapping, a second chance is ok, start from beginning
nextIndex = text.indexOf(searchTerm, 0);
} else if (nextIndex == -1 && allTabs) {
// For searching in all tabs, wrapping always happens.
int tempIndex = tabIndex;
// Look for searchterm in all tabs.
while (tabIndex <= sketch.getCodeCount() - 1) {
if (tabIndex == sketch.getCodeCount() - 1) {
// System.out.println("wrapping.");
tabIndex = -1;
} else if (tabIndex == sketch.getCodeCount() - 1) {
break;
}
try {
Document doc = sketch.getCode(tabIndex + 1).getDocument();
if(doc != null) {
text = doc.getText(0, doc.getLength()); // this thing has the latest changes
}
else {
text = sketch.getCode(tabIndex + 1).getProgram(); // not this thing.
}
} catch (BadLocationException e) {
e.printStackTrace();
}
tabIndex++;
if (ignoreCase) {
text = text.toLowerCase();
}
nextIndex = text.indexOf(searchTerm, 0);
if (nextIndex != -1 || tabIndex == tempIndex) {
break;
}
}
// searchterm wasn't found in any of the tabs.
// No tab switching should happen, restore tabIndex
if (nextIndex == -1) {
tabIndex = tempIndex;
}
}
} else {
//int selectionStart = editor.textarea.getSelectionStart();
int selectionStart = editor.getSelectionStart()-1;
if (selectionStart >= 0) {
nextIndex = text.lastIndexOf(searchTerm, selectionStart);
} else {
nextIndex = -1;
}
if (wrap && !allTabs && nextIndex == -1) {
// if wrapping, a second chance is ok, start from the end
nextIndex = text.lastIndexOf(searchTerm);
} else if (nextIndex == -1 && allTabs) {
int tempIndex = tabIndex;
// Look for search term in previous tabs.
while (tabIndex >= 0) {
if (tabIndex == 0) {
//System.out.println("wrapping.");
tabIndex = sketch.getCodeCount();
} else if (tabIndex == 0) {
break;
}
try {
Document doc = sketch.getCode(tabIndex - 1).getDocument();
if(doc != null) {
text = doc.getText(0, doc.getLength()); // this thing has the latest changes
}
else {
text = sketch.getCode(tabIndex - 1).getProgram(); // not this thing.
}
} catch (BadLocationException e) {
e.printStackTrace();
}
tabIndex--;
if (ignoreCase) {
text = text.toLowerCase();
}
nextIndex = text.lastIndexOf(searchTerm);
if (nextIndex != -1 || tabIndex == tempIndex) {
break;
}
}
// search term wasn't found in any of the tabs.
// No tab switching should happen, restore tabIndex
if (nextIndex == -1) {
tabIndex = tempIndex;
}
}
}
if (nextIndex != -1) {
if (allTabs) {
sketch.setCurrentCode(tabIndex);
}
editor.setSelection(nextIndex, nextIndex + searchTerm.length());
} else {
//Toolkit.getDefaultToolkit().beep();
}
if (nextIndex != -1) {
setFound(true);
return true;
}
}
setFound(false);
return false;
}
protected void setFound(boolean found) {
replaceButton.setEnabled(found);
replaceAndFindButton.setEnabled(found);
}
/**
* Replace the current selection with whatever's in the
* replacement text field.
* @param isCompoundEdit True if the action is to be marked as a copmound edit
*/
public void replace(boolean isCompoundEdit) {
editor.setSelectedText(replaceField.getText(), isCompoundEdit);
editor.getSketch().setModified(true); // This necessary- calling replace()
// doesn't seem to mark a sketch as modified
setFound(false);
}
/**
* Replace the current selection with whatever's in the
* replacement text field, marking the action as a compound edit.
*/
public void replace() {
replace(true);
}
/**
* Replace the current selection with whatever's in the
* replacement text field, and then find the next match
*/
public void replaceAndFindNext() {
replace();
findNext();
}
/**
* Replace everything that matches by doing find and replace
* alternately until nothing more found.
*/
public void replaceAll() {
// move to the beginning
editor.setSelection(0, 0);
boolean foundAtLeastOne = false;
int startTab = -1;
int startIndex = -1;
int counter = 10000; // prevent infinite loop
editor.startCompoundEdit();
while (--counter > 0) {
if (find(false, false)) {
int caret = editor.getSelectionStart();
int stopIndex = startIndex + replaceField.getText().length();
if (editor.getSketch().getCurrentCodeIndex() == startTab &&
(caret >= startIndex && (caret <= stopIndex))) {
// we've reached where we started, so stop the replace
Toolkit.beep();
editor.statusNotice("Reached beginning of search!");
break;
}
if (!foundAtLeastOne) {
foundAtLeastOne = true;
startTab = editor.getSketch().getCurrentCodeIndex();
startIndex = editor.getSelectionStart();
}
replace(false);
} else {
break;
}
}
editor.stopCompoundEdit();
if (!foundAtLeastOne) {
Toolkit.beep();
}
setFound(false);
}
public void setFindText(String t) {
findField.setText(t);
findString = t;
}
public void findNext() {
if (!find(wrapAround, false)) {
Toolkit.beep();
}
}
public void findPrevious() {
if (!find(wrapAround, true)) {
Toolkit.beep();
}
}
/**
* Returns true if find next/previous will work, for graying-
* out of menu items.
*/
public boolean canFindNext() {
return findField.getText().length() != 0;
}
}
| processing/processing | app/src/processing/app/ui/FindReplace.java | 4,108 | // ordering is different on mac versus pc | line_comment | nl | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-19 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
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, version 2.
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, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app.ui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.GroupLayout.Group;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import processing.app.Language;
import processing.app.Platform;
import processing.app.Sketch;
/**
* Find & Replace window for the Processing editor.
*/
public class FindReplace extends JFrame {
Editor editor;
static final int BORDER = Platform.isMacOS() ? 20 : 13;
JTextField findField;
JTextField replaceField;
static String findString;
static String replaceString;
JButton replaceButton;
JButton replaceAllButton;
JButton replaceAndFindButton;
JButton previousButton;
JButton findButton;
JCheckBox ignoreCaseBox;
static boolean ignoreCase = true;
JCheckBox allTabsBox;
static boolean allTabs = false;
JCheckBox wrapAroundBox;
static boolean wrapAround = true;
public FindReplace(Editor editor) {
super(Language.text("find"));
this.editor = editor;
Container pain = getContentPane();
JLabel findLabel = new JLabel(Language.text("find.find"));
JLabel replaceLabel = new JLabel(Language.text("find.replace_with"));
findField = new JTextField();
replaceField = new JTextField();
if (findString != null) findField.setText(findString);
if (replaceString != null) replaceField.setText(replaceString);
ignoreCaseBox = new JCheckBox(Language.text("find.ignore_case"));
ignoreCaseBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ignoreCase = ignoreCaseBox.isSelected();
}
});
ignoreCaseBox.setSelected(ignoreCase);
allTabsBox = new JCheckBox(Language.text("find.all_tabs"));
allTabsBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
allTabs = allTabsBox.isSelected();
}
});
allTabsBox.setSelected(allTabs);
allTabsBox.setEnabled(true);
wrapAroundBox = new JCheckBox(Language.text("find.wrap_around"));
wrapAroundBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
wrapAround = wrapAroundBox.isSelected();
}
});
wrapAroundBox.setSelected(wrapAround);
GroupLayout layout = new GroupLayout(pain);
pain.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
// To hold the buttons in the specified order depending on the OS
Group buttonsHorizontalGroup = layout.createSequentialGroup();
replaceAllButton = new JButton(Language.text("find.btn.replace_all"));
replaceButton = new JButton(Language.text("find.btn.replace"));
replaceAndFindButton = new JButton(Language.text("find.btn.replace_and_find"));
previousButton = new JButton(Language.text("find.btn.previous"));
findButton = new JButton(Language.text("find.btn.find"));
// ordering is<SUF>
if (Platform.isMacOS()) {
buttonsHorizontalGroup.addComponent(replaceAllButton)
.addComponent(replaceButton)
.addComponent(replaceAndFindButton)
.addComponent(previousButton)
.addComponent(findButton);
} else {
buttonsHorizontalGroup.addComponent(findButton)
.addComponent(previousButton)
.addComponent(replaceAndFindButton)
.addComponent(replaceButton)
.addComponent(replaceAllButton);
}
setFound(false);
Group buttonsVerticalGroup = layout.createParallelGroup(); // Creates group for arranging buttons vertically
buttonsVerticalGroup.addComponent(findButton)
.addComponent(previousButton)
.addComponent(replaceAndFindButton)
.addComponent(replaceButton)
.addComponent(replaceAllButton);
layout.setHorizontalGroup(layout
.createSequentialGroup()
.addGap(BORDER)
.addGroup(layout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, // TRAILING makes everything right alinged
layout.createSequentialGroup()
.addGap(replaceLabel.getPreferredSize().width
- findLabel.getPreferredSize().width)
.addComponent(findLabel)
.addComponent(findField))
.addGroup(GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(replaceLabel)
.addGroup(layout.createParallelGroup()
.addComponent(replaceField)
.addGroup(GroupLayout.Alignment.LEADING,
layout.createSequentialGroup()
.addComponent(ignoreCaseBox)
.addComponent(allTabsBox)
.addComponent(wrapAroundBox)
.addGap(0))))
.addGroup(GroupLayout.Alignment.CENTER,buttonsHorizontalGroup))
.addGap(BORDER)
);
// layout.linkSize(SwingConstants.HORIZONTAL, findButton, replaceButton, replaceAllButton, replaceAndFindButton, previousButton);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGap(BORDER)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(findLabel)
.addComponent(findField))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(replaceLabel)
.addComponent(replaceField))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(ignoreCaseBox)
.addComponent(allTabsBox)
.addComponent(wrapAroundBox))
.addGroup(buttonsVerticalGroup)
.addGap(BORDER)
);
setLocationRelativeTo(null); // center
Dimension size = layout.preferredLayoutSize(pain);
setSize(size.width, size.height);
Dimension screen = Toolkit.getScreenSize();
setLocation((screen.width - size.width) / 2,
(screen.height - size.height) / 2);
replaceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
replace();
}
});
replaceAllButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
replaceAll();
}
});
replaceAndFindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
replaceAndFindNext();
}
});
findButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findNext();
}
});
previousButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findPrevious();
}
});
// you mustn't replace what you haven't found, my son
// semantics of replace are "replace the current selection with the replace field"
// so whether we have found before or not is irrelevent
// replaceButton.setEnabled(false);
// replaceFindButton.setEnabled(false);
// make the find button the blinky default
getRootPane().setDefaultButton(findButton);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
handleClose();
}
});
Toolkit.registerWindowCloseKeys(getRootPane(), new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
handleClose();
}
});
Toolkit.setIcon(this);
// hack to to get first field to focus properly on osx
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
//System.out.println("activating");
/*boolean ok =*/ findField.requestFocusInWindow();
//System.out.println("got " + ok);
findField.selectAll();
}
});
pack();
setResizable(true);
setLocationRelativeTo(null);
}
public void handleClose() {
//System.out.println("handling close now");
findString = findField.getText();
replaceString = replaceField.getText();
// this object should eventually become dereferenced
setVisible(false);
}
// look for the next instance of the find string to be found
// once found, select it (and go to that line)
private boolean find(boolean wrap, boolean backwards) {
String searchTerm = findField.getText();
// this will catch "find next" being called when no search yet
if (searchTerm.length() != 0) {
String text = editor.getText();
// Started work on find/replace across tabs. These two variables store
// the original tab and selection position so that it knew when to stop
// rotating through.
Sketch sketch = editor.getSketch();
int tabIndex = sketch.getCurrentCodeIndex();
// int selIndex = backwards ?
// editor.getSelectionStart() : editor.getSelectionStop();
if (ignoreCase) {
searchTerm = searchTerm.toLowerCase();
text = text.toLowerCase();
}
int nextIndex;
if (!backwards) {
//int selectionStart = editor.textarea.getSelectionStart();
int selectionEnd = editor.getSelectionStop();
nextIndex = text.indexOf(searchTerm, selectionEnd);
if (nextIndex == -1 && wrap && !allTabs) {
// if wrapping, a second chance is ok, start from beginning
nextIndex = text.indexOf(searchTerm, 0);
} else if (nextIndex == -1 && allTabs) {
// For searching in all tabs, wrapping always happens.
int tempIndex = tabIndex;
// Look for searchterm in all tabs.
while (tabIndex <= sketch.getCodeCount() - 1) {
if (tabIndex == sketch.getCodeCount() - 1) {
// System.out.println("wrapping.");
tabIndex = -1;
} else if (tabIndex == sketch.getCodeCount() - 1) {
break;
}
try {
Document doc = sketch.getCode(tabIndex + 1).getDocument();
if(doc != null) {
text = doc.getText(0, doc.getLength()); // this thing has the latest changes
}
else {
text = sketch.getCode(tabIndex + 1).getProgram(); // not this thing.
}
} catch (BadLocationException e) {
e.printStackTrace();
}
tabIndex++;
if (ignoreCase) {
text = text.toLowerCase();
}
nextIndex = text.indexOf(searchTerm, 0);
if (nextIndex != -1 || tabIndex == tempIndex) {
break;
}
}
// searchterm wasn't found in any of the tabs.
// No tab switching should happen, restore tabIndex
if (nextIndex == -1) {
tabIndex = tempIndex;
}
}
} else {
//int selectionStart = editor.textarea.getSelectionStart();
int selectionStart = editor.getSelectionStart()-1;
if (selectionStart >= 0) {
nextIndex = text.lastIndexOf(searchTerm, selectionStart);
} else {
nextIndex = -1;
}
if (wrap && !allTabs && nextIndex == -1) {
// if wrapping, a second chance is ok, start from the end
nextIndex = text.lastIndexOf(searchTerm);
} else if (nextIndex == -1 && allTabs) {
int tempIndex = tabIndex;
// Look for search term in previous tabs.
while (tabIndex >= 0) {
if (tabIndex == 0) {
//System.out.println("wrapping.");
tabIndex = sketch.getCodeCount();
} else if (tabIndex == 0) {
break;
}
try {
Document doc = sketch.getCode(tabIndex - 1).getDocument();
if(doc != null) {
text = doc.getText(0, doc.getLength()); // this thing has the latest changes
}
else {
text = sketch.getCode(tabIndex - 1).getProgram(); // not this thing.
}
} catch (BadLocationException e) {
e.printStackTrace();
}
tabIndex--;
if (ignoreCase) {
text = text.toLowerCase();
}
nextIndex = text.lastIndexOf(searchTerm);
if (nextIndex != -1 || tabIndex == tempIndex) {
break;
}
}
// search term wasn't found in any of the tabs.
// No tab switching should happen, restore tabIndex
if (nextIndex == -1) {
tabIndex = tempIndex;
}
}
}
if (nextIndex != -1) {
if (allTabs) {
sketch.setCurrentCode(tabIndex);
}
editor.setSelection(nextIndex, nextIndex + searchTerm.length());
} else {
//Toolkit.getDefaultToolkit().beep();
}
if (nextIndex != -1) {
setFound(true);
return true;
}
}
setFound(false);
return false;
}
protected void setFound(boolean found) {
replaceButton.setEnabled(found);
replaceAndFindButton.setEnabled(found);
}
/**
* Replace the current selection with whatever's in the
* replacement text field.
* @param isCompoundEdit True if the action is to be marked as a copmound edit
*/
public void replace(boolean isCompoundEdit) {
editor.setSelectedText(replaceField.getText(), isCompoundEdit);
editor.getSketch().setModified(true); // This necessary- calling replace()
// doesn't seem to mark a sketch as modified
setFound(false);
}
/**
* Replace the current selection with whatever's in the
* replacement text field, marking the action as a compound edit.
*/
public void replace() {
replace(true);
}
/**
* Replace the current selection with whatever's in the
* replacement text field, and then find the next match
*/
public void replaceAndFindNext() {
replace();
findNext();
}
/**
* Replace everything that matches by doing find and replace
* alternately until nothing more found.
*/
public void replaceAll() {
// move to the beginning
editor.setSelection(0, 0);
boolean foundAtLeastOne = false;
int startTab = -1;
int startIndex = -1;
int counter = 10000; // prevent infinite loop
editor.startCompoundEdit();
while (--counter > 0) {
if (find(false, false)) {
int caret = editor.getSelectionStart();
int stopIndex = startIndex + replaceField.getText().length();
if (editor.getSketch().getCurrentCodeIndex() == startTab &&
(caret >= startIndex && (caret <= stopIndex))) {
// we've reached where we started, so stop the replace
Toolkit.beep();
editor.statusNotice("Reached beginning of search!");
break;
}
if (!foundAtLeastOne) {
foundAtLeastOne = true;
startTab = editor.getSketch().getCurrentCodeIndex();
startIndex = editor.getSelectionStart();
}
replace(false);
} else {
break;
}
}
editor.stopCompoundEdit();
if (!foundAtLeastOne) {
Toolkit.beep();
}
setFound(false);
}
public void setFindText(String t) {
findField.setText(t);
findString = t;
}
public void findNext() {
if (!find(wrapAround, false)) {
Toolkit.beep();
}
}
public void findPrevious() {
if (!find(wrapAround, true)) {
Toolkit.beep();
}
}
/**
* Returns true if find next/previous will work, for graying-
* out of menu items.
*/
public boolean canFindNext() {
return findField.getText().length() != 0;
}
}
|
202902_6 | /*******************************************************************************
* Copyright (c) 2005-2016, G. Weirich and Elexis
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* G. Weirich - initial implementation
* MEDEVIT - major refactorings due to multi-stock implementation
*******************************************************************************/
package ch.elexis.data;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.interfaces.IArticle;
import ch.elexis.core.data.interfaces.IFall;
import ch.elexis.core.data.service.CoreModelServiceHolder;
import ch.rgw.tools.Money;
import ch.rgw.tools.StringTool;
import ch.rgw.tools.TimeTool;
public class Artikel extends VerrechenbarAdapter implements IArticle {
public static final String TABLENAME = "ARTIKEL";
public static final String FLD_EAN = "EAN";
public static final String FLD_CODECLASS = "Codeclass";
public static final String FLD_KLASSE = "Klasse";
public static final String XID_PHARMACODE = "www.xid.ch/id/pharmacode/ch";
public static final String FLD_SUB_ID = "SubID";
public static final String ARTIKEL = "Artikel";
public static final String FLD_PHARMACODE = "Pharmacode";
public static final String FLD_EXTID = "ExtID";
public static final String VERKAUFSEINHEIT = "Verkaufseinheit";
public static final String VERPACKUNGSEINHEIT = "Verpackungseinheit";
public static final String FLD_VK_PREIS = "VK_Preis";
public static final String FLD_EK_PREIS = "EK_Preis";
public static final String EIGENNAME = "Eigenname";
public static final String FLD_TYP = "Typ";
public static final String FLD_NAME = "Name";
public static final String FLD_ATC_CODE = "ATC_code";
public static final Pattern NAME_VE_PATTERN = Pattern.compile(".+ ([0-9]+) Stk.*");
static {
addMapping(TABLENAME, FLD_NAME, FLD_EK_PREIS, FLD_VK_PREIS, FLD_TYP, FLD_EXTINFO, FLD_EAN, FLD_SUB_ID,
EIGENNAME + "=Name_intern", FLD_CODECLASS, FLD_KLASSE, FLD_ATC_CODE, FLD_EXTID);
// TODO move to NoPo initialisation
Xid.localRegisterXIDDomainIfNotExists(XID_PHARMACODE, FLD_PHARMACODE, Xid.ASSIGNMENT_REGIONAL);
}
@Override
protected String getTableName() {
return TABLENAME;
}
public String getXidDomain() {
return XID_PHARMACODE;
}
/**
* This implementation of PersistentObject#load is special in that it tries to
* load the actual appropriate subclass
*/
public static Artikel load(final String id) {
if (id == null) {
return null;
}
Artikel ret = new Artikel(id);
if (!ret.exists()) {
return ret;
}
String clazz = ret.get(FLD_KLASSE);
if (!StringTool.isNothing(clazz)) {
try {
ret = (Artikel) CoreHub.poFactory.createFromString(clazz + "::" + id);
} catch (Exception ex) {
log.error("Fehlerhafter Leistungscode " + clazz + "::" + id);
}
}
return ret;
}
/**
* Einen neuen Artikel mit vorgegebenen Parametern erstellen
*
* @param Name
* @param Typ
*/
public Artikel(final String Name, final String Typ) {
create(null);
set(new String[] { FLD_NAME, FLD_TYP }, new String[] { Name, Typ });
}
public Artikel(final String Name, final String Typ, final String subid) {
create(null);
set(new String[] { FLD_NAME, FLD_TYP, FLD_SUB_ID }, Name, Typ, subid);
}
@Override
public String getLabel() {
if (!exists()) {
return "(" + getName() + ")";
}
return getInternalName();
}
public String[] getDisplayedFields() {
return new String[] { FLD_TYP, FLD_NAME };
}
/**
* Den internen Namen setzen. Dieser ist vom Anwender frei wählbar und erscheint
* in der Artikelauswahl und auf der Rechnung.
*
* @param nick Der "Spitzname"
*/
public void setInternalName(final String nick) {
set(EIGENNAME, nick);
}
/**
* Den internen Namen holen
*
* @return
*/
public String getInternalName() {
String ret = get(EIGENNAME);
if (StringTool.isNothing(ret)) {
ret = getName();
}
return ret;
}
/**
* Den offiziellen namen holen
*
* @return
*/
public String getName() {
return checkNull(get(FLD_NAME));
}
/**
* Den "echten" Namen setzen. Dies ist der offizielle Name des Artikels, wie er
* beispielsweise in Katalogen aufgeführt ist. Dieser sollte normalerweise nicht
* geändert werden.
*
* @param name der neue "echte" Name
*/
public void setName(final String name) {
set(FLD_NAME, name);
}
/**
* Basis-Einkaufspreis in Rappen pro Einheit
*
* @return
*/
public Money getEKPreis() {
try {
return new Money(checkZero(get(FLD_EK_PREIS)));
} catch (Throwable ex) {
log.error("Fehler beim Einlesen von EK für " + getLabel());
}
return new Money();
}
/**
* Basis-Verkaufspreis in Rappen pro Einheit
*
* @return
*/
public Money getVKPreis() {
try {
return new Money(checkZero(get(FLD_VK_PREIS)));
} catch (Throwable ex) {
log.error("Fehler beim Einlesen von VK für " + getLabel());
}
return new Money();
}
/**
* Einkaufspreis setzen. Das sollte normalerweise nur der Importer tun
*
* @param preis
*/
public void setEKPreis(final Money preis) {
set(FLD_EK_PREIS, preis.getCentsAsString());
}
/**
* Den Verkaufspreis setzen. Das sollte bei gesetztlich festgelegten Artikeln
* nur der Importer tun.
*
* @param preis
*/
public void setVKPreis(final Money preis) {
set(FLD_VK_PREIS, preis.getCentsAsString());
}
/**
* Versuche, die Verpakcungseinheit herauszufinden. Entweder haben wir sie im
* Artikeldetail angegeben, dann ist es trivial, oder vielleicht steht im Namen
* etwas wie xx Stk.
*
* @return einen educated guess oder 0 (unknown)
*/
public int guessVE() {
int ret = getVerpackungsEinheit();
if (ret == 0) {
String name = getName();
Matcher matcher = NAME_VE_PATTERN.matcher(name);
if (matcher.matches()) {
String num = matcher.group(1);
try {
return Integer.parseInt(num);
} catch (Exception ex) {
}
}
}
return ret;
}
public String getEAN() {
return get(FLD_EAN);
}
@Override
public String getGTIN() {
return getEAN();
}
public void setEAN(String ean) {
set(FLD_EAN, ean);
}
public boolean isVaccination() {
String atcCode = getATC_code();
if (atcCode != null) {
if (atcCode.toUpperCase().startsWith("J07") && !atcCode.toUpperCase().startsWith("J07AX")) {
return true;
}
}
return false;
}
public String getATC_code() {
String ATC_code = get(FLD_ATC_CODE);
return ATC_code;
}
public void setATC_code(String ATC_code) {
set(FLD_ATC_CODE, ATC_code);
}
public void setPharmaCode(String pharmacode) {
Map<Object, Object> ext = getMap(FLD_EXTINFO);
ext.put(FLD_PHARMACODE, pharmacode);
setMap(FLD_EXTINFO, ext);
}
public String getPharmaCode() {
return checkNull(getExt(FLD_PHARMACODE));
}
public int getVerpackungsEinheit() {
return checkZero((String) getExtInfoStoredObjectByKey(VERPACKUNGSEINHEIT));
}
@Override
public int getPackageUnit() {
return getVerpackungsEinheit();
}
public void setVerpackungsEinheit(int ve) {
setExt(VERPACKUNGSEINHEIT, Integer.toString(ve));
}
public int getVerkaufseinheit() {
return checkZero(getExt(VERKAUFSEINHEIT));
}
@Override
public int getSellingUnit() {
return getVerkaufseinheit();
}
public void setVerkaufseinheit(int number) {
setExt(VERKAUFSEINHEIT, Integer.toString(number));
}
/**
* @return the package size, zero if not defined
*/
public int getPackungsGroesse() {
return checkZero(getExt(VERPACKUNGSEINHEIT));
}
public void setPackungsGroesse(int packageSize) {
setExtInfoStoredObjectByKey(VERPACKUNGSEINHEIT, Integer.toString(packageSize));
}
public String getPackungsGroesseDesc() {
return Integer.toString(getPackungsGroesse());
}
public int getAbgabeEinheit() {
return checkZero(getExt(VERKAUFSEINHEIT));
}
@SuppressWarnings("unchecked")
public void setExt(final String name, final String value) {
Map h = getMap(FLD_EXTINFO);
if (value == null) {
h.remove(name);
} else {
h.put(name, value);
}
setMap(FLD_EXTINFO, h);
}
@SuppressWarnings("unchecked")
public String getExt(final String name) {
Map h = getMap(FLD_EXTINFO);
return checkNull((String) h.get(name));
}
protected Artikel(final String id) {
super(id);
}
protected Artikel() {
}
/************************ Verrechenbar ************************/
@Override
public String getCode() {
return getId();
}
@Override
public String getText() {
return getInternalName();
}
@Override
public String getCodeSystemName() {
return ARTIKEL;
}
@Override
public boolean isProduct() {
return false;
}
@SuppressWarnings("unchecked")
public int getPreis(final TimeTool dat, final IFall fall) {
double vkt = checkZeroDouble(get(FLD_VK_PREIS));
Map ext = getMap(FLD_EXTINFO);
double vpe = checkZeroDouble((String) ext.get(VERPACKUNGSEINHEIT));
double vke = checkZeroDouble((String) ext.get(VERKAUFSEINHEIT));
if ((vpe > 0.0 && vke > 0.0) && (vpe != vke)) {
return (int) Math.round(vke * (vkt / vpe));
} else {
return (int) Math.round(vkt);
}
}
@SuppressWarnings("unchecked")
@Override
public Money getKosten(final TimeTool dat) {
double vkt = checkZeroDouble(get(FLD_EK_PREIS));
Map ext = getMap(FLD_EXTINFO);
double vpe = checkZeroDouble((String) ext.get(VERPACKUNGSEINHEIT));
double vke = checkZeroDouble((String) ext.get(VERKAUFSEINHEIT));
if ((vpe > 0.0 && vke > 0.0) && (vpe != vke)) {
return new Money((int) Math.round(vke * (vkt / vpe)));
} else {
return new Money((int) Math.round(vkt));
}
}
public int getTP(final TimeTool date, final IFall fall) {
return getPreis(date, fall);
}
public double getFactor(final TimeTool date, final IFall fall) {
return 1.0;
}
@Override
protected String[] getExportFields() {
return new String[] { FLD_EAN, FLD_SUB_ID, FLD_KLASSE, FLD_NAME, FLD_EK_PREIS, FLD_VK_PREIS, FLD_TYP,
FLD_CODECLASS, FLD_ATC_CODE, FLD_EXTINFO };
}
@Override
protected String getExportUIDValue() {
String pharmacode = getExt(FLD_PHARMACODE);
String ean = get(FLD_EAN);
return ean + "_" + pharmacode;
}
/**
* Convenience conversion method, loads object via model service
*
* @return
* @since 3.8
* @throws IllegalStateException if entity could not be loaded
*/
public ch.elexis.core.model.IArticle toIArticle() {
return CoreModelServiceHolder.get().load(getId(), ch.elexis.core.model.IArticle.class)
.orElseThrow(() -> new IllegalStateException("Could not convert article [" + getId() + "]"));
}
}
| elexis/elexis-3-core | bundles/ch.elexis.core.data/src/ch/elexis/data/Artikel.java | 3,582 | /**
* Den offiziellen namen holen
*
* @return
*/ | block_comment | nl | /*******************************************************************************
* Copyright (c) 2005-2016, G. Weirich and Elexis
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* G. Weirich - initial implementation
* MEDEVIT - major refactorings due to multi-stock implementation
*******************************************************************************/
package ch.elexis.data;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.interfaces.IArticle;
import ch.elexis.core.data.interfaces.IFall;
import ch.elexis.core.data.service.CoreModelServiceHolder;
import ch.rgw.tools.Money;
import ch.rgw.tools.StringTool;
import ch.rgw.tools.TimeTool;
public class Artikel extends VerrechenbarAdapter implements IArticle {
public static final String TABLENAME = "ARTIKEL";
public static final String FLD_EAN = "EAN";
public static final String FLD_CODECLASS = "Codeclass";
public static final String FLD_KLASSE = "Klasse";
public static final String XID_PHARMACODE = "www.xid.ch/id/pharmacode/ch";
public static final String FLD_SUB_ID = "SubID";
public static final String ARTIKEL = "Artikel";
public static final String FLD_PHARMACODE = "Pharmacode";
public static final String FLD_EXTID = "ExtID";
public static final String VERKAUFSEINHEIT = "Verkaufseinheit";
public static final String VERPACKUNGSEINHEIT = "Verpackungseinheit";
public static final String FLD_VK_PREIS = "VK_Preis";
public static final String FLD_EK_PREIS = "EK_Preis";
public static final String EIGENNAME = "Eigenname";
public static final String FLD_TYP = "Typ";
public static final String FLD_NAME = "Name";
public static final String FLD_ATC_CODE = "ATC_code";
public static final Pattern NAME_VE_PATTERN = Pattern.compile(".+ ([0-9]+) Stk.*");
static {
addMapping(TABLENAME, FLD_NAME, FLD_EK_PREIS, FLD_VK_PREIS, FLD_TYP, FLD_EXTINFO, FLD_EAN, FLD_SUB_ID,
EIGENNAME + "=Name_intern", FLD_CODECLASS, FLD_KLASSE, FLD_ATC_CODE, FLD_EXTID);
// TODO move to NoPo initialisation
Xid.localRegisterXIDDomainIfNotExists(XID_PHARMACODE, FLD_PHARMACODE, Xid.ASSIGNMENT_REGIONAL);
}
@Override
protected String getTableName() {
return TABLENAME;
}
public String getXidDomain() {
return XID_PHARMACODE;
}
/**
* This implementation of PersistentObject#load is special in that it tries to
* load the actual appropriate subclass
*/
public static Artikel load(final String id) {
if (id == null) {
return null;
}
Artikel ret = new Artikel(id);
if (!ret.exists()) {
return ret;
}
String clazz = ret.get(FLD_KLASSE);
if (!StringTool.isNothing(clazz)) {
try {
ret = (Artikel) CoreHub.poFactory.createFromString(clazz + "::" + id);
} catch (Exception ex) {
log.error("Fehlerhafter Leistungscode " + clazz + "::" + id);
}
}
return ret;
}
/**
* Einen neuen Artikel mit vorgegebenen Parametern erstellen
*
* @param Name
* @param Typ
*/
public Artikel(final String Name, final String Typ) {
create(null);
set(new String[] { FLD_NAME, FLD_TYP }, new String[] { Name, Typ });
}
public Artikel(final String Name, final String Typ, final String subid) {
create(null);
set(new String[] { FLD_NAME, FLD_TYP, FLD_SUB_ID }, Name, Typ, subid);
}
@Override
public String getLabel() {
if (!exists()) {
return "(" + getName() + ")";
}
return getInternalName();
}
public String[] getDisplayedFields() {
return new String[] { FLD_TYP, FLD_NAME };
}
/**
* Den internen Namen setzen. Dieser ist vom Anwender frei wählbar und erscheint
* in der Artikelauswahl und auf der Rechnung.
*
* @param nick Der "Spitzname"
*/
public void setInternalName(final String nick) {
set(EIGENNAME, nick);
}
/**
* Den internen Namen holen
*
* @return
*/
public String getInternalName() {
String ret = get(EIGENNAME);
if (StringTool.isNothing(ret)) {
ret = getName();
}
return ret;
}
/**
* Den offiziellen namen<SUF>*/
public String getName() {
return checkNull(get(FLD_NAME));
}
/**
* Den "echten" Namen setzen. Dies ist der offizielle Name des Artikels, wie er
* beispielsweise in Katalogen aufgeführt ist. Dieser sollte normalerweise nicht
* geändert werden.
*
* @param name der neue "echte" Name
*/
public void setName(final String name) {
set(FLD_NAME, name);
}
/**
* Basis-Einkaufspreis in Rappen pro Einheit
*
* @return
*/
public Money getEKPreis() {
try {
return new Money(checkZero(get(FLD_EK_PREIS)));
} catch (Throwable ex) {
log.error("Fehler beim Einlesen von EK für " + getLabel());
}
return new Money();
}
/**
* Basis-Verkaufspreis in Rappen pro Einheit
*
* @return
*/
public Money getVKPreis() {
try {
return new Money(checkZero(get(FLD_VK_PREIS)));
} catch (Throwable ex) {
log.error("Fehler beim Einlesen von VK für " + getLabel());
}
return new Money();
}
/**
* Einkaufspreis setzen. Das sollte normalerweise nur der Importer tun
*
* @param preis
*/
public void setEKPreis(final Money preis) {
set(FLD_EK_PREIS, preis.getCentsAsString());
}
/**
* Den Verkaufspreis setzen. Das sollte bei gesetztlich festgelegten Artikeln
* nur der Importer tun.
*
* @param preis
*/
public void setVKPreis(final Money preis) {
set(FLD_VK_PREIS, preis.getCentsAsString());
}
/**
* Versuche, die Verpakcungseinheit herauszufinden. Entweder haben wir sie im
* Artikeldetail angegeben, dann ist es trivial, oder vielleicht steht im Namen
* etwas wie xx Stk.
*
* @return einen educated guess oder 0 (unknown)
*/
public int guessVE() {
int ret = getVerpackungsEinheit();
if (ret == 0) {
String name = getName();
Matcher matcher = NAME_VE_PATTERN.matcher(name);
if (matcher.matches()) {
String num = matcher.group(1);
try {
return Integer.parseInt(num);
} catch (Exception ex) {
}
}
}
return ret;
}
public String getEAN() {
return get(FLD_EAN);
}
@Override
public String getGTIN() {
return getEAN();
}
public void setEAN(String ean) {
set(FLD_EAN, ean);
}
public boolean isVaccination() {
String atcCode = getATC_code();
if (atcCode != null) {
if (atcCode.toUpperCase().startsWith("J07") && !atcCode.toUpperCase().startsWith("J07AX")) {
return true;
}
}
return false;
}
public String getATC_code() {
String ATC_code = get(FLD_ATC_CODE);
return ATC_code;
}
public void setATC_code(String ATC_code) {
set(FLD_ATC_CODE, ATC_code);
}
public void setPharmaCode(String pharmacode) {
Map<Object, Object> ext = getMap(FLD_EXTINFO);
ext.put(FLD_PHARMACODE, pharmacode);
setMap(FLD_EXTINFO, ext);
}
public String getPharmaCode() {
return checkNull(getExt(FLD_PHARMACODE));
}
public int getVerpackungsEinheit() {
return checkZero((String) getExtInfoStoredObjectByKey(VERPACKUNGSEINHEIT));
}
@Override
public int getPackageUnit() {
return getVerpackungsEinheit();
}
public void setVerpackungsEinheit(int ve) {
setExt(VERPACKUNGSEINHEIT, Integer.toString(ve));
}
public int getVerkaufseinheit() {
return checkZero(getExt(VERKAUFSEINHEIT));
}
@Override
public int getSellingUnit() {
return getVerkaufseinheit();
}
public void setVerkaufseinheit(int number) {
setExt(VERKAUFSEINHEIT, Integer.toString(number));
}
/**
* @return the package size, zero if not defined
*/
public int getPackungsGroesse() {
return checkZero(getExt(VERPACKUNGSEINHEIT));
}
public void setPackungsGroesse(int packageSize) {
setExtInfoStoredObjectByKey(VERPACKUNGSEINHEIT, Integer.toString(packageSize));
}
public String getPackungsGroesseDesc() {
return Integer.toString(getPackungsGroesse());
}
public int getAbgabeEinheit() {
return checkZero(getExt(VERKAUFSEINHEIT));
}
@SuppressWarnings("unchecked")
public void setExt(final String name, final String value) {
Map h = getMap(FLD_EXTINFO);
if (value == null) {
h.remove(name);
} else {
h.put(name, value);
}
setMap(FLD_EXTINFO, h);
}
@SuppressWarnings("unchecked")
public String getExt(final String name) {
Map h = getMap(FLD_EXTINFO);
return checkNull((String) h.get(name));
}
protected Artikel(final String id) {
super(id);
}
protected Artikel() {
}
/************************ Verrechenbar ************************/
@Override
public String getCode() {
return getId();
}
@Override
public String getText() {
return getInternalName();
}
@Override
public String getCodeSystemName() {
return ARTIKEL;
}
@Override
public boolean isProduct() {
return false;
}
@SuppressWarnings("unchecked")
public int getPreis(final TimeTool dat, final IFall fall) {
double vkt = checkZeroDouble(get(FLD_VK_PREIS));
Map ext = getMap(FLD_EXTINFO);
double vpe = checkZeroDouble((String) ext.get(VERPACKUNGSEINHEIT));
double vke = checkZeroDouble((String) ext.get(VERKAUFSEINHEIT));
if ((vpe > 0.0 && vke > 0.0) && (vpe != vke)) {
return (int) Math.round(vke * (vkt / vpe));
} else {
return (int) Math.round(vkt);
}
}
@SuppressWarnings("unchecked")
@Override
public Money getKosten(final TimeTool dat) {
double vkt = checkZeroDouble(get(FLD_EK_PREIS));
Map ext = getMap(FLD_EXTINFO);
double vpe = checkZeroDouble((String) ext.get(VERPACKUNGSEINHEIT));
double vke = checkZeroDouble((String) ext.get(VERKAUFSEINHEIT));
if ((vpe > 0.0 && vke > 0.0) && (vpe != vke)) {
return new Money((int) Math.round(vke * (vkt / vpe)));
} else {
return new Money((int) Math.round(vkt));
}
}
public int getTP(final TimeTool date, final IFall fall) {
return getPreis(date, fall);
}
public double getFactor(final TimeTool date, final IFall fall) {
return 1.0;
}
@Override
protected String[] getExportFields() {
return new String[] { FLD_EAN, FLD_SUB_ID, FLD_KLASSE, FLD_NAME, FLD_EK_PREIS, FLD_VK_PREIS, FLD_TYP,
FLD_CODECLASS, FLD_ATC_CODE, FLD_EXTINFO };
}
@Override
protected String getExportUIDValue() {
String pharmacode = getExt(FLD_PHARMACODE);
String ean = get(FLD_EAN);
return ean + "_" + pharmacode;
}
/**
* Convenience conversion method, loads object via model service
*
* @return
* @since 3.8
* @throws IllegalStateException if entity could not be loaded
*/
public ch.elexis.core.model.IArticle toIArticle() {
return CoreModelServiceHolder.get().load(getId(), ch.elexis.core.model.IArticle.class)
.orElseThrow(() -> new IllegalStateException("Could not convert article [" + getId() + "]"));
}
}
|
202955_44 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.Env;
/** Generated Model for M_MovementLine
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_M_MovementLine extends org.compiere.model.PO implements I_M_MovementLine, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 1007297111L;
/** Standard Constructor */
public X_M_MovementLine (Properties ctx, int M_MovementLine_ID, String trxName)
{
super (ctx, M_MovementLine_ID, trxName);
/** if (M_MovementLine_ID == 0)
{
setLine (0);
// @SQL=SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID=@M_Movement_ID@
setM_Locator_ID (0);
// @M_Locator_ID@
setM_LocatorTo_ID (0);
// @M_LocatorTo_ID@
setM_Movement_ID (0);
setM_MovementLine_ID (0);
setM_Product_ID (0);
setMovementQty (Env.ZERO);
// 1
setProcessed (false);
setTargetQty (Env.ZERO);
// 0
} */
}
/** Load Constructor */
public X_M_MovementLine (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder ("X_M_MovementLine[")
.append(get_ID()).append("]");
return sb.toString();
}
@Override
public org.compiere.model.I_C_Activity getC_Activity() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Activity_ID, org.compiere.model.I_C_Activity.class);
}
@Override
public void setC_Activity(org.compiere.model.I_C_Activity C_Activity)
{
set_ValueFromPO(COLUMNNAME_C_Activity_ID, org.compiere.model.I_C_Activity.class, C_Activity);
}
/** Set Kostenstelle.
@param C_Activity_ID
Kostenstelle
*/
@Override
public void setC_Activity_ID (int C_Activity_ID)
{
if (C_Activity_ID < 1)
set_Value (COLUMNNAME_C_Activity_ID, null);
else
set_Value (COLUMNNAME_C_Activity_ID, Integer.valueOf(C_Activity_ID));
}
/** Get Kostenstelle.
@return Kostenstelle
*/
@Override
public int getC_Activity_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Activity_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_Activity getC_ActivityFrom() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_ActivityFrom_ID, org.compiere.model.I_C_Activity.class);
}
@Override
public void setC_ActivityFrom(org.compiere.model.I_C_Activity C_ActivityFrom)
{
set_ValueFromPO(COLUMNNAME_C_ActivityFrom_ID, org.compiere.model.I_C_Activity.class, C_ActivityFrom);
}
/** Set Activity From.
@param C_ActivityFrom_ID Activity From */
@Override
public void setC_ActivityFrom_ID (int C_ActivityFrom_ID)
{
if (C_ActivityFrom_ID < 1)
set_Value (COLUMNNAME_C_ActivityFrom_ID, null);
else
set_Value (COLUMNNAME_C_ActivityFrom_ID, Integer.valueOf(C_ActivityFrom_ID));
}
/** Get Activity From.
@return Activity From */
@Override
public int getC_ActivityFrom_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ActivityFrom_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bestätigte Menge.
@param ConfirmedQty
Confirmation of a received quantity
*/
@Override
public void setConfirmedQty (java.math.BigDecimal ConfirmedQty)
{
set_Value (COLUMNNAME_ConfirmedQty, ConfirmedQty);
}
/** Get Bestätigte Menge.
@return Confirmation of a received quantity
*/
@Override
public java.math.BigDecimal getConfirmedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ConfirmedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
@Override
public org.eevolution.model.I_DD_OrderLine_Alternative getDD_OrderLine_Alternative() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DD_OrderLine_Alternative_ID, org.eevolution.model.I_DD_OrderLine_Alternative.class);
}
@Override
public void setDD_OrderLine_Alternative(org.eevolution.model.I_DD_OrderLine_Alternative DD_OrderLine_Alternative)
{
set_ValueFromPO(COLUMNNAME_DD_OrderLine_Alternative_ID, org.eevolution.model.I_DD_OrderLine_Alternative.class, DD_OrderLine_Alternative);
}
/** Set Distribution Order Line Alternative.
@param DD_OrderLine_Alternative_ID Distribution Order Line Alternative */
@Override
public void setDD_OrderLine_Alternative_ID (int DD_OrderLine_Alternative_ID)
{
if (DD_OrderLine_Alternative_ID < 1)
set_Value (COLUMNNAME_DD_OrderLine_Alternative_ID, null);
else
set_Value (COLUMNNAME_DD_OrderLine_Alternative_ID, Integer.valueOf(DD_OrderLine_Alternative_ID));
}
/** Get Distribution Order Line Alternative.
@return Distribution Order Line Alternative */
@Override
public int getDD_OrderLine_Alternative_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DD_OrderLine_Alternative_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.eevolution.model.I_DD_OrderLine getDD_OrderLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class);
}
@Override
public void setDD_OrderLine(org.eevolution.model.I_DD_OrderLine DD_OrderLine)
{
set_ValueFromPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class, DD_OrderLine);
}
/** Set Distribution Order Line.
@param DD_OrderLine_ID Distribution Order Line */
@Override
public void setDD_OrderLine_ID (int DD_OrderLine_ID)
{
if (DD_OrderLine_ID < 1)
set_Value (COLUMNNAME_DD_OrderLine_ID, null);
else
set_Value (COLUMNNAME_DD_OrderLine_ID, Integer.valueOf(DD_OrderLine_ID));
}
/** Get Distribution Order Line.
@return Distribution Order Line */
@Override
public int getDD_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DD_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Zeile Nr..
@param Line
Unique line for this document
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstance(org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance);
}
/** Set Ausprägung Merkmals-Satz.
@param M_AttributeSetInstance_ID
Product Attribute Set Instance
*/
@Override
public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID));
}
/** Get Ausprägung Merkmals-Satz.
@return Product Attribute Set Instance
*/
@Override
public int getM_AttributeSetInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstanceTo() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstanceTo_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstanceTo(org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstanceTo)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstanceTo_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstanceTo);
}
/** Set Attribute Set Instance To.
@param M_AttributeSetInstanceTo_ID
Target Product Attribute Set Instance
*/
@Override
public void setM_AttributeSetInstanceTo_ID (int M_AttributeSetInstanceTo_ID)
{
if (M_AttributeSetInstanceTo_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstanceTo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstanceTo_ID, Integer.valueOf(M_AttributeSetInstanceTo_ID));
}
/** Get Attribute Set Instance To.
@return Target Product Attribute Set Instance
*/
@Override
public int getM_AttributeSetInstanceTo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstanceTo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_InOutLine getM_InOutLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class);
}
@Override
public void setM_InOutLine(org.compiere.model.I_M_InOutLine M_InOutLine)
{
set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine);
}
/** Set Versand-/Wareneingangsposition.
@param M_InOutLine_ID
Position auf Versand- oder Wareneingangsbeleg
*/
@Override
public void setM_InOutLine_ID (int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID));
}
/** Get Versand-/Wareneingangsposition.
@return Position auf Versand- oder Wareneingangsbeleg
*/
@Override
public int getM_InOutLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Locator getM_Locator() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Locator_ID, org.compiere.model.I_M_Locator.class);
}
@Override
public void setM_Locator(org.compiere.model.I_M_Locator M_Locator)
{
set_ValueFromPO(COLUMNNAME_M_Locator_ID, org.compiere.model.I_M_Locator.class, M_Locator);
}
/** Set Lagerort.
@param M_Locator_ID
Warehouse Locator
*/
@Override
public void setM_Locator_ID (int M_Locator_ID)
{
if (M_Locator_ID < 1)
set_Value (COLUMNNAME_M_Locator_ID, null);
else
set_Value (COLUMNNAME_M_Locator_ID, Integer.valueOf(M_Locator_ID));
}
/** Get Lagerort.
@return Warehouse Locator
*/
@Override
public int getM_Locator_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Locator_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Locator getM_LocatorTo() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_LocatorTo_ID, org.compiere.model.I_M_Locator.class);
}
@Override
public void setM_LocatorTo(org.compiere.model.I_M_Locator M_LocatorTo)
{
set_ValueFromPO(COLUMNNAME_M_LocatorTo_ID, org.compiere.model.I_M_Locator.class, M_LocatorTo);
}
/** Set Lagerort An.
@param M_LocatorTo_ID
Location inventory is moved to
*/
@Override
public void setM_LocatorTo_ID (int M_LocatorTo_ID)
{
if (M_LocatorTo_ID < 1)
set_Value (COLUMNNAME_M_LocatorTo_ID, null);
else
set_Value (COLUMNNAME_M_LocatorTo_ID, Integer.valueOf(M_LocatorTo_ID));
}
/** Get Lagerort An.
@return Location inventory is moved to
*/
@Override
public int getM_LocatorTo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LocatorTo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Movement getM_Movement() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Movement_ID, org.compiere.model.I_M_Movement.class);
}
@Override
public void setM_Movement(org.compiere.model.I_M_Movement M_Movement)
{
set_ValueFromPO(COLUMNNAME_M_Movement_ID, org.compiere.model.I_M_Movement.class, M_Movement);
}
/** Set Warenbewegung.
@param M_Movement_ID
Movement of Inventory
*/
@Override
public void setM_Movement_ID (int M_Movement_ID)
{
if (M_Movement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Movement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Movement_ID, Integer.valueOf(M_Movement_ID));
}
/** Get Warenbewegung.
@return Movement of Inventory
*/
@Override
public int getM_Movement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Warenbewegungs- Position.
@param M_MovementLine_ID
Inventory Move document Line
*/
@Override
public void setM_MovementLine_ID (int M_MovementLine_ID)
{
if (M_MovementLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_MovementLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_MovementLine_ID, Integer.valueOf(M_MovementLine_ID));
}
/** Get Warenbewegungs- Position.
@return Inventory Move document Line
*/
@Override
public int getM_MovementLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bewegungs-Menge.
@param MovementQty
Quantity of a product moved.
*/
@Override
public void setMovementQty (java.math.BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
/** Get Bewegungs-Menge.
@return Quantity of a product moved.
*/
@Override
public java.math.BigDecimal getMovementQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_M_MovementLine getReversalLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class);
}
@Override
public void setReversalLine(org.compiere.model.I_M_MovementLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class, ReversalLine);
}
/** Set Reversal Line.
@param ReversalLine_ID
Use to keep the reversal line ID for reversing costing purpose
*/
@Override
public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Reversal Line.
@return Use to keep the reversal line ID for reversing costing purpose
*/
@Override
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verworfene Menge.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
@Override
public void setScrappedQty (java.math.BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Verworfene Menge.
@return The Quantity scrapped due to QA issues
*/
@Override
public java.math.BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zielmenge.
@param TargetQty
Target Movement Quantity
*/
@Override
public void setTargetQty (java.math.BigDecimal TargetQty)
{
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Zielmenge.
@return Target Movement Quantity
*/
@Override
public java.math.BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
throw new IllegalArgumentException ("Value is virtual column"); }
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
@Override
public org.compiere.model.I_M_SectionCode getM_SectionCode()
{
return get_ValueAsPO(COLUMNNAME_M_SectionCode_ID, org.compiere.model.I_M_SectionCode.class);
}
@Override
public void setM_SectionCode(final org.compiere.model.I_M_SectionCode M_SectionCode)
{
set_ValueFromPO(COLUMNNAME_M_SectionCode_ID, org.compiere.model.I_M_SectionCode.class, M_SectionCode);
}
@Override
public void setM_SectionCode_ID (final int M_SectionCode_ID)
{
if (M_SectionCode_ID < 1)
set_Value (COLUMNNAME_M_SectionCode_ID, null);
else
set_Value (COLUMNNAME_M_SectionCode_ID, M_SectionCode_ID);
}
@Override
public int getM_SectionCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_SectionCode_ID);
}
}
| metasfresh/metasfresh | backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_M_MovementLine.java | 6,750 | /** Get Zielmenge.
@return Target Movement Quantity
*/ | block_comment | nl | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.Env;
/** Generated Model for M_MovementLine
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_M_MovementLine extends org.compiere.model.PO implements I_M_MovementLine, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 1007297111L;
/** Standard Constructor */
public X_M_MovementLine (Properties ctx, int M_MovementLine_ID, String trxName)
{
super (ctx, M_MovementLine_ID, trxName);
/** if (M_MovementLine_ID == 0)
{
setLine (0);
// @SQL=SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID=@M_Movement_ID@
setM_Locator_ID (0);
// @M_Locator_ID@
setM_LocatorTo_ID (0);
// @M_LocatorTo_ID@
setM_Movement_ID (0);
setM_MovementLine_ID (0);
setM_Product_ID (0);
setMovementQty (Env.ZERO);
// 1
setProcessed (false);
setTargetQty (Env.ZERO);
// 0
} */
}
/** Load Constructor */
public X_M_MovementLine (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder ("X_M_MovementLine[")
.append(get_ID()).append("]");
return sb.toString();
}
@Override
public org.compiere.model.I_C_Activity getC_Activity() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Activity_ID, org.compiere.model.I_C_Activity.class);
}
@Override
public void setC_Activity(org.compiere.model.I_C_Activity C_Activity)
{
set_ValueFromPO(COLUMNNAME_C_Activity_ID, org.compiere.model.I_C_Activity.class, C_Activity);
}
/** Set Kostenstelle.
@param C_Activity_ID
Kostenstelle
*/
@Override
public void setC_Activity_ID (int C_Activity_ID)
{
if (C_Activity_ID < 1)
set_Value (COLUMNNAME_C_Activity_ID, null);
else
set_Value (COLUMNNAME_C_Activity_ID, Integer.valueOf(C_Activity_ID));
}
/** Get Kostenstelle.
@return Kostenstelle
*/
@Override
public int getC_Activity_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Activity_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_Activity getC_ActivityFrom() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_ActivityFrom_ID, org.compiere.model.I_C_Activity.class);
}
@Override
public void setC_ActivityFrom(org.compiere.model.I_C_Activity C_ActivityFrom)
{
set_ValueFromPO(COLUMNNAME_C_ActivityFrom_ID, org.compiere.model.I_C_Activity.class, C_ActivityFrom);
}
/** Set Activity From.
@param C_ActivityFrom_ID Activity From */
@Override
public void setC_ActivityFrom_ID (int C_ActivityFrom_ID)
{
if (C_ActivityFrom_ID < 1)
set_Value (COLUMNNAME_C_ActivityFrom_ID, null);
else
set_Value (COLUMNNAME_C_ActivityFrom_ID, Integer.valueOf(C_ActivityFrom_ID));
}
/** Get Activity From.
@return Activity From */
@Override
public int getC_ActivityFrom_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ActivityFrom_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bestätigte Menge.
@param ConfirmedQty
Confirmation of a received quantity
*/
@Override
public void setConfirmedQty (java.math.BigDecimal ConfirmedQty)
{
set_Value (COLUMNNAME_ConfirmedQty, ConfirmedQty);
}
/** Get Bestätigte Menge.
@return Confirmation of a received quantity
*/
@Override
public java.math.BigDecimal getConfirmedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ConfirmedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
@Override
public org.eevolution.model.I_DD_OrderLine_Alternative getDD_OrderLine_Alternative() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DD_OrderLine_Alternative_ID, org.eevolution.model.I_DD_OrderLine_Alternative.class);
}
@Override
public void setDD_OrderLine_Alternative(org.eevolution.model.I_DD_OrderLine_Alternative DD_OrderLine_Alternative)
{
set_ValueFromPO(COLUMNNAME_DD_OrderLine_Alternative_ID, org.eevolution.model.I_DD_OrderLine_Alternative.class, DD_OrderLine_Alternative);
}
/** Set Distribution Order Line Alternative.
@param DD_OrderLine_Alternative_ID Distribution Order Line Alternative */
@Override
public void setDD_OrderLine_Alternative_ID (int DD_OrderLine_Alternative_ID)
{
if (DD_OrderLine_Alternative_ID < 1)
set_Value (COLUMNNAME_DD_OrderLine_Alternative_ID, null);
else
set_Value (COLUMNNAME_DD_OrderLine_Alternative_ID, Integer.valueOf(DD_OrderLine_Alternative_ID));
}
/** Get Distribution Order Line Alternative.
@return Distribution Order Line Alternative */
@Override
public int getDD_OrderLine_Alternative_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DD_OrderLine_Alternative_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.eevolution.model.I_DD_OrderLine getDD_OrderLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class);
}
@Override
public void setDD_OrderLine(org.eevolution.model.I_DD_OrderLine DD_OrderLine)
{
set_ValueFromPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class, DD_OrderLine);
}
/** Set Distribution Order Line.
@param DD_OrderLine_ID Distribution Order Line */
@Override
public void setDD_OrderLine_ID (int DD_OrderLine_ID)
{
if (DD_OrderLine_ID < 1)
set_Value (COLUMNNAME_DD_OrderLine_ID, null);
else
set_Value (COLUMNNAME_DD_OrderLine_ID, Integer.valueOf(DD_OrderLine_ID));
}
/** Get Distribution Order Line.
@return Distribution Order Line */
@Override
public int getDD_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DD_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Zeile Nr..
@param Line
Unique line for this document
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstance(org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance);
}
/** Set Ausprägung Merkmals-Satz.
@param M_AttributeSetInstance_ID
Product Attribute Set Instance
*/
@Override
public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID));
}
/** Get Ausprägung Merkmals-Satz.
@return Product Attribute Set Instance
*/
@Override
public int getM_AttributeSetInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstanceTo() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstanceTo_ID, org.compiere.model.I_M_AttributeSetInstance.class);
}
@Override
public void setM_AttributeSetInstanceTo(org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstanceTo)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstanceTo_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstanceTo);
}
/** Set Attribute Set Instance To.
@param M_AttributeSetInstanceTo_ID
Target Product Attribute Set Instance
*/
@Override
public void setM_AttributeSetInstanceTo_ID (int M_AttributeSetInstanceTo_ID)
{
if (M_AttributeSetInstanceTo_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstanceTo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstanceTo_ID, Integer.valueOf(M_AttributeSetInstanceTo_ID));
}
/** Get Attribute Set Instance To.
@return Target Product Attribute Set Instance
*/
@Override
public int getM_AttributeSetInstanceTo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstanceTo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_InOutLine getM_InOutLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class);
}
@Override
public void setM_InOutLine(org.compiere.model.I_M_InOutLine M_InOutLine)
{
set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine);
}
/** Set Versand-/Wareneingangsposition.
@param M_InOutLine_ID
Position auf Versand- oder Wareneingangsbeleg
*/
@Override
public void setM_InOutLine_ID (int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID));
}
/** Get Versand-/Wareneingangsposition.
@return Position auf Versand- oder Wareneingangsbeleg
*/
@Override
public int getM_InOutLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Locator getM_Locator() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Locator_ID, org.compiere.model.I_M_Locator.class);
}
@Override
public void setM_Locator(org.compiere.model.I_M_Locator M_Locator)
{
set_ValueFromPO(COLUMNNAME_M_Locator_ID, org.compiere.model.I_M_Locator.class, M_Locator);
}
/** Set Lagerort.
@param M_Locator_ID
Warehouse Locator
*/
@Override
public void setM_Locator_ID (int M_Locator_ID)
{
if (M_Locator_ID < 1)
set_Value (COLUMNNAME_M_Locator_ID, null);
else
set_Value (COLUMNNAME_M_Locator_ID, Integer.valueOf(M_Locator_ID));
}
/** Get Lagerort.
@return Warehouse Locator
*/
@Override
public int getM_Locator_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Locator_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Locator getM_LocatorTo() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_LocatorTo_ID, org.compiere.model.I_M_Locator.class);
}
@Override
public void setM_LocatorTo(org.compiere.model.I_M_Locator M_LocatorTo)
{
set_ValueFromPO(COLUMNNAME_M_LocatorTo_ID, org.compiere.model.I_M_Locator.class, M_LocatorTo);
}
/** Set Lagerort An.
@param M_LocatorTo_ID
Location inventory is moved to
*/
@Override
public void setM_LocatorTo_ID (int M_LocatorTo_ID)
{
if (M_LocatorTo_ID < 1)
set_Value (COLUMNNAME_M_LocatorTo_ID, null);
else
set_Value (COLUMNNAME_M_LocatorTo_ID, Integer.valueOf(M_LocatorTo_ID));
}
/** Get Lagerort An.
@return Location inventory is moved to
*/
@Override
public int getM_LocatorTo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LocatorTo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Movement getM_Movement() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Movement_ID, org.compiere.model.I_M_Movement.class);
}
@Override
public void setM_Movement(org.compiere.model.I_M_Movement M_Movement)
{
set_ValueFromPO(COLUMNNAME_M_Movement_ID, org.compiere.model.I_M_Movement.class, M_Movement);
}
/** Set Warenbewegung.
@param M_Movement_ID
Movement of Inventory
*/
@Override
public void setM_Movement_ID (int M_Movement_ID)
{
if (M_Movement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Movement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Movement_ID, Integer.valueOf(M_Movement_ID));
}
/** Get Warenbewegung.
@return Movement of Inventory
*/
@Override
public int getM_Movement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Warenbewegungs- Position.
@param M_MovementLine_ID
Inventory Move document Line
*/
@Override
public void setM_MovementLine_ID (int M_MovementLine_ID)
{
if (M_MovementLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_MovementLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_MovementLine_ID, Integer.valueOf(M_MovementLine_ID));
}
/** Get Warenbewegungs- Position.
@return Inventory Move document Line
*/
@Override
public int getM_MovementLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bewegungs-Menge.
@param MovementQty
Quantity of a product moved.
*/
@Override
public void setMovementQty (java.math.BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
/** Get Bewegungs-Menge.
@return Quantity of a product moved.
*/
@Override
public java.math.BigDecimal getMovementQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_M_MovementLine getReversalLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class);
}
@Override
public void setReversalLine(org.compiere.model.I_M_MovementLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class, ReversalLine);
}
/** Set Reversal Line.
@param ReversalLine_ID
Use to keep the reversal line ID for reversing costing purpose
*/
@Override
public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Reversal Line.
@return Use to keep the reversal line ID for reversing costing purpose
*/
@Override
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verworfene Menge.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
@Override
public void setScrappedQty (java.math.BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Verworfene Menge.
@return The Quantity scrapped due to QA issues
*/
@Override
public java.math.BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zielmenge.
@param TargetQty
Target Movement Quantity
*/
@Override
public void setTargetQty (java.math.BigDecimal TargetQty)
{
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Zielmenge.
<SUF>*/
@Override
public java.math.BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
throw new IllegalArgumentException ("Value is virtual column"); }
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
@Override
public org.compiere.model.I_M_SectionCode getM_SectionCode()
{
return get_ValueAsPO(COLUMNNAME_M_SectionCode_ID, org.compiere.model.I_M_SectionCode.class);
}
@Override
public void setM_SectionCode(final org.compiere.model.I_M_SectionCode M_SectionCode)
{
set_ValueFromPO(COLUMNNAME_M_SectionCode_ID, org.compiere.model.I_M_SectionCode.class, M_SectionCode);
}
@Override
public void setM_SectionCode_ID (final int M_SectionCode_ID)
{
if (M_SectionCode_ID < 1)
set_Value (COLUMNNAME_M_SectionCode_ID, null);
else
set_Value (COLUMNNAME_M_SectionCode_ID, M_SectionCode_ID);
}
@Override
public int getM_SectionCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_SectionCode_ID);
}
}
|
202980_2 | /*
* Licensed to the Technische Universität Darmstadt under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The Technische Universität Darmstadt
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.
*
* 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 org.dkpro.jwpl.parser.mediawiki;
import java.lang.invoke.MethodHandles;
import java.util.List;
import org.dkpro.jwpl.parser.Link;
import org.dkpro.jwpl.parser.ParsedPage;
import org.dkpro.jwpl.parser.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the TemplateParser for the german language, with special treatment for all the german
* templates, like "Dieser Artikel" or "Deutschlandlastig".
*/
public class GermanTemplateParser
implements MediaWikiTemplateParser
{
private static final Logger logger = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private final String templatePrefix = "TEMPLATE[";
private final String templatePostfix = "]";
private final String parameterDivisor = ", ";
private final String templateNotImplementedPrefix = "TEMPLATE NOT IMPLEMENTED[";
private final String templateNotImplementedPostfix = "]";
private final String emptyLinkText = "[ ]";
// private MediaWikiContentElementParser parser;
private final List<String> deleteTemplates;
private final List<String> parseTemplates;
public GermanTemplateParser(MediaWikiContentElementParser parser, List<String> deleteTemplates,
List<String> parseTemplates)
{
this.deleteTemplates = deleteTemplates;
this.parseTemplates = parseTemplates;
// this.parser = parser;
}
public String configurationInfo()
{
StringBuilder result = new StringBuilder();
result.append("Standard Template treatment: ShowNameAndParameters");
result.append("\nDelete Templates: ");
for (String s : deleteTemplates) {
result.append("\"" + s + "\" ");
}
result.append("\nParse Templates: ");
for (String s : parseTemplates) {
result.append("\"" + s + "\" ");
}
return result.toString();
}
public ResolvedTemplate parseTemplate(Template t, ParsedPage pp)
{
final String templateName = t.getName();
// Show Name and Parameters as Standart treatment.
ResolvedTemplate result = new ResolvedTemplate(t);
result.setPreParseReplacement(ResolvedTemplate.TEMPLATESPACER);
StringBuilder sb = new StringBuilder();
sb.append(templatePrefix);
sb.append(t.getName() + parameterDivisor);
for (String s : t.getParameters()) {
sb.append(s + parameterDivisor);
}
sb.delete(sb.length() - parameterDivisor.length(), sb.length());
sb.append(templatePostfix);
result.setPostParseReplacement(sb.toString());
result.setParsedObject(t);
// Delete Template if it is in the List
for (String s : deleteTemplates) {
if (s.equals(templateName)) {
result.setPostParseReplacement("");
result.setParsedObject(null);
return result;
}
}
// Parse Template if it is in the List
for (String s : parseTemplates) {
List<String> templateParameters = t.getParameters();
if (s.equals(templateName)) {
logger.info("ParseTemplate: {}", templateName);
if (templateName.equals("Dieser Artikel")) {
// I removed that from the core API, as it is not likely to be present in most
// non-German articles. (TZ)
// pp.setAboutArticle( parser.parseContentElement( templateParameters.get(0) ));
result.setPostParseReplacement("");
result.setParsedObject(null);
return result;
}
else if (templateName.equals("Audio") || templateName.equals("Audio genau")) {
if (templateParameters.size() == 0) {
break;
}
if (templateParameters.size() == 1) {
templateParameters.add(emptyLinkText);
}
result.setPostParseReplacement(t.getParameters().get(1));
result.setParsedObject(new Link(null, t.getPos(), templateParameters.get(0),
Link.type.AUDIO, null));
return result;
}
else if (templateName.equals("Video")) {
if (templateParameters.size() == 0) {
break;
}
if (templateParameters.size() == 1) {
templateParameters.add(emptyLinkText);
}
result.setPostParseReplacement(t.getParameters().get(1));
result.setParsedObject(new Link(null, t.getPos(), t.getParameters().get(0),
Link.type.VIDEO, null));
return result;
}
else {
result.setPostParseReplacement(templateNotImplementedPrefix + templateName
+ templateNotImplementedPostfix);
return result;
}
}
}
return result;
}
}
| dkpro/dkpro-jwpl | dkpro-jwpl-parser/src/main/java/org/dkpro/jwpl/parser/mediawiki/GermanTemplateParser.java | 1,337 | // private MediaWikiContentElementParser parser; | line_comment | nl | /*
* Licensed to the Technische Universität Darmstadt under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The Technische Universität Darmstadt
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.
*
* 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 org.dkpro.jwpl.parser.mediawiki;
import java.lang.invoke.MethodHandles;
import java.util.List;
import org.dkpro.jwpl.parser.Link;
import org.dkpro.jwpl.parser.ParsedPage;
import org.dkpro.jwpl.parser.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the TemplateParser for the german language, with special treatment for all the german
* templates, like "Dieser Artikel" or "Deutschlandlastig".
*/
public class GermanTemplateParser
implements MediaWikiTemplateParser
{
private static final Logger logger = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
private final String templatePrefix = "TEMPLATE[";
private final String templatePostfix = "]";
private final String parameterDivisor = ", ";
private final String templateNotImplementedPrefix = "TEMPLATE NOT IMPLEMENTED[";
private final String templateNotImplementedPostfix = "]";
private final String emptyLinkText = "[ ]";
// private MediaWikiContentElementParser<SUF>
private final List<String> deleteTemplates;
private final List<String> parseTemplates;
public GermanTemplateParser(MediaWikiContentElementParser parser, List<String> deleteTemplates,
List<String> parseTemplates)
{
this.deleteTemplates = deleteTemplates;
this.parseTemplates = parseTemplates;
// this.parser = parser;
}
public String configurationInfo()
{
StringBuilder result = new StringBuilder();
result.append("Standard Template treatment: ShowNameAndParameters");
result.append("\nDelete Templates: ");
for (String s : deleteTemplates) {
result.append("\"" + s + "\" ");
}
result.append("\nParse Templates: ");
for (String s : parseTemplates) {
result.append("\"" + s + "\" ");
}
return result.toString();
}
public ResolvedTemplate parseTemplate(Template t, ParsedPage pp)
{
final String templateName = t.getName();
// Show Name and Parameters as Standart treatment.
ResolvedTemplate result = new ResolvedTemplate(t);
result.setPreParseReplacement(ResolvedTemplate.TEMPLATESPACER);
StringBuilder sb = new StringBuilder();
sb.append(templatePrefix);
sb.append(t.getName() + parameterDivisor);
for (String s : t.getParameters()) {
sb.append(s + parameterDivisor);
}
sb.delete(sb.length() - parameterDivisor.length(), sb.length());
sb.append(templatePostfix);
result.setPostParseReplacement(sb.toString());
result.setParsedObject(t);
// Delete Template if it is in the List
for (String s : deleteTemplates) {
if (s.equals(templateName)) {
result.setPostParseReplacement("");
result.setParsedObject(null);
return result;
}
}
// Parse Template if it is in the List
for (String s : parseTemplates) {
List<String> templateParameters = t.getParameters();
if (s.equals(templateName)) {
logger.info("ParseTemplate: {}", templateName);
if (templateName.equals("Dieser Artikel")) {
// I removed that from the core API, as it is not likely to be present in most
// non-German articles. (TZ)
// pp.setAboutArticle( parser.parseContentElement( templateParameters.get(0) ));
result.setPostParseReplacement("");
result.setParsedObject(null);
return result;
}
else if (templateName.equals("Audio") || templateName.equals("Audio genau")) {
if (templateParameters.size() == 0) {
break;
}
if (templateParameters.size() == 1) {
templateParameters.add(emptyLinkText);
}
result.setPostParseReplacement(t.getParameters().get(1));
result.setParsedObject(new Link(null, t.getPos(), templateParameters.get(0),
Link.type.AUDIO, null));
return result;
}
else if (templateName.equals("Video")) {
if (templateParameters.size() == 0) {
break;
}
if (templateParameters.size() == 1) {
templateParameters.add(emptyLinkText);
}
result.setPostParseReplacement(t.getParameters().get(1));
result.setParsedObject(new Link(null, t.getPos(), t.getParameters().get(0),
Link.type.VIDEO, null));
return result;
}
else {
result.setPostParseReplacement(templateNotImplementedPrefix + templateName
+ templateNotImplementedPostfix);
return result;
}
}
}
return result;
}
}
|
202999_66 | //package de.webshop.util;
//
////import java.lang.invoke.MethodHandles;
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import de.webshop.artikelverwaltung.domain.Artikel;
//import de.webshop.artikelverwaltung.domain.Artikel.Kategorie;
//import de.webshop.bestellverwaltung.domain.Bestellung;
//import de.webshop.bestellverwaltung.domain.Position;
//import de.webshop.kundenverwaltung.domain.Adresse;
//import de.webshop.kundenverwaltung.domain.Adresse.Land;
//import de.webshop.kundenverwaltung.domain.Kunde;
//import de.webshop.kundenverwaltung.domain.Kundentyp;
//
////import org.jboss.logging.Logger;
//
//public final class Mock {
//
// // private static final Logger logger =
//
// private static final int MAX_ID = 99;
// private static final int MAX_KUNDEN = 8;
// private static final int MAX_BESTELLUNGEN = 4;
//
// public static Position findPositionById(Long id) {
// if (id > MAX_ID) {
// return null;
// }
//
// final Position position = new Position();
// position.setAnzahl(new Integer(2));
//
// position.setArtikel(Mock.findArtikelById(id));
// position.setID(id);
//
// return position;
// }
//
// public static Artikel findArtikelById(Long id) {
// final Artikel artikel = new Artikel();
// artikel.setID(id);
// artikel.setArtikelnummer("R2D2uC3PO");
// artikel.setBezeichnung("Robobike");
// artikel.setKurzBeschreibung("Das Robobike weiss wohin ...");
// artikel.setBeschreibung("Lange Robobikebeschreibu...........");
// artikel.setKategorie(Kategorie.KOMPLETTRAEDER);
// final Integer tempLaBe = new Integer(13);
// artikel.setLagerbestand(tempLaBe);
// final BigDecimal tempPreis = new BigDecimal(1300.50);
// artikel.setPreis(tempPreis);
//
// return artikel;
// }
//
// public static List<Position> findPositionenByBestellung(Bestellung bestellung) {
// final List<Position> positionen = bestellung.getPositionen();
// return positionen;
// }
//
// public static Kunde findKundeById(Long id) {
// if (id > MAX_ID) {
// return null;
// }
//
// final Kunde kunde = new Kunde();
// kunde.setID(id);
// kunde.setName("Nachname" + id);
// kunde.setEmail("" + id + "@hska.de");
//
// final Adresse adresse = new Adresse();
//
// if (id % 2 == 0) {
// adresse.setHausnummer("L4D");
// adresse.setID(id + 1);
// adresse.setLand(Land.DE);
// adresse.setPlz("76133");
// adresse.setStadt("Megashophausen");
// adresse.setStrasse("Bikestrasse");
// adresse.setKunde(kunde);
// }
// else {
// adresse.setHausnummer("B2B");
// adresse.setID(id + 1);
// adresse.setLand(Land.AT);
// adresse.setPlz("1885");
// adresse.setStadt("Weizen");
// adresse.setStrasse("Naturtruebweg");
// adresse.setKunde(kunde);
// }
// kunde.setAdresse(adresse);
//
// return kunde;
// }
//
// public static List<Kunde> findAllKunden() {
// final int anzahl = MAX_KUNDEN;
// final List<Kunde> kunden = new ArrayList<>(anzahl);
// for (int i = 1; i <= anzahl; i++) {
// final Kunde kunde = findKundeById(Long.valueOf(i));
// kunden.add(kunde);
// }
// return kunden;
// }
//
// public static List<Kunde> findKundenByNachname(String nachname) {
// final int anzahl = nachname.length();
// final List<Kunde> kunden = new ArrayList<>(anzahl);
// for (int i = 1; i <= anzahl; i++) {
// final Kunde kunde = findKundeById(Long.valueOf(i));
// kunde.setName(nachname);
// kunden.add(kunde);
// }
// return kunden;
// }
//
// public static Kunde findKundeByEmail(String email) {
// if (email.startsWith("x")) {
// return null;
// }
//
// final Kunde kunde = new Kunde();
// kunde.setID(Long.valueOf(email.length()));
// kunde.setName("Nachname");
// kunde.setVorname("Vorname");
// kunde.setEmail(email);
// kunde.setTyp(Kundentyp.PRIVATKUNDE);
// // final GregorianCalendar seitCal = new GregorianCalendar(JAHR, MONAT,
// // TAG);
// // final Date seit = seitCal.getTime();
// // kunde.setSeit(seit);
//
// final Adresse adresse = new Adresse();
// adresse.setID(kunde.getID() + 1); // andere ID fuer die Adresse
// adresse.setPlz("12345");
// adresse.setStadt("Testort");
// adresse.setKunde(kunde);
// kunde.setAdresse(adresse);
//
// return kunde;
// }
//
// public static Bestellung createBestellung(Bestellung bestellung, long kundeId) {
// System.out.printf("Neue Bestellung: %s fuer Kunde: %d\n", bestellung, kundeId);
// return bestellung;
// }
//
// public static List<Bestellung> findBestellungenByKunde(Kunde kunde) {
// // Beziehungsgeflecht zwischen Kunde und Bestellungen aufbauen
// final int anzahl = kunde.getID().intValue() % MAX_BESTELLUNGEN + 1;
// // 1 2 3 oder 4 Bestellungen
// final List<Bestellung> bestellungen = new ArrayList<>(anzahl);
// for (int i = 1; i <= anzahl; i++) {
// final Bestellung bestellung = findBestellungById(Long.valueOf(i));
// bestellung.setKunde(kunde);
// bestellungen.add(bestellung);
// }
//
// return bestellungen;
// }
//
// public static Bestellung findBestellungById(Long id) {
// if (id > MAX_ID) {
// return null;
// }
//
// final Kunde kunde = findKundeById(id + 1); // andere ID fuer den
// // Kunden
//
// final Bestellung bestellung = new Bestellung();
// bestellung.setID(id);
// bestellung.setKunde(kunde);
// final Date tempBestDatum = new Date(1234567890);
// bestellung.setBestelldatum(tempBestDatum);
//
// final List<Position> positionen = new ArrayList<Position>();
// positionen.add(findPositionById(1L));
// positionen.add(findPositionById(2L));
// bestellung.setPositionen(positionen);
//
// return bestellung;
// }
//
// public static Kunde createKunde(Kunde kunde) {
// // Neue IDs fuer Kunde und zugehoerige Adresse
// // Ein neuer Kunde hat auch keine Bestellungen
// final String nachname = kunde.getName();
// kunde.setID(Long.valueOf(nachname.length() ^ kunde.hashCode()));
//
//
// final Adresse adresse = kunde.getAdresse();
// adresse.setID((Long.valueOf(nachname.length())) + 1);
// adresse.setKunde(kunde);
//
// System.out.printf("Neuer Kunde: %s" , kunde);
// return kunde;
// }
//
// public static void updateKunde(Kunde kunde) {
// System.out.printf("Aktualisierter Kunde: %s" , kunde);
// }
//
// public static void deleteKunde(Long kundeId) {
// System.out.println("Delete Kunde");
// }
//
// public static Position createPosition(Position position, Bestellung bestellung) {
// if (position == null) {
// position = new Position();
// System.out.println("uebergebene Position ungueltig");
// }
// else {
// System.out.println(String.format("Create Position %d", position.getID()));
// }
//
// final Long tempId = new Long(12);
// position.setID(tempId);
// return position;
// }
//
// public static void updatePosition(Position position) {
// // gespeicherte Position finden
// // gesp. Position mir Werten aus Parameter ueberschreiben
//
// if (position == null) {
// System.out.println("Update fehlgeschlagen");
// }
// else {
// System.out.println(String.format("Update position %d", position.getID()));
// }
// }
//
// public static void deletePosition(long positionId) {
// System.out.println(String.format("Delete Position %d", positionId));
// }
//
// private Mock() { /**/
// }
//
// public static Artikel updateArtikel(Artikel artikel) {
// if (artikel == null) {
// System.out.println("Update fehlgeschlagen");
//
// artikel = new Artikel();
// }
// else {
// System.out.println(String.format("Update artikel %d", artikel.getID()));
// }
//
// return artikel;
// }
//
// public static Artikel createArtikel(Artikel artikel) {
// if (artikel == null) {
// System.out.println("Create fehlgeschlagen");
//
// artikel = new Artikel();
// }
// else {
// System.out.println("Create artikel");
// }
//
// final Long tempId = new Long(13);
// artikel.setID(tempId);
//
// return artikel;
// }
//
//}
| dastdev/shop-repo | webshop/src/main/java/de/webshop/util/Mock.java | 2,716 | // public static void deleteKunde(Long kundeId) {
| line_comment | nl | //package de.webshop.util;
//
////import java.lang.invoke.MethodHandles;
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import de.webshop.artikelverwaltung.domain.Artikel;
//import de.webshop.artikelverwaltung.domain.Artikel.Kategorie;
//import de.webshop.bestellverwaltung.domain.Bestellung;
//import de.webshop.bestellverwaltung.domain.Position;
//import de.webshop.kundenverwaltung.domain.Adresse;
//import de.webshop.kundenverwaltung.domain.Adresse.Land;
//import de.webshop.kundenverwaltung.domain.Kunde;
//import de.webshop.kundenverwaltung.domain.Kundentyp;
//
////import org.jboss.logging.Logger;
//
//public final class Mock {
//
// // private static final Logger logger =
//
// private static final int MAX_ID = 99;
// private static final int MAX_KUNDEN = 8;
// private static final int MAX_BESTELLUNGEN = 4;
//
// public static Position findPositionById(Long id) {
// if (id > MAX_ID) {
// return null;
// }
//
// final Position position = new Position();
// position.setAnzahl(new Integer(2));
//
// position.setArtikel(Mock.findArtikelById(id));
// position.setID(id);
//
// return position;
// }
//
// public static Artikel findArtikelById(Long id) {
// final Artikel artikel = new Artikel();
// artikel.setID(id);
// artikel.setArtikelnummer("R2D2uC3PO");
// artikel.setBezeichnung("Robobike");
// artikel.setKurzBeschreibung("Das Robobike weiss wohin ...");
// artikel.setBeschreibung("Lange Robobikebeschreibu...........");
// artikel.setKategorie(Kategorie.KOMPLETTRAEDER);
// final Integer tempLaBe = new Integer(13);
// artikel.setLagerbestand(tempLaBe);
// final BigDecimal tempPreis = new BigDecimal(1300.50);
// artikel.setPreis(tempPreis);
//
// return artikel;
// }
//
// public static List<Position> findPositionenByBestellung(Bestellung bestellung) {
// final List<Position> positionen = bestellung.getPositionen();
// return positionen;
// }
//
// public static Kunde findKundeById(Long id) {
// if (id > MAX_ID) {
// return null;
// }
//
// final Kunde kunde = new Kunde();
// kunde.setID(id);
// kunde.setName("Nachname" + id);
// kunde.setEmail("" + id + "@hska.de");
//
// final Adresse adresse = new Adresse();
//
// if (id % 2 == 0) {
// adresse.setHausnummer("L4D");
// adresse.setID(id + 1);
// adresse.setLand(Land.DE);
// adresse.setPlz("76133");
// adresse.setStadt("Megashophausen");
// adresse.setStrasse("Bikestrasse");
// adresse.setKunde(kunde);
// }
// else {
// adresse.setHausnummer("B2B");
// adresse.setID(id + 1);
// adresse.setLand(Land.AT);
// adresse.setPlz("1885");
// adresse.setStadt("Weizen");
// adresse.setStrasse("Naturtruebweg");
// adresse.setKunde(kunde);
// }
// kunde.setAdresse(adresse);
//
// return kunde;
// }
//
// public static List<Kunde> findAllKunden() {
// final int anzahl = MAX_KUNDEN;
// final List<Kunde> kunden = new ArrayList<>(anzahl);
// for (int i = 1; i <= anzahl; i++) {
// final Kunde kunde = findKundeById(Long.valueOf(i));
// kunden.add(kunde);
// }
// return kunden;
// }
//
// public static List<Kunde> findKundenByNachname(String nachname) {
// final int anzahl = nachname.length();
// final List<Kunde> kunden = new ArrayList<>(anzahl);
// for (int i = 1; i <= anzahl; i++) {
// final Kunde kunde = findKundeById(Long.valueOf(i));
// kunde.setName(nachname);
// kunden.add(kunde);
// }
// return kunden;
// }
//
// public static Kunde findKundeByEmail(String email) {
// if (email.startsWith("x")) {
// return null;
// }
//
// final Kunde kunde = new Kunde();
// kunde.setID(Long.valueOf(email.length()));
// kunde.setName("Nachname");
// kunde.setVorname("Vorname");
// kunde.setEmail(email);
// kunde.setTyp(Kundentyp.PRIVATKUNDE);
// // final GregorianCalendar seitCal = new GregorianCalendar(JAHR, MONAT,
// // TAG);
// // final Date seit = seitCal.getTime();
// // kunde.setSeit(seit);
//
// final Adresse adresse = new Adresse();
// adresse.setID(kunde.getID() + 1); // andere ID fuer die Adresse
// adresse.setPlz("12345");
// adresse.setStadt("Testort");
// adresse.setKunde(kunde);
// kunde.setAdresse(adresse);
//
// return kunde;
// }
//
// public static Bestellung createBestellung(Bestellung bestellung, long kundeId) {
// System.out.printf("Neue Bestellung: %s fuer Kunde: %d\n", bestellung, kundeId);
// return bestellung;
// }
//
// public static List<Bestellung> findBestellungenByKunde(Kunde kunde) {
// // Beziehungsgeflecht zwischen Kunde und Bestellungen aufbauen
// final int anzahl = kunde.getID().intValue() % MAX_BESTELLUNGEN + 1;
// // 1 2 3 oder 4 Bestellungen
// final List<Bestellung> bestellungen = new ArrayList<>(anzahl);
// for (int i = 1; i <= anzahl; i++) {
// final Bestellung bestellung = findBestellungById(Long.valueOf(i));
// bestellung.setKunde(kunde);
// bestellungen.add(bestellung);
// }
//
// return bestellungen;
// }
//
// public static Bestellung findBestellungById(Long id) {
// if (id > MAX_ID) {
// return null;
// }
//
// final Kunde kunde = findKundeById(id + 1); // andere ID fuer den
// // Kunden
//
// final Bestellung bestellung = new Bestellung();
// bestellung.setID(id);
// bestellung.setKunde(kunde);
// final Date tempBestDatum = new Date(1234567890);
// bestellung.setBestelldatum(tempBestDatum);
//
// final List<Position> positionen = new ArrayList<Position>();
// positionen.add(findPositionById(1L));
// positionen.add(findPositionById(2L));
// bestellung.setPositionen(positionen);
//
// return bestellung;
// }
//
// public static Kunde createKunde(Kunde kunde) {
// // Neue IDs fuer Kunde und zugehoerige Adresse
// // Ein neuer Kunde hat auch keine Bestellungen
// final String nachname = kunde.getName();
// kunde.setID(Long.valueOf(nachname.length() ^ kunde.hashCode()));
//
//
// final Adresse adresse = kunde.getAdresse();
// adresse.setID((Long.valueOf(nachname.length())) + 1);
// adresse.setKunde(kunde);
//
// System.out.printf("Neuer Kunde: %s" , kunde);
// return kunde;
// }
//
// public static void updateKunde(Kunde kunde) {
// System.out.printf("Aktualisierter Kunde: %s" , kunde);
// }
//
// public static<SUF>
// System.out.println("Delete Kunde");
// }
//
// public static Position createPosition(Position position, Bestellung bestellung) {
// if (position == null) {
// position = new Position();
// System.out.println("uebergebene Position ungueltig");
// }
// else {
// System.out.println(String.format("Create Position %d", position.getID()));
// }
//
// final Long tempId = new Long(12);
// position.setID(tempId);
// return position;
// }
//
// public static void updatePosition(Position position) {
// // gespeicherte Position finden
// // gesp. Position mir Werten aus Parameter ueberschreiben
//
// if (position == null) {
// System.out.println("Update fehlgeschlagen");
// }
// else {
// System.out.println(String.format("Update position %d", position.getID()));
// }
// }
//
// public static void deletePosition(long positionId) {
// System.out.println(String.format("Delete Position %d", positionId));
// }
//
// private Mock() { /**/
// }
//
// public static Artikel updateArtikel(Artikel artikel) {
// if (artikel == null) {
// System.out.println("Update fehlgeschlagen");
//
// artikel = new Artikel();
// }
// else {
// System.out.println(String.format("Update artikel %d", artikel.getID()));
// }
//
// return artikel;
// }
//
// public static Artikel createArtikel(Artikel artikel) {
// if (artikel == null) {
// System.out.println("Create fehlgeschlagen");
//
// artikel = new Artikel();
// }
// else {
// System.out.println("Create artikel");
// }
//
// final Long tempId = new Long(13);
// artikel.setID(tempId);
//
// return artikel;
// }
//
//}
|
203255_0 | /*
* Copyright (c) 2020 De Staat der Nederlanden, Ministerie van Volksgezondheid, Welzijn en Sport.
* Licensed under the EUROPEAN UNION PUBLIC LICENCE v. 1.2
*
* SPDX-License-Identifier: EUPL-1.2
*
*/
package nl.rijksoverheid.dbco.util;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
public class Obfuscator {
private static final byte OFFSET = -17;
/**
* Obfuscates the input into an unidentifiable text.
*
* @param input The string to hide the content of.
* @return The obfuscated string.
*/
public static String obfuscate(String input) {
// create bytes from the string
byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
// offset
byte[] offsetted = new byte[bytes.length];
for (int i = 0; i < bytes.length; ++i) {
byte current = bytes[i];
if (current + OFFSET < 0) {
offsetted[i] = (byte) (0xff + (current + OFFSET));
} else {
offsetted[i] = (byte) (current + OFFSET);
}
}
// byte value and order invert
byte[] unordered = new byte[offsetted.length];
for (int i = 0; i < offsetted.length; ++i) {
unordered[unordered.length - i - 1] = (byte) (~offsetted[i] & 0xff);
}
// base64 encode
byte[] result = Base64.encode(unordered, Base64.DEFAULT);
return new String(result, StandardCharsets.UTF_8);
}
/**
* Deobfuscates the string using our own methods
*
* @param input The string to deobfuscate.
* @return The result, which should equal with the input string of the obfuscation method.
*/
public static String deObfuscate(String input) {
// Input should be first Base64 decoded.
byte[] base64Decoded = Base64.decode(input, Base64.DEFAULT);
// Bytes are inverted in value and also order
byte[] ordered = new byte[base64Decoded.length];
for (int i = 0; i < base64Decoded.length; ++i) {
ordered[ordered.length - i - 1] = (byte) (~base64Decoded[i] & 0xff);
}
// they also have an offset
byte[] result = new byte[ordered.length];
for (int i = 0; i < ordered.length; ++i) {
byte current = ordered[i];
if (current - OFFSET > 0xff) {
result[i] = (byte) (current - OFFSET - 0xff);
} else {
result[i] = (byte) (current - OFFSET);
}
}
return new String(result, StandardCharsets.UTF_8);
}
/**
* With this method you can test if the obfuscator truly works on any string.
*
* @param input The string to test.
* @return True if the obfuscator works.
*/
public static boolean test(String input) {
String probe = deObfuscate(obfuscate(input));
return input.equals(probe);
}
} | minvws/nl-covid19-dbco-app-android | app/src/main/java/nl/rijksoverheid/dbco/util/Obfuscator.java | 840 | /*
* Copyright (c) 2020 De Staat der Nederlanden, Ministerie van Volksgezondheid, Welzijn en Sport.
* Licensed under the EUROPEAN UNION PUBLIC LICENCE v. 1.2
*
* SPDX-License-Identifier: EUPL-1.2
*
*/ | block_comment | nl | /*
* Copyright (c) 2020<SUF>*/
package nl.rijksoverheid.dbco.util;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
public class Obfuscator {
private static final byte OFFSET = -17;
/**
* Obfuscates the input into an unidentifiable text.
*
* @param input The string to hide the content of.
* @return The obfuscated string.
*/
public static String obfuscate(String input) {
// create bytes from the string
byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
// offset
byte[] offsetted = new byte[bytes.length];
for (int i = 0; i < bytes.length; ++i) {
byte current = bytes[i];
if (current + OFFSET < 0) {
offsetted[i] = (byte) (0xff + (current + OFFSET));
} else {
offsetted[i] = (byte) (current + OFFSET);
}
}
// byte value and order invert
byte[] unordered = new byte[offsetted.length];
for (int i = 0; i < offsetted.length; ++i) {
unordered[unordered.length - i - 1] = (byte) (~offsetted[i] & 0xff);
}
// base64 encode
byte[] result = Base64.encode(unordered, Base64.DEFAULT);
return new String(result, StandardCharsets.UTF_8);
}
/**
* Deobfuscates the string using our own methods
*
* @param input The string to deobfuscate.
* @return The result, which should equal with the input string of the obfuscation method.
*/
public static String deObfuscate(String input) {
// Input should be first Base64 decoded.
byte[] base64Decoded = Base64.decode(input, Base64.DEFAULT);
// Bytes are inverted in value and also order
byte[] ordered = new byte[base64Decoded.length];
for (int i = 0; i < base64Decoded.length; ++i) {
ordered[ordered.length - i - 1] = (byte) (~base64Decoded[i] & 0xff);
}
// they also have an offset
byte[] result = new byte[ordered.length];
for (int i = 0; i < ordered.length; ++i) {
byte current = ordered[i];
if (current - OFFSET > 0xff) {
result[i] = (byte) (current - OFFSET - 0xff);
} else {
result[i] = (byte) (current - OFFSET);
}
}
return new String(result, StandardCharsets.UTF_8);
}
/**
* With this method you can test if the obfuscator truly works on any string.
*
* @param input The string to test.
* @return True if the obfuscator works.
*/
public static boolean test(String input) {
String probe = deObfuscate(obfuscate(input));
return input.equals(probe);
}
} |
203261_1 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.brp.util.autconv;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.DienstbundelGroep;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PartijRol;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PersoonAfnemerindicatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortElementAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Stelsel;
import nl.bzk.algemeenbrp.test.dal.data.Data;
import nl.bzk.algemeenbrp.util.common.DatumUtil;
import nl.bzk.brp.domain.element.AttribuutElement;
import nl.bzk.brp.domain.element.ElementHelper;
import org.junit.Assert;
import org.junit.Test;
@Data(resources = {"classpath:dbunit-alleen-gba-autorisatie.xml", "classpath:dbunit-cleanup.xml"})
public class GbaAutConvIntegratieTest extends AbstractIntegratietest {
private static final String AFLEVERPUNT_BRP = "mijnuri";
static {
System.setProperty("afleverpunt", AFLEVERPUNT_BRP);
}
@PersistenceContext(unitName = "nl.bzk.brp.master")
private EntityManager em;
@Test
public void test() throws IOException {
final List<Leveringsautorisatie> preConversie = geefLeveringautorisaties();
Assert.assertTrue(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertFalse(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
getConverteerder().converteer();
controleerConversieLeveringsautorisatie();
controleerConversieToegangLeveringsautorisatie();
controleerAfnemerindicaties();
}
private void controleerAfnemerindicaties() {
final List<PersoonAfnemerindicatie> persoonAfnemerindicaties = geefAfnemerindicaties();
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).count());
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).count());
}
private void controleerConversieToegangLeveringsautorisatie() {
final List<ToegangLeveringsAutorisatie> toegangLeveringsAutorisaties = geefLo3ToegangLeveringsautorisaties();
final Optional<ToegangLeveringsAutorisatie> optionalLo3Autorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<ToegangLeveringsAutorisatie> optionalBrpAutorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final ToegangLeveringsAutorisatie lo3toegang = optionalLo3Autorisatie.get();
final ToegangLeveringsAutorisatie brptoegang = optionalBrpAutorisatie.get();
Assert.assertEquals(lo3toegang.getDatumIngang(), brptoegang.getDatumIngang());
Assert.assertEquals(20130101, brptoegang.getDatumIngang().intValue());
Assert.assertEquals(lo3toegang.getDatumEinde(), brptoegang.getDatumEinde());
Assert.assertEquals(20200101, brptoegang.getDatumEinde().intValue());
Assert.assertEquals(AFLEVERPUNT_BRP, brptoegang.getAfleverpunt());
Assert.assertEquals(lo3toegang.getIndicatieGeblokkeerd(), brptoegang.getIndicatieGeblokkeerd());
Assert.assertNull(brptoegang.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3toegang.getNaderePopulatiebeperking(), brptoegang.getNaderePopulatiebeperking());
Assert.assertEquals("naderepopulatiebeperking", brptoegang.getNaderePopulatiebeperking());
Assert.assertNull(brptoegang.getTransporteur());
Assert.assertNull(brptoegang.getOndertekenaar());
controleerPartijRol(lo3toegang.getGeautoriseerde(), brptoegang.getGeautoriseerde());
}
private void controleerPartijRol(final PartijRol lo3partijrol, final PartijRol brppartijrol) {
Assert.assertFalse(lo3partijrol == brppartijrol);
Assert.assertEquals(lo3partijrol.getDatumIngang(), brppartijrol.getDatumIngang());
Assert.assertEquals(lo3partijrol.getDatumEinde(), brppartijrol.getDatumEinde());
Assert.assertEquals(lo3partijrol.getRol(), brppartijrol.getRol());
controleerPartij(lo3partijrol.getPartij(), brppartijrol.getPartij());
}
private void controleerPartij(final Partij lo3partij, final Partij brppartij) {
Assert.assertEquals(lo3partij.getDatumIngang(), brppartij.getDatumIngang());
Assert.assertEquals(lo3partij.getDatumEinde(), brppartij.getDatumEinde());
Assert.assertEquals(lo3partij.getNaam() + "BRP" + lo3partij.getId().toString(), brppartij.getNaam());
Assert.assertEquals(lo3partij.getOin(), brppartij.getOin());
Assert.assertEquals(lo3partij.getIndicatieAutomatischFiatteren(), brppartij.getIndicatieAutomatischFiatteren());
Assert.assertEquals(DatumUtil.vandaag(), brppartij.getDatumOvergangNaarBrp().intValue());
Assert.assertNotEquals(lo3partij.getCode(), brppartij.getCode());
}
private void controleerConversieLeveringsautorisatie() {
//assert nu een GBA + BRP autorsatie
final List<Leveringsautorisatie> postConversie = geefLeveringautorisaties();
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
//start controle conversieregels
final Optional<Leveringsautorisatie> optionalLo3Autorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<Leveringsautorisatie> optionalBrpAutorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final Leveringsautorisatie lo3levAut = optionalLo3Autorisatie.get();
final Leveringsautorisatie brpLevAut = optionalBrpAutorisatie.get();
Assert.assertNotEquals(lo3levAut.getNaam(), brpLevAut.getNaam());
Assert.assertEquals("Rijksinstituut voor Volksgezondheid en Milieu (RIVM)/Onderzoek & crisissitBRP" + lo3levAut.getId(), brpLevAut.getNaam());
Assert.assertEquals(lo3levAut.getIndicatieModelautorisatie(), brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(false, brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(lo3levAut.getProtocolleringsniveau(), brpLevAut.getProtocolleringsniveau());
Assert.assertNull(brpLevAut.getProtocolleringsniveau());
Assert.assertEquals(lo3levAut.getIndicatieAliasSoortAdministratieveHandelingLeveren(),
brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertNull(brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertEquals(lo3levAut.getDatumIngang(), brpLevAut.getDatumIngang());
Assert.assertEquals(20130101, brpLevAut.getDatumIngang().intValue());
Assert.assertEquals(lo3levAut.getDatumEinde(), brpLevAut.getDatumEinde());
Assert.assertNull(brpLevAut.getDatumEinde());
Assert.assertEquals(lo3levAut.getPopulatiebeperking(), brpLevAut.getPopulatiebeperking());
Assert.assertEquals("WAAR", brpLevAut.getPopulatiebeperking());
Assert.assertEquals(lo3levAut.getToelichting(), brpLevAut.getToelichting());
Assert.assertEquals("toelichting", brpLevAut.getToelichting());
Assert.assertEquals(lo3levAut.getIndicatieGeblokkeerd(), brpLevAut.getIndicatieGeblokkeerd());
Assert.assertNull(brpLevAut.getIndicatieGeblokkeerd());
controleerDienstbundel(lo3levAut, brpLevAut);
}
private void controleerDienstbundel(final Leveringsautorisatie lo3levAut, final Leveringsautorisatie brpLevAut) {
Assert.assertEquals(lo3levAut.getDienstbundelSet().size(), 1);
Assert.assertEquals(brpLevAut.getDienstbundelSet().size(), 1);
final Dienstbundel lo3bundel = lo3levAut.getDienstbundelSet().iterator().next();
final Dienstbundel brpbundel = brpLevAut.getDienstbundelSet().iterator().next();
Assert.assertNotEquals(lo3bundel.getNaam(), brpbundel.getNaam());
Assert.assertEquals("Regionale Uitvoeringsdienst Drenthe (BSBm: Bestuurlijke Strafbeschikking mBRP" + lo3bundel.getId(), brpbundel.getNaam());
Assert.assertEquals(lo3bundel.getIndicatieGeblokkeerd(), brpbundel.getIndicatieGeblokkeerd());
Assert.assertNull(brpbundel.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3bundel.getToelichting(), brpbundel.getToelichting());
Assert.assertNull(brpbundel.getToelichting());
Assert.assertEquals(lo3bundel.getDatumIngang(), brpbundel.getDatumIngang());
Assert.assertEquals(20130101, brpbundel.getDatumIngang().intValue());
Assert.assertEquals(lo3bundel.getDatumEinde(), brpbundel.getDatumEinde());
Assert.assertEquals(20200101, brpbundel.getDatumEinde().intValue());
Assert.assertEquals(lo3bundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd(),
brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
Assert.assertNull(brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
controleerDienst(lo3bundel, brpbundel);
controleerDienstbundelGroep(brpbundel.getDienstbundelGroepSet());
}
private void controleerDienstbundelGroep(final Set<DienstbundelGroep> dienstbundelGroepSet) {
final Map<Element, DienstbundelGroep> groepMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> groepMap.put(dienstbundelGroep.getGroep(), dienstbundelGroep));
final Map<Element, Element> attribuutMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> dienstbundelGroep.getDienstbundelGroepAttribuutSet()
.forEach(dienstbundelGroepAttribuut -> attribuutMap.put(dienstbundelGroepAttribuut.getAttribuut(), dienstbundelGroep.getGroep())));
final Consumer<Element> assertAlleenVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertAlles = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertTrue(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieelEnVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieel = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
//01.01.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER));
//02.81.20
assertAlles.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GEBOORTE);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GESLACHTSAANDUIDING);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_SAMENGESTELDENAAM);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERSCHAP);
assertAlles.accept(Element.GERELATEERDEOUDER_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERLIJKGEZAG);
//58.12.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING));
assertMaterieel.accept(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING.getGroep());
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_GEBOORTE);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_IDENTIFICATIENUMMERS);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_SAMENGESTELDENAAM);
assertAlles.accept(Element.GERELATEERDEKIND_PERSOON_IDENTITEIT);
assertMaterieelEnVerantwoording.accept(Element.PERSOON_OUDER_OUDERSCHAP);
assertAlles.accept(Element.PERSOON_OUDER_IDENTITEIT);
//52.01.10
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER.getGroep());
//controleer uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_BIJHOUDINGSAARDCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_NADEREBIJHOUDINGSAARDCODE));
//controleer conditionele uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_INDICATIEPERSOONAANGETROFFENOPADRES));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEKIND_PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEOUDER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEHUWELIJKSPARTNER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEGEREGISTREERDEPARTNER_PERSOON_SOORTCODE));
//controleer uitzonderingen mbt onderzoek
final Consumer<Element> assertGeenVlaggen = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
assertGeenVlaggen.accept(Element.ONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_IDENTITEIT);
assertGeenVlaggen.accept(Element.ONDERZOEK_STANDAARD);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_STANDAARD);
assertGeenVlaggen.accept(Element.GEGEVENINONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.GEGEVENINONDERZOEK_IDENTITEIT);
}
private void controleerDienst(final Dienstbundel lo3bundel, final Dienstbundel brpbundel) {
Assert.assertEquals(lo3bundel.getDienstSet().size(), 1);
Assert.assertEquals(brpbundel.getDienstSet().size(), 1);
final Dienst lo3dienst = lo3bundel.getDienstSet().iterator().next();
final Dienst brpdienst = brpbundel.getDienstSet().iterator().next();
Assert.assertEquals(lo3dienst.getSoortDienst(), brpdienst.getSoortDienst());
Assert.assertEquals(SoortDienst.MUTATIELEVERING_OP_BASIS_VAN_DOELBINDING, brpdienst.getSoortDienst());
Assert.assertEquals(lo3dienst.getIndicatieGeblokkeerd(), brpdienst.getIndicatieGeblokkeerd());
Assert.assertNull(brpdienst.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3dienst.getDatumIngang(), brpdienst.getDatumIngang());
Assert.assertEquals(20130101, brpdienst.getDatumIngang().intValue());
Assert.assertEquals(lo3dienst.getDatumEinde(), brpdienst.getDatumEinde());
Assert.assertEquals(20200101, brpdienst.getDatumEinde().intValue());
Assert.assertEquals(lo3dienst.getAttenderingscriterium(), brpdienst.getAttenderingscriterium());
Assert.assertEquals("WAAR", brpdienst.getAttenderingscriterium());
Assert.assertEquals(lo3dienst.getEersteSelectieDatum(), brpdienst.getEersteSelectieDatum());
Assert.assertEquals(lo3dienst.getEffectAfnemerindicaties(), brpdienst.getEffectAfnemerindicaties());
Assert.assertEquals(lo3dienst.getMaximumAantalZoekresultaten(), brpdienst.getMaximumAantalZoekresultaten());
}
private List<Leveringsautorisatie> geefLeveringautorisaties() {
final TypedQuery<Leveringsautorisatie> query =
em.createQuery("select la from Leveringsautorisatie la ", Leveringsautorisatie.class);
return query.getResultList();
}
private List<ToegangLeveringsAutorisatie> geefLo3ToegangLeveringsautorisaties() {
final TypedQuery<ToegangLeveringsAutorisatie> query =
em.createQuery("select tla from ToegangLeveringsAutorisatie tla "
, ToegangLeveringsAutorisatie.class);
return query.getResultList();
}
private void assertBevatGroep(Element element, boolean formeel, boolean materieel, boolean verantwoording) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(),
queryBuilder().queryForObject(
String.format("select count(*) from autaut.dienstbundelgroep where groep = %d", element.getId()), Integer.class).intValue(), 1);
}
private List<PersoonAfnemerindicatie> geefAfnemerindicaties() {
final TypedQuery<PersoonAfnemerindicatie> query =
em.createQuery("select p from PersoonAfnemerindicatie p"
, PersoonAfnemerindicatie.class);
return query.getResultList();
}
private void assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element element) {
for (AttribuutElement attribuutElement : ElementHelper.getGroepElement(element).getAttributenInGroep()) {
boolean moetBevatten = attribuutElement.getAutorisatie() == SoortElementAutorisatie.AANBEVOLEN
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.VERPLICHT
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.OPTIONEEL;
assertBevatAttribuut(attribuutElement.getElement(), moetBevatten);
}
}
private void assertBevatAttribuut(Element element, boolean bevat) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(), queryBuilder().queryForObject(String.format("select count(*) from "
+ "autaut.dienstbundelgroepattr where attr = %d", element.getId()), Integer.class).intValue(), bevat ? 1 : 0);
}
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/brp/utils/lo3brp-autorisatie-conversie/src/test/java/nl/bzk/brp/util/autconv/GbaAutConvIntegratieTest.java | 5,902 | //assert nu een GBA + BRP autorsatie | line_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.brp.util.autconv;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.DienstbundelGroep;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PartijRol;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PersoonAfnemerindicatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortElementAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Stelsel;
import nl.bzk.algemeenbrp.test.dal.data.Data;
import nl.bzk.algemeenbrp.util.common.DatumUtil;
import nl.bzk.brp.domain.element.AttribuutElement;
import nl.bzk.brp.domain.element.ElementHelper;
import org.junit.Assert;
import org.junit.Test;
@Data(resources = {"classpath:dbunit-alleen-gba-autorisatie.xml", "classpath:dbunit-cleanup.xml"})
public class GbaAutConvIntegratieTest extends AbstractIntegratietest {
private static final String AFLEVERPUNT_BRP = "mijnuri";
static {
System.setProperty("afleverpunt", AFLEVERPUNT_BRP);
}
@PersistenceContext(unitName = "nl.bzk.brp.master")
private EntityManager em;
@Test
public void test() throws IOException {
final List<Leveringsautorisatie> preConversie = geefLeveringautorisaties();
Assert.assertTrue(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertFalse(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
getConverteerder().converteer();
controleerConversieLeveringsautorisatie();
controleerConversieToegangLeveringsautorisatie();
controleerAfnemerindicaties();
}
private void controleerAfnemerindicaties() {
final List<PersoonAfnemerindicatie> persoonAfnemerindicaties = geefAfnemerindicaties();
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).count());
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).count());
}
private void controleerConversieToegangLeveringsautorisatie() {
final List<ToegangLeveringsAutorisatie> toegangLeveringsAutorisaties = geefLo3ToegangLeveringsautorisaties();
final Optional<ToegangLeveringsAutorisatie> optionalLo3Autorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<ToegangLeveringsAutorisatie> optionalBrpAutorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final ToegangLeveringsAutorisatie lo3toegang = optionalLo3Autorisatie.get();
final ToegangLeveringsAutorisatie brptoegang = optionalBrpAutorisatie.get();
Assert.assertEquals(lo3toegang.getDatumIngang(), brptoegang.getDatumIngang());
Assert.assertEquals(20130101, brptoegang.getDatumIngang().intValue());
Assert.assertEquals(lo3toegang.getDatumEinde(), brptoegang.getDatumEinde());
Assert.assertEquals(20200101, brptoegang.getDatumEinde().intValue());
Assert.assertEquals(AFLEVERPUNT_BRP, brptoegang.getAfleverpunt());
Assert.assertEquals(lo3toegang.getIndicatieGeblokkeerd(), brptoegang.getIndicatieGeblokkeerd());
Assert.assertNull(brptoegang.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3toegang.getNaderePopulatiebeperking(), brptoegang.getNaderePopulatiebeperking());
Assert.assertEquals("naderepopulatiebeperking", brptoegang.getNaderePopulatiebeperking());
Assert.assertNull(brptoegang.getTransporteur());
Assert.assertNull(brptoegang.getOndertekenaar());
controleerPartijRol(lo3toegang.getGeautoriseerde(), brptoegang.getGeautoriseerde());
}
private void controleerPartijRol(final PartijRol lo3partijrol, final PartijRol brppartijrol) {
Assert.assertFalse(lo3partijrol == brppartijrol);
Assert.assertEquals(lo3partijrol.getDatumIngang(), brppartijrol.getDatumIngang());
Assert.assertEquals(lo3partijrol.getDatumEinde(), brppartijrol.getDatumEinde());
Assert.assertEquals(lo3partijrol.getRol(), brppartijrol.getRol());
controleerPartij(lo3partijrol.getPartij(), brppartijrol.getPartij());
}
private void controleerPartij(final Partij lo3partij, final Partij brppartij) {
Assert.assertEquals(lo3partij.getDatumIngang(), brppartij.getDatumIngang());
Assert.assertEquals(lo3partij.getDatumEinde(), brppartij.getDatumEinde());
Assert.assertEquals(lo3partij.getNaam() + "BRP" + lo3partij.getId().toString(), brppartij.getNaam());
Assert.assertEquals(lo3partij.getOin(), brppartij.getOin());
Assert.assertEquals(lo3partij.getIndicatieAutomatischFiatteren(), brppartij.getIndicatieAutomatischFiatteren());
Assert.assertEquals(DatumUtil.vandaag(), brppartij.getDatumOvergangNaarBrp().intValue());
Assert.assertNotEquals(lo3partij.getCode(), brppartij.getCode());
}
private void controleerConversieLeveringsautorisatie() {
//assert nu<SUF>
final List<Leveringsautorisatie> postConversie = geefLeveringautorisaties();
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
//start controle conversieregels
final Optional<Leveringsautorisatie> optionalLo3Autorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<Leveringsautorisatie> optionalBrpAutorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final Leveringsautorisatie lo3levAut = optionalLo3Autorisatie.get();
final Leveringsautorisatie brpLevAut = optionalBrpAutorisatie.get();
Assert.assertNotEquals(lo3levAut.getNaam(), brpLevAut.getNaam());
Assert.assertEquals("Rijksinstituut voor Volksgezondheid en Milieu (RIVM)/Onderzoek & crisissitBRP" + lo3levAut.getId(), brpLevAut.getNaam());
Assert.assertEquals(lo3levAut.getIndicatieModelautorisatie(), brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(false, brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(lo3levAut.getProtocolleringsniveau(), brpLevAut.getProtocolleringsniveau());
Assert.assertNull(brpLevAut.getProtocolleringsniveau());
Assert.assertEquals(lo3levAut.getIndicatieAliasSoortAdministratieveHandelingLeveren(),
brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertNull(brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertEquals(lo3levAut.getDatumIngang(), brpLevAut.getDatumIngang());
Assert.assertEquals(20130101, brpLevAut.getDatumIngang().intValue());
Assert.assertEquals(lo3levAut.getDatumEinde(), brpLevAut.getDatumEinde());
Assert.assertNull(brpLevAut.getDatumEinde());
Assert.assertEquals(lo3levAut.getPopulatiebeperking(), brpLevAut.getPopulatiebeperking());
Assert.assertEquals("WAAR", brpLevAut.getPopulatiebeperking());
Assert.assertEquals(lo3levAut.getToelichting(), brpLevAut.getToelichting());
Assert.assertEquals("toelichting", brpLevAut.getToelichting());
Assert.assertEquals(lo3levAut.getIndicatieGeblokkeerd(), brpLevAut.getIndicatieGeblokkeerd());
Assert.assertNull(brpLevAut.getIndicatieGeblokkeerd());
controleerDienstbundel(lo3levAut, brpLevAut);
}
private void controleerDienstbundel(final Leveringsautorisatie lo3levAut, final Leveringsautorisatie brpLevAut) {
Assert.assertEquals(lo3levAut.getDienstbundelSet().size(), 1);
Assert.assertEquals(brpLevAut.getDienstbundelSet().size(), 1);
final Dienstbundel lo3bundel = lo3levAut.getDienstbundelSet().iterator().next();
final Dienstbundel brpbundel = brpLevAut.getDienstbundelSet().iterator().next();
Assert.assertNotEquals(lo3bundel.getNaam(), brpbundel.getNaam());
Assert.assertEquals("Regionale Uitvoeringsdienst Drenthe (BSBm: Bestuurlijke Strafbeschikking mBRP" + lo3bundel.getId(), brpbundel.getNaam());
Assert.assertEquals(lo3bundel.getIndicatieGeblokkeerd(), brpbundel.getIndicatieGeblokkeerd());
Assert.assertNull(brpbundel.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3bundel.getToelichting(), brpbundel.getToelichting());
Assert.assertNull(brpbundel.getToelichting());
Assert.assertEquals(lo3bundel.getDatumIngang(), brpbundel.getDatumIngang());
Assert.assertEquals(20130101, brpbundel.getDatumIngang().intValue());
Assert.assertEquals(lo3bundel.getDatumEinde(), brpbundel.getDatumEinde());
Assert.assertEquals(20200101, brpbundel.getDatumEinde().intValue());
Assert.assertEquals(lo3bundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd(),
brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
Assert.assertNull(brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
controleerDienst(lo3bundel, brpbundel);
controleerDienstbundelGroep(brpbundel.getDienstbundelGroepSet());
}
private void controleerDienstbundelGroep(final Set<DienstbundelGroep> dienstbundelGroepSet) {
final Map<Element, DienstbundelGroep> groepMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> groepMap.put(dienstbundelGroep.getGroep(), dienstbundelGroep));
final Map<Element, Element> attribuutMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> dienstbundelGroep.getDienstbundelGroepAttribuutSet()
.forEach(dienstbundelGroepAttribuut -> attribuutMap.put(dienstbundelGroepAttribuut.getAttribuut(), dienstbundelGroep.getGroep())));
final Consumer<Element> assertAlleenVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertAlles = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertTrue(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieelEnVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieel = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
//01.01.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER));
//02.81.20
assertAlles.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GEBOORTE);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GESLACHTSAANDUIDING);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_SAMENGESTELDENAAM);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERSCHAP);
assertAlles.accept(Element.GERELATEERDEOUDER_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERLIJKGEZAG);
//58.12.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING));
assertMaterieel.accept(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING.getGroep());
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_GEBOORTE);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_IDENTIFICATIENUMMERS);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_SAMENGESTELDENAAM);
assertAlles.accept(Element.GERELATEERDEKIND_PERSOON_IDENTITEIT);
assertMaterieelEnVerantwoording.accept(Element.PERSOON_OUDER_OUDERSCHAP);
assertAlles.accept(Element.PERSOON_OUDER_IDENTITEIT);
//52.01.10
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER.getGroep());
//controleer uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_BIJHOUDINGSAARDCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_NADEREBIJHOUDINGSAARDCODE));
//controleer conditionele uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_INDICATIEPERSOONAANGETROFFENOPADRES));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEKIND_PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEOUDER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEHUWELIJKSPARTNER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEGEREGISTREERDEPARTNER_PERSOON_SOORTCODE));
//controleer uitzonderingen mbt onderzoek
final Consumer<Element> assertGeenVlaggen = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
assertGeenVlaggen.accept(Element.ONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_IDENTITEIT);
assertGeenVlaggen.accept(Element.ONDERZOEK_STANDAARD);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_STANDAARD);
assertGeenVlaggen.accept(Element.GEGEVENINONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.GEGEVENINONDERZOEK_IDENTITEIT);
}
private void controleerDienst(final Dienstbundel lo3bundel, final Dienstbundel brpbundel) {
Assert.assertEquals(lo3bundel.getDienstSet().size(), 1);
Assert.assertEquals(brpbundel.getDienstSet().size(), 1);
final Dienst lo3dienst = lo3bundel.getDienstSet().iterator().next();
final Dienst brpdienst = brpbundel.getDienstSet().iterator().next();
Assert.assertEquals(lo3dienst.getSoortDienst(), brpdienst.getSoortDienst());
Assert.assertEquals(SoortDienst.MUTATIELEVERING_OP_BASIS_VAN_DOELBINDING, brpdienst.getSoortDienst());
Assert.assertEquals(lo3dienst.getIndicatieGeblokkeerd(), brpdienst.getIndicatieGeblokkeerd());
Assert.assertNull(brpdienst.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3dienst.getDatumIngang(), brpdienst.getDatumIngang());
Assert.assertEquals(20130101, brpdienst.getDatumIngang().intValue());
Assert.assertEquals(lo3dienst.getDatumEinde(), brpdienst.getDatumEinde());
Assert.assertEquals(20200101, brpdienst.getDatumEinde().intValue());
Assert.assertEquals(lo3dienst.getAttenderingscriterium(), brpdienst.getAttenderingscriterium());
Assert.assertEquals("WAAR", brpdienst.getAttenderingscriterium());
Assert.assertEquals(lo3dienst.getEersteSelectieDatum(), brpdienst.getEersteSelectieDatum());
Assert.assertEquals(lo3dienst.getEffectAfnemerindicaties(), brpdienst.getEffectAfnemerindicaties());
Assert.assertEquals(lo3dienst.getMaximumAantalZoekresultaten(), brpdienst.getMaximumAantalZoekresultaten());
}
private List<Leveringsautorisatie> geefLeveringautorisaties() {
final TypedQuery<Leveringsautorisatie> query =
em.createQuery("select la from Leveringsautorisatie la ", Leveringsautorisatie.class);
return query.getResultList();
}
private List<ToegangLeveringsAutorisatie> geefLo3ToegangLeveringsautorisaties() {
final TypedQuery<ToegangLeveringsAutorisatie> query =
em.createQuery("select tla from ToegangLeveringsAutorisatie tla "
, ToegangLeveringsAutorisatie.class);
return query.getResultList();
}
private void assertBevatGroep(Element element, boolean formeel, boolean materieel, boolean verantwoording) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(),
queryBuilder().queryForObject(
String.format("select count(*) from autaut.dienstbundelgroep where groep = %d", element.getId()), Integer.class).intValue(), 1);
}
private List<PersoonAfnemerindicatie> geefAfnemerindicaties() {
final TypedQuery<PersoonAfnemerindicatie> query =
em.createQuery("select p from PersoonAfnemerindicatie p"
, PersoonAfnemerindicatie.class);
return query.getResultList();
}
private void assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element element) {
for (AttribuutElement attribuutElement : ElementHelper.getGroepElement(element).getAttributenInGroep()) {
boolean moetBevatten = attribuutElement.getAutorisatie() == SoortElementAutorisatie.AANBEVOLEN
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.VERPLICHT
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.OPTIONEEL;
assertBevatAttribuut(attribuutElement.getElement(), moetBevatten);
}
}
private void assertBevatAttribuut(Element element, boolean bevat) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(), queryBuilder().queryForObject(String.format("select count(*) from "
+ "autaut.dienstbundelgroepattr where attr = %d", element.getId()), Integer.class).intValue(), bevat ? 1 : 0);
}
}
|
203261_4 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.brp.util.autconv;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.DienstbundelGroep;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PartijRol;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PersoonAfnemerindicatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortElementAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Stelsel;
import nl.bzk.algemeenbrp.test.dal.data.Data;
import nl.bzk.algemeenbrp.util.common.DatumUtil;
import nl.bzk.brp.domain.element.AttribuutElement;
import nl.bzk.brp.domain.element.ElementHelper;
import org.junit.Assert;
import org.junit.Test;
@Data(resources = {"classpath:dbunit-alleen-gba-autorisatie.xml", "classpath:dbunit-cleanup.xml"})
public class GbaAutConvIntegratieTest extends AbstractIntegratietest {
private static final String AFLEVERPUNT_BRP = "mijnuri";
static {
System.setProperty("afleverpunt", AFLEVERPUNT_BRP);
}
@PersistenceContext(unitName = "nl.bzk.brp.master")
private EntityManager em;
@Test
public void test() throws IOException {
final List<Leveringsautorisatie> preConversie = geefLeveringautorisaties();
Assert.assertTrue(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertFalse(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
getConverteerder().converteer();
controleerConversieLeveringsautorisatie();
controleerConversieToegangLeveringsautorisatie();
controleerAfnemerindicaties();
}
private void controleerAfnemerindicaties() {
final List<PersoonAfnemerindicatie> persoonAfnemerindicaties = geefAfnemerindicaties();
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).count());
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).count());
}
private void controleerConversieToegangLeveringsautorisatie() {
final List<ToegangLeveringsAutorisatie> toegangLeveringsAutorisaties = geefLo3ToegangLeveringsautorisaties();
final Optional<ToegangLeveringsAutorisatie> optionalLo3Autorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<ToegangLeveringsAutorisatie> optionalBrpAutorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final ToegangLeveringsAutorisatie lo3toegang = optionalLo3Autorisatie.get();
final ToegangLeveringsAutorisatie brptoegang = optionalBrpAutorisatie.get();
Assert.assertEquals(lo3toegang.getDatumIngang(), brptoegang.getDatumIngang());
Assert.assertEquals(20130101, brptoegang.getDatumIngang().intValue());
Assert.assertEquals(lo3toegang.getDatumEinde(), brptoegang.getDatumEinde());
Assert.assertEquals(20200101, brptoegang.getDatumEinde().intValue());
Assert.assertEquals(AFLEVERPUNT_BRP, brptoegang.getAfleverpunt());
Assert.assertEquals(lo3toegang.getIndicatieGeblokkeerd(), brptoegang.getIndicatieGeblokkeerd());
Assert.assertNull(brptoegang.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3toegang.getNaderePopulatiebeperking(), brptoegang.getNaderePopulatiebeperking());
Assert.assertEquals("naderepopulatiebeperking", brptoegang.getNaderePopulatiebeperking());
Assert.assertNull(brptoegang.getTransporteur());
Assert.assertNull(brptoegang.getOndertekenaar());
controleerPartijRol(lo3toegang.getGeautoriseerde(), brptoegang.getGeautoriseerde());
}
private void controleerPartijRol(final PartijRol lo3partijrol, final PartijRol brppartijrol) {
Assert.assertFalse(lo3partijrol == brppartijrol);
Assert.assertEquals(lo3partijrol.getDatumIngang(), brppartijrol.getDatumIngang());
Assert.assertEquals(lo3partijrol.getDatumEinde(), brppartijrol.getDatumEinde());
Assert.assertEquals(lo3partijrol.getRol(), brppartijrol.getRol());
controleerPartij(lo3partijrol.getPartij(), brppartijrol.getPartij());
}
private void controleerPartij(final Partij lo3partij, final Partij brppartij) {
Assert.assertEquals(lo3partij.getDatumIngang(), brppartij.getDatumIngang());
Assert.assertEquals(lo3partij.getDatumEinde(), brppartij.getDatumEinde());
Assert.assertEquals(lo3partij.getNaam() + "BRP" + lo3partij.getId().toString(), brppartij.getNaam());
Assert.assertEquals(lo3partij.getOin(), brppartij.getOin());
Assert.assertEquals(lo3partij.getIndicatieAutomatischFiatteren(), brppartij.getIndicatieAutomatischFiatteren());
Assert.assertEquals(DatumUtil.vandaag(), brppartij.getDatumOvergangNaarBrp().intValue());
Assert.assertNotEquals(lo3partij.getCode(), brppartij.getCode());
}
private void controleerConversieLeveringsautorisatie() {
//assert nu een GBA + BRP autorsatie
final List<Leveringsautorisatie> postConversie = geefLeveringautorisaties();
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
//start controle conversieregels
final Optional<Leveringsautorisatie> optionalLo3Autorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<Leveringsautorisatie> optionalBrpAutorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final Leveringsautorisatie lo3levAut = optionalLo3Autorisatie.get();
final Leveringsautorisatie brpLevAut = optionalBrpAutorisatie.get();
Assert.assertNotEquals(lo3levAut.getNaam(), brpLevAut.getNaam());
Assert.assertEquals("Rijksinstituut voor Volksgezondheid en Milieu (RIVM)/Onderzoek & crisissitBRP" + lo3levAut.getId(), brpLevAut.getNaam());
Assert.assertEquals(lo3levAut.getIndicatieModelautorisatie(), brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(false, brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(lo3levAut.getProtocolleringsniveau(), brpLevAut.getProtocolleringsniveau());
Assert.assertNull(brpLevAut.getProtocolleringsniveau());
Assert.assertEquals(lo3levAut.getIndicatieAliasSoortAdministratieveHandelingLeveren(),
brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertNull(brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertEquals(lo3levAut.getDatumIngang(), brpLevAut.getDatumIngang());
Assert.assertEquals(20130101, brpLevAut.getDatumIngang().intValue());
Assert.assertEquals(lo3levAut.getDatumEinde(), brpLevAut.getDatumEinde());
Assert.assertNull(brpLevAut.getDatumEinde());
Assert.assertEquals(lo3levAut.getPopulatiebeperking(), brpLevAut.getPopulatiebeperking());
Assert.assertEquals("WAAR", brpLevAut.getPopulatiebeperking());
Assert.assertEquals(lo3levAut.getToelichting(), brpLevAut.getToelichting());
Assert.assertEquals("toelichting", brpLevAut.getToelichting());
Assert.assertEquals(lo3levAut.getIndicatieGeblokkeerd(), brpLevAut.getIndicatieGeblokkeerd());
Assert.assertNull(brpLevAut.getIndicatieGeblokkeerd());
controleerDienstbundel(lo3levAut, brpLevAut);
}
private void controleerDienstbundel(final Leveringsautorisatie lo3levAut, final Leveringsautorisatie brpLevAut) {
Assert.assertEquals(lo3levAut.getDienstbundelSet().size(), 1);
Assert.assertEquals(brpLevAut.getDienstbundelSet().size(), 1);
final Dienstbundel lo3bundel = lo3levAut.getDienstbundelSet().iterator().next();
final Dienstbundel brpbundel = brpLevAut.getDienstbundelSet().iterator().next();
Assert.assertNotEquals(lo3bundel.getNaam(), brpbundel.getNaam());
Assert.assertEquals("Regionale Uitvoeringsdienst Drenthe (BSBm: Bestuurlijke Strafbeschikking mBRP" + lo3bundel.getId(), brpbundel.getNaam());
Assert.assertEquals(lo3bundel.getIndicatieGeblokkeerd(), brpbundel.getIndicatieGeblokkeerd());
Assert.assertNull(brpbundel.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3bundel.getToelichting(), brpbundel.getToelichting());
Assert.assertNull(brpbundel.getToelichting());
Assert.assertEquals(lo3bundel.getDatumIngang(), brpbundel.getDatumIngang());
Assert.assertEquals(20130101, brpbundel.getDatumIngang().intValue());
Assert.assertEquals(lo3bundel.getDatumEinde(), brpbundel.getDatumEinde());
Assert.assertEquals(20200101, brpbundel.getDatumEinde().intValue());
Assert.assertEquals(lo3bundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd(),
brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
Assert.assertNull(brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
controleerDienst(lo3bundel, brpbundel);
controleerDienstbundelGroep(brpbundel.getDienstbundelGroepSet());
}
private void controleerDienstbundelGroep(final Set<DienstbundelGroep> dienstbundelGroepSet) {
final Map<Element, DienstbundelGroep> groepMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> groepMap.put(dienstbundelGroep.getGroep(), dienstbundelGroep));
final Map<Element, Element> attribuutMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> dienstbundelGroep.getDienstbundelGroepAttribuutSet()
.forEach(dienstbundelGroepAttribuut -> attribuutMap.put(dienstbundelGroepAttribuut.getAttribuut(), dienstbundelGroep.getGroep())));
final Consumer<Element> assertAlleenVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertAlles = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertTrue(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieelEnVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieel = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
//01.01.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER));
//02.81.20
assertAlles.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GEBOORTE);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GESLACHTSAANDUIDING);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_SAMENGESTELDENAAM);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERSCHAP);
assertAlles.accept(Element.GERELATEERDEOUDER_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERLIJKGEZAG);
//58.12.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING));
assertMaterieel.accept(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING.getGroep());
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_GEBOORTE);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_IDENTIFICATIENUMMERS);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_SAMENGESTELDENAAM);
assertAlles.accept(Element.GERELATEERDEKIND_PERSOON_IDENTITEIT);
assertMaterieelEnVerantwoording.accept(Element.PERSOON_OUDER_OUDERSCHAP);
assertAlles.accept(Element.PERSOON_OUDER_IDENTITEIT);
//52.01.10
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER.getGroep());
//controleer uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_BIJHOUDINGSAARDCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_NADEREBIJHOUDINGSAARDCODE));
//controleer conditionele uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_INDICATIEPERSOONAANGETROFFENOPADRES));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEKIND_PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEOUDER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEHUWELIJKSPARTNER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEGEREGISTREERDEPARTNER_PERSOON_SOORTCODE));
//controleer uitzonderingen mbt onderzoek
final Consumer<Element> assertGeenVlaggen = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
assertGeenVlaggen.accept(Element.ONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_IDENTITEIT);
assertGeenVlaggen.accept(Element.ONDERZOEK_STANDAARD);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_STANDAARD);
assertGeenVlaggen.accept(Element.GEGEVENINONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.GEGEVENINONDERZOEK_IDENTITEIT);
}
private void controleerDienst(final Dienstbundel lo3bundel, final Dienstbundel brpbundel) {
Assert.assertEquals(lo3bundel.getDienstSet().size(), 1);
Assert.assertEquals(brpbundel.getDienstSet().size(), 1);
final Dienst lo3dienst = lo3bundel.getDienstSet().iterator().next();
final Dienst brpdienst = brpbundel.getDienstSet().iterator().next();
Assert.assertEquals(lo3dienst.getSoortDienst(), brpdienst.getSoortDienst());
Assert.assertEquals(SoortDienst.MUTATIELEVERING_OP_BASIS_VAN_DOELBINDING, brpdienst.getSoortDienst());
Assert.assertEquals(lo3dienst.getIndicatieGeblokkeerd(), brpdienst.getIndicatieGeblokkeerd());
Assert.assertNull(brpdienst.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3dienst.getDatumIngang(), brpdienst.getDatumIngang());
Assert.assertEquals(20130101, brpdienst.getDatumIngang().intValue());
Assert.assertEquals(lo3dienst.getDatumEinde(), brpdienst.getDatumEinde());
Assert.assertEquals(20200101, brpdienst.getDatumEinde().intValue());
Assert.assertEquals(lo3dienst.getAttenderingscriterium(), brpdienst.getAttenderingscriterium());
Assert.assertEquals("WAAR", brpdienst.getAttenderingscriterium());
Assert.assertEquals(lo3dienst.getEersteSelectieDatum(), brpdienst.getEersteSelectieDatum());
Assert.assertEquals(lo3dienst.getEffectAfnemerindicaties(), brpdienst.getEffectAfnemerindicaties());
Assert.assertEquals(lo3dienst.getMaximumAantalZoekresultaten(), brpdienst.getMaximumAantalZoekresultaten());
}
private List<Leveringsautorisatie> geefLeveringautorisaties() {
final TypedQuery<Leveringsautorisatie> query =
em.createQuery("select la from Leveringsautorisatie la ", Leveringsautorisatie.class);
return query.getResultList();
}
private List<ToegangLeveringsAutorisatie> geefLo3ToegangLeveringsautorisaties() {
final TypedQuery<ToegangLeveringsAutorisatie> query =
em.createQuery("select tla from ToegangLeveringsAutorisatie tla "
, ToegangLeveringsAutorisatie.class);
return query.getResultList();
}
private void assertBevatGroep(Element element, boolean formeel, boolean materieel, boolean verantwoording) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(),
queryBuilder().queryForObject(
String.format("select count(*) from autaut.dienstbundelgroep where groep = %d", element.getId()), Integer.class).intValue(), 1);
}
private List<PersoonAfnemerindicatie> geefAfnemerindicaties() {
final TypedQuery<PersoonAfnemerindicatie> query =
em.createQuery("select p from PersoonAfnemerindicatie p"
, PersoonAfnemerindicatie.class);
return query.getResultList();
}
private void assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element element) {
for (AttribuutElement attribuutElement : ElementHelper.getGroepElement(element).getAttributenInGroep()) {
boolean moetBevatten = attribuutElement.getAutorisatie() == SoortElementAutorisatie.AANBEVOLEN
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.VERPLICHT
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.OPTIONEEL;
assertBevatAttribuut(attribuutElement.getElement(), moetBevatten);
}
}
private void assertBevatAttribuut(Element element, boolean bevat) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(), queryBuilder().queryForObject(String.format("select count(*) from "
+ "autaut.dienstbundelgroepattr where attr = %d", element.getId()), Integer.class).intValue(), bevat ? 1 : 0);
}
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/brp/utils/lo3brp-autorisatie-conversie/src/test/java/nl/bzk/brp/util/autconv/GbaAutConvIntegratieTest.java | 5,902 | //controleer uitzonderingen mbt onderzoek | line_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.brp.util.autconv;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.DienstbundelGroep;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Partij;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PartijRol;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.PersoonAfnemerindicatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Element;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortElementAutorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.enums.Stelsel;
import nl.bzk.algemeenbrp.test.dal.data.Data;
import nl.bzk.algemeenbrp.util.common.DatumUtil;
import nl.bzk.brp.domain.element.AttribuutElement;
import nl.bzk.brp.domain.element.ElementHelper;
import org.junit.Assert;
import org.junit.Test;
@Data(resources = {"classpath:dbunit-alleen-gba-autorisatie.xml", "classpath:dbunit-cleanup.xml"})
public class GbaAutConvIntegratieTest extends AbstractIntegratietest {
private static final String AFLEVERPUNT_BRP = "mijnuri";
static {
System.setProperty("afleverpunt", AFLEVERPUNT_BRP);
}
@PersistenceContext(unitName = "nl.bzk.brp.master")
private EntityManager em;
@Test
public void test() throws IOException {
final List<Leveringsautorisatie> preConversie = geefLeveringautorisaties();
Assert.assertTrue(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertFalse(preConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
getConverteerder().converteer();
controleerConversieLeveringsautorisatie();
controleerConversieToegangLeveringsautorisatie();
controleerAfnemerindicaties();
}
private void controleerAfnemerindicaties() {
final List<PersoonAfnemerindicatie> persoonAfnemerindicaties = geefAfnemerindicaties();
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).count());
Assert.assertEquals(2, persoonAfnemerindicaties.stream().filter(persoonAfnemerindicatie -> persoonAfnemerindicatie
.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).count());
}
private void controleerConversieToegangLeveringsautorisatie() {
final List<ToegangLeveringsAutorisatie> toegangLeveringsAutorisaties = geefLo3ToegangLeveringsautorisaties();
final Optional<ToegangLeveringsAutorisatie> optionalLo3Autorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<ToegangLeveringsAutorisatie> optionalBrpAutorisatie = toegangLeveringsAutorisaties.stream().filter(t
-> t.getLeveringsautorisatie().getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final ToegangLeveringsAutorisatie lo3toegang = optionalLo3Autorisatie.get();
final ToegangLeveringsAutorisatie brptoegang = optionalBrpAutorisatie.get();
Assert.assertEquals(lo3toegang.getDatumIngang(), brptoegang.getDatumIngang());
Assert.assertEquals(20130101, brptoegang.getDatumIngang().intValue());
Assert.assertEquals(lo3toegang.getDatumEinde(), brptoegang.getDatumEinde());
Assert.assertEquals(20200101, brptoegang.getDatumEinde().intValue());
Assert.assertEquals(AFLEVERPUNT_BRP, brptoegang.getAfleverpunt());
Assert.assertEquals(lo3toegang.getIndicatieGeblokkeerd(), brptoegang.getIndicatieGeblokkeerd());
Assert.assertNull(brptoegang.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3toegang.getNaderePopulatiebeperking(), brptoegang.getNaderePopulatiebeperking());
Assert.assertEquals("naderepopulatiebeperking", brptoegang.getNaderePopulatiebeperking());
Assert.assertNull(brptoegang.getTransporteur());
Assert.assertNull(brptoegang.getOndertekenaar());
controleerPartijRol(lo3toegang.getGeautoriseerde(), brptoegang.getGeautoriseerde());
}
private void controleerPartijRol(final PartijRol lo3partijrol, final PartijRol brppartijrol) {
Assert.assertFalse(lo3partijrol == brppartijrol);
Assert.assertEquals(lo3partijrol.getDatumIngang(), brppartijrol.getDatumIngang());
Assert.assertEquals(lo3partijrol.getDatumEinde(), brppartijrol.getDatumEinde());
Assert.assertEquals(lo3partijrol.getRol(), brppartijrol.getRol());
controleerPartij(lo3partijrol.getPartij(), brppartijrol.getPartij());
}
private void controleerPartij(final Partij lo3partij, final Partij brppartij) {
Assert.assertEquals(lo3partij.getDatumIngang(), brppartij.getDatumIngang());
Assert.assertEquals(lo3partij.getDatumEinde(), brppartij.getDatumEinde());
Assert.assertEquals(lo3partij.getNaam() + "BRP" + lo3partij.getId().toString(), brppartij.getNaam());
Assert.assertEquals(lo3partij.getOin(), brppartij.getOin());
Assert.assertEquals(lo3partij.getIndicatieAutomatischFiatteren(), brppartij.getIndicatieAutomatischFiatteren());
Assert.assertEquals(DatumUtil.vandaag(), brppartij.getDatumOvergangNaarBrp().intValue());
Assert.assertNotEquals(lo3partij.getCode(), brppartij.getCode());
}
private void controleerConversieLeveringsautorisatie() {
//assert nu een GBA + BRP autorsatie
final List<Leveringsautorisatie> postConversie = geefLeveringautorisaties();
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.GBA));
Assert.assertTrue(postConversie.stream().anyMatch(leveringsautorisatie -> leveringsautorisatie.getStelsel() == Stelsel.BRP));
//start controle conversieregels
final Optional<Leveringsautorisatie> optionalLo3Autorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.GBA).findFirst();
Assert.assertTrue(optionalLo3Autorisatie.isPresent());
final Optional<Leveringsautorisatie> optionalBrpAutorisatie = postConversie.stream().filter(leveringsautorisatie
-> leveringsautorisatie.getStelsel() == Stelsel.BRP).findFirst();
Assert.assertTrue(optionalBrpAutorisatie.isPresent());
final Leveringsautorisatie lo3levAut = optionalLo3Autorisatie.get();
final Leveringsautorisatie brpLevAut = optionalBrpAutorisatie.get();
Assert.assertNotEquals(lo3levAut.getNaam(), brpLevAut.getNaam());
Assert.assertEquals("Rijksinstituut voor Volksgezondheid en Milieu (RIVM)/Onderzoek & crisissitBRP" + lo3levAut.getId(), brpLevAut.getNaam());
Assert.assertEquals(lo3levAut.getIndicatieModelautorisatie(), brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(false, brpLevAut.getIndicatieModelautorisatie());
Assert.assertEquals(lo3levAut.getProtocolleringsniveau(), brpLevAut.getProtocolleringsniveau());
Assert.assertNull(brpLevAut.getProtocolleringsniveau());
Assert.assertEquals(lo3levAut.getIndicatieAliasSoortAdministratieveHandelingLeveren(),
brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertNull(brpLevAut.getIndicatieAliasSoortAdministratieveHandelingLeveren());
Assert.assertEquals(lo3levAut.getDatumIngang(), brpLevAut.getDatumIngang());
Assert.assertEquals(20130101, brpLevAut.getDatumIngang().intValue());
Assert.assertEquals(lo3levAut.getDatumEinde(), brpLevAut.getDatumEinde());
Assert.assertNull(brpLevAut.getDatumEinde());
Assert.assertEquals(lo3levAut.getPopulatiebeperking(), brpLevAut.getPopulatiebeperking());
Assert.assertEquals("WAAR", brpLevAut.getPopulatiebeperking());
Assert.assertEquals(lo3levAut.getToelichting(), brpLevAut.getToelichting());
Assert.assertEquals("toelichting", brpLevAut.getToelichting());
Assert.assertEquals(lo3levAut.getIndicatieGeblokkeerd(), brpLevAut.getIndicatieGeblokkeerd());
Assert.assertNull(brpLevAut.getIndicatieGeblokkeerd());
controleerDienstbundel(lo3levAut, brpLevAut);
}
private void controleerDienstbundel(final Leveringsautorisatie lo3levAut, final Leveringsautorisatie brpLevAut) {
Assert.assertEquals(lo3levAut.getDienstbundelSet().size(), 1);
Assert.assertEquals(brpLevAut.getDienstbundelSet().size(), 1);
final Dienstbundel lo3bundel = lo3levAut.getDienstbundelSet().iterator().next();
final Dienstbundel brpbundel = brpLevAut.getDienstbundelSet().iterator().next();
Assert.assertNotEquals(lo3bundel.getNaam(), brpbundel.getNaam());
Assert.assertEquals("Regionale Uitvoeringsdienst Drenthe (BSBm: Bestuurlijke Strafbeschikking mBRP" + lo3bundel.getId(), brpbundel.getNaam());
Assert.assertEquals(lo3bundel.getIndicatieGeblokkeerd(), brpbundel.getIndicatieGeblokkeerd());
Assert.assertNull(brpbundel.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3bundel.getToelichting(), brpbundel.getToelichting());
Assert.assertNull(brpbundel.getToelichting());
Assert.assertEquals(lo3bundel.getDatumIngang(), brpbundel.getDatumIngang());
Assert.assertEquals(20130101, brpbundel.getDatumIngang().intValue());
Assert.assertEquals(lo3bundel.getDatumEinde(), brpbundel.getDatumEinde());
Assert.assertEquals(20200101, brpbundel.getDatumEinde().intValue());
Assert.assertEquals(lo3bundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd(),
brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
Assert.assertNull(brpbundel.getIndicatieNaderePopulatiebeperkingVolledigGeconverteerd());
controleerDienst(lo3bundel, brpbundel);
controleerDienstbundelGroep(brpbundel.getDienstbundelGroepSet());
}
private void controleerDienstbundelGroep(final Set<DienstbundelGroep> dienstbundelGroepSet) {
final Map<Element, DienstbundelGroep> groepMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> groepMap.put(dienstbundelGroep.getGroep(), dienstbundelGroep));
final Map<Element, Element> attribuutMap = Maps.newHashMap();
dienstbundelGroepSet.forEach(dienstbundelGroep -> dienstbundelGroep.getDienstbundelGroepAttribuutSet()
.forEach(dienstbundelGroepAttribuut -> attribuutMap.put(dienstbundelGroepAttribuut.getAttribuut(), dienstbundelGroep.getGroep())));
final Consumer<Element> assertAlleenVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertAlles = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertTrue(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieelEnVerantwoording = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertTrue(g.getIndicatieVerantwoording());
};
final Consumer<Element> assertMaterieel = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertTrue(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
//01.01.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER));
//02.81.20
assertAlles.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GEBOORTE);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_GESLACHTSAANDUIDING);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_SAMENGESTELDENAAM);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERSCHAP);
assertAlles.accept(Element.GERELATEERDEOUDER_IDENTITEIT);
assertAlleenVerantwoording.accept(Element.GERELATEERDEOUDER_OUDERLIJKGEZAG);
//58.12.10
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING));
assertMaterieel.accept(Element.PERSOON_ADRES_LOCATIEOMSCHRIJVING.getGroep());
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_GEBOORTE);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_IDENTIFICATIENUMMERS);
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEKIND_PERSOON_SAMENGESTELDENAAM);
assertAlles.accept(Element.GERELATEERDEKIND_PERSOON_IDENTITEIT);
assertMaterieelEnVerantwoording.accept(Element.PERSOON_OUDER_OUDERSCHAP);
assertAlles.accept(Element.PERSOON_OUDER_IDENTITEIT);
//52.01.10
assertMaterieelEnVerantwoording.accept(Element.GERELATEERDEOUDER_PERSOON_IDENTIFICATIENUMMERS_ADMINISTRATIENUMMER.getGroep());
//controleer uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_BIJHOUDINGSAARDCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_BIJHOUDING_NADEREBIJHOUDINGSAARDCODE));
//controleer conditionele uitzonderingen
Assert.assertTrue(attribuutMap.containsKey(Element.PERSOON_ADRES_INDICATIEPERSOONAANGETROFFENOPADRES));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEKIND_PERSOON_SOORTCODE));
Assert.assertTrue(attribuutMap.containsKey(Element.GERELATEERDEOUDER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEHUWELIJKSPARTNER_PERSOON_SOORTCODE));
Assert.assertFalse(attribuutMap.containsKey(Element.GERELATEERDEGEREGISTREERDEPARTNER_PERSOON_SOORTCODE));
//controleer uitzonderingen<SUF>
final Consumer<Element> assertGeenVlaggen = (e) -> {
final DienstbundelGroep g = groepMap.get(e);
Assert.assertNotNull(g);
Assert.assertFalse(g.getIndicatieFormeleHistorie());
Assert.assertFalse(g.getIndicatieMaterieleHistorie());
Assert.assertFalse(g.getIndicatieVerantwoording());
};
assertGeenVlaggen.accept(Element.ONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_IDENTITEIT);
assertGeenVlaggen.accept(Element.ONDERZOEK_STANDAARD);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.ONDERZOEK_STANDAARD);
assertGeenVlaggen.accept(Element.GEGEVENINONDERZOEK_IDENTITEIT);
assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element.GEGEVENINONDERZOEK_IDENTITEIT);
}
private void controleerDienst(final Dienstbundel lo3bundel, final Dienstbundel brpbundel) {
Assert.assertEquals(lo3bundel.getDienstSet().size(), 1);
Assert.assertEquals(brpbundel.getDienstSet().size(), 1);
final Dienst lo3dienst = lo3bundel.getDienstSet().iterator().next();
final Dienst brpdienst = brpbundel.getDienstSet().iterator().next();
Assert.assertEquals(lo3dienst.getSoortDienst(), brpdienst.getSoortDienst());
Assert.assertEquals(SoortDienst.MUTATIELEVERING_OP_BASIS_VAN_DOELBINDING, brpdienst.getSoortDienst());
Assert.assertEquals(lo3dienst.getIndicatieGeblokkeerd(), brpdienst.getIndicatieGeblokkeerd());
Assert.assertNull(brpdienst.getIndicatieGeblokkeerd());
Assert.assertEquals(lo3dienst.getDatumIngang(), brpdienst.getDatumIngang());
Assert.assertEquals(20130101, brpdienst.getDatumIngang().intValue());
Assert.assertEquals(lo3dienst.getDatumEinde(), brpdienst.getDatumEinde());
Assert.assertEquals(20200101, brpdienst.getDatumEinde().intValue());
Assert.assertEquals(lo3dienst.getAttenderingscriterium(), brpdienst.getAttenderingscriterium());
Assert.assertEquals("WAAR", brpdienst.getAttenderingscriterium());
Assert.assertEquals(lo3dienst.getEersteSelectieDatum(), brpdienst.getEersteSelectieDatum());
Assert.assertEquals(lo3dienst.getEffectAfnemerindicaties(), brpdienst.getEffectAfnemerindicaties());
Assert.assertEquals(lo3dienst.getMaximumAantalZoekresultaten(), brpdienst.getMaximumAantalZoekresultaten());
}
private List<Leveringsautorisatie> geefLeveringautorisaties() {
final TypedQuery<Leveringsautorisatie> query =
em.createQuery("select la from Leveringsautorisatie la ", Leveringsautorisatie.class);
return query.getResultList();
}
private List<ToegangLeveringsAutorisatie> geefLo3ToegangLeveringsautorisaties() {
final TypedQuery<ToegangLeveringsAutorisatie> query =
em.createQuery("select tla from ToegangLeveringsAutorisatie tla "
, ToegangLeveringsAutorisatie.class);
return query.getResultList();
}
private void assertBevatGroep(Element element, boolean formeel, boolean materieel, boolean verantwoording) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(),
queryBuilder().queryForObject(
String.format("select count(*) from autaut.dienstbundelgroep where groep = %d", element.getId()), Integer.class).intValue(), 1);
}
private List<PersoonAfnemerindicatie> geefAfnemerindicaties() {
final TypedQuery<PersoonAfnemerindicatie> query =
em.createQuery("select p from PersoonAfnemerindicatie p"
, PersoonAfnemerindicatie.class);
return query.getResultList();
}
private void assertGroepBevatOptioneleVerplichtAanbevolenAttributen(Element element) {
for (AttribuutElement attribuutElement : ElementHelper.getGroepElement(element).getAttributenInGroep()) {
boolean moetBevatten = attribuutElement.getAutorisatie() == SoortElementAutorisatie.AANBEVOLEN
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.VERPLICHT
|| attribuutElement.getAutorisatie() == SoortElementAutorisatie.OPTIONEEL;
assertBevatAttribuut(attribuutElement.getElement(), moetBevatten);
}
}
private void assertBevatAttribuut(Element element, boolean bevat) {
Assert.assertEquals("Groep niet aanwezig: " + element.getNaam(), queryBuilder().queryForObject(String.format("select count(*) from "
+ "autaut.dienstbundelgroepattr where attr = %d", element.getId()), Integer.class).intValue(), bevat ? 1 : 0);
}
}
|
203276_2 | package be.mxs.common.util.diagnostics;
import be.mxs.common.util.db.MedwanQuery;
import java.sql.*;
/**
* Created by IntelliJ IDEA.
* User: frank
* Date: 7-okt-2005
* Time: 13:05:14
* To change this template use Options | File Templates.
*/
public class CleanUsers extends Diagnostic{
public CleanUsers(){
name="CheckUsersTable";
id="MXS.2";
author="[email protected]";
description="Checks if there are no double User records. Corrects if there are.";
version="1.0";
date="12/10/2005";
}
public Diagnosis check(){
Diagnosis diagnosis = new Diagnosis();
Connection connection=MedwanQuery.getInstance().getAdminConnection();
PreparedStatement ps;
ResultSet rs;
try {
ps = connection.prepareStatement("select count(*) total,userid from Users group by userid order by total DESC");
rs=ps.executeQuery();
while (rs.next()){
if (rs.getInt("total")>1){
diagnosis.values.add(new Integer(rs.getInt("userid")));
diagnosis.hasProblems=true;
}
}
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return diagnosis;
}
public boolean correct(Diagnosis diagnosis){
boolean correct=true;
Connection connection = MedwanQuery.getInstance().getAdminConnection();
PreparedStatement ps;
ResultSet rs;
try {
for (int n=0;n<diagnosis.values.size();n++){
//We gaan eerst de blijvende gebruiker voor elke van deze dubbele userid's opzoeken
int userid=((Integer)diagnosis.values.elementAt(n)).intValue();
ps = connection.prepareStatement("select a.* from Users a,Admin b where a.personid=b.personid and userid=? order by a.updatetime DESC");
ps.setInt(1,userid);
rs=ps.executeQuery();
if (rs.next()){
int goodPersonId = rs.getInt("personid");
int goodUserId=rs.getInt("userid");
Timestamp goodStart = rs.getTimestamp("start");
Timestamp goodStop = rs.getTimestamp("stop");
Timestamp goodUpdatetime = rs.getTimestamp("updatetime");
String goodProject=rs.getString("project");
byte[] goodPassword = rs.getBytes("encryptedpassword");
rs.close();
ps.close();
ps = connection.prepareStatement("delete from Users where userid=?");
ps.setInt(1,userid);
ps.execute();
ps = connection.prepareStatement("insert into Users(userid,personid,start,stop,updatetime,project,encryptedpassword) values(?,?,?,?,?,?,?)");
ps.setInt(1,goodUserId);
ps.setInt(2,goodPersonId);
ps.setTimestamp(3,goodStart);
ps.setTimestamp(4,goodStop);
ps.setTimestamp(5,goodUpdatetime);
ps.setString(6,goodProject);
ps.setBytes(7,goodPassword);
ps.execute();
ps.close();
}
else {
rs.close();
ps.close();
}
}
} catch (SQLException e) {
correct=false;
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return correct;
}
}
| freemed/openclinicga-old | src/be/mxs/common/util/diagnostics/CleanUsers.java | 927 | //We gaan eerst de blijvende gebruiker voor elke van deze dubbele userid's opzoeken
| line_comment | nl | package be.mxs.common.util.diagnostics;
import be.mxs.common.util.db.MedwanQuery;
import java.sql.*;
/**
* Created by IntelliJ IDEA.
* User: frank
* Date: 7-okt-2005
* Time: 13:05:14
* To change this template use Options | File Templates.
*/
public class CleanUsers extends Diagnostic{
public CleanUsers(){
name="CheckUsersTable";
id="MXS.2";
author="[email protected]";
description="Checks if there are no double User records. Corrects if there are.";
version="1.0";
date="12/10/2005";
}
public Diagnosis check(){
Diagnosis diagnosis = new Diagnosis();
Connection connection=MedwanQuery.getInstance().getAdminConnection();
PreparedStatement ps;
ResultSet rs;
try {
ps = connection.prepareStatement("select count(*) total,userid from Users group by userid order by total DESC");
rs=ps.executeQuery();
while (rs.next()){
if (rs.getInt("total")>1){
diagnosis.values.add(new Integer(rs.getInt("userid")));
diagnosis.hasProblems=true;
}
}
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return diagnosis;
}
public boolean correct(Diagnosis diagnosis){
boolean correct=true;
Connection connection = MedwanQuery.getInstance().getAdminConnection();
PreparedStatement ps;
ResultSet rs;
try {
for (int n=0;n<diagnosis.values.size();n++){
//We gaan<SUF>
int userid=((Integer)diagnosis.values.elementAt(n)).intValue();
ps = connection.prepareStatement("select a.* from Users a,Admin b where a.personid=b.personid and userid=? order by a.updatetime DESC");
ps.setInt(1,userid);
rs=ps.executeQuery();
if (rs.next()){
int goodPersonId = rs.getInt("personid");
int goodUserId=rs.getInt("userid");
Timestamp goodStart = rs.getTimestamp("start");
Timestamp goodStop = rs.getTimestamp("stop");
Timestamp goodUpdatetime = rs.getTimestamp("updatetime");
String goodProject=rs.getString("project");
byte[] goodPassword = rs.getBytes("encryptedpassword");
rs.close();
ps.close();
ps = connection.prepareStatement("delete from Users where userid=?");
ps.setInt(1,userid);
ps.execute();
ps = connection.prepareStatement("insert into Users(userid,personid,start,stop,updatetime,project,encryptedpassword) values(?,?,?,?,?,?,?)");
ps.setInt(1,goodUserId);
ps.setInt(2,goodPersonId);
ps.setTimestamp(3,goodStart);
ps.setTimestamp(4,goodStop);
ps.setTimestamp(5,goodUpdatetime);
ps.setString(6,goodProject);
ps.setBytes(7,goodPassword);
ps.execute();
ps.close();
}
else {
rs.close();
ps.close();
}
}
} catch (SQLException e) {
correct=false;
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return correct;
}
}
|
203288_0 | package be.vdab.controlers;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import be.vdab.entities.Employee;
import be.vdab.services.EmployeeService;
/**
* Controller voor het opzoeken van een werknemer
* @author cursist
*
*/
@Component
@Scope("request")
public class EmployeeSearchController implements Serializable {
private static final long serialVersionUID = 1L;
private String waarde;
private List<Employee> employees;
private transient EmployeeService employeeService;
@Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public List<Employee> getEmployees() {
return employees;
}
public List<Employee> autoComplete(String query){
return employeeService.findByNaamContaining(query);
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public String findAllContaining() {
employees = employeeService.findByNaamContaining(waarde);
return null;
}
public String getWaarde() {
return waarde;
}
public void setWaarde(String waarde) {
this.waarde = waarde;
}
/* @PostConstruct
public void init() {
employees = new ArrayList<Employee>();
}*/
}
| GlennLefevere/JSFBeanValidation | src/main/java/be/vdab/controlers/EmployeeSearchController.java | 368 | /**
* Controller voor het opzoeken van een werknemer
* @author cursist
*
*/ | block_comment | nl | package be.vdab.controlers;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import be.vdab.entities.Employee;
import be.vdab.services.EmployeeService;
/**
* Controller voor het<SUF>*/
@Component
@Scope("request")
public class EmployeeSearchController implements Serializable {
private static final long serialVersionUID = 1L;
private String waarde;
private List<Employee> employees;
private transient EmployeeService employeeService;
@Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public List<Employee> getEmployees() {
return employees;
}
public List<Employee> autoComplete(String query){
return employeeService.findByNaamContaining(query);
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public String findAllContaining() {
employees = employeeService.findByNaamContaining(waarde);
return null;
}
public String getWaarde() {
return waarde;
}
public void setWaarde(String waarde) {
this.waarde = waarde;
}
/* @PostConstruct
public void init() {
employees = new ArrayList<Employee>();
}*/
}
|
203297_0 | package nl.kadaster.business;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.kadaster.web.domain.Adres;
import nl.kadaster.data.AdresRepository;
@Service
public class BusinessServiceObject implements BusinessService {
private static final Logger LOG = LoggerFactory.getLogger(BusinessServiceObject.class);
@Autowired
private AdresRepository adresRepository;
public void setAdresRepository(AdresRepository adresRepository) {
this.adresRepository = adresRepository;
}
public BusinessServiceObject() {
LOG.trace("BusinessServiceObject instantiated");
}
@Override
public List<Adres> getAdressen() {
// eventueel eerst checken of het mag
List<nl.kadaster.core.domain.Adres> adressen = adresRepository.getAdressen();
List<Adres> result = new ArrayList<Adres>(adressen.size());
for (nl.kadaster.core.domain.Adres adres : adressen)
result.add(new Adres(adres));
return result;
}
@Override
public Adres getAdres(int index) {
nl.kadaster.core.domain.Adres gevondenAdres = adresRepository.getAdres(index);
Adres adres = null;
if (gevondenAdres != null)
adres = new Adres(gevondenAdres);
return adres;
}
@Override
public void saveAdres(Adres adres) {
adresRepository.storeAdres(adres.toAdres());
}
@Override
public boolean[] saveAdres(Adres adres, String straat, String huisnummer,
String toevoeging, String postcode, String woonplaats) {
boolean[] errorCodes = new boolean[6];
// met JavaBeans, Retrospect/Introspect PropertyDescriptor etc. te refactoren?
// check straat
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[1] = true;
// anders:
adres.setStraat(straat);
try {
adres.setHuisnummer(Short.parseShort(huisnummer));
}
catch (NumberFormatException e) {
errorCodes[0] = errorCodes[2] = true;
}
// check toevoeging
// indien foutief: errorCodes[0] = errorCodes[3] = true;
// anders:
adres.setToevoeging(toevoeging);
// check postcode
switch(postcode.length()) {
case 6:
if (postcode.matches("[1-9]\\d{3}[a-zA-Z]{2}")) {
adres.setPostcode( postcode.substring(0,4) + " " + postcode.substring(4,6).toUpperCase() );
break;
}
case 7:
if (postcode.matches("[1-9]\\d{3}\\s[a-zA-Z]{2}")) {
adres.setPostcode( postcode.toUpperCase() );
break;
}
default:
errorCodes[0] = errorCodes[4] = true;
}
// check woonplaats
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[5] = true;
// anders:
adres.setWoonplaats(woonplaats);
if (!errorCodes[0])
adresRepository.storeAdres(adres.toAdres());
return errorCodes;
}
@Override
public void verwijderAdres(Adres adres) throws Exception {
adresRepository.removeAdres(adres.toAdres());
}
@Override
public void updateAdres(Adres adres) throws Exception {
adresRepository.updateAdres(adres.toAdres());
}
}
| javacoe/workshop | AdresSysteem/application_layer/src/main/java/nl/kadaster/business/BusinessServiceObject.java | 1,038 | // eventueel eerst checken of het mag
| line_comment | nl | package nl.kadaster.business;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.kadaster.web.domain.Adres;
import nl.kadaster.data.AdresRepository;
@Service
public class BusinessServiceObject implements BusinessService {
private static final Logger LOG = LoggerFactory.getLogger(BusinessServiceObject.class);
@Autowired
private AdresRepository adresRepository;
public void setAdresRepository(AdresRepository adresRepository) {
this.adresRepository = adresRepository;
}
public BusinessServiceObject() {
LOG.trace("BusinessServiceObject instantiated");
}
@Override
public List<Adres> getAdressen() {
// eventueel eerst<SUF>
List<nl.kadaster.core.domain.Adres> adressen = adresRepository.getAdressen();
List<Adres> result = new ArrayList<Adres>(adressen.size());
for (nl.kadaster.core.domain.Adres adres : adressen)
result.add(new Adres(adres));
return result;
}
@Override
public Adres getAdres(int index) {
nl.kadaster.core.domain.Adres gevondenAdres = adresRepository.getAdres(index);
Adres adres = null;
if (gevondenAdres != null)
adres = new Adres(gevondenAdres);
return adres;
}
@Override
public void saveAdres(Adres adres) {
adresRepository.storeAdres(adres.toAdres());
}
@Override
public boolean[] saveAdres(Adres adres, String straat, String huisnummer,
String toevoeging, String postcode, String woonplaats) {
boolean[] errorCodes = new boolean[6];
// met JavaBeans, Retrospect/Introspect PropertyDescriptor etc. te refactoren?
// check straat
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[1] = true;
// anders:
adres.setStraat(straat);
try {
adres.setHuisnummer(Short.parseShort(huisnummer));
}
catch (NumberFormatException e) {
errorCodes[0] = errorCodes[2] = true;
}
// check toevoeging
// indien foutief: errorCodes[0] = errorCodes[3] = true;
// anders:
adres.setToevoeging(toevoeging);
// check postcode
switch(postcode.length()) {
case 6:
if (postcode.matches("[1-9]\\d{3}[a-zA-Z]{2}")) {
adres.setPostcode( postcode.substring(0,4) + " " + postcode.substring(4,6).toUpperCase() );
break;
}
case 7:
if (postcode.matches("[1-9]\\d{3}\\s[a-zA-Z]{2}")) {
adres.setPostcode( postcode.toUpperCase() );
break;
}
default:
errorCodes[0] = errorCodes[4] = true;
}
// check woonplaats
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[5] = true;
// anders:
adres.setWoonplaats(woonplaats);
if (!errorCodes[0])
adresRepository.storeAdres(adres.toAdres());
return errorCodes;
}
@Override
public void verwijderAdres(Adres adres) throws Exception {
adresRepository.removeAdres(adres.toAdres());
}
@Override
public void updateAdres(Adres adres) throws Exception {
adresRepository.updateAdres(adres.toAdres());
}
}
|
203297_2 | package nl.kadaster.business;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.kadaster.web.domain.Adres;
import nl.kadaster.data.AdresRepository;
@Service
public class BusinessServiceObject implements BusinessService {
private static final Logger LOG = LoggerFactory.getLogger(BusinessServiceObject.class);
@Autowired
private AdresRepository adresRepository;
public void setAdresRepository(AdresRepository adresRepository) {
this.adresRepository = adresRepository;
}
public BusinessServiceObject() {
LOG.trace("BusinessServiceObject instantiated");
}
@Override
public List<Adres> getAdressen() {
// eventueel eerst checken of het mag
List<nl.kadaster.core.domain.Adres> adressen = adresRepository.getAdressen();
List<Adres> result = new ArrayList<Adres>(adressen.size());
for (nl.kadaster.core.domain.Adres adres : adressen)
result.add(new Adres(adres));
return result;
}
@Override
public Adres getAdres(int index) {
nl.kadaster.core.domain.Adres gevondenAdres = adresRepository.getAdres(index);
Adres adres = null;
if (gevondenAdres != null)
adres = new Adres(gevondenAdres);
return adres;
}
@Override
public void saveAdres(Adres adres) {
adresRepository.storeAdres(adres.toAdres());
}
@Override
public boolean[] saveAdres(Adres adres, String straat, String huisnummer,
String toevoeging, String postcode, String woonplaats) {
boolean[] errorCodes = new boolean[6];
// met JavaBeans, Retrospect/Introspect PropertyDescriptor etc. te refactoren?
// check straat
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[1] = true;
// anders:
adres.setStraat(straat);
try {
adres.setHuisnummer(Short.parseShort(huisnummer));
}
catch (NumberFormatException e) {
errorCodes[0] = errorCodes[2] = true;
}
// check toevoeging
// indien foutief: errorCodes[0] = errorCodes[3] = true;
// anders:
adres.setToevoeging(toevoeging);
// check postcode
switch(postcode.length()) {
case 6:
if (postcode.matches("[1-9]\\d{3}[a-zA-Z]{2}")) {
adres.setPostcode( postcode.substring(0,4) + " " + postcode.substring(4,6).toUpperCase() );
break;
}
case 7:
if (postcode.matches("[1-9]\\d{3}\\s[a-zA-Z]{2}")) {
adres.setPostcode( postcode.toUpperCase() );
break;
}
default:
errorCodes[0] = errorCodes[4] = true;
}
// check woonplaats
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[5] = true;
// anders:
adres.setWoonplaats(woonplaats);
if (!errorCodes[0])
adresRepository.storeAdres(adres.toAdres());
return errorCodes;
}
@Override
public void verwijderAdres(Adres adres) throws Exception {
adresRepository.removeAdres(adres.toAdres());
}
@Override
public void updateAdres(Adres adres) throws Exception {
adresRepository.updateAdres(adres.toAdres());
}
}
| javacoe/workshop | AdresSysteem/application_layer/src/main/java/nl/kadaster/business/BusinessServiceObject.java | 1,038 | //TODO Mag niet leeg zijn, anders opzoeken met postcode
| line_comment | nl | package nl.kadaster.business;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.kadaster.web.domain.Adres;
import nl.kadaster.data.AdresRepository;
@Service
public class BusinessServiceObject implements BusinessService {
private static final Logger LOG = LoggerFactory.getLogger(BusinessServiceObject.class);
@Autowired
private AdresRepository adresRepository;
public void setAdresRepository(AdresRepository adresRepository) {
this.adresRepository = adresRepository;
}
public BusinessServiceObject() {
LOG.trace("BusinessServiceObject instantiated");
}
@Override
public List<Adres> getAdressen() {
// eventueel eerst checken of het mag
List<nl.kadaster.core.domain.Adres> adressen = adresRepository.getAdressen();
List<Adres> result = new ArrayList<Adres>(adressen.size());
for (nl.kadaster.core.domain.Adres adres : adressen)
result.add(new Adres(adres));
return result;
}
@Override
public Adres getAdres(int index) {
nl.kadaster.core.domain.Adres gevondenAdres = adresRepository.getAdres(index);
Adres adres = null;
if (gevondenAdres != null)
adres = new Adres(gevondenAdres);
return adres;
}
@Override
public void saveAdres(Adres adres) {
adresRepository.storeAdres(adres.toAdres());
}
@Override
public boolean[] saveAdres(Adres adres, String straat, String huisnummer,
String toevoeging, String postcode, String woonplaats) {
boolean[] errorCodes = new boolean[6];
// met JavaBeans, Retrospect/Introspect PropertyDescriptor etc. te refactoren?
// check straat
//TODO Mag<SUF>
// indien foutief: errorCodes[0] = errorCodes[1] = true;
// anders:
adres.setStraat(straat);
try {
adres.setHuisnummer(Short.parseShort(huisnummer));
}
catch (NumberFormatException e) {
errorCodes[0] = errorCodes[2] = true;
}
// check toevoeging
// indien foutief: errorCodes[0] = errorCodes[3] = true;
// anders:
adres.setToevoeging(toevoeging);
// check postcode
switch(postcode.length()) {
case 6:
if (postcode.matches("[1-9]\\d{3}[a-zA-Z]{2}")) {
adres.setPostcode( postcode.substring(0,4) + " " + postcode.substring(4,6).toUpperCase() );
break;
}
case 7:
if (postcode.matches("[1-9]\\d{3}\\s[a-zA-Z]{2}")) {
adres.setPostcode( postcode.toUpperCase() );
break;
}
default:
errorCodes[0] = errorCodes[4] = true;
}
// check woonplaats
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[5] = true;
// anders:
adres.setWoonplaats(woonplaats);
if (!errorCodes[0])
adresRepository.storeAdres(adres.toAdres());
return errorCodes;
}
@Override
public void verwijderAdres(Adres adres) throws Exception {
adresRepository.removeAdres(adres.toAdres());
}
@Override
public void updateAdres(Adres adres) throws Exception {
adresRepository.updateAdres(adres.toAdres());
}
}
|
203297_5 | package nl.kadaster.business;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.kadaster.web.domain.Adres;
import nl.kadaster.data.AdresRepository;
@Service
public class BusinessServiceObject implements BusinessService {
private static final Logger LOG = LoggerFactory.getLogger(BusinessServiceObject.class);
@Autowired
private AdresRepository adresRepository;
public void setAdresRepository(AdresRepository adresRepository) {
this.adresRepository = adresRepository;
}
public BusinessServiceObject() {
LOG.trace("BusinessServiceObject instantiated");
}
@Override
public List<Adres> getAdressen() {
// eventueel eerst checken of het mag
List<nl.kadaster.core.domain.Adres> adressen = adresRepository.getAdressen();
List<Adres> result = new ArrayList<Adres>(adressen.size());
for (nl.kadaster.core.domain.Adres adres : adressen)
result.add(new Adres(adres));
return result;
}
@Override
public Adres getAdres(int index) {
nl.kadaster.core.domain.Adres gevondenAdres = adresRepository.getAdres(index);
Adres adres = null;
if (gevondenAdres != null)
adres = new Adres(gevondenAdres);
return adres;
}
@Override
public void saveAdres(Adres adres) {
adresRepository.storeAdres(adres.toAdres());
}
@Override
public boolean[] saveAdres(Adres adres, String straat, String huisnummer,
String toevoeging, String postcode, String woonplaats) {
boolean[] errorCodes = new boolean[6];
// met JavaBeans, Retrospect/Introspect PropertyDescriptor etc. te refactoren?
// check straat
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[1] = true;
// anders:
adres.setStraat(straat);
try {
adres.setHuisnummer(Short.parseShort(huisnummer));
}
catch (NumberFormatException e) {
errorCodes[0] = errorCodes[2] = true;
}
// check toevoeging
// indien foutief: errorCodes[0] = errorCodes[3] = true;
// anders:
adres.setToevoeging(toevoeging);
// check postcode
switch(postcode.length()) {
case 6:
if (postcode.matches("[1-9]\\d{3}[a-zA-Z]{2}")) {
adres.setPostcode( postcode.substring(0,4) + " " + postcode.substring(4,6).toUpperCase() );
break;
}
case 7:
if (postcode.matches("[1-9]\\d{3}\\s[a-zA-Z]{2}")) {
adres.setPostcode( postcode.toUpperCase() );
break;
}
default:
errorCodes[0] = errorCodes[4] = true;
}
// check woonplaats
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[5] = true;
// anders:
adres.setWoonplaats(woonplaats);
if (!errorCodes[0])
adresRepository.storeAdres(adres.toAdres());
return errorCodes;
}
@Override
public void verwijderAdres(Adres adres) throws Exception {
adresRepository.removeAdres(adres.toAdres());
}
@Override
public void updateAdres(Adres adres) throws Exception {
adresRepository.updateAdres(adres.toAdres());
}
}
| javacoe/workshop | AdresSysteem/application_layer/src/main/java/nl/kadaster/business/BusinessServiceObject.java | 1,038 | //TODO Mag niet leeg zijn, anders opzoeken met postcode
| line_comment | nl | package nl.kadaster.business;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.kadaster.web.domain.Adres;
import nl.kadaster.data.AdresRepository;
@Service
public class BusinessServiceObject implements BusinessService {
private static final Logger LOG = LoggerFactory.getLogger(BusinessServiceObject.class);
@Autowired
private AdresRepository adresRepository;
public void setAdresRepository(AdresRepository adresRepository) {
this.adresRepository = adresRepository;
}
public BusinessServiceObject() {
LOG.trace("BusinessServiceObject instantiated");
}
@Override
public List<Adres> getAdressen() {
// eventueel eerst checken of het mag
List<nl.kadaster.core.domain.Adres> adressen = adresRepository.getAdressen();
List<Adres> result = new ArrayList<Adres>(adressen.size());
for (nl.kadaster.core.domain.Adres adres : adressen)
result.add(new Adres(adres));
return result;
}
@Override
public Adres getAdres(int index) {
nl.kadaster.core.domain.Adres gevondenAdres = adresRepository.getAdres(index);
Adres adres = null;
if (gevondenAdres != null)
adres = new Adres(gevondenAdres);
return adres;
}
@Override
public void saveAdres(Adres adres) {
adresRepository.storeAdres(adres.toAdres());
}
@Override
public boolean[] saveAdres(Adres adres, String straat, String huisnummer,
String toevoeging, String postcode, String woonplaats) {
boolean[] errorCodes = new boolean[6];
// met JavaBeans, Retrospect/Introspect PropertyDescriptor etc. te refactoren?
// check straat
//TODO Mag niet leeg zijn, anders opzoeken met postcode
// indien foutief: errorCodes[0] = errorCodes[1] = true;
// anders:
adres.setStraat(straat);
try {
adres.setHuisnummer(Short.parseShort(huisnummer));
}
catch (NumberFormatException e) {
errorCodes[0] = errorCodes[2] = true;
}
// check toevoeging
// indien foutief: errorCodes[0] = errorCodes[3] = true;
// anders:
adres.setToevoeging(toevoeging);
// check postcode
switch(postcode.length()) {
case 6:
if (postcode.matches("[1-9]\\d{3}[a-zA-Z]{2}")) {
adres.setPostcode( postcode.substring(0,4) + " " + postcode.substring(4,6).toUpperCase() );
break;
}
case 7:
if (postcode.matches("[1-9]\\d{3}\\s[a-zA-Z]{2}")) {
adres.setPostcode( postcode.toUpperCase() );
break;
}
default:
errorCodes[0] = errorCodes[4] = true;
}
// check woonplaats
//TODO Mag<SUF>
// indien foutief: errorCodes[0] = errorCodes[5] = true;
// anders:
adres.setWoonplaats(woonplaats);
if (!errorCodes[0])
adresRepository.storeAdres(adres.toAdres());
return errorCodes;
}
@Override
public void verwijderAdres(Adres adres) throws Exception {
adresRepository.removeAdres(adres.toAdres());
}
@Override
public void updateAdres(Adres adres) throws Exception {
adresRepository.updateAdres(adres.toAdres());
}
}
|
203304_0 | package nl.b3p.brmo.service.util;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import nl.b3p.brmo.loader.util.BrmoException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ConfigUtil implements Servlet {
private static final Log log = LogFactory.getLog(ConfigUtil.class);
private static final String JNDI_NAME = "java:comp/env";
private static final String JDBC_NAME_STAGING = "jdbc/brmo/staging";
private static final String JDBC_NAME_RSGB = "jdbc/brmo/rsgb";
private static final String JDBC_NAME_RSGB_BAG = "jdbc/brmo/rsgbbag";
private static final String JDBC_NAME_RSGB_BGT = "jdbc/brmo/rsgbbgt";
private static final String JDBC_NAME_RSGB_TOPNL = "jdbc/brmo/rsgbtopnl";
private static DataSource datasourceStaging = null;
private static DataSource datasourceRsgb = null;
private static DataSource datasourceRsgbBag = null;
private static DataSource datasourceRsgbBgt = null;
private static DataSource datasourceTopNL = null;
public static Integer MAX_UPLOAD_SIZE;
public static String TEMP_FOLDER;
@Override
public void init(ServletConfig config) throws ServletException {
String tempSize = config.getInitParameter("max_upload_size");
if (tempSize != null && !tempSize.isEmpty()) {
MAX_UPLOAD_SIZE = Integer.valueOf(tempSize) * 1024 * 1024;
} else {
MAX_UPLOAD_SIZE = 10000 * 1024 * 1024;
}
String tempFolder = config.getInitParameter("temp_folder");
if (tempFolder != null && !tempFolder.isEmpty()) {
TEMP_FOLDER = tempFolder;
} else {
TEMP_FOLDER = System.getProperty("java.io.tmpdir");
}
}
public static DataSource getDataSourceStaging() throws BrmoException {
try {
if (datasourceStaging == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceStaging = (DataSource) xmlContext.lookup(JDBC_NAME_STAGING);
}
} catch (Exception ex) {
log.error("Fout verbinden naar staging db. ", ex);
throw new BrmoException(ex);
}
return datasourceStaging;
}
public static DataSource getDataSourceRsgb() throws BrmoException {
try {
if (datasourceRsgb == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgb = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB);
}
} catch (Exception ex) {
log.error("Fout verbinden naar rsgb db. ", ex);
throw new BrmoException(ex);
}
return datasourceRsgb;
}
public static DataSource getDataSourceRsgbBag() throws BrmoException {
return getDataSourceRsgbBag(true);
}
public static DataSource getDataSourceRsgbBag(boolean logErrors) throws BrmoException {
try {
if (datasourceRsgbBag == null) {
InitialContext ic = new InitialContext();
Context context = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBag = (DataSource) context.lookup(JDBC_NAME_RSGB_BAG);
}
} catch (Exception ex) {
if (logErrors) {
log.error("Fout verbinden naar 'rsgbbag' schema.", ex);
}
throw new BrmoException("Fout verbinden naar 'rsgbbag' schema: ", ex);
}
return datasourceRsgbBag;
}
public static DataSource getDataSourceRsgbBgt() throws BrmoException {
try {
if (datasourceRsgbBgt == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBgt = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_BGT);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'rsgbbgt' schema.", ex);
throw new BrmoException("Fout verbinden naar 'rsgbbgt' schema.", ex);
}
return datasourceRsgbBgt;
}
/**
*
* @return de gevraagde datasource
* @throws BrmoException als opzoeken van de datasource in de jndi context
* mislukt
*/
public static DataSource getDataSourceTopNL() throws BrmoException {
try {
if (datasourceTopNL == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceTopNL = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_TOPNL);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'topnl' schema.", ex);
throw new BrmoException("Fout verbinden naar 'topnl' schema.", ex);
}
return datasourceTopNL;
}
public ServletConfig getServletConfig() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void service(ServletRequest sr, ServletResponse sr1) throws ServletException, IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getServletInfo() {
return "Servlet voor configuratie parameters in web.xml";
}
public void destroy() {
// nothing
}
}
| puckipedia/brmo | brmo-init-util/src/main/java/nl/b3p/brmo/service/util/ConfigUtil.java | 1,490 | /**
*
* @return de gevraagde datasource
* @throws BrmoException als opzoeken van de datasource in de jndi context
* mislukt
*/ | block_comment | nl | package nl.b3p.brmo.service.util;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import nl.b3p.brmo.loader.util.BrmoException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ConfigUtil implements Servlet {
private static final Log log = LogFactory.getLog(ConfigUtil.class);
private static final String JNDI_NAME = "java:comp/env";
private static final String JDBC_NAME_STAGING = "jdbc/brmo/staging";
private static final String JDBC_NAME_RSGB = "jdbc/brmo/rsgb";
private static final String JDBC_NAME_RSGB_BAG = "jdbc/brmo/rsgbbag";
private static final String JDBC_NAME_RSGB_BGT = "jdbc/brmo/rsgbbgt";
private static final String JDBC_NAME_RSGB_TOPNL = "jdbc/brmo/rsgbtopnl";
private static DataSource datasourceStaging = null;
private static DataSource datasourceRsgb = null;
private static DataSource datasourceRsgbBag = null;
private static DataSource datasourceRsgbBgt = null;
private static DataSource datasourceTopNL = null;
public static Integer MAX_UPLOAD_SIZE;
public static String TEMP_FOLDER;
@Override
public void init(ServletConfig config) throws ServletException {
String tempSize = config.getInitParameter("max_upload_size");
if (tempSize != null && !tempSize.isEmpty()) {
MAX_UPLOAD_SIZE = Integer.valueOf(tempSize) * 1024 * 1024;
} else {
MAX_UPLOAD_SIZE = 10000 * 1024 * 1024;
}
String tempFolder = config.getInitParameter("temp_folder");
if (tempFolder != null && !tempFolder.isEmpty()) {
TEMP_FOLDER = tempFolder;
} else {
TEMP_FOLDER = System.getProperty("java.io.tmpdir");
}
}
public static DataSource getDataSourceStaging() throws BrmoException {
try {
if (datasourceStaging == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceStaging = (DataSource) xmlContext.lookup(JDBC_NAME_STAGING);
}
} catch (Exception ex) {
log.error("Fout verbinden naar staging db. ", ex);
throw new BrmoException(ex);
}
return datasourceStaging;
}
public static DataSource getDataSourceRsgb() throws BrmoException {
try {
if (datasourceRsgb == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgb = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB);
}
} catch (Exception ex) {
log.error("Fout verbinden naar rsgb db. ", ex);
throw new BrmoException(ex);
}
return datasourceRsgb;
}
public static DataSource getDataSourceRsgbBag() throws BrmoException {
return getDataSourceRsgbBag(true);
}
public static DataSource getDataSourceRsgbBag(boolean logErrors) throws BrmoException {
try {
if (datasourceRsgbBag == null) {
InitialContext ic = new InitialContext();
Context context = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBag = (DataSource) context.lookup(JDBC_NAME_RSGB_BAG);
}
} catch (Exception ex) {
if (logErrors) {
log.error("Fout verbinden naar 'rsgbbag' schema.", ex);
}
throw new BrmoException("Fout verbinden naar 'rsgbbag' schema: ", ex);
}
return datasourceRsgbBag;
}
public static DataSource getDataSourceRsgbBgt() throws BrmoException {
try {
if (datasourceRsgbBgt == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBgt = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_BGT);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'rsgbbgt' schema.", ex);
throw new BrmoException("Fout verbinden naar 'rsgbbgt' schema.", ex);
}
return datasourceRsgbBgt;
}
/**
*
* @return de gevraagde<SUF>*/
public static DataSource getDataSourceTopNL() throws BrmoException {
try {
if (datasourceTopNL == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceTopNL = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_TOPNL);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'topnl' schema.", ex);
throw new BrmoException("Fout verbinden naar 'topnl' schema.", ex);
}
return datasourceTopNL;
}
public ServletConfig getServletConfig() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void service(ServletRequest sr, ServletResponse sr1) throws ServletException, IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getServletInfo() {
return "Servlet voor configuratie parameters in web.xml";
}
public void destroy() {
// nothing
}
}
|
203311_0 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.common.misc.email.templates;
import static nl.procura.gba.web.services.beheer.link.PersonenLinkType.NIEUWE_GEBRUIKER;
import nl.procura.gba.common.DateTime;
import nl.procura.gba.web.common.misc.email.EmailAddressType;
import nl.procura.gba.web.common.misc.email.Verzending;
import nl.procura.gba.web.services.Services;
import nl.procura.gba.web.services.beheer.email.EmailTemplate;
import nl.procura.gba.web.services.beheer.email.EmailVariable;
import nl.procura.gba.web.services.beheer.gebruiker.Gebruiker;
import nl.procura.gba.web.services.beheer.link.LinkService;
import nl.procura.gba.web.services.beheer.link.PersonenLink;
import nl.procura.gba.web.services.beheer.link.PersonenLinkProperty;
import nl.procura.standard.ProcuraDate;
public class NieuweGebruikerEmail extends TemplateEmail {
public NieuweGebruikerEmail(EmailTemplate template, Services services, String applicationUrl,
Verzending verzending) {
super(template, services, applicationUrl);
Gebruiker gebruiker = verzending.getGebruiker();
String emailAdres = verzending.getEmailAdres();
String url = applicationUrl.replaceAll("/$", "");
LinkService links = services.getLinkService();
// Email opzoeken in de database
PersonenLink link = new PersonenLink(links.getRandomId(), NIEUWE_GEBRUIKER);
// Properties toevoegen aan de link
link.getProperties().put(PersonenLinkProperty.GEBRUIKER.getCode(), gebruiker.getGebruikersnaam());
link.getProperties().put(PersonenLinkProperty.EMAIL.getCode(), emailAdres);
// Verloopdatum toevoegen
link.setDatumEinde(new DateTime(new ProcuraDate().addDays(getDuration()).getDateFormat()));
links.addPersonenLink(link);
// Maak wachtwoord
getAdresses().add(EmailAddressType.TO, "", gebruiker.getEmail());
replaceValue(EmailVariable.NAAM.getCode(), gebruiker.getNaam());
replaceValue(EmailVariable.LINK.getCode(), url + "?link=" + link.getId());
replaceValue(EmailVariable.LINK_GELDIG.getCode(), getDurationInDays());
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/common/misc/email/templates/NieuweGebruikerEmail.java | 813 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/ | block_comment | nl | /*
* Copyright 2021 -<SUF>*/
package nl.procura.gba.web.common.misc.email.templates;
import static nl.procura.gba.web.services.beheer.link.PersonenLinkType.NIEUWE_GEBRUIKER;
import nl.procura.gba.common.DateTime;
import nl.procura.gba.web.common.misc.email.EmailAddressType;
import nl.procura.gba.web.common.misc.email.Verzending;
import nl.procura.gba.web.services.Services;
import nl.procura.gba.web.services.beheer.email.EmailTemplate;
import nl.procura.gba.web.services.beheer.email.EmailVariable;
import nl.procura.gba.web.services.beheer.gebruiker.Gebruiker;
import nl.procura.gba.web.services.beheer.link.LinkService;
import nl.procura.gba.web.services.beheer.link.PersonenLink;
import nl.procura.gba.web.services.beheer.link.PersonenLinkProperty;
import nl.procura.standard.ProcuraDate;
public class NieuweGebruikerEmail extends TemplateEmail {
public NieuweGebruikerEmail(EmailTemplate template, Services services, String applicationUrl,
Verzending verzending) {
super(template, services, applicationUrl);
Gebruiker gebruiker = verzending.getGebruiker();
String emailAdres = verzending.getEmailAdres();
String url = applicationUrl.replaceAll("/$", "");
LinkService links = services.getLinkService();
// Email opzoeken in de database
PersonenLink link = new PersonenLink(links.getRandomId(), NIEUWE_GEBRUIKER);
// Properties toevoegen aan de link
link.getProperties().put(PersonenLinkProperty.GEBRUIKER.getCode(), gebruiker.getGebruikersnaam());
link.getProperties().put(PersonenLinkProperty.EMAIL.getCode(), emailAdres);
// Verloopdatum toevoegen
link.setDatumEinde(new DateTime(new ProcuraDate().addDays(getDuration()).getDateFormat()));
links.addPersonenLink(link);
// Maak wachtwoord
getAdresses().add(EmailAddressType.TO, "", gebruiker.getEmail());
replaceValue(EmailVariable.NAAM.getCode(), gebruiker.getNaam());
replaceValue(EmailVariable.LINK.getCode(), url + "?link=" + link.getId());
replaceValue(EmailVariable.LINK_GELDIG.getCode(), getDurationInDays());
}
}
|
203311_1 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.common.misc.email.templates;
import static nl.procura.gba.web.services.beheer.link.PersonenLinkType.NIEUWE_GEBRUIKER;
import nl.procura.gba.common.DateTime;
import nl.procura.gba.web.common.misc.email.EmailAddressType;
import nl.procura.gba.web.common.misc.email.Verzending;
import nl.procura.gba.web.services.Services;
import nl.procura.gba.web.services.beheer.email.EmailTemplate;
import nl.procura.gba.web.services.beheer.email.EmailVariable;
import nl.procura.gba.web.services.beheer.gebruiker.Gebruiker;
import nl.procura.gba.web.services.beheer.link.LinkService;
import nl.procura.gba.web.services.beheer.link.PersonenLink;
import nl.procura.gba.web.services.beheer.link.PersonenLinkProperty;
import nl.procura.standard.ProcuraDate;
public class NieuweGebruikerEmail extends TemplateEmail {
public NieuweGebruikerEmail(EmailTemplate template, Services services, String applicationUrl,
Verzending verzending) {
super(template, services, applicationUrl);
Gebruiker gebruiker = verzending.getGebruiker();
String emailAdres = verzending.getEmailAdres();
String url = applicationUrl.replaceAll("/$", "");
LinkService links = services.getLinkService();
// Email opzoeken in de database
PersonenLink link = new PersonenLink(links.getRandomId(), NIEUWE_GEBRUIKER);
// Properties toevoegen aan de link
link.getProperties().put(PersonenLinkProperty.GEBRUIKER.getCode(), gebruiker.getGebruikersnaam());
link.getProperties().put(PersonenLinkProperty.EMAIL.getCode(), emailAdres);
// Verloopdatum toevoegen
link.setDatumEinde(new DateTime(new ProcuraDate().addDays(getDuration()).getDateFormat()));
links.addPersonenLink(link);
// Maak wachtwoord
getAdresses().add(EmailAddressType.TO, "", gebruiker.getEmail());
replaceValue(EmailVariable.NAAM.getCode(), gebruiker.getNaam());
replaceValue(EmailVariable.LINK.getCode(), url + "?link=" + link.getId());
replaceValue(EmailVariable.LINK_GELDIG.getCode(), getDurationInDays());
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/common/misc/email/templates/NieuweGebruikerEmail.java | 813 | // Email opzoeken in de database | line_comment | nl | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.common.misc.email.templates;
import static nl.procura.gba.web.services.beheer.link.PersonenLinkType.NIEUWE_GEBRUIKER;
import nl.procura.gba.common.DateTime;
import nl.procura.gba.web.common.misc.email.EmailAddressType;
import nl.procura.gba.web.common.misc.email.Verzending;
import nl.procura.gba.web.services.Services;
import nl.procura.gba.web.services.beheer.email.EmailTemplate;
import nl.procura.gba.web.services.beheer.email.EmailVariable;
import nl.procura.gba.web.services.beheer.gebruiker.Gebruiker;
import nl.procura.gba.web.services.beheer.link.LinkService;
import nl.procura.gba.web.services.beheer.link.PersonenLink;
import nl.procura.gba.web.services.beheer.link.PersonenLinkProperty;
import nl.procura.standard.ProcuraDate;
public class NieuweGebruikerEmail extends TemplateEmail {
public NieuweGebruikerEmail(EmailTemplate template, Services services, String applicationUrl,
Verzending verzending) {
super(template, services, applicationUrl);
Gebruiker gebruiker = verzending.getGebruiker();
String emailAdres = verzending.getEmailAdres();
String url = applicationUrl.replaceAll("/$", "");
LinkService links = services.getLinkService();
// Email opzoeken<SUF>
PersonenLink link = new PersonenLink(links.getRandomId(), NIEUWE_GEBRUIKER);
// Properties toevoegen aan de link
link.getProperties().put(PersonenLinkProperty.GEBRUIKER.getCode(), gebruiker.getGebruikersnaam());
link.getProperties().put(PersonenLinkProperty.EMAIL.getCode(), emailAdres);
// Verloopdatum toevoegen
link.setDatumEinde(new DateTime(new ProcuraDate().addDays(getDuration()).getDateFormat()));
links.addPersonenLink(link);
// Maak wachtwoord
getAdresses().add(EmailAddressType.TO, "", gebruiker.getEmail());
replaceValue(EmailVariable.NAAM.getCode(), gebruiker.getNaam());
replaceValue(EmailVariable.LINK.getCode(), url + "?link=" + link.getId());
replaceValue(EmailVariable.LINK_GELDIG.getCode(), getDurationInDays());
}
}
|
203313_2 | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
| puckipedia/brmo | brmo-service/src/main/java/nl/b3p/brmo/service/scanner/MailRapportage.java | 2,160 | /**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/ | block_comment | nl | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van<SUF>*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
|
203313_4 | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
| puckipedia/brmo | brmo-service/src/main/java/nl/b3p/brmo/service/scanner/MailRapportage.java | 2,160 | // bericht mailText samenstellen | line_comment | nl | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText<SUF>
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
|
203313_5 | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
| puckipedia/brmo | brmo-service/src/main/java/nl/b3p/brmo/service/scanner/MailRapportage.java | 2,160 | /**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/ | block_comment | nl | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst<SUF>*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
|
203313_9 | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
| puckipedia/brmo | brmo-service/src/main/java/nl/b3p/brmo/service/scanner/MailRapportage.java | 2,160 | // TODO eventueel filter op dtype | line_comment | nl | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel<SUF>
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
|
203313_10 | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
| puckipedia/brmo | brmo-service/src/main/java/nl/b3p/brmo/service/scanner/MailRapportage.java | 2,160 | // niet het eigen proces rapporteren | line_comment | nl | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het<SUF>
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
|
203313_11 | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op status, daarna op datum zodat errors bovenaan staan
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
| puckipedia/brmo | brmo-service/src/main/java/nl/b3p/brmo/service/scanner/MailRapportage.java | 2,160 | // sorteer op status, daarna op datum zodat errors bovenaan staan | line_comment | nl | /*
* Copyright (C) 2015 B3Partners B.V.
*/
package nl.b3p.brmo.service.scanner;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.b3p.brmo.loader.util.BrmoException;
import nl.b3p.brmo.persistence.staging.MailRapportageProces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.b3p.brmo.persistence.staging.AutomatischProces;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.LOG_NEWLINE;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.ERROR;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.PROCESSING;
import static nl.b3p.brmo.persistence.staging.AutomatischProces.ProcessingStatus.WAITING;
import nl.b3p.brmo.persistence.staging.ClobElement;
import org.stripesstuff.stripersist.Stripersist;
/**
* Mailt rapporten.
*
* @author mprins
*/
public class MailRapportage extends AbstractExecutableProces {
private static final Log log = LogFactory.getLog(MailRapportage.class);
private MailRapportageProces config;
public MailRapportage(MailRapportageProces config) {
this.config = config;
}
/**
* De inhoud van dit bericht bestaat uit de samenvattingen en de status van
* de geselecteerde processen, indien niets geselecteerd rapportage van
* alles behalve het eigen proces.
*
* @throws BrmoException als er een fout optreed in het opzoeken van de
* mailserver (indi) of het versturen van de mail
*/
@Override
public void execute() throws BrmoException {
this.active = true;
StringBuilder sb = new StringBuilder();
config.setStatus(PROCESSING);
String logMsg = String.format("De mail rapportage met ID %d is gestart op %tc.", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
try {
Context init = new InitialContext();
Context env = (Context) init.lookup("java:comp/env");
Session session = (Session) env.lookup("mail/session");
Message msg = new MimeMessage(session);
msg.setFrom(/* 'mail.from' property uit jndi session object */);
msg.setSentDate(new Date());
// subject
String sForStatus = (config.getForStatus() == null ? "alle" : config.getForStatus().toString());
String sPIDS = (config.getConfig().get(MailRapportageProces.PIDS) == null ? "alle" : config.getConfig().get(MailRapportageProces.PIDS).getValue());
String label = (ClobElement.nullSafeGet(config.getConfig().get("label")) == null ? "" : config.getConfig().get("label").getValue());
String subject = String.format("BRMO rapport: %d (%s) voor status: %s (taken: %s)", config.getId(), label, sForStatus, sPIDS);
msg.setSubject(subject);
// ontvangers
String[] adressen = this.config.getMailAdressenArray();
InternetAddress[] aanAdr = new InternetAddress[adressen.length];
for (int i = 0; i < adressen.length; i++) {
aanAdr[i] = new InternetAddress(adressen[i]);
}
msg.setRecipients(Message.RecipientType.TO, aanAdr);
StringBuilder mailText = new StringBuilder();
List<AutomatischProces> processen = this.getProcessen();
// bericht mailText samenstellen
for (AutomatischProces p : processen) {
logMsg = String.format("Rapportage van taak %d met status: %s", p.getId(), p.getStatus());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
mailText.append("Rapport van taak: ").append(p.getId()).append(" ").append(label)
.append(", type: ").append(p.getClass().getSimpleName()).append(LOG_NEWLINE);
mailText.append("Status van de taak: ").append(p.getStatus()).append(LOG_NEWLINE);
mailText.append("Samenvatting: ").append(LOG_NEWLINE);
mailText.append(p.getSamenvatting()).append(LOG_NEWLINE);
mailText.append("---------------------------------").append(LOG_NEWLINE);
}
if (processen.isEmpty()) {
mailText.append("Er waren geen automatische processen die voldeden aan de opgegeven voorwaarden: ").append(LOG_NEWLINE);
mailText.append(" - Status: ").append(sForStatus).append(LOG_NEWLINE);
mailText.append(" - Taken: ").append(sPIDS).append(LOG_NEWLINE);
}
log.debug(mailText.toString());
msg.setText(mailText.toString());
Transport.send(msg);
logMsg = String.format("Klaar met taak %d op %tc", config.getId(), Calendar.getInstance());
log.info(logMsg);
sb.append(logMsg).append(LOG_NEWLINE);
config.setStatus(WAITING);
config.updateSamenvattingEnLogfile(sb.toString());
config.setLastrun(new Date());
} catch (MessagingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} catch (NamingException ex) {
log.error(ex);
config.setStatus(ERROR);
throw new BrmoException(ex);
} finally {
this.active = false;
}
}
/**
* Haalt de lijst met processen op uit de database.
*
* @return lijst met te rapporten processen
* @todo Eventueel andere mail rapportage processen ook uitsluiten?
*/
private List<AutomatischProces> getProcessen() {
// unit test in nl.b3p.brmo.persistence.staging.MailRapportageProcesTest#testRapportageLijst()
List<Predicate> predicates = new ArrayList<Predicate>();
final EntityManager em = Stripersist.getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AutomatischProces> cq = cb.createQuery(AutomatischProces.class);
Root<AutomatischProces> from = cq.from(AutomatischProces.class);
// where status=... filter
if (this.config.getForStatus() != null) {
Predicate where = cb.equal(from.get("status"), this.config.getForStatus());
predicates.add(where);
}
// processen in... filter
String pids = ClobElement.nullSafeGet(this.config.getConfig().get(MailRapportageProces.PIDS));
if (pids != null) {
List<Long> pidLijst = new ArrayList<Long>();
Matcher match = (Pattern.compile("[0-9]+")).matcher(pids);
while (match.find()) {
pidLijst.add(Long.valueOf(match.group()));
}
Predicate in = from.get("id").in(pidLijst);
predicates.add(in);
}
// TODO eventueel filter op dtype
// niet het eigen proces rapporteren
Predicate notIn = from.get("id").in(this.config.getId()).not();
predicates.add(notIn);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
// sorteer op<SUF>
cq.orderBy(cb.asc(from.get("status")));
cq.orderBy(cb.asc(from.get("lastrun")));
return em.createQuery(cq).getResultList();
}
@Override
public void execute(ProgressUpdateListener listener) {
try {
this.execute();
} catch (BrmoException ex) {
log.error(ex);
}
}
}
|
203320_0 | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn de reqs
// als 1 van deze 2 values 0 is
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} | thepassle/software-engineering-training | java-exercises/opdracht12-fusion/SogyoFusion.java | 2,435 | /** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/ | block_comment | nl | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt,<SUF>*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn de reqs
// als 1 van deze 2 values 0 is
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} |
203320_1 | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn de reqs
// als 1 van deze 2 values 0 is
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} | thepassle/software-engineering-training | java-exercises/opdracht12-fusion/SogyoFusion.java | 2,435 | /** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/ | block_comment | nl | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi<SUF>*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn de reqs
// als 1 van deze 2 values 0 is
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} |
203320_2 | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn de reqs
// als 1 van deze 2 values 0 is
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} | thepassle/software-engineering-training | java-exercises/opdracht12-fusion/SogyoFusion.java | 2,435 | // dit zijn de reqs | line_comment | nl | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn<SUF>
// als 1 van deze 2 values 0 is
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} |
203320_3 | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn de reqs
// als 1 van deze 2 values 0 is
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} | thepassle/software-engineering-training | java-exercises/opdracht12-fusion/SogyoFusion.java | 2,435 | // als 1 van deze 2 values 0 is | line_comment | nl | import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
/** Goedkoopste zoeken werkt, 'alleen' nog de tree printen
TO DO:
- Tree node/binary tree opzoeken
- JSON voorbeeld?
*/
public class SogyoFusion {
public static void main(String[] args) {
Data data = new Data();
data.compare("Power I", 0);
}
}
class BasicItem {
public String name;
public int price;
public int itemLvl;
BasicItem(String _name, int _price, int _itemLvl){
name = _name;
price = _price;
itemLvl = _itemLvl;
}
}
class FusedItem {
public String name;
public String[] requirements;
public int totalPrice;
public boolean isBuyable;
FusedItem(String _name, String[] _requirements, int _totalPrice, boolean _isBuyable){
name = _name;
requirements = _requirements;
totalPrice = _totalPrice;
isBuyable = _isBuyable;
}
}
class Data {
public ArrayList<BasicItem> basicItems = new ArrayList<BasicItem>();
public ArrayList<FusedItem> fusedItems = new ArrayList<FusedItem>();
public void run(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
}
public void compare(String input, int index){
Data data = new Data();
System.out.println();
System.out.println();
int basicPrice = data.getBasicPrice(input);
/** Wat wel mooi zou zijn is een nieuw fusion object, dat de laagste fusion price
heeft en de requirements en de naam van het item.
class Fusion{
String name;
String[] requirements;
int price;
Fusion(String _name, String[] _requirements, int _price){
name = _name;
requirements = _requirements;
price = _price;
}
methods etc
}
*/
int lowestFusionPrice = data.getLowestFusionPrice(input);
String[] lowestFusionRequirements = data.getLowestFusionRequirements(input);
boolean requirementsForSale = true;
System.out.println("IN: "+input);
System.out.println(" -Buy cost: " +basicPrice);
System.out.println(" -Fuse cost: "+lowestFusionPrice);
System.out.println(" -To fuse you would need: ");
for(String item : lowestFusionRequirements){
System.out.println(" -"+item);
}
System.out.println();
if(basicPrice > lowestFusionPrice && index < 10 || basicPrice == 0){
System.out.println("You should FUSE the: " + input);
for(String requirement : lowestFusionRequirements){
index++;
System.out.println("Index: " + index);
data.compare(requirement, index);
}
} else {
System.out.println("You should BUY the: " + input);
}
}
public int getBasicPrice(String input){
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int basicPrice = 0;
for(int i = 0; i < basicItems.size(); i++){
if(basicItems.get(i).name.equals( input )){
basicPrice = basicItems.get(i).price;
}
}
return basicPrice;
}
public int getLowestFusionPrice(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
boolean bothForSale = true;
ArrayList<Integer> prices = new ArrayList<Integer>();
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
bothForSale = true;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
// dit zijn de reqs
// als 1<SUF>
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
if(priceTemp == 0){
bothForSale = false;
break;
}
}
if(bothForSale){
prices.add(priceTemp);
}
}
}
int min = prices.get(0);
for(Integer i: prices) {
if(i < min) min = i;
}
return min;
}
public String[] getLowestFusionRequirements(String input){
Data data = new Data();
ArrayList<FusedItem> fusedItems = data.getFusedItems();
int lowestFusionPrice = 0;
int priceTemp = 0;
int prevPrice = 0;
String[] requirements = new String[2];
int lowestPrice = data.getLowestFusionPrice(input);
for(int i = 0; i < fusedItems.size(); i++){
priceTemp = 0;
if(fusedItems.get(i).name.equals(input)){
for(int j = 0; j < fusedItems.get(i).requirements.length; j++){
priceTemp += data.getBasicPrice( fusedItems.get(i).requirements[j] );
}
if(priceTemp == lowestPrice){
requirements[0] = fusedItems.get(i).requirements[0];
requirements[1] = fusedItems.get(i).requirements[1];
}
}
}
return requirements;
}
public ArrayList<FusedItem> getFusedItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
Data data = new Data();
ArrayList<BasicItem> basicItems = data.getBasicItems();
int parsingItemLvl = 1;
boolean isBuyable = false;
int totalPrice = 0;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(lines.get(i).contains("+") && lines.get(i).contains("=")){
String[] requirements = new String[2];
String name = "";
isBuyable = false;
totalPrice = 0;
String[] splitLine = lines.get(i).split("\\+");
requirements[0] = splitLine[0].trim();
String[] splitLine2 = splitLine[1].split("=");
requirements[1] = splitLine2[0].trim();
for(int k = 0; k < requirements.length; k++){
for(int l = 0; l < basicItems.size(); l++){
if(requirements[k].equals( basicItems.get(l).name )){
totalPrice += basicItems.get(l).price;
isBuyable = true;
break;
} else {
isBuyable = false;
}
}
}
name = splitLine2[1].trim();
FusedItem fusedItem = new FusedItem(name, requirements, totalPrice, isBuyable);
fusedItems.add(fusedItem);
}
}
return fusedItems;
}
public ArrayList<BasicItem> getBasicItems() {
File file;
Scanner sc;
ArrayList<String> lines = new ArrayList<String>();
int parsingItemLvl = 1;
try {
sc = new Scanner(new File("item-fusion-data.txt"));
while(sc.hasNextLine()) {
lines.add(sc.nextLine());
}
sc.close();
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
}
for(int i = 0; i < lines.size(); i++){
if(parsingItemLvl == 6){
break;
}
if(lines.get(i).contains("*****")){
parsingItemLvl += 1;
}
if(lines.get(i).contains("~") && !lines.get(i).contains("Name") && parsingItemLvl == 1){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
if(lines.get(i).length() > 0){
if(lines.get(i).charAt(0) == '*' && parsingItemLvl >= 2 && lines.get(i).contains("~")){
String line = lines.get(i).replace("*","");
String[] splitLine = line.split("~");
BasicItem basicItem = new BasicItem(splitLine[0].trim(), Integer.parseInt(splitLine[1].trim()), parsingItemLvl);
basicItems.add(basicItem);
}
}
}
return basicItems;
}
} |
203323_0 | import sun.util.locale.provider.AvailableLanguageTags;
import java.util.*;
public class SpeedTest {
private List<Integer> anArrayList = new ArrayList<>();
private List<Integer> aLinkendList = new LinkedList<>();
private Random random = new Random();
//Hoeveel getallen moeten er in de lijsten gestoken worden
private final int testGrootte;
//Wat is het hoogst mogelijke getal in de lijst
private final int MAXIMUM_GETAL;
public SpeedTest() {
this(50000);
}
public SpeedTest(int aantalGetallen) {
testGrootte = aantalGetallen;
MAXIMUM_GETAL = 1000;
}
public int getTestGrootte() {
return testGrootte;
}
private void maakLists() {
anArrayList.clear();
aLinkendList.clear();
for (int i = 0; i < testGrootte; i++) {
int randomGetal = random.nextInt(MAXIMUM_GETAL);
anArrayList.add(randomGetal);
aLinkendList.add(randomGetal);
}
}
public SpeedTestResult testInsertLast() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("achteraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testInsertFirst() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testDeleteFirst() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.remove(0);
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.remove(0);
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan verwijderen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testGet() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.get(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.get(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("elementen opzoeken", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testSorteren() {
maakLists();
long startTime = System.currentTimeMillis();
Collections.sort(anArrayList);
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
Collections.sort(aLinkendList);
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("sorteren", this.testGrootte, arrayListTimer, linkedListTimer);
}
}
| gvdhaege/KdG | Java Programming/OOPROG/P2W5/SpeedTest/src/SpeedTest.java | 1,081 | //Hoeveel getallen moeten er in de lijsten gestoken worden | line_comment | nl | import sun.util.locale.provider.AvailableLanguageTags;
import java.util.*;
public class SpeedTest {
private List<Integer> anArrayList = new ArrayList<>();
private List<Integer> aLinkendList = new LinkedList<>();
private Random random = new Random();
//Hoeveel getallen<SUF>
private final int testGrootte;
//Wat is het hoogst mogelijke getal in de lijst
private final int MAXIMUM_GETAL;
public SpeedTest() {
this(50000);
}
public SpeedTest(int aantalGetallen) {
testGrootte = aantalGetallen;
MAXIMUM_GETAL = 1000;
}
public int getTestGrootte() {
return testGrootte;
}
private void maakLists() {
anArrayList.clear();
aLinkendList.clear();
for (int i = 0; i < testGrootte; i++) {
int randomGetal = random.nextInt(MAXIMUM_GETAL);
anArrayList.add(randomGetal);
aLinkendList.add(randomGetal);
}
}
public SpeedTestResult testInsertLast() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("achteraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testInsertFirst() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testDeleteFirst() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.remove(0);
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.remove(0);
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan verwijderen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testGet() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.get(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.get(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("elementen opzoeken", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testSorteren() {
maakLists();
long startTime = System.currentTimeMillis();
Collections.sort(anArrayList);
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
Collections.sort(aLinkendList);
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("sorteren", this.testGrootte, arrayListTimer, linkedListTimer);
}
}
|
203323_1 | import sun.util.locale.provider.AvailableLanguageTags;
import java.util.*;
public class SpeedTest {
private List<Integer> anArrayList = new ArrayList<>();
private List<Integer> aLinkendList = new LinkedList<>();
private Random random = new Random();
//Hoeveel getallen moeten er in de lijsten gestoken worden
private final int testGrootte;
//Wat is het hoogst mogelijke getal in de lijst
private final int MAXIMUM_GETAL;
public SpeedTest() {
this(50000);
}
public SpeedTest(int aantalGetallen) {
testGrootte = aantalGetallen;
MAXIMUM_GETAL = 1000;
}
public int getTestGrootte() {
return testGrootte;
}
private void maakLists() {
anArrayList.clear();
aLinkendList.clear();
for (int i = 0; i < testGrootte; i++) {
int randomGetal = random.nextInt(MAXIMUM_GETAL);
anArrayList.add(randomGetal);
aLinkendList.add(randomGetal);
}
}
public SpeedTestResult testInsertLast() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("achteraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testInsertFirst() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testDeleteFirst() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.remove(0);
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.remove(0);
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan verwijderen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testGet() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.get(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.get(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("elementen opzoeken", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testSorteren() {
maakLists();
long startTime = System.currentTimeMillis();
Collections.sort(anArrayList);
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
Collections.sort(aLinkendList);
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("sorteren", this.testGrootte, arrayListTimer, linkedListTimer);
}
}
| gvdhaege/KdG | Java Programming/OOPROG/P2W5/SpeedTest/src/SpeedTest.java | 1,081 | //Wat is het hoogst mogelijke getal in de lijst | line_comment | nl | import sun.util.locale.provider.AvailableLanguageTags;
import java.util.*;
public class SpeedTest {
private List<Integer> anArrayList = new ArrayList<>();
private List<Integer> aLinkendList = new LinkedList<>();
private Random random = new Random();
//Hoeveel getallen moeten er in de lijsten gestoken worden
private final int testGrootte;
//Wat is<SUF>
private final int MAXIMUM_GETAL;
public SpeedTest() {
this(50000);
}
public SpeedTest(int aantalGetallen) {
testGrootte = aantalGetallen;
MAXIMUM_GETAL = 1000;
}
public int getTestGrootte() {
return testGrootte;
}
private void maakLists() {
anArrayList.clear();
aLinkendList.clear();
for (int i = 0; i < testGrootte; i++) {
int randomGetal = random.nextInt(MAXIMUM_GETAL);
anArrayList.add(randomGetal);
aLinkendList.add(randomGetal);
}
}
public SpeedTestResult testInsertLast() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("achteraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testInsertFirst() {
anArrayList.clear();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
aLinkendList.clear();
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.add(0, random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan toevoegen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testDeleteFirst() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.remove(0);
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.remove(0);
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("vooraan verwijderen", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testGet() {
maakLists();
long startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
anArrayList.get(random.nextInt(MAXIMUM_GETAL));
}
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < testGrootte; i++) {
aLinkendList.get(random.nextInt(MAXIMUM_GETAL));
}
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("elementen opzoeken", this.testGrootte, arrayListTimer, linkedListTimer);
}
public SpeedTestResult testSorteren() {
maakLists();
long startTime = System.currentTimeMillis();
Collections.sort(anArrayList);
long arrayListTimer = System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
Collections.sort(aLinkendList);
long linkedListTimer = System.currentTimeMillis() - startTime;
return new SpeedTestResult("sorteren", this.testGrootte, arrayListTimer, linkedListTimer);
}
}
|
203326_1 | package be.ucll.java.ent.controller;
import be.ucll.java.ent.domain.LeermoduleDTO;
import be.ucll.java.ent.model.LeermoduleDAO;
import be.ucll.java.ent.model.LeermoduleEntity;
import be.ucll.java.ent.model.StudentDAO;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Stateless
// Student - Enterprise Java Bean
public class LeermoduleEJB implements LeermoduleEJBLocal {
@PersistenceContext(unitName = "LocalPostgresPU")
private EntityManager em;
private LeermoduleDAO dao;
@PostConstruct
public void init() {
dao = new LeermoduleDAO(em);
}
@Override
public long createLeermodule(LeermoduleDTO leermodule) throws IllegalArgumentException {
// Code en beschrijving verondersteld als verplicht veld
if (leermodule == null) throw new IllegalArgumentException("Leermodule aanmaken gefaald. Inputdata ontbreekt");
if (leermodule.getCode() == null || leermodule.getCode().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Code ontbreekt");
if (leermodule.getBeschrijving() == null || leermodule.getBeschrijving().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Beschrijving ontbreekt");
LeermoduleDTO lm = null;
try {
lm = getLeermoduleByCode(leermodule.getCode());
if (lm != null) {
throw new IllegalArgumentException("Een leermodule met de code " + lm.getCode() + " bestaat al met beschrijving " + lm.getBeschrijving());
}
} catch (IllegalArgumentException e) {
if (e.getMessage().startsWith("Geen leermodule gevonden")){
// No problem, continue
} else {
throw e;
}
}
LeermoduleEntity lme = new LeermoduleEntity(0L,leermodule.getCode(), leermodule.getBeschrijving(), leermodule.getSchooljaar());
dao.create(lme);
leermodule.setId(lme.getId());
return lme.getId();
}
@Override
public LeermoduleDTO getLeermoduleById(long leermoduleId) throws IllegalArgumentException{
if (leermoduleId <= 0) throw new IllegalArgumentException("Leermodule ophalen gefaald. Leermodule ID ontbreekt");
Optional<LeermoduleEntity> value = dao.get(leermoduleId);
if (value.isPresent()) {
return new LeermoduleDTO(value.get().getId(), value.get().getCode(), value.get().getBeschrijving(), value.get().getSchooljaar());
} else {
throw new IllegalArgumentException("Geen leermodule gevonden met ID: " + leermoduleId);
}
}
@Override
public LeermoduleDTO getLeermoduleByCode(String code) throws IllegalArgumentException {
if (code == null || code.trim().length() == 0)
throw new IllegalArgumentException("Leermodule opzoeken op code gefaald. Inputdata ontbreekt");
Optional<LeermoduleEntity> value = dao.getOneByCode(code);
if (value.isPresent()) {
return new LeermoduleDTO(value.get().getId(), value.get().getCode(), value.get().getBeschrijving(), value.get().getSchooljaar());
} else {
throw new IllegalArgumentException("Geen leermodule gevonden met code: " + code);
}
}
@Override
public void updateLeermodule(LeermoduleDTO leermodule) throws IllegalArgumentException {
if (leermodule == null) throw new IllegalArgumentException("Leermodule wijzigen gefaald. Inputdata ontbreekt");
if (leermodule.getId() <= 0) throw new IllegalArgumentException("Leermodule wijzigen gefaald. Leermodule ID ontbreekt");
if (leermodule.getCode() == null || leermodule.getCode().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Code ontbreekt");
if (leermodule.getBeschrijving() == null || leermodule.getBeschrijving().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Beschrijving ontbreekt");
LeermoduleEntity lme = new LeermoduleEntity(leermodule.getId(),leermodule.getCode(), leermodule.getBeschrijving(), leermodule.getSchooljaar());
dao.update(lme);
}
@Override
public void deleteLeermodule(long leermoduleId) throws IllegalArgumentException {
if (leermoduleId <= 0) throw new IllegalArgumentException("Leermodule verwijderen gefaald. Leermodule ID ontbreekt");
dao.delete(leermoduleId);
}
@Override
public List<LeermoduleDTO> getLeermodules(String code) throws IllegalArgumentException {
if (code == null || code.trim().length() == 0) {
throw new IllegalArgumentException("Leermodules ophalen met de code gefaald. Code leeg");
}
List<LeermoduleEntity> lst = dao.getLeermoduleByCode(code);
return queryListToLeermoduleDTOList(lst);
}
@Override
public List<LeermoduleDTO> getAllLeermodules() {
return queryListToLeermoduleDTOList(dao.getAll());
}
@Override
public long countLeermodules() {
return dao.countAll();
}
private List<LeermoduleDTO> queryListToLeermoduleDTOList(List<LeermoduleEntity> lst){
Stream<LeermoduleDTO> stream = lst.stream()
.map(rec -> {
LeermoduleDTO dto = new LeermoduleDTO();
dto.setId(rec.getId());
dto.setCode(rec.getCode());
dto.setBeschrijving(rec.getBeschrijving());
dto.setSchooljaar(rec.getSchooljaar());
return dto;
});
return stream.collect(Collectors.toList());
}
// Methods hereunder only needed for Unit testing.
public void setEm(EntityManager em) {
this.em = em;
}
public void setDao(LeermoduleDAO dao) {
this.dao = dao;
}
}
| UcllJavaEnterprise/stubs-vaadin-demo | src/main/java/be/ucll/java/ent/controller/LeermoduleEJB.java | 1,505 | // Code en beschrijving verondersteld als verplicht veld | line_comment | nl | package be.ucll.java.ent.controller;
import be.ucll.java.ent.domain.LeermoduleDTO;
import be.ucll.java.ent.model.LeermoduleDAO;
import be.ucll.java.ent.model.LeermoduleEntity;
import be.ucll.java.ent.model.StudentDAO;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Stateless
// Student - Enterprise Java Bean
public class LeermoduleEJB implements LeermoduleEJBLocal {
@PersistenceContext(unitName = "LocalPostgresPU")
private EntityManager em;
private LeermoduleDAO dao;
@PostConstruct
public void init() {
dao = new LeermoduleDAO(em);
}
@Override
public long createLeermodule(LeermoduleDTO leermodule) throws IllegalArgumentException {
// Code en<SUF>
if (leermodule == null) throw new IllegalArgumentException("Leermodule aanmaken gefaald. Inputdata ontbreekt");
if (leermodule.getCode() == null || leermodule.getCode().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Code ontbreekt");
if (leermodule.getBeschrijving() == null || leermodule.getBeschrijving().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Beschrijving ontbreekt");
LeermoduleDTO lm = null;
try {
lm = getLeermoduleByCode(leermodule.getCode());
if (lm != null) {
throw new IllegalArgumentException("Een leermodule met de code " + lm.getCode() + " bestaat al met beschrijving " + lm.getBeschrijving());
}
} catch (IllegalArgumentException e) {
if (e.getMessage().startsWith("Geen leermodule gevonden")){
// No problem, continue
} else {
throw e;
}
}
LeermoduleEntity lme = new LeermoduleEntity(0L,leermodule.getCode(), leermodule.getBeschrijving(), leermodule.getSchooljaar());
dao.create(lme);
leermodule.setId(lme.getId());
return lme.getId();
}
@Override
public LeermoduleDTO getLeermoduleById(long leermoduleId) throws IllegalArgumentException{
if (leermoduleId <= 0) throw new IllegalArgumentException("Leermodule ophalen gefaald. Leermodule ID ontbreekt");
Optional<LeermoduleEntity> value = dao.get(leermoduleId);
if (value.isPresent()) {
return new LeermoduleDTO(value.get().getId(), value.get().getCode(), value.get().getBeschrijving(), value.get().getSchooljaar());
} else {
throw new IllegalArgumentException("Geen leermodule gevonden met ID: " + leermoduleId);
}
}
@Override
public LeermoduleDTO getLeermoduleByCode(String code) throws IllegalArgumentException {
if (code == null || code.trim().length() == 0)
throw new IllegalArgumentException("Leermodule opzoeken op code gefaald. Inputdata ontbreekt");
Optional<LeermoduleEntity> value = dao.getOneByCode(code);
if (value.isPresent()) {
return new LeermoduleDTO(value.get().getId(), value.get().getCode(), value.get().getBeschrijving(), value.get().getSchooljaar());
} else {
throw new IllegalArgumentException("Geen leermodule gevonden met code: " + code);
}
}
@Override
public void updateLeermodule(LeermoduleDTO leermodule) throws IllegalArgumentException {
if (leermodule == null) throw new IllegalArgumentException("Leermodule wijzigen gefaald. Inputdata ontbreekt");
if (leermodule.getId() <= 0) throw new IllegalArgumentException("Leermodule wijzigen gefaald. Leermodule ID ontbreekt");
if (leermodule.getCode() == null || leermodule.getCode().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Code ontbreekt");
if (leermodule.getBeschrijving() == null || leermodule.getBeschrijving().trim().length() == 0)
throw new IllegalArgumentException("Leermodule aanmaken gefaald. Beschrijving ontbreekt");
LeermoduleEntity lme = new LeermoduleEntity(leermodule.getId(),leermodule.getCode(), leermodule.getBeschrijving(), leermodule.getSchooljaar());
dao.update(lme);
}
@Override
public void deleteLeermodule(long leermoduleId) throws IllegalArgumentException {
if (leermoduleId <= 0) throw new IllegalArgumentException("Leermodule verwijderen gefaald. Leermodule ID ontbreekt");
dao.delete(leermoduleId);
}
@Override
public List<LeermoduleDTO> getLeermodules(String code) throws IllegalArgumentException {
if (code == null || code.trim().length() == 0) {
throw new IllegalArgumentException("Leermodules ophalen met de code gefaald. Code leeg");
}
List<LeermoduleEntity> lst = dao.getLeermoduleByCode(code);
return queryListToLeermoduleDTOList(lst);
}
@Override
public List<LeermoduleDTO> getAllLeermodules() {
return queryListToLeermoduleDTOList(dao.getAll());
}
@Override
public long countLeermodules() {
return dao.countAll();
}
private List<LeermoduleDTO> queryListToLeermoduleDTOList(List<LeermoduleEntity> lst){
Stream<LeermoduleDTO> stream = lst.stream()
.map(rec -> {
LeermoduleDTO dto = new LeermoduleDTO();
dto.setId(rec.getId());
dto.setCode(rec.getCode());
dto.setBeschrijving(rec.getBeschrijving());
dto.setSchooljaar(rec.getSchooljaar());
return dto;
});
return stream.collect(Collectors.toList());
}
// Methods hereunder only needed for Unit testing.
public void setEm(EntityManager em) {
this.em = em;
}
public void setDao(LeermoduleDAO dao) {
this.dao = dao;
}
}
|
203327_0 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,556 | // Hoofdscherm waarin de verschillende fragmenten geladen worden | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin<SUF>
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} |
203327_1 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,556 | // Controle ingelogde user om te checken of de login gewerkt heeft | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde<SUF>
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} |
203327_4 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,556 | // Voor het weergeven van het menu rechtsboven | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het<SUF>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} |
203327_6 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,556 | // Instellen van de opties van het menu | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van<SUF>
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} |
203327_8 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,556 | // De rol van de gebruiker opzoeken, member of project manager | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol<SUF>
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} |
203329_0 | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of er al iemand ingelogd is
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er op de register knop wordt geklikt
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor het in te loggen bij de firebase authenticatie
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/LoginActivity.java | 1,298 | // Checken of er al iemand ingelogd is | line_comment | nl | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of<SUF>
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er op de register knop wordt geklikt
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor het in te loggen bij de firebase authenticatie
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} |
203329_2 | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of er al iemand ingelogd is
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er op de register knop wordt geklikt
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor het in te loggen bij de firebase authenticatie
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/LoginActivity.java | 1,298 | // Wanneer er op de register knop wordt geklikt | line_comment | nl | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of er al iemand ingelogd is
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er<SUF>
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor het in te loggen bij de firebase authenticatie
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} |
203329_3 | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of er al iemand ingelogd is
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er op de register knop wordt geklikt
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor het in te loggen bij de firebase authenticatie
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/LoginActivity.java | 1,298 | // Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina | line_comment | nl | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of er al iemand ingelogd is
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er op de register knop wordt geklikt
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in<SUF>
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor het in te loggen bij de firebase authenticatie
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} |
203329_4 | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of er al iemand ingelogd is
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er op de register knop wordt geklikt
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor het in te loggen bij de firebase authenticatie
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/LoginActivity.java | 1,298 | // Methode voor het in te loggen bij de firebase authenticatie | line_comment | nl | package be.ucll.workloadplanner;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.widget.Toast;
// Het Loginscherm
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Checken of er al iemand ingelogd is
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// Wanneer er op de login knop wordt geklikt
Button login = findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText phoneNumberEditText = findViewById(R.id.phoneNumber);
String phoneNumber = phoneNumberEditText.getText().toString();
checkPhoneNumberInDatabase(phoneNumber);
}
});
// Wanneer er op de register knop wordt geklikt
Button register = findViewById(R.id.registerButton);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
// Opzoeken in de database of het telefoonnr al bestaat en dan eventueel doorsturen naar de verificatie pagina
private void checkPhoneNumberInDatabase(String phoneNumber) {
db.collection("users")
.whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(LoginActivity.this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("LoginActivity", "Phone number verification failed", e);
Toast.makeText(LoginActivity.this, "Phone number verification failed. Please try again.", Toast.LENGTH_SHORT).show();
}
@Override
public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("verificationId", verificationId);
startActivity(intent);
}
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
} else {
Toast.makeText(LoginActivity.this, "Phone number not registered. Please register first.", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LoginActivity", "Error checking phone number in database", e);
Toast.makeText(LoginActivity.this, "Error checking phone number. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
// Methode voor<SUF>
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("LoginActivity", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Log.w("LoginActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
} |
203334_0 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/services/zaken/reisdocumenten/ReisdocumentService.java | 4,820 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/ | block_comment | nl | /*
* Copyright 2021 -<SUF>*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
|
203334_1 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/services/zaken/reisdocumenten/ReisdocumentService.java | 4,820 | /**
* Geef aanvraagnummer terug op basis van het documentNummer
*/ | block_comment | nl | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug<SUF>*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
|
203334_3 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/services/zaken/reisdocumenten/ReisdocumentService.java | 4,820 | /**
* Zoek reisdocumenthistorie op de PL
*/ | block_comment | nl | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op<SUF>*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
|
203334_4 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/services/zaken/reisdocumenten/ReisdocumentService.java | 4,820 | /**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/ | block_comment | nl | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten<SUF>*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
|
203334_5 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/services/zaken/reisdocumenten/ReisdocumentService.java | 4,820 | // Op verwerkt zetten na uitreiking
| line_comment | nl | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt<SUF>
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
|
203334_6 | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de geboorteaanvraag
*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
| vrijBRP/vrijBRP-Balie | gba-services/src/main/java/nl/procura/gba/web/services/zaken/reisdocumenten/ReisdocumentService.java | 4,820 | /**
* Verwijderen van de geboorteaanvraag
*/ | block_comment | nl | /*
* Copyright 2021 - 2022 Procura B.V.
*
* In licentie gegeven krachtens de EUPL, versie 1.2
* U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie.
* U kunt een kopie van de licentie vinden op:
*
* https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md
*
* Deze bevat zowel de Nederlandse als de Engelse tekst
*
* Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk
* is overeengekomen, wordt software krachtens deze licentie verspreid
* "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet
* noch impliciet.
* Zie de licentie voor de specifieke bepalingen voor toestemmingen en
* beperkingen op grond van de licentie.
*/
package nl.procura.gba.web.services.zaken.reisdocumenten;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_BEZIT_BUITENL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AAND_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.AUTORIT_VAN_AFGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_EINDE_GELDIG_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_INH_VERMIS_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.DATUM_UITGIFTE_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.NR_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC;
import static nl.procura.burgerzaken.gba.core.enums.GBAElem.SOORT_NL_REISDOC;
import static nl.procura.gba.common.MiscUtils.copy;
import static nl.procura.gba.common.MiscUtils.copyList;
import static nl.procura.gba.common.MiscUtils.to;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT;
import static nl.procura.gba.common.ZaakStatusType.VERWERKT_IN_GBA;
import static nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoonType.AANGEVER;
import static nl.procura.standard.Globalfunctions.fil;
import static nl.procura.standard.Globalfunctions.pos;
import static nl.procura.standard.Globalfunctions.toNul;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import nl.procura.burgerzaken.gba.core.enums.GBACat;
import nl.procura.burgerzaken.gba.core.enums.GBAElem;
import nl.procura.diensten.gba.ple.base.BasePLRec;
import nl.procura.diensten.gba.ple.base.BasePLSet;
import nl.procura.diensten.gba.ple.extensions.BasePLExt;
import nl.procura.diensten.gba.ple.openoffice.DocumentPL;
import nl.procura.diensten.gba.ple.openoffice.formats.Naamformats;
import nl.procura.dto.raas.aanvraag.DocAanvraagDto;
import nl.procura.gba.common.ConditionalMap;
import nl.procura.gba.common.ZaakStatusType;
import nl.procura.gba.common.ZaakType;
import nl.procura.gba.jpa.personen.dao.Rdm01Dao;
import nl.procura.gba.jpa.personen.dao.ReisdocDao;
import nl.procura.gba.jpa.personen.dao.ZaakKey;
import nl.procura.gba.jpa.personen.db.Rdm01;
import nl.procura.gba.jpa.personen.db.Reisdoc;
import nl.procura.gba.jpa.personen.db.Usr;
import nl.procura.gba.web.common.misc.ZakenList;
import nl.procura.gba.web.services.ServiceEvent;
import nl.procura.gba.web.services.aop.ThrowException;
import nl.procura.gba.web.services.aop.Timer;
import nl.procura.gba.web.services.aop.Transactional;
import nl.procura.gba.web.services.beheer.parameter.ParameterConstant;
import nl.procura.gba.web.services.beheer.raas.RaasService;
import nl.procura.gba.web.services.beheer.vrs.VrsRequest;
import nl.procura.gba.web.services.beheer.vrs.VrsService;
import nl.procura.gba.web.services.zaken.algemeen.AbstractZaakContactService;
import nl.procura.gba.web.services.zaken.algemeen.ControleerbareService;
import nl.procura.gba.web.services.zaken.algemeen.Zaak;
import nl.procura.gba.web.services.zaken.algemeen.ZaakArgumenten;
import nl.procura.gba.web.services.zaken.algemeen.ZaakService;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact;
import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContactpersoon;
import nl.procura.gba.web.services.zaken.algemeen.controle.Controles;
import nl.procura.gba.web.services.zaken.algemeen.controle.ControlesListener;
import nl.procura.gba.web.services.zaken.inhoudingen.DocumentInhoudingenService;
import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.Clausules;
import nl.procura.raas.rest.domain.aanvraag.FindAanvraagRequest;
import nl.procura.validation.Bsn;
public class ReisdocumentService extends AbstractZaakContactService<ReisdocumentAanvraag>
implements ZaakService<ReisdocumentAanvraag>, ControleerbareService {
public ReisdocumentService() {
super("Reisdocumenten", ZaakType.REISDOCUMENT);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public int getZakenCount(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findCount(getArgumentenToMap(zaakArgumenten));
}
@Override
public ReisdocumentAanvraag setVolledigeZaakExtra(ReisdocumentAanvraag zaak) {
ReisdocumentAanvraag impl = to(zaak, ReisdocumentAanvraag.class);
BasePLExt pl = findPL(impl.getAnummer(), impl.getBurgerServiceNummer());
if (impl.getClausules().getPartner() == null) {
BasePLRec actueelRecord = pl.getHuwelijk().getActueelOfMutatieRecord();
String partnerAnr = pl.getHuwelijk().getAnr().getCode();
String partnerBsn = pl.getHuwelijk().getBsn().getCode();
String gesl = actueelRecord.getElemVal(GBAElem.GESLACHTSNAAM).getDescr();
String voorn = actueelRecord.getElemVal(GBAElem.VOORNAMEN).getDescr();
String voorv = actueelRecord.getElemVal(GBAElem.VOORV_GESLACHTSNAAM).getDescr();
String titel = actueelRecord.getElemVal(GBAElem.TITEL_PREDIKAAT).getDescr();
Clausules clausulesImpl = impl.getClausules();
if (fil(gesl)) {
if (pos(partnerAnr) || pos(partnerBsn)) {
clausulesImpl.setPartner(new DocumentPL(getPersoonslijst(partnerAnr, partnerBsn)));
}
if (clausulesImpl.getPartner() == null) {
clausulesImpl.setPartner(new DocumentPL(new BasePLExt()));
}
clausulesImpl.getPartner()
.getPersoon()
.getFormats()
.setNaam(new Naamformats(voorn, gesl, voorv, titel, "E", null));
}
}
DocumentInhoudingenService inhoudingen = getServices().getDocumentInhoudingenService();
impl.setInhoudingen(
inhoudingen.getInhoudingenVanDeZaak(impl, findPL(impl.getAnummer(), impl.getBurgerServiceNummer())));
impl.setDocumentHistorie(inhoudingen.getActueelReisdocumentHistorie(pl));
return super.setVolledigeZaakExtra(zaak);
}
/**
* Geef aanvraagnummer terug op basis van het documentNummer
*/
public String getBackOfficeAanvraag(String documentNummer) {
String sql = String.format("select x.aanvrNr from Rdm01 x where x.nrNlDoc = '%s'", documentNummer);
List<String[]> records = getServices().getProbevSqlService().find(sql);
return records.stream().findFirst().map(row -> row[0]).orElse("");
}
public Optional<RdmRaasComparison> getRaasComparison(ReisdocumentAanvraag zaak, boolean updateProweb) {
RaasService raasService = getServices().getRaasService();
if (raasService.isRaasServiceActive()) {
FindAanvraagRequest fr = new FindAanvraagRequest(zaak.getAanvraagnummer().toLong());
if (updateProweb) {
fr.setUpdateProweb(true);
}
Optional<DocAanvraagDto> result = raasService.findFirst(fr);
if (result.isPresent()) {
DocAanvraagDto documentAanvraag = result.get();
return Optional.of(new RdmRaasComparison(zaak, documentAanvraag));
}
}
return Optional.empty();
}
@Override
public ZaakContact getContact(ReisdocumentAanvraag zaak) {
ZaakContact zaakContact = new ZaakContact();
BasePLExt basisPersoon = getBasisPersoon(zaak);
if (basisPersoon != null) {
ZaakContactpersoon persoon = new ZaakContactpersoon(AANGEVER, basisPersoon);
persoon.setContactgegevens(getServices().getContactgegevensService().getContactgegevens(zaak));
zaakContact.add(persoon);
}
return zaakContact;
}
@Override
public Controles getControles(ControlesListener listener) {
return new ReisdocumentZaakControles(this).getControles(listener);
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van de reisdocumenten")
public List<ReisdocumentAanvraag> getMinimalZaken(ZaakArgumenten zaakArgumenten) {
return new ZakenList<>(
copyList(Rdm01Dao.find(getArgumentenToMap(zaakArgumenten)), ReisdocumentAanvraag.class));
}
@Override
public Zaak getNewZaak() {
return aanvullenZaak(new ReisdocumentAanvraag());
}
/**
* Nieuwe aanvraag
*/
public ReisdocumentAanvraag getNewZaak(BasePLExt persoonslijst) {
ReisdocumentAanvraag aanvraag = (ReisdocumentAanvraag) getNewZaak();
aanvraag.setBasisPersoon(persoonslijst);
return aanvraag;
}
/**
* Zoek reisdocumenthistorie op de PL
*/
public List<Reisdocument> getReisdocumentHistorie(BasePLExt pl) {
List<Reisdocument> documenten = new ArrayList<>();
for (BasePLSet set : pl.getCat(GBACat.REISDOC).getSets()) {
BasePLRec record = set.getLatestRec();
Reisdocument doc = new Reisdocument();
doc.setAanduidingInhoudingVermissing(
record.getElemVal(AAND_INH_VERMIS_NL_REISDOC));
doc.setAutoriteitVanAfgifte(record.getElemVal(AUTORIT_VAN_AFGIFTE_NL_REISDOC));
doc.setBuitenlandsReisdocument(record.getElemVal(AAND_BEZIT_BUITENL_REISDOC));
doc.setDatumEindeGeldigheid(record.getElemVal(DATUM_EINDE_GELDIG_NL_REISDOC));
doc.setDatumInhoudingVermissing(
record.getElemVal(DATUM_INH_VERMIS_NL_REISDOC));
doc.setDatumUitgifte(record.getElemVal(DATUM_UITGIFTE_NL_REISDOC));
doc.setNederlandsReisdocument(record.getElemVal(SOORT_NL_REISDOC));
doc.setNummerDocument(record.getElemVal(NR_NL_REISDOC));
doc.setSignalering(record.getElemVal(SIG_MET_BETREK_TOT_VERSTREK_NL_REISDOC));
documenten.add(doc);
}
return documenten;
}
/**
* Geeft de reisdocumenten uit de reisdocumententabel terug.
*
* @return List<Reisdocument>
*/
@ThrowException("Fout bij het ophalen van gegevens uit de database")
public List<SoortReisdocument> getSoortReisdocumenten() {
List<SoortReisdocument> list = new ArrayList<>();
for (Reisdoc reisDoc : ReisdocDao.findAllReisdocs()) {
list.add(copy(reisDoc, SoortReisdocument.class));
}
return list;
}
@Override
public ReisdocumentAanvraag getStandardZaak(ReisdocumentAanvraag zaak) {
return new ReisdocumentZaakControles(this).controleer(super.getStandardZaak(zaak));
}
@Override
@Timer
@ThrowException("Fout bij het zoeken van zaak-ids")
public List<ZaakKey> getZaakKeys(ZaakArgumenten zaakArgumenten) {
return Rdm01Dao.findZaakKeys(getArgumentenToMap(zaakArgumenten));
}
@ThrowException("Fout bij het opzoeken van aanvraagnummers")
public boolean nummerBestaat(Aanvraagnummer aanvraagNummer) {
return pos(aanvraagNummer.getNummer()) &&
Rdm01Dao.findFirstByExample(new Rdm01(aanvraagNummer.getNummer())) != null;
}
@Override
@Transactional
@ThrowException("Fout bij het opslaan van de reisdocument aanvraag")
public void save(ReisdocumentAanvraag zaak) {
getZaakStatussen().setInitieleStatus(zaak, ZaakStatusType.INCOMPLEET);
if (isSaved(zaak)) {
// Op verwerkt zetten na uitreiking
if (!zaak.getZaakHistorie().getStatusHistorie().isEindStatus()) {
if (zaak.getReisdocumentStatus().getStatusAfsluiting().getCode() > SluitingType.AANVRAAG_NIET_AFGESLOTEN
.getCode()) {
ZaakStatusType status = VERWERKT;
if (getServices().getRaasService().isRaasServiceActive()) {
Long aanvrNr = zaak.getAanvraagnummer().toLong();
if (getServices().getRaasService().isAanvraag(aanvrNr)) {
status = VERWERKT_IN_GBA;
}
}
updateStatus(zaak, zaak.getStatus(), status, "");
}
}
opslaanStandaardZaak(zaak);
} else {
zaak.setUsr1(findEntity(Usr.class, toNul(zaak.getGebruikerAanvraag().getValue())));
zaak.setUsr2(findEntity(Usr.class, toNul(zaak.getGebruikerUitgifte().getValue())));
zaak.setIdVaststelling(getIdentificatie(zaak).getKorteOmschrijving());
opslaanStandaardZaak(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
/**
* Verwijderen van de<SUF>*/
@Override
@Transactional
@ThrowException("Fout bij het verwijderen")
public void delete(ReisdocumentAanvraag zaak) {
if (fil(zaak.getAanvraagnummer().getNummer())) {
ConditionalMap map = new ConditionalMap();
map.put(Rdm01Dao.ZAAK_ID, zaak.getAanvraagnummer().getNummer());
map.put(Rdm01Dao.MAX_CORRECT_RESULTS, 1);
removeEntities(Rdm01Dao.find(map));
deleteZaakRelaties(zaak);
}
callListeners(ServiceEvent.CHANGE);
}
public Optional<SignaleringResult> checkIdentiteit(BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build());
}
return Optional.empty();
}
public boolean isVrsEnabled() {
return new VrsService(getServices().getParameterService()).isEnabled();
}
public Optional<SignaleringResult> checkAanvraag(Aanvraagnummer aanvraagnummer, BasePLExt pl) {
VrsService vrsService = new VrsService(getServices().getParameterService());
if (vrsService.isEnabled()) {
return vrsService.checkSignalering(VrsRequest.builder()
.aanvraagnummer(aanvraagnummer)
.bsn(new Bsn(pl.getPersoon().getBsn().getDescr()))
.build())
.filter(SignaleringResult::isHit);
} else {
return signaleringFromPl(pl);
}
}
private Optional<SignaleringResult> signaleringFromPl(BasePLExt pl) {
if (pl.getReisdoc().heeftSignalering()) {
return Optional
.of(SignaleringResult.builder()
.mededelingRvIG(getSysteemParm(ParameterConstant.REISD_SIGNAL_INFO, false))
.resultaatOmschrijving("Signalering met betrekking tot verstrekken Nederlands reisdocument op de PL")
.build());
}
return Optional.empty();
}
private ConditionalMap getArgumentenToMap(ZaakArgumenten zaakArgumenten) {
ConditionalMap map = getAlgemeneArgumentenToMap(zaakArgumenten);
if (!zaakArgumenten.isAll()) {
if (zaakArgumenten instanceof ReisdocumentZaakArgumenten) {
String documentNummer = ((ReisdocumentZaakArgumenten) zaakArgumenten).getDocumentnummer();
map.putString(Rdm01Dao.NR_NL_DOC, documentNummer);
}
}
return map;
}
}
|
203340_1 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor opzoeken partijen.
*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.
* @return lijst met alle partijen.
*/
List<Partij> geefAllePartijen();
/**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-bericht-model/src/main/java/nl/bzk/migratiebrp/bericht/model/sync/register/PartijRegister.java | 306 | /**
* Partij register voor opzoeken partijen.
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor<SUF>*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.
* @return lijst met alle partijen.
*/
List<Partij> geefAllePartijen();
/**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
|
203340_2 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor opzoeken partijen.
*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.
* @return lijst met alle partijen.
*/
List<Partij> geefAllePartijen();
/**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-bericht-model/src/main/java/nl/bzk/migratiebrp/bericht/model/sync/register/PartijRegister.java | 306 | /**
* Geef alle partijen.
* @return lijst met alle partijen.
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor opzoeken partijen.
*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.<SUF>*/
List<Partij> geefAllePartijen();
/**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
|
203340_3 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor opzoeken partijen.
*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.
* @return lijst met alle partijen.
*/
List<Partij> geefAllePartijen();
/**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-bericht-model/src/main/java/nl/bzk/migratiebrp/bericht/model/sync/register/PartijRegister.java | 306 | /**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor opzoeken partijen.
*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.
* @return lijst met alle partijen.
*/
List<Partij> geefAllePartijen();
/**
* Geef een partij<SUF>*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
|
203340_4 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor opzoeken partijen.
*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.
* @return lijst met alle partijen.
*/
List<Partij> geefAllePartijen();
/**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-bericht-model/src/main/java/nl/bzk/migratiebrp/bericht/model/sync/register/PartijRegister.java | 306 | /**
* Geef een partij terug op basis van gegeven gemeente code.
* @param gemeenteCode gemeente code van de gezochte partij
* @return de partij
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.bericht.model.sync.register;
import java.io.Serializable;
import java.util.List;
/**
* Partij register voor opzoeken partijen.
*/
public interface PartijRegister extends Serializable {
/**
* Geef alle partijen.
* @return lijst met alle partijen.
*/
List<Partij> geefAllePartijen();
/**
* Geef een partij terug op basis van gegeven partij code.
* @param partijCode partij code van de gezochte partij
* @return de partij
*/
Partij zoekPartijOpPartijCode(String partijCode);
/**
* Geef een partij<SUF>*/
Partij zoekPartijOpGemeenteCode(String gemeenteCode);
}
|
203342_1 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service;
import java.util.Collection;
import java.util.List;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.migratiebrp.conversie.model.brp.autorisatie.BrpAutorisatie;
/**
* Interface class voor alle operaties die nodig zijn voor autorisaties voor de DAL.
*/
public interface BrpAutorisatieService {
/**
* Geef de lijst met alle actieve gba autorisaties.
* @return De lijst met alle actieve gba autorisaties.
*/
Collection<Leveringsautorisatie> geefAlleGbaAutorisaties();
/**
* Slaat een autorisatie (partij, toegang leveringsautorisatie, leveringsautorisaties, dienstbundels en diensten) op
* in de BRP database.
* @param brpAutorisatie De autorisatie in het BRP-migratiemodelformaat.
* @return de opgeslagen abonnementen
* @throws PartijNietGevondenException als de partij niet gevonden kan worden in de database
*/
List<ToegangLeveringsAutorisatie> persisteerAutorisatie(BrpAutorisatie brpAutorisatie) throws PartijNietGevondenException;
/**
* Vraag een autorisatie op uit de BRP database voor de gegeven partijCode, naam en ingangsDatumRegel, deze moet
* bestaan anders treedt er een fout op.
* @param partijCode de partij waarvoor we de autorisatie opzoeken
* @param naam de naam van het autorisatiebesluit
* @param ingangsDatumRegel de ingangsdatum van de autorisatietabelregel
* @return De autorisatie in het BRP-migratiemodelformaat.
* @throws IllegalStateException als de autorisatie niet gevonden kan worden
*/
BrpAutorisatie bevraagAutorisatie(String partijCode, String naam, Integer ingangsDatumRegel);
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-synchronisatie-dal/src/main/java/nl/bzk/migratiebrp/synchronisatie/dal/service/BrpAutorisatieService.java | 589 | /**
* Interface class voor alle operaties die nodig zijn voor autorisaties voor de DAL.
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service;
import java.util.Collection;
import java.util.List;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.migratiebrp.conversie.model.brp.autorisatie.BrpAutorisatie;
/**
* Interface class voor<SUF>*/
public interface BrpAutorisatieService {
/**
* Geef de lijst met alle actieve gba autorisaties.
* @return De lijst met alle actieve gba autorisaties.
*/
Collection<Leveringsautorisatie> geefAlleGbaAutorisaties();
/**
* Slaat een autorisatie (partij, toegang leveringsautorisatie, leveringsautorisaties, dienstbundels en diensten) op
* in de BRP database.
* @param brpAutorisatie De autorisatie in het BRP-migratiemodelformaat.
* @return de opgeslagen abonnementen
* @throws PartijNietGevondenException als de partij niet gevonden kan worden in de database
*/
List<ToegangLeveringsAutorisatie> persisteerAutorisatie(BrpAutorisatie brpAutorisatie) throws PartijNietGevondenException;
/**
* Vraag een autorisatie op uit de BRP database voor de gegeven partijCode, naam en ingangsDatumRegel, deze moet
* bestaan anders treedt er een fout op.
* @param partijCode de partij waarvoor we de autorisatie opzoeken
* @param naam de naam van het autorisatiebesluit
* @param ingangsDatumRegel de ingangsdatum van de autorisatietabelregel
* @return De autorisatie in het BRP-migratiemodelformaat.
* @throws IllegalStateException als de autorisatie niet gevonden kan worden
*/
BrpAutorisatie bevraagAutorisatie(String partijCode, String naam, Integer ingangsDatumRegel);
}
|
203342_3 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service;
import java.util.Collection;
import java.util.List;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.migratiebrp.conversie.model.brp.autorisatie.BrpAutorisatie;
/**
* Interface class voor alle operaties die nodig zijn voor autorisaties voor de DAL.
*/
public interface BrpAutorisatieService {
/**
* Geef de lijst met alle actieve gba autorisaties.
* @return De lijst met alle actieve gba autorisaties.
*/
Collection<Leveringsautorisatie> geefAlleGbaAutorisaties();
/**
* Slaat een autorisatie (partij, toegang leveringsautorisatie, leveringsautorisaties, dienstbundels en diensten) op
* in de BRP database.
* @param brpAutorisatie De autorisatie in het BRP-migratiemodelformaat.
* @return de opgeslagen abonnementen
* @throws PartijNietGevondenException als de partij niet gevonden kan worden in de database
*/
List<ToegangLeveringsAutorisatie> persisteerAutorisatie(BrpAutorisatie brpAutorisatie) throws PartijNietGevondenException;
/**
* Vraag een autorisatie op uit de BRP database voor de gegeven partijCode, naam en ingangsDatumRegel, deze moet
* bestaan anders treedt er een fout op.
* @param partijCode de partij waarvoor we de autorisatie opzoeken
* @param naam de naam van het autorisatiebesluit
* @param ingangsDatumRegel de ingangsdatum van de autorisatietabelregel
* @return De autorisatie in het BRP-migratiemodelformaat.
* @throws IllegalStateException als de autorisatie niet gevonden kan worden
*/
BrpAutorisatie bevraagAutorisatie(String partijCode, String naam, Integer ingangsDatumRegel);
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-synchronisatie-dal/src/main/java/nl/bzk/migratiebrp/synchronisatie/dal/service/BrpAutorisatieService.java | 589 | /**
* Slaat een autorisatie (partij, toegang leveringsautorisatie, leveringsautorisaties, dienstbundels en diensten) op
* in de BRP database.
* @param brpAutorisatie De autorisatie in het BRP-migratiemodelformaat.
* @return de opgeslagen abonnementen
* @throws PartijNietGevondenException als de partij niet gevonden kan worden in de database
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service;
import java.util.Collection;
import java.util.List;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.migratiebrp.conversie.model.brp.autorisatie.BrpAutorisatie;
/**
* Interface class voor alle operaties die nodig zijn voor autorisaties voor de DAL.
*/
public interface BrpAutorisatieService {
/**
* Geef de lijst met alle actieve gba autorisaties.
* @return De lijst met alle actieve gba autorisaties.
*/
Collection<Leveringsautorisatie> geefAlleGbaAutorisaties();
/**
* Slaat een autorisatie<SUF>*/
List<ToegangLeveringsAutorisatie> persisteerAutorisatie(BrpAutorisatie brpAutorisatie) throws PartijNietGevondenException;
/**
* Vraag een autorisatie op uit de BRP database voor de gegeven partijCode, naam en ingangsDatumRegel, deze moet
* bestaan anders treedt er een fout op.
* @param partijCode de partij waarvoor we de autorisatie opzoeken
* @param naam de naam van het autorisatiebesluit
* @param ingangsDatumRegel de ingangsdatum van de autorisatietabelregel
* @return De autorisatie in het BRP-migratiemodelformaat.
* @throws IllegalStateException als de autorisatie niet gevonden kan worden
*/
BrpAutorisatie bevraagAutorisatie(String partijCode, String naam, Integer ingangsDatumRegel);
}
|
203342_4 | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service;
import java.util.Collection;
import java.util.List;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.migratiebrp.conversie.model.brp.autorisatie.BrpAutorisatie;
/**
* Interface class voor alle operaties die nodig zijn voor autorisaties voor de DAL.
*/
public interface BrpAutorisatieService {
/**
* Geef de lijst met alle actieve gba autorisaties.
* @return De lijst met alle actieve gba autorisaties.
*/
Collection<Leveringsautorisatie> geefAlleGbaAutorisaties();
/**
* Slaat een autorisatie (partij, toegang leveringsautorisatie, leveringsautorisaties, dienstbundels en diensten) op
* in de BRP database.
* @param brpAutorisatie De autorisatie in het BRP-migratiemodelformaat.
* @return de opgeslagen abonnementen
* @throws PartijNietGevondenException als de partij niet gevonden kan worden in de database
*/
List<ToegangLeveringsAutorisatie> persisteerAutorisatie(BrpAutorisatie brpAutorisatie) throws PartijNietGevondenException;
/**
* Vraag een autorisatie op uit de BRP database voor de gegeven partijCode, naam en ingangsDatumRegel, deze moet
* bestaan anders treedt er een fout op.
* @param partijCode de partij waarvoor we de autorisatie opzoeken
* @param naam de naam van het autorisatiebesluit
* @param ingangsDatumRegel de ingangsdatum van de autorisatietabelregel
* @return De autorisatie in het BRP-migratiemodelformaat.
* @throws IllegalStateException als de autorisatie niet gevonden kan worden
*/
BrpAutorisatie bevraagAutorisatie(String partijCode, String naam, Integer ingangsDatumRegel);
}
| EdwinSmink/OperatieBRP | 02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-synchronisatie-dal/src/main/java/nl/bzk/migratiebrp/synchronisatie/dal/service/BrpAutorisatieService.java | 589 | /**
* Vraag een autorisatie op uit de BRP database voor de gegeven partijCode, naam en ingangsDatumRegel, deze moet
* bestaan anders treedt er een fout op.
* @param partijCode de partij waarvoor we de autorisatie opzoeken
* @param naam de naam van het autorisatiebesluit
* @param ingangsDatumRegel de ingangsdatum van de autorisatietabelregel
* @return De autorisatie in het BRP-migratiemodelformaat.
* @throws IllegalStateException als de autorisatie niet gevonden kan worden
*/ | block_comment | nl | /**
* This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations).
* It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation.
* The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP.
*/
package nl.bzk.migratiebrp.synchronisatie.dal.service;
import java.util.Collection;
import java.util.List;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.Leveringsautorisatie;
import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie;
import nl.bzk.migratiebrp.conversie.model.brp.autorisatie.BrpAutorisatie;
/**
* Interface class voor alle operaties die nodig zijn voor autorisaties voor de DAL.
*/
public interface BrpAutorisatieService {
/**
* Geef de lijst met alle actieve gba autorisaties.
* @return De lijst met alle actieve gba autorisaties.
*/
Collection<Leveringsautorisatie> geefAlleGbaAutorisaties();
/**
* Slaat een autorisatie (partij, toegang leveringsautorisatie, leveringsautorisaties, dienstbundels en diensten) op
* in de BRP database.
* @param brpAutorisatie De autorisatie in het BRP-migratiemodelformaat.
* @return de opgeslagen abonnementen
* @throws PartijNietGevondenException als de partij niet gevonden kan worden in de database
*/
List<ToegangLeveringsAutorisatie> persisteerAutorisatie(BrpAutorisatie brpAutorisatie) throws PartijNietGevondenException;
/**
* Vraag een autorisatie<SUF>*/
BrpAutorisatie bevraagAutorisatie(String partijCode, String naam, Integer ingangsDatumRegel);
}
|
203346_0 | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-migrate/src/main/java/nl/overheid/stelsel/gba/reva/migrate/gemeentecode/MigrateGemeenteCodeCommand.java | 1,785 | // Controleer de gemeentecodes. | line_comment | nl | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de<SUF>
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
|
203346_1 | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-migrate/src/main/java/nl/overheid/stelsel/gba/reva/migrate/gemeentecode/MigrateGemeenteCodeCommand.java | 1,785 | // Voer de migratie uit. | line_comment | nl | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de<SUF>
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
|
203346_4 | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-migrate/src/main/java/nl/overheid/stelsel/gba/reva/migrate/gemeentecode/MigrateGemeenteCodeCommand.java | 1,785 | // Lege gemeentecode is niet toegestaan. | line_comment | nl | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode<SUF>
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
|
203346_5 | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-migrate/src/main/java/nl/overheid/stelsel/gba/reva/migrate/gemeentecode/MigrateGemeenteCodeCommand.java | 1,785 | // De gemeente code opzoeken in tabel33 | line_comment | nl | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente<SUF>
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
|
203346_6 | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet nog steeds legitiem zijn.
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-migrate/src/main/java/nl/overheid/stelsel/gba/reva/migrate/gemeentecode/MigrateGemeenteCodeCommand.java | 1,785 | // Gemeentecode moet nog steeds legitiem zijn. | line_comment | nl | package nl.overheid.stelsel.gba.reva.migrate.gemeentecode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.overheid.stelsel.digimelding.astore.AnnotationStoreService;
import nl.overheid.stelsel.digimelding.astore.core.commands.NamedQueryAnnotationCommand;
import org.apache.clerezza.rdf.core.Resource;
import org.apache.clerezza.rdf.core.sparql.ResultSet;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.commands.basic.DefaultActionPreparator;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Command( scope = "migrate", name = "gemeentecode", description = "Wijzigt voor registraties de gemeente van inschrijving (loketgemeente) naar een nieuwe gemeentecode. Gebruik dubbel-quotes(\") indien de gemeentecode met een 0 begint." )
public class MigrateGemeenteCodeCommand extends OsgiCommandSupport {
// -------------------------------------------------------------------------
// Class attributes
// -------------------------------------------------------------------------
private static Logger logger = LoggerFactory.getLogger( MigrateGemeenteCodeCommand.class );
private static final String QUERY_ANALYSE = "migratieAnalyseOudeGemeenten";
private static final String QUERY_MIGRATE = "migratieWijzigLoketGemeente";
private static final String QUERY_GEMCODE = "migratieOphalenGemeenteCode";
// -------------------------------------------------------------------------
// Command Arguments
// -------------------------------------------------------------------------
@Argument( index = 0, name = "oudeGemeenteCode", description = "De oorspronkelijke gemeentecode", required = false, multiValued = false )
private String oudeGemeenteCode;
@Argument( index = 1, name = "nieuweGemeenteCode", description = "De nieuw te gebruiken gemeentecode", required = false, multiValued = false )
private String nieuweGemeenteCode;
// -------------------------------------------------------------------------
// Command Options
// -------------------------------------------------------------------------
@Option( name = "-a", aliases = { "--analyse" }, description = "Bestaande registratie analyseren, geen aanvullende argumenten nodig.", required = false, multiValued = false )
private boolean isAnalyse;
@Option( name = "-d", aliases = { "--dryrun" }, description = "Alleen controles uitvoeren, niet echt migreren.", required = false, multiValued = false )
private boolean isDryRun;
// -------------------------------------------------------------------------
// NamedQueryCommand overrides
// -------------------------------------------------------------------------
@Override
protected Object doExecute() throws Exception {
if( isAnalyse ) {
return doAnalyse();
} else {
// Controleer de gemeentecodes.
boolean beeindigd = true;
boolean doorgaan = checkGemeenteCode( oudeGemeenteCode, beeindigd, "oudeGemeenteCode" );
doorgaan &= checkGemeenteCode( nieuweGemeenteCode, !beeindigd, "nieuweGemeenteCode" );
if( !isDryRun && doorgaan ) {
// Voer de migratie uit.
migrateGemeenteCode( oudeGemeenteCode, nieuweGemeenteCode );
}
}
return "";
}
// -------------------------------------------------------------------------
// Private Methods
// -------------------------------------------------------------------------
private Object doAnalyse() throws Exception {
// Delegate query to the named query command
NamedQueryAnnotationCommand queryCommand = new NamedQueryAnnotationCommand();
queryCommand.setBundleContext( getBundleContext() );
// Construct a session for command delegation
DefaultActionPreparator preparator = new DefaultActionPreparator();
preparator.prepare( queryCommand, session, Arrays.<Object> asList( QUERY_ANALYSE ) );
// Execute delegate
return queryCommand.execute( session );
}
private boolean checkGemeenteCode( String gemeenteCode, Boolean beeindigd, String veld ) {
if( gemeenteCode == null || gemeenteCode.trim().length() == 0 ) {
// Lege gemeentecode is niet toegestaan.
output( "Lege gemeentecode voor '" + veld + "' is niet toegestaan!", true );
return false;
}
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "gemeenteCode", gemeenteCode );
// De gemeente code opzoeken in tabel33
String nieuweGemeenteCode = null;
try {
Object response = getAnnotationStoreService().namedQuery( QUERY_GEMCODE, arguments );
if( response instanceof ResultSet ) {
ResultSet resultSet = ResultSet.class.cast( response );
if( !resultSet.hasNext() ) {
// Niet gevonden
output( "Onbekende gemeentecode '" + gemeenteCode + "', migratie niet toegestaan!", true );
return false;
}
Resource nieuweCode = resultSet.next().get( "nieuweCode" );
if( nieuweCode != null ) {
nieuweGemeenteCode = nieuweCode.toString();
}
}
} catch( Exception ex ) {
output( "Fout bij het controleren van gemeentecode (voor details zie log)", false );
log.error( "Fout bij het controleren van gemeentecode!", ex );
return false;
}
if( !beeindigd && nieuweGemeenteCode != null ) {
// Gemeentecode moet<SUF>
output( "Gemeentecode '" + gemeenteCode + "' voor '" + veld + "' is reeds vervallen, gebruik " + nieuweGemeenteCode, true );
return false;
}
return true;
}
private void migrateGemeenteCode( String oudeGemeenteCode, String nieuweGemeenteCode ) {
// Query arguments
Map<String, String> arguments = new HashMap<>();
arguments.put( "oudeGemeenteCode", oudeGemeenteCode );
arguments.put( "nieuweGemeenteCode", nieuweGemeenteCode );
// Execute migration query
try {
getAnnotationStoreService().namedQuery( QUERY_MIGRATE, arguments );
output( "Gemeentecode migratie uitgevoerd: " + oudeGemeenteCode + " --> " + nieuweGemeenteCode, true );
} catch( Exception ex ) {
output( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, false );
log.warn( "Gemeentecode migratie niet gelukt voor: " + oudeGemeenteCode, ex );
}
}
private void output( String message, boolean log ) {
session.getConsole().println( message );
if( log ) {
logger.info( message );
}
}
// -------------------------------------------------------------------------
// Getters / Setters
// -------------------------------------------------------------------------
public AnnotationStoreService getAnnotationStoreService() {
BundleContext context = getBundleContext();
ServiceReference<AnnotationStoreService> serviceRef = context.getServiceReference( AnnotationStoreService.class );
if( serviceRef == null ) {
throw new ServiceException( "AnnotationStoreService service not available" );
}
return context.getService( serviceRef );
}
}
|
203358_0 | package nl.topicus.eduarte.krd.web.pages.intake;
import org.apache.wicket.MetaDataKey;
/**
* Key voor het opzoeken van IntakeWizardModel gegevens in de sessie. Deze worden
* opgeslagen in de metadata van de sessie om zo versie conflicten te voorkomen tussen
* pagina-overgangen (een gebruiker kan van voor naar achter gaan in de wizard).
*/
public class IntakeWizardMetaDataKey extends MetaDataKey<IntakeWizardMetaDataValues>
{
private static final long serialVersionUID = 1L;
public IntakeWizardMetaDataKey()
{
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/module-krd/src/main/java/nl/topicus/eduarte/krd/web/pages/intake/IntakeWizardMetaDataKey.java | 142 | /**
* Key voor het opzoeken van IntakeWizardModel gegevens in de sessie. Deze worden
* opgeslagen in de metadata van de sessie om zo versie conflicten te voorkomen tussen
* pagina-overgangen (een gebruiker kan van voor naar achter gaan in de wizard).
*/ | block_comment | nl | package nl.topicus.eduarte.krd.web.pages.intake;
import org.apache.wicket.MetaDataKey;
/**
* Key voor het<SUF>*/
public class IntakeWizardMetaDataKey extends MetaDataKey<IntakeWizardMetaDataValues>
{
private static final long serialVersionUID = 1L;
public IntakeWizardMetaDataKey()
{
}
}
|
203359_0 | package nl.b3p.brmo.service.util;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import nl.b3p.brmo.loader.util.BrmoException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ConfigUtil implements Servlet {
private static final Log log = LogFactory.getLog(ConfigUtil.class);
private static final String JNDI_NAME = "java:comp/env";
private static final String JDBC_NAME_STAGING = "jdbc/brmo/staging";
private static final String JDBC_NAME_RSGB = "jdbc/brmo/rsgb";
private static final String JDBC_NAME_RSGBBRK = "jdbc/brmo/rsgbbrk";
private static final String JDBC_NAME_RSGB_BAG = "jdbc/brmo/rsgbbag";
private static final String JDBC_NAME_RSGB_BGT = "jdbc/brmo/rsgbbgt";
private static final String JDBC_NAME_RSGB_TOPNL = "jdbc/brmo/rsgbtopnl";
private static DataSource datasourceStaging = null;
private static DataSource datasourceRsgb = null;
private static DataSource datasourceRsgbBrk = null;
private static DataSource datasourceRsgbBag = null;
private static DataSource datasourceRsgbBgt = null;
private static DataSource datasourceTopNL = null;
public static Long MAX_UPLOAD_SIZE;
public static String TEMP_FOLDER;
@Override
public void init(ServletConfig config) throws ServletException {
String tempSize = config.getInitParameter("max_upload_size");
if (tempSize != null && !tempSize.isEmpty()) {
MAX_UPLOAD_SIZE = Long.parseLong(tempSize) * 1024 * 1024;
} else {
MAX_UPLOAD_SIZE = 10000L * 1024 * 1024;
}
String tempFolder = config.getInitParameter("temp_folder");
if (tempFolder != null && !tempFolder.isEmpty()) {
TEMP_FOLDER = tempFolder;
} else {
TEMP_FOLDER = System.getProperty("java.io.tmpdir");
}
}
public static DataSource getDataSourceStaging() throws BrmoException {
try {
if (datasourceStaging == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceStaging = (DataSource) xmlContext.lookup(JDBC_NAME_STAGING);
}
} catch (Exception ex) {
log.error("Fout verbinden naar staging db. ", ex);
throw new BrmoException(ex);
}
return datasourceStaging;
}
public static DataSource getDataSourceRsgb() throws BrmoException {
try {
if (datasourceRsgb == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgb = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB);
}
} catch (Exception ex) {
log.error("Fout verbinden naar rsgb db. ", ex);
throw new BrmoException(ex);
}
return datasourceRsgb;
}
public static DataSource getDataSourceRsgbBrk() throws BrmoException {
try {
if (datasourceRsgbBrk == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBrk = (DataSource) xmlContext.lookup(JDBC_NAME_RSGBBRK);
}
} catch (Exception ex) {
log.error("Fout verbinden naar rsgb db. ", ex);
throw new BrmoException(ex);
}
return datasourceRsgbBrk;
}
public static DataSource getDataSourceRsgbBag() throws BrmoException {
return getDataSourceRsgbBag(true);
}
public static DataSource getDataSourceRsgbBag(boolean logErrors) throws BrmoException {
try {
if (datasourceRsgbBag == null) {
InitialContext ic = new InitialContext();
Context context = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBag = (DataSource) context.lookup(JDBC_NAME_RSGB_BAG);
}
} catch (Exception ex) {
if (logErrors) {
log.error("Fout verbinden naar 'rsgbbag' schema.", ex);
}
throw new BrmoException("Fout verbinden naar 'rsgbbag' schema: ", ex);
}
return datasourceRsgbBag;
}
public static DataSource getDataSourceRsgbBgt() throws BrmoException {
try {
if (datasourceRsgbBgt == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBgt = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_BGT);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'rsgbbgt' schema.", ex);
throw new BrmoException("Fout verbinden naar 'rsgbbgt' schema.", ex);
}
return datasourceRsgbBgt;
}
/**
* @return de gevraagde datasource
* @throws BrmoException als opzoeken van de datasource in de jndi context mislukt
*/
public static DataSource getDataSourceTopNL() throws BrmoException {
try {
if (datasourceTopNL == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceTopNL = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_TOPNL);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'topnl' schema.", ex);
throw new BrmoException("Fout verbinden naar 'topnl' schema.", ex);
}
return datasourceTopNL;
}
@Override
public ServletConfig getServletConfig() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void service(ServletRequest sr, ServletResponse sr1) throws ServletException, IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getServletInfo() {
return "Servlet voor configuratie parameters in web.xml";
}
@Override
public void destroy() {
// nothing
}
}
| B3Partners/brmo | brmo-init-util/src/main/java/nl/b3p/brmo/service/util/ConfigUtil.java | 1,677 | /**
* @return de gevraagde datasource
* @throws BrmoException als opzoeken van de datasource in de jndi context mislukt
*/ | block_comment | nl | package nl.b3p.brmo.service.util;
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import nl.b3p.brmo.loader.util.BrmoException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ConfigUtil implements Servlet {
private static final Log log = LogFactory.getLog(ConfigUtil.class);
private static final String JNDI_NAME = "java:comp/env";
private static final String JDBC_NAME_STAGING = "jdbc/brmo/staging";
private static final String JDBC_NAME_RSGB = "jdbc/brmo/rsgb";
private static final String JDBC_NAME_RSGBBRK = "jdbc/brmo/rsgbbrk";
private static final String JDBC_NAME_RSGB_BAG = "jdbc/brmo/rsgbbag";
private static final String JDBC_NAME_RSGB_BGT = "jdbc/brmo/rsgbbgt";
private static final String JDBC_NAME_RSGB_TOPNL = "jdbc/brmo/rsgbtopnl";
private static DataSource datasourceStaging = null;
private static DataSource datasourceRsgb = null;
private static DataSource datasourceRsgbBrk = null;
private static DataSource datasourceRsgbBag = null;
private static DataSource datasourceRsgbBgt = null;
private static DataSource datasourceTopNL = null;
public static Long MAX_UPLOAD_SIZE;
public static String TEMP_FOLDER;
@Override
public void init(ServletConfig config) throws ServletException {
String tempSize = config.getInitParameter("max_upload_size");
if (tempSize != null && !tempSize.isEmpty()) {
MAX_UPLOAD_SIZE = Long.parseLong(tempSize) * 1024 * 1024;
} else {
MAX_UPLOAD_SIZE = 10000L * 1024 * 1024;
}
String tempFolder = config.getInitParameter("temp_folder");
if (tempFolder != null && !tempFolder.isEmpty()) {
TEMP_FOLDER = tempFolder;
} else {
TEMP_FOLDER = System.getProperty("java.io.tmpdir");
}
}
public static DataSource getDataSourceStaging() throws BrmoException {
try {
if (datasourceStaging == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceStaging = (DataSource) xmlContext.lookup(JDBC_NAME_STAGING);
}
} catch (Exception ex) {
log.error("Fout verbinden naar staging db. ", ex);
throw new BrmoException(ex);
}
return datasourceStaging;
}
public static DataSource getDataSourceRsgb() throws BrmoException {
try {
if (datasourceRsgb == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgb = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB);
}
} catch (Exception ex) {
log.error("Fout verbinden naar rsgb db. ", ex);
throw new BrmoException(ex);
}
return datasourceRsgb;
}
public static DataSource getDataSourceRsgbBrk() throws BrmoException {
try {
if (datasourceRsgbBrk == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBrk = (DataSource) xmlContext.lookup(JDBC_NAME_RSGBBRK);
}
} catch (Exception ex) {
log.error("Fout verbinden naar rsgb db. ", ex);
throw new BrmoException(ex);
}
return datasourceRsgbBrk;
}
public static DataSource getDataSourceRsgbBag() throws BrmoException {
return getDataSourceRsgbBag(true);
}
public static DataSource getDataSourceRsgbBag(boolean logErrors) throws BrmoException {
try {
if (datasourceRsgbBag == null) {
InitialContext ic = new InitialContext();
Context context = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBag = (DataSource) context.lookup(JDBC_NAME_RSGB_BAG);
}
} catch (Exception ex) {
if (logErrors) {
log.error("Fout verbinden naar 'rsgbbag' schema.", ex);
}
throw new BrmoException("Fout verbinden naar 'rsgbbag' schema: ", ex);
}
return datasourceRsgbBag;
}
public static DataSource getDataSourceRsgbBgt() throws BrmoException {
try {
if (datasourceRsgbBgt == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceRsgbBgt = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_BGT);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'rsgbbgt' schema.", ex);
throw new BrmoException("Fout verbinden naar 'rsgbbgt' schema.", ex);
}
return datasourceRsgbBgt;
}
/**
* @return de gevraagde<SUF>*/
public static DataSource getDataSourceTopNL() throws BrmoException {
try {
if (datasourceTopNL == null) {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup(JNDI_NAME);
datasourceTopNL = (DataSource) xmlContext.lookup(JDBC_NAME_RSGB_TOPNL);
}
} catch (Exception ex) {
log.error("Fout verbinden naar 'topnl' schema.", ex);
throw new BrmoException("Fout verbinden naar 'topnl' schema.", ex);
}
return datasourceTopNL;
}
@Override
public ServletConfig getServletConfig() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void service(ServletRequest sr, ServletResponse sr1) throws ServletException, IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getServletInfo() {
return "Servlet voor configuratie parameters in web.xml";
}
@Override
public void destroy() {
// nothing
}
}
|
203363_3 | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
| hu-team/atd-garagesysteem | src/nl/atd/dao/ReserveringDAO.java | 1,958 | /**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/ | block_comment | nl | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op<SUF>*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
|
203363_4 | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
| hu-team/atd-garagesysteem | src/nl/atd/dao/ReserveringDAO.java | 1,958 | /**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/ | block_comment | nl | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van<SUF>*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
|
203363_5 | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
| hu-team/atd-garagesysteem | src/nl/atd/dao/ReserveringDAO.java | 1,958 | /**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/ | block_comment | nl | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op<SUF>*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
|
203363_7 | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
| hu-team/atd-garagesysteem | src/nl/atd/dao/ReserveringDAO.java | 1,958 | /**
* Get reserveringid, zoeken van reserveringid op unieke parameters.
* @param van
* @param parkeerplek
* @return ReserveringID of 0
*/ | block_comment | nl | package nl.atd.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import nl.atd.model.Klant;
import nl.atd.model.Parkeerplek;
import nl.atd.model.Reservering;
import nl.atd.service.ServiceProvider;
public class ReserveringDAO extends BaseDAO {
/**
* Get reserveringen, prepared statement
* @param ps Prepared statement
* @return array met reserveringen
*/
private ArrayList<Reservering> getReserveringen(PreparedStatement ps) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
ResultSet set = ps.executeQuery();
while(set.next()) {
Reservering reservering = new Reservering(ServiceProvider.getKlantService().getKlantByGebruikersnaam(set.getString("klant")), ServiceProvider.getAutoService().getAuto(set.getInt("auto")));
Calendar van = Calendar.getInstance();
Calendar tot = Calendar.getInstance();
van.setTimeInMillis(set.getTimestamp("van").getTime());
tot.setTimeInMillis(set.getTimestamp("tot").getTime());
reservering.setVan(van);
reservering.setTot(tot);
reservering.setParkeerplek(ServiceProvider.getParkeerplekService().getParkeerplekOpId(set.getInt("parkeerplek")));
reserveringen.add(reservering);
}
ps.getConnection().close();
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen met query (object mapping)
* @param query
* @return array
*/
private ArrayList<Reservering> getReserveringen(String query) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement st = this.getPreparedStatement(query);
reserveringen = this.getReserveringen(st);
st.getConnection().close();
st.close();
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get alle reserveringen
* @return reserveringen in array
*/
public ArrayList<Reservering> getAlleReserveringen() {
return this.getReserveringen("SELECT * FROM reservering");
}
/**
* Get reserveringen op parkeerplek
* @param parkeerplekid
* @return lijst met reserveringen op plek
*/
public ArrayList<Reservering> getReserveringenOpPlek(int parkeerplekid) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE parkeerplek = ?");
ps.setInt(1, parkeerplekid);
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {}
return reserveringen;
}
/**
* Get reserveringen van klant
* @param klant
* @return lijst met reserveringen van klant
*/
public ArrayList<Reservering> getReserveringenVanKlant(Klant klant) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE klant LIKE ?");
ps.setString(1, klant.getGebruikersnaam());
reserveringen = this.getReserveringen(ps);
}catch(Exception e) {e.printStackTrace();}
return reserveringen;
}
/**
* Get reserveringen op maand en jaar
* @param datum
* @return lijst met reserveringen
*/
public ArrayList<Reservering> getReserveringenOpMaand(Calendar datum){
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE MONTH(van)=? AND YEAR(van)=?;");
ps.setInt(1, datum.get(Calendar.MONTH) + 1);
ps.setInt(2, datum.get(Calendar.YEAR));
reserveringen = this.getReserveringen(ps);
}catch(Exception e){
e.printStackTrace();
}
return reserveringen;
}
/**
* Get reserveringen
* @param id
* @return reservering of null
*/
public Reservering getReserveringOpId(int id) {
ArrayList<Reservering> reserveringen = new ArrayList<Reservering>();
try{
PreparedStatement ps = this.getPreparedStatement("SELECT * FROM reservering WHERE reserveringid = ?");
ps.setInt(1, id);
reserveringen = this.getReserveringen(ps);
ps.getConnection().close();
ps.close();
}catch(Exception e){}
return reserveringen.size() > 0 ? reserveringen.get(0) : null;
}
/**
* Get reserveringid, zoeken<SUF>*/
public int getReserveringId(Calendar van, Parkeerplek plek){
return this.getReserveringIdOpQuery("SELECT reserveringid FROM reservering WHERE "
+ "van >= FROM_UNIXTIME(" + (van.getTimeInMillis() / 1000) + ") "
+ "AND "
+ "parkeerplek = " + ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(plek) + ";");
}
/**
* ReserveringID opzoeken met query
* @param query
* @return id of 0
*/
private int getReserveringIdOpQuery(String query) {
int nr = 0;
try {
Connection connection = this.getConnection();
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(query);
while (set.next()) {
nr = set.getInt("reserveringid");
}
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return nr;
}
/**
* Add reservering
* @param reservering
* @return gelukt
*/
public boolean addReservering(Reservering reservering){
try{
PreparedStatement ps = this.getPreparedStatement("INSERT INTO reservering (van, tot, auto, klant, parkeerplek) VALUES(?, ?, ?, ?, ?)");
ps.setTimestamp(1, new Timestamp(reservering.getVan().getTimeInMillis()));
ps.setTimestamp(2, new Timestamp(reservering.getTot().getTimeInMillis()));
ps.setInt(3, ServiceProvider.getAutoService().getAutoIdOpKenteken(reservering.getAuto().getKenteken()));
ps.setString(4, reservering.getKlant().getGebruikersnaam());
ps.setInt(5, ServiceProvider.getParkeerplekService().getParkeerplekIdOpPlek(reservering.getParkeerplek()));
ps.execute();
ps.getConnection().close();
ps.close();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
}
|
203435_0 | package com.example.pattern.model;
public class PersonenAuto extends Product {
private double gewicht;
private double motorinhoud;
public PersonenAuto(String merk, double gewicht, double motorinhoud) {
super(merk);
this.gewicht = gewicht;
this.motorinhoud = motorinhoud;
}
public double getGewicht() {
return gewicht;
}
public double getMotorinhoud() {
return motorinhoud;
}
@Override
public double getHuurPrijs() {
return 50.0; // Huurprijs is 50 euro per dag
}
@Override
public double getVerzekeringPrijs() {
return 0.01 * motorinhoud; // Verzekering is 0,01 euro per cc motorinhoud per dag
}
} | Ozancann01/pattern | src/main/java/com/example/pattern/model/PersonenAuto.java | 203 | // Huurprijs is 50 euro per dag | line_comment | nl | package com.example.pattern.model;
public class PersonenAuto extends Product {
private double gewicht;
private double motorinhoud;
public PersonenAuto(String merk, double gewicht, double motorinhoud) {
super(merk);
this.gewicht = gewicht;
this.motorinhoud = motorinhoud;
}
public double getGewicht() {
return gewicht;
}
public double getMotorinhoud() {
return motorinhoud;
}
@Override
public double getHuurPrijs() {
return 50.0; // Huurprijs is<SUF>
}
@Override
public double getVerzekeringPrijs() {
return 0.01 * motorinhoud; // Verzekering is 0,01 euro per cc motorinhoud per dag
}
} |
203435_1 | package com.example.pattern.model;
public class PersonenAuto extends Product {
private double gewicht;
private double motorinhoud;
public PersonenAuto(String merk, double gewicht, double motorinhoud) {
super(merk);
this.gewicht = gewicht;
this.motorinhoud = motorinhoud;
}
public double getGewicht() {
return gewicht;
}
public double getMotorinhoud() {
return motorinhoud;
}
@Override
public double getHuurPrijs() {
return 50.0; // Huurprijs is 50 euro per dag
}
@Override
public double getVerzekeringPrijs() {
return 0.01 * motorinhoud; // Verzekering is 0,01 euro per cc motorinhoud per dag
}
} | Ozancann01/pattern | src/main/java/com/example/pattern/model/PersonenAuto.java | 203 | // Verzekering is 0,01 euro per cc motorinhoud per dag | line_comment | nl | package com.example.pattern.model;
public class PersonenAuto extends Product {
private double gewicht;
private double motorinhoud;
public PersonenAuto(String merk, double gewicht, double motorinhoud) {
super(merk);
this.gewicht = gewicht;
this.motorinhoud = motorinhoud;
}
public double getGewicht() {
return gewicht;
}
public double getMotorinhoud() {
return motorinhoud;
}
@Override
public double getHuurPrijs() {
return 50.0; // Huurprijs is 50 euro per dag
}
@Override
public double getVerzekeringPrijs() {
return 0.01 * motorinhoud; // Verzekering is<SUF>
}
} |
203470_69 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Evaluation {
public static double calculateTripError(List<Trajectory> original, List<Trajectory>
synthetic, int gridCellCount) {
// find data boundaries so that an appropriate grid can be laid
List<Double> boundaries = Main.getDataBoundaries(original);
double minX = boundaries.get(0);
double maxX = boundaries.get(1);
double minY = boundaries.get(2);
double maxY = boundaries.get(3);
// lay grid on original and synthetic databases
Grid ug = new Grid(gridCellCount, minX, maxX, minY, maxY);
List<GridTrajectory> origDBgrid = Main.convertTrajToGridTraj(original, ug, true);
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(synthetic, ug, true);
// get trip distributions (a high epsilon budget of 10000 yields noiseless results)
TripDistribution origTD = new TripDistribution(origDBgrid, ug, 10000.0);
TripDistribution synTD = new TripDistribution(synDBgrid, ug, 10000.0);
// calculate JSD between the two trip distributions
List<Double> origDist = origTD.getTripProbsAsList();
List<Double> synDist = synTD.getTripProbsAsList();
return calcJSD(origDist, synDist);
}
public static double calculateDiameterError(List<Trajectory> original, List<Trajectory>
synthetic, int numberOfBuckets) {
// get diameters of original database
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
List<Double> originalDiameters = new ArrayList<Double>();
for (Trajectory t : original) {
double dia = t.getDiameter();
originalDiameters.add(dia);
if (dia < min)
min = dia;
if (dia > max)
max = dia;
}
// get diameters of synthetic database
List<Double> syntheticDiameters = new ArrayList<Double>();
for (Trajectory t : synthetic) {
double dia = t.getDiameter();
syntheticDiameters.add(dia);
}
// bucketize the diameters to find diameter counts in each bucket
double bucketSize = (max-min)/numberOfBuckets;
List<Integer> origDiaCount = new ArrayList<Integer>();
List<Integer> synDiaCount = new ArrayList<Integer>();
for (int i = 0; i < numberOfBuckets; i++) {
double currStart = i * bucketSize;
double currFinish = (i+1) * bucketSize;
int cnt = 0;
//System.out.print("[" + currStart + "," + currFinish + "] ");
for (Double d : originalDiameters) {
if (d >= currStart && d < currFinish)
cnt++;
}
origDiaCount.add(cnt);
cnt = 0;
for (Double d : syntheticDiameters) {
if (d >= currStart && d < currFinish)
cnt++;
}
synDiaCount.add(cnt);
}
// find the diameter distribution of original and synthetic database
List<Double> origDiaProbs = new ArrayList<Double>();
List<Double> synDiaProbs = new ArrayList<Double>();
for (int i = 0; i < numberOfBuckets; i++) {
origDiaProbs.add(((double)origDiaCount.get(i)/((double)originalDiameters.size())));
synDiaProbs.add(((double)synDiaCount.get(i)/((double)syntheticDiameters.size())));
}
// calculate and return JSD
return calcJSD(origDiaProbs, synDiaProbs);
}
public static double calculateTravelDistanceError(List<Trajectory> original,
List<Trajectory> synthetic, int numberOfBuckets) {
// get travel lengths of original database
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
List<Double> originalLengths = new ArrayList<Double>();
for (Trajectory t : original) {
double dia = t.getDistanceTravelled();
originalLengths.add(dia);
if (dia < min)
min = dia;
if (dia > max)
max = dia;
}
// get travel lengths of synthetic database
List<Double> syntheticLengths = new ArrayList<Double>();
for (Trajectory t : synthetic) {
double dia = t.getDistanceTravelled();
syntheticLengths.add(dia);
}
// bucketize the lengths to find counts in each bucket
double bucketSize = (max-min)/numberOfBuckets;
List<Integer> origCount = new ArrayList<Integer>();
List<Integer> synCount = new ArrayList<Integer>();
for (int i = 0; i < numberOfBuckets; i++) {
double currStart = i * bucketSize;
double currFinish = (i+1) * bucketSize;
int cnt = 0;
//System.out.print("[" + currStart + "," + currFinish + "] ");
for (Double d : originalLengths) {
if (d >= currStart && d < currFinish)
cnt++;
}
origCount.add(cnt);
cnt = 0;
for (Double d : syntheticLengths) {
if (d >= currStart && d < currFinish)
cnt++;
}
synCount.add(cnt);
}
// find the distributions
List<Double> origProbs = new ArrayList<Double>();
List<Double> synProbs = new ArrayList<Double>();
for (int i = 0; i < numberOfBuckets; i++) {
origProbs.add(((double)origCount.get(i)/((double)originalLengths.size())));
synProbs.add(((double)synCount.get(i)/((double)syntheticLengths.size())));
}
// calculate and return JSD
return calcJSD(origProbs, synProbs);
}
public static Query[] generateQueries (List<Trajectory> db, int queryCount, String fn) {
List<Double> boundaries = Main.getDataBoundaries(db);
double dataMinX = boundaries.get(0);
double dataMaxX = boundaries.get(1);
double dataMinY = boundaries.get(2);
double dataMaxY = boundaries.get(3);
Query[] tbr = new Query[queryCount];
for (int i = 0; i < queryCount; i++) {
tbr[i] = new Query(dataMinX, dataMaxX, dataMinY, dataMaxY, fn);
}
return tbr;
}
public static double calculateQueryError(List<Trajectory> originalDB,
List<Trajectory> syntheticDB, Query[] queries, double sanityBound) {
// evaluate queries on the two databases
int[] actualAnswers = new int[queries.length];
int[] syntheticAnswers = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
Query q = queries[i];
actualAnswers[i] = q.evaluateQueryOnDatabase(originalDB);
syntheticAnswers[i] = q.evaluateQueryOnDatabase(syntheticDB);
}
//System.out.println(Arrays.toString(actualAnswers));
//System.out.println(Arrays.toString(syntheticAnswers));
// measure relative errors using the sanity bound
double[] error = new double[queries.length];
for (int i = 0; i < queries.length; i++) {
double numerator = Math.abs(syntheticAnswers[i]-actualAnswers[i]);
double denominator = actualAnswers[i];
if (originalDB.size() * sanityBound > denominator)
denominator = originalDB.size() * sanityBound;
error[i] = ((double)numerator)/((double)denominator);
}
// measure average relative error
double sumErr = 0.0;
for (int i = 0; i < error.length; i++) {
sumErr = sumErr + error[i];
}
return sumErr/((double)error.length);
}
public static Map<Pattern, Integer> minePatterns (List<GridTrajectory> db,
int minSize, int maxSize) {
Map<Pattern, Integer> tbr = new HashMap<Pattern, Integer>();
for (int currentSize = minSize; currentSize <= maxSize; currentSize++) {
//System.out.println("Currently mining patterns of size: " + currentSize);
for (GridTrajectory t : db) {
// get sub-lists of length currentSize from t. check if we hit t.size
for (int i = 0; i <= t.getCells().size()-currentSize; i++) {
Pattern p = new Pattern(t.getCells().subList(i, i+currentSize));
if (tbr.containsKey(p)) {
tbr.put(p, tbr.get(p)+1);
} else {
tbr.put(p, 1);
}
}
}
}
return tbr;
}
// from: http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return ( o2.getValue() ).compareTo( o1.getValue() ); // reverse order
}
} );
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
// same function as above, sorts in reverse order: small to large (ascending)
public static <K, V extends Comparable<? super V>> Map<K, V> sortReverseOrder
( Map<K, V> map ) {
List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return ( o1.getValue() ).compareTo( o2.getValue() ); // reverse order
}
} );
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
private static boolean checkMapSorting(Map<Pattern, Integer> candidate) {
Integer previous = null;
for(Map.Entry<Pattern, Integer> entry : candidate.entrySet()) {
if (entry.getValue() == null) {
System.out.println("null obtained in minePatterns function?!!?");
return false;
}
if (previous != null) {
if (entry.getValue() > previous) {
System.out.println("sorted map is not sorted !!!");
return false;
}
}
previous = entry.getValue();
}
return true;
}
public static double patternMiningF1Error (Map<Pattern, Integer> originalPatterns,
int topK, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns and synthetic patterns maps
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
Map<Pattern, Integer> sortedSynPatterns = Evaluation.sortByValue(synPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
if (!Evaluation.checkMapSorting(sortedSynPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original and synthetic
List<Pattern> origTopK = new ArrayList<Pattern>();
List<Pattern> synTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < topK) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
for (Map.Entry<Pattern, Integer> entry : sortedSynPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (synTopK.size() < topK) {
synTopK.add(entry.getKey());
}
else {
break; // out of the for loop
}
}
return calcF1(origTopK, synTopK);
}
public static double patternMiningJaccardSim (Map<Pattern, Integer> originalPatterns,
int topK, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns and synthetic patterns maps
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
Map<Pattern, Integer> sortedSynPatterns = Evaluation.sortByValue(synPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
if (!Evaluation.checkMapSorting(sortedSynPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original and synthetic
List<Pattern> origTopK = new ArrayList<Pattern>();
List<Pattern> synTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < topK) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
for (Map.Entry<Pattern, Integer> entry : sortedSynPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (synTopK.size() < topK) {
synTopK.add(entry.getKey());
}
else {
break; // out of the for loop
}
}
return JaccardSimilarity(origTopK, synTopK);
}
public static double patternMiningSupport (Map<Pattern, Integer> originalPatterns,
int topK, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns in descending order of support
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original
List<Pattern> origTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < topK) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
double sumErr = 0.0;
for (int i = 0; i < origTopK.size(); i++) {
Pattern freqPat = origTopK.get(i);
int origSupport = originalPatterns.get(freqPat);
int synSupport = 0;
if (synPatterns.containsKey(freqPat))
synSupport = synPatterns.get(freqPat);
//System.out.println("origSup: " + origSupport + ", synSup: " + synSupport);
sumErr = sumErr + Math.abs(origSupport-synSupport)/((double)origSupport);
}
return sumErr/((double)origTopK.size());
}
// uses Kendall's tau coefficient for ranking correlation
public static double patternMiningRanking (Map<Pattern, Integer> originalPatterns,
int rankingN, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns in descending order of support
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original
List<Pattern> origTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < rankingN) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
// calculate Kendall's tau for topK patterns
int concordantPairs = 0;
int reversedPairs = 0;
for (int i = 0; i < origTopK.size(); i++) {
for (int j = i+1; j < origTopK.size(); j++) {
Pattern moreFreq = origTopK.get(i);
Pattern lessFreq = origTopK.get(j);
if (!synPatterns.containsKey(moreFreq) && !synPatterns.containsKey(lessFreq)) {
// tie, do nothing
} else if (synPatterns.containsKey(moreFreq) && !synPatterns.containsKey(lessFreq)) {
concordantPairs++;
} else if (!synPatterns.containsKey(moreFreq) && synPatterns.containsKey(lessFreq)) {
reversedPairs++;
} else { // contains both
if (synPatterns.get(moreFreq) > synPatterns.get(lessFreq))
concordantPairs++;
else if (synPatterns.get(lessFreq) > synPatterns.get(moreFreq))
reversedPairs++;
}
}
}
int n = origTopK.size();
double denom = n*(n-1)/((double)2.0);
//System.out.println("Concordant: " + concordantPairs + ", reversed: " + reversedPairs);
return ((double)concordantPairs-reversedPairs)/((double)denom);
}
// Measure the error in location coverage thru Kendall's tau for rank correlation
public static double locationCoverageKendallTau(List<Trajectory> original, List<Trajectory>
synthetic, int gridCell) {
// find data boundaries so that an appropriate grid can be laid
List<Double> boundaries = Main.getDataBoundaries(original);
double minX = boundaries.get(0);
double maxX = boundaries.get(1);
double minY = boundaries.get(2);
double maxY = boundaries.get(3);
// lay grid on original and synthetic databases
Grid ug = new Grid(gridCell, minX, maxX, minY, maxY);
List<GridTrajectory> origDBgrid = Main.convertTrajToGridTraj(original, ug, true);
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(synthetic, ug, true);
// how many trajectories visited each cell?
List<Cell> cells = ug.getCells();
int[] actualCounts = new int[cells.size()];
int[] syntheticCounts = new int[cells.size()];
for (int i = 0; i < cells.size(); i++) {
actualCounts[i] = 0;
syntheticCounts[i] = 0;
Cell c = cells.get(i);
for (GridTrajectory t : origDBgrid) {
if (t.passesThrough(c))
actualCounts[i] = actualCounts[i]+1;
}
for (GridTrajectory t : synDBgrid) {
if (t.passesThrough(c))
syntheticCounts[i] = syntheticCounts[i]+1;
}
}
// measure kendall tau with actualCounts and syntheticCounts
int concordantPairs = 0;
int reversedPairs = 0;
for (int i = 0; i < actualCounts.length; i++) {
for (int j = i+1; j < actualCounts.length; j++) {
if (actualCounts[i] > actualCounts[j]) {
if (syntheticCounts[i] > syntheticCounts[j])
concordantPairs++;
else
reversedPairs++;
}
if (actualCounts[i] < actualCounts[j]) {
if (syntheticCounts[i] > syntheticCounts[j])
reversedPairs++;
else
concordantPairs++;
}
}
}
int n = cells.size();
double denom = n*(n-1)/((double)2.0);
//System.out.println("Concordant: " + concordantPairs + ", reversed: " + reversedPairs);
return ((double)concordantPairs-reversedPairs)/((double)denom);
}
public static double calcJSD(List<Double> origProb, List<Double> synProb) {
List<Double> avgProb = new ArrayList<Double>();
for (int i = 0; i < origProb.size(); i++) {
avgProb.add((origProb.get(i)+synProb.get(i))/2.0);
}
//System.out.println(origProb);
//System.out.println(avgProb);
//System.out.println(synProb);
return 0.5*calcKL(origProb,avgProb) + 0.5*calcKL(synProb,avgProb);
}
private static double calcKL(List<Double> prob1, List<Double> prob2) {
double KL = 0.0;
for (int i = 0; i < prob1.size(); i++) {
double Qofi = prob2.get(i);
double Pofi = prob1.get(i);
if (Pofi != 0.0)
KL = KL + Math.log(Pofi/Qofi)*Pofi;
}
return KL;
}
private static double calcF1(List<Pattern> original, List<Pattern> synthetic) {
double noCorrectPositives = 0.0;
for (Pattern p : synthetic) {
for (Pattern p2 : original) {
if (p.isEqual(p2)) {
noCorrectPositives++;
break;
}
}
}
//System.out.println("# of correct positives: " + noCorrectPositives);
double precision = noCorrectPositives / synthetic.size();
double recall = noCorrectPositives / original.size();
return (2*precision*recall)/(precision+recall);
}
private static double JaccardSimilarity(List<Pattern> original, List<Pattern> synthetic) {
List<Pattern> intersection = new ArrayList<Pattern>();
for (Pattern p : original) {
for (int i = 0; i < synthetic.size(); i++) {
if (synthetic.get(i).isEqual(p)) {
intersection.add(p);
break;
}
}
}
List<Pattern> union = new ArrayList<Pattern>();
for (Pattern p : original) {
union.add(p);
}
for (Pattern p : synthetic) {
if (!intersection.contains(p))
union.add(p);
}
return ((double)intersection.size())/((double)union.size());
}
public static double calculateDTW (List<Point> list1, List<Point> list2) {
double[][] dtwMatrix = new double[list1.size()+1][list2.size()+1];
// fill first row and column
for (int i = 1; i <= list1.size(); i++) {
dtwMatrix[i][0] = Double.POSITIVE_INFINITY;
}
for (int i = 1; i < list2.size(); i++) {
dtwMatrix[0][i] = Double.POSITIVE_INFINITY;
}
dtwMatrix[0][0] = 0;
// do O(mn) computations
for (int i = 1; i <= list1.size(); i++) {
for (int j = 1; j <= list2.size(); j++) {
Point p1 = list1.get(i-1);
Point p2 = list2.get(j-1);
double euclidDist = p1.euclideanDistTo(p2);
// find min
double min = Double.POSITIVE_INFINITY;
if (dtwMatrix[i-1][j] < min)
min = dtwMatrix[i-1][j];
if (dtwMatrix[i][j-1] < min)
min = dtwMatrix[i][j-1];
if (dtwMatrix[i-1][j-1] < min)
min = dtwMatrix[i-1][j-1];
// enter into dtw matrix
dtwMatrix[i][j] = euclidDist + min;
}
}
// end
return dtwMatrix[list1.size()][list2.size()];
}
}
| git-disl/AdaTrace | src/Evaluation.java | 7,003 | // enter into dtw matrix
| line_comment | nl | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Evaluation {
public static double calculateTripError(List<Trajectory> original, List<Trajectory>
synthetic, int gridCellCount) {
// find data boundaries so that an appropriate grid can be laid
List<Double> boundaries = Main.getDataBoundaries(original);
double minX = boundaries.get(0);
double maxX = boundaries.get(1);
double minY = boundaries.get(2);
double maxY = boundaries.get(3);
// lay grid on original and synthetic databases
Grid ug = new Grid(gridCellCount, minX, maxX, minY, maxY);
List<GridTrajectory> origDBgrid = Main.convertTrajToGridTraj(original, ug, true);
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(synthetic, ug, true);
// get trip distributions (a high epsilon budget of 10000 yields noiseless results)
TripDistribution origTD = new TripDistribution(origDBgrid, ug, 10000.0);
TripDistribution synTD = new TripDistribution(synDBgrid, ug, 10000.0);
// calculate JSD between the two trip distributions
List<Double> origDist = origTD.getTripProbsAsList();
List<Double> synDist = synTD.getTripProbsAsList();
return calcJSD(origDist, synDist);
}
public static double calculateDiameterError(List<Trajectory> original, List<Trajectory>
synthetic, int numberOfBuckets) {
// get diameters of original database
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
List<Double> originalDiameters = new ArrayList<Double>();
for (Trajectory t : original) {
double dia = t.getDiameter();
originalDiameters.add(dia);
if (dia < min)
min = dia;
if (dia > max)
max = dia;
}
// get diameters of synthetic database
List<Double> syntheticDiameters = new ArrayList<Double>();
for (Trajectory t : synthetic) {
double dia = t.getDiameter();
syntheticDiameters.add(dia);
}
// bucketize the diameters to find diameter counts in each bucket
double bucketSize = (max-min)/numberOfBuckets;
List<Integer> origDiaCount = new ArrayList<Integer>();
List<Integer> synDiaCount = new ArrayList<Integer>();
for (int i = 0; i < numberOfBuckets; i++) {
double currStart = i * bucketSize;
double currFinish = (i+1) * bucketSize;
int cnt = 0;
//System.out.print("[" + currStart + "," + currFinish + "] ");
for (Double d : originalDiameters) {
if (d >= currStart && d < currFinish)
cnt++;
}
origDiaCount.add(cnt);
cnt = 0;
for (Double d : syntheticDiameters) {
if (d >= currStart && d < currFinish)
cnt++;
}
synDiaCount.add(cnt);
}
// find the diameter distribution of original and synthetic database
List<Double> origDiaProbs = new ArrayList<Double>();
List<Double> synDiaProbs = new ArrayList<Double>();
for (int i = 0; i < numberOfBuckets; i++) {
origDiaProbs.add(((double)origDiaCount.get(i)/((double)originalDiameters.size())));
synDiaProbs.add(((double)synDiaCount.get(i)/((double)syntheticDiameters.size())));
}
// calculate and return JSD
return calcJSD(origDiaProbs, synDiaProbs);
}
public static double calculateTravelDistanceError(List<Trajectory> original,
List<Trajectory> synthetic, int numberOfBuckets) {
// get travel lengths of original database
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
List<Double> originalLengths = new ArrayList<Double>();
for (Trajectory t : original) {
double dia = t.getDistanceTravelled();
originalLengths.add(dia);
if (dia < min)
min = dia;
if (dia > max)
max = dia;
}
// get travel lengths of synthetic database
List<Double> syntheticLengths = new ArrayList<Double>();
for (Trajectory t : synthetic) {
double dia = t.getDistanceTravelled();
syntheticLengths.add(dia);
}
// bucketize the lengths to find counts in each bucket
double bucketSize = (max-min)/numberOfBuckets;
List<Integer> origCount = new ArrayList<Integer>();
List<Integer> synCount = new ArrayList<Integer>();
for (int i = 0; i < numberOfBuckets; i++) {
double currStart = i * bucketSize;
double currFinish = (i+1) * bucketSize;
int cnt = 0;
//System.out.print("[" + currStart + "," + currFinish + "] ");
for (Double d : originalLengths) {
if (d >= currStart && d < currFinish)
cnt++;
}
origCount.add(cnt);
cnt = 0;
for (Double d : syntheticLengths) {
if (d >= currStart && d < currFinish)
cnt++;
}
synCount.add(cnt);
}
// find the distributions
List<Double> origProbs = new ArrayList<Double>();
List<Double> synProbs = new ArrayList<Double>();
for (int i = 0; i < numberOfBuckets; i++) {
origProbs.add(((double)origCount.get(i)/((double)originalLengths.size())));
synProbs.add(((double)synCount.get(i)/((double)syntheticLengths.size())));
}
// calculate and return JSD
return calcJSD(origProbs, synProbs);
}
public static Query[] generateQueries (List<Trajectory> db, int queryCount, String fn) {
List<Double> boundaries = Main.getDataBoundaries(db);
double dataMinX = boundaries.get(0);
double dataMaxX = boundaries.get(1);
double dataMinY = boundaries.get(2);
double dataMaxY = boundaries.get(3);
Query[] tbr = new Query[queryCount];
for (int i = 0; i < queryCount; i++) {
tbr[i] = new Query(dataMinX, dataMaxX, dataMinY, dataMaxY, fn);
}
return tbr;
}
public static double calculateQueryError(List<Trajectory> originalDB,
List<Trajectory> syntheticDB, Query[] queries, double sanityBound) {
// evaluate queries on the two databases
int[] actualAnswers = new int[queries.length];
int[] syntheticAnswers = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
Query q = queries[i];
actualAnswers[i] = q.evaluateQueryOnDatabase(originalDB);
syntheticAnswers[i] = q.evaluateQueryOnDatabase(syntheticDB);
}
//System.out.println(Arrays.toString(actualAnswers));
//System.out.println(Arrays.toString(syntheticAnswers));
// measure relative errors using the sanity bound
double[] error = new double[queries.length];
for (int i = 0; i < queries.length; i++) {
double numerator = Math.abs(syntheticAnswers[i]-actualAnswers[i]);
double denominator = actualAnswers[i];
if (originalDB.size() * sanityBound > denominator)
denominator = originalDB.size() * sanityBound;
error[i] = ((double)numerator)/((double)denominator);
}
// measure average relative error
double sumErr = 0.0;
for (int i = 0; i < error.length; i++) {
sumErr = sumErr + error[i];
}
return sumErr/((double)error.length);
}
public static Map<Pattern, Integer> minePatterns (List<GridTrajectory> db,
int minSize, int maxSize) {
Map<Pattern, Integer> tbr = new HashMap<Pattern, Integer>();
for (int currentSize = minSize; currentSize <= maxSize; currentSize++) {
//System.out.println("Currently mining patterns of size: " + currentSize);
for (GridTrajectory t : db) {
// get sub-lists of length currentSize from t. check if we hit t.size
for (int i = 0; i <= t.getCells().size()-currentSize; i++) {
Pattern p = new Pattern(t.getCells().subList(i, i+currentSize));
if (tbr.containsKey(p)) {
tbr.put(p, tbr.get(p)+1);
} else {
tbr.put(p, 1);
}
}
}
}
return tbr;
}
// from: http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return ( o2.getValue() ).compareTo( o1.getValue() ); // reverse order
}
} );
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
// same function as above, sorts in reverse order: small to large (ascending)
public static <K, V extends Comparable<? super V>> Map<K, V> sortReverseOrder
( Map<K, V> map ) {
List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return ( o1.getValue() ).compareTo( o2.getValue() ); // reverse order
}
} );
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
private static boolean checkMapSorting(Map<Pattern, Integer> candidate) {
Integer previous = null;
for(Map.Entry<Pattern, Integer> entry : candidate.entrySet()) {
if (entry.getValue() == null) {
System.out.println("null obtained in minePatterns function?!!?");
return false;
}
if (previous != null) {
if (entry.getValue() > previous) {
System.out.println("sorted map is not sorted !!!");
return false;
}
}
previous = entry.getValue();
}
return true;
}
public static double patternMiningF1Error (Map<Pattern, Integer> originalPatterns,
int topK, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns and synthetic patterns maps
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
Map<Pattern, Integer> sortedSynPatterns = Evaluation.sortByValue(synPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
if (!Evaluation.checkMapSorting(sortedSynPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original and synthetic
List<Pattern> origTopK = new ArrayList<Pattern>();
List<Pattern> synTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < topK) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
for (Map.Entry<Pattern, Integer> entry : sortedSynPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (synTopK.size() < topK) {
synTopK.add(entry.getKey());
}
else {
break; // out of the for loop
}
}
return calcF1(origTopK, synTopK);
}
public static double patternMiningJaccardSim (Map<Pattern, Integer> originalPatterns,
int topK, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns and synthetic patterns maps
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
Map<Pattern, Integer> sortedSynPatterns = Evaluation.sortByValue(synPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
if (!Evaluation.checkMapSorting(sortedSynPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original and synthetic
List<Pattern> origTopK = new ArrayList<Pattern>();
List<Pattern> synTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < topK) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
for (Map.Entry<Pattern, Integer> entry : sortedSynPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (synTopK.size() < topK) {
synTopK.add(entry.getKey());
}
else {
break; // out of the for loop
}
}
return JaccardSimilarity(origTopK, synTopK);
}
public static double patternMiningSupport (Map<Pattern, Integer> originalPatterns,
int topK, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns in descending order of support
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original
List<Pattern> origTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < topK) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
double sumErr = 0.0;
for (int i = 0; i < origTopK.size(); i++) {
Pattern freqPat = origTopK.get(i);
int origSupport = originalPatterns.get(freqPat);
int synSupport = 0;
if (synPatterns.containsKey(freqPat))
synSupport = synPatterns.get(freqPat);
//System.out.println("origSup: " + origSupport + ", synSup: " + synSupport);
sumErr = sumErr + Math.abs(origSupport-synSupport)/((double)origSupport);
}
return sumErr/((double)origTopK.size());
}
// uses Kendall's tau coefficient for ranking correlation
public static double patternMiningRanking (Map<Pattern, Integer> originalPatterns,
int rankingN, List<Trajectory> syntheticDatabase, Grid grid,
int minFPsize, int maxFPsize) {
// find synthetic patterns
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(
syntheticDatabase, grid, true);
Map<Pattern, Integer> synPatterns = Evaluation.minePatterns(synDBgrid,
minFPsize, maxFPsize);
// sort originalPatterns in descending order of support
Map<Pattern, Integer> sortedOrigPatterns = Evaluation.sortByValue(originalPatterns);
// debug: check if these are actually sorted
if (!Evaluation.checkMapSorting(sortedOrigPatterns))
System.out.println("Sorting error @ FP mining.");
// find top-k patterns in original
List<Pattern> origTopK = new ArrayList<Pattern>();
for (Map.Entry<Pattern, Integer> entry : sortedOrigPatterns.entrySet()) {
if (entry.getValue() == null)
System.out.println("null obtained in minePatterns function?!");
if (origTopK.size() < rankingN) {
origTopK.add(entry.getKey());
//System.out.println("Pattern: " + entry.getKey().toString() +
// ", supp: " + entry.getValue());
}
else {
break; // out of the for loop
}
}
// calculate Kendall's tau for topK patterns
int concordantPairs = 0;
int reversedPairs = 0;
for (int i = 0; i < origTopK.size(); i++) {
for (int j = i+1; j < origTopK.size(); j++) {
Pattern moreFreq = origTopK.get(i);
Pattern lessFreq = origTopK.get(j);
if (!synPatterns.containsKey(moreFreq) && !synPatterns.containsKey(lessFreq)) {
// tie, do nothing
} else if (synPatterns.containsKey(moreFreq) && !synPatterns.containsKey(lessFreq)) {
concordantPairs++;
} else if (!synPatterns.containsKey(moreFreq) && synPatterns.containsKey(lessFreq)) {
reversedPairs++;
} else { // contains both
if (synPatterns.get(moreFreq) > synPatterns.get(lessFreq))
concordantPairs++;
else if (synPatterns.get(lessFreq) > synPatterns.get(moreFreq))
reversedPairs++;
}
}
}
int n = origTopK.size();
double denom = n*(n-1)/((double)2.0);
//System.out.println("Concordant: " + concordantPairs + ", reversed: " + reversedPairs);
return ((double)concordantPairs-reversedPairs)/((double)denom);
}
// Measure the error in location coverage thru Kendall's tau for rank correlation
public static double locationCoverageKendallTau(List<Trajectory> original, List<Trajectory>
synthetic, int gridCell) {
// find data boundaries so that an appropriate grid can be laid
List<Double> boundaries = Main.getDataBoundaries(original);
double minX = boundaries.get(0);
double maxX = boundaries.get(1);
double minY = boundaries.get(2);
double maxY = boundaries.get(3);
// lay grid on original and synthetic databases
Grid ug = new Grid(gridCell, minX, maxX, minY, maxY);
List<GridTrajectory> origDBgrid = Main.convertTrajToGridTraj(original, ug, true);
List<GridTrajectory> synDBgrid = Main.convertTrajToGridTraj(synthetic, ug, true);
// how many trajectories visited each cell?
List<Cell> cells = ug.getCells();
int[] actualCounts = new int[cells.size()];
int[] syntheticCounts = new int[cells.size()];
for (int i = 0; i < cells.size(); i++) {
actualCounts[i] = 0;
syntheticCounts[i] = 0;
Cell c = cells.get(i);
for (GridTrajectory t : origDBgrid) {
if (t.passesThrough(c))
actualCounts[i] = actualCounts[i]+1;
}
for (GridTrajectory t : synDBgrid) {
if (t.passesThrough(c))
syntheticCounts[i] = syntheticCounts[i]+1;
}
}
// measure kendall tau with actualCounts and syntheticCounts
int concordantPairs = 0;
int reversedPairs = 0;
for (int i = 0; i < actualCounts.length; i++) {
for (int j = i+1; j < actualCounts.length; j++) {
if (actualCounts[i] > actualCounts[j]) {
if (syntheticCounts[i] > syntheticCounts[j])
concordantPairs++;
else
reversedPairs++;
}
if (actualCounts[i] < actualCounts[j]) {
if (syntheticCounts[i] > syntheticCounts[j])
reversedPairs++;
else
concordantPairs++;
}
}
}
int n = cells.size();
double denom = n*(n-1)/((double)2.0);
//System.out.println("Concordant: " + concordantPairs + ", reversed: " + reversedPairs);
return ((double)concordantPairs-reversedPairs)/((double)denom);
}
public static double calcJSD(List<Double> origProb, List<Double> synProb) {
List<Double> avgProb = new ArrayList<Double>();
for (int i = 0; i < origProb.size(); i++) {
avgProb.add((origProb.get(i)+synProb.get(i))/2.0);
}
//System.out.println(origProb);
//System.out.println(avgProb);
//System.out.println(synProb);
return 0.5*calcKL(origProb,avgProb) + 0.5*calcKL(synProb,avgProb);
}
private static double calcKL(List<Double> prob1, List<Double> prob2) {
double KL = 0.0;
for (int i = 0; i < prob1.size(); i++) {
double Qofi = prob2.get(i);
double Pofi = prob1.get(i);
if (Pofi != 0.0)
KL = KL + Math.log(Pofi/Qofi)*Pofi;
}
return KL;
}
private static double calcF1(List<Pattern> original, List<Pattern> synthetic) {
double noCorrectPositives = 0.0;
for (Pattern p : synthetic) {
for (Pattern p2 : original) {
if (p.isEqual(p2)) {
noCorrectPositives++;
break;
}
}
}
//System.out.println("# of correct positives: " + noCorrectPositives);
double precision = noCorrectPositives / synthetic.size();
double recall = noCorrectPositives / original.size();
return (2*precision*recall)/(precision+recall);
}
private static double JaccardSimilarity(List<Pattern> original, List<Pattern> synthetic) {
List<Pattern> intersection = new ArrayList<Pattern>();
for (Pattern p : original) {
for (int i = 0; i < synthetic.size(); i++) {
if (synthetic.get(i).isEqual(p)) {
intersection.add(p);
break;
}
}
}
List<Pattern> union = new ArrayList<Pattern>();
for (Pattern p : original) {
union.add(p);
}
for (Pattern p : synthetic) {
if (!intersection.contains(p))
union.add(p);
}
return ((double)intersection.size())/((double)union.size());
}
public static double calculateDTW (List<Point> list1, List<Point> list2) {
double[][] dtwMatrix = new double[list1.size()+1][list2.size()+1];
// fill first row and column
for (int i = 1; i <= list1.size(); i++) {
dtwMatrix[i][0] = Double.POSITIVE_INFINITY;
}
for (int i = 1; i < list2.size(); i++) {
dtwMatrix[0][i] = Double.POSITIVE_INFINITY;
}
dtwMatrix[0][0] = 0;
// do O(mn) computations
for (int i = 1; i <= list1.size(); i++) {
for (int j = 1; j <= list2.size(); j++) {
Point p1 = list1.get(i-1);
Point p2 = list2.get(j-1);
double euclidDist = p1.euclideanDistTo(p2);
// find min
double min = Double.POSITIVE_INFINITY;
if (dtwMatrix[i-1][j] < min)
min = dtwMatrix[i-1][j];
if (dtwMatrix[i][j-1] < min)
min = dtwMatrix[i][j-1];
if (dtwMatrix[i-1][j-1] < min)
min = dtwMatrix[i-1][j-1];
// enter into<SUF>
dtwMatrix[i][j] = euclidDist + min;
}
}
// end
return dtwMatrix[list1.size()][list2.size()];
}
}
|
203479_11 | package org.springframework.richclient.util;
import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.error.ErrorInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.binding.form.FormModel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.richclient.application.Application;
import org.springframework.richclient.application.ApplicationServicesLocator;
import org.springframework.richclient.application.ApplicationWindow;
import org.springframework.richclient.application.config.ApplicationObjectConfigurer;
import org.springframework.richclient.application.support.DefaultApplicationServices;
import org.springframework.richclient.command.AbstractCommand;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.command.config.CommandButtonConfigurer;
import org.springframework.richclient.command.config.CommandConfigurer;
import org.springframework.richclient.command.config.CommandFaceDescriptor;
import org.springframework.richclient.command.support.DataEditorWidgetViewCommand;
import org.springframework.richclient.exceptionhandling.JdicEmailNotifierErrorReporter;
import org.springframework.richclient.factory.ButtonFactory;
import org.springframework.richclient.factory.DefaultButtonFactory;
import org.springframework.richclient.image.IconSource;
import org.springframework.richclient.widget.editor.DefaultDataEditorWidget;
import org.springframework.util.StringUtils;
import javax.swing.*;
import java.awt.*;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
public class RcpSupport
{
public static final String ERROR_KEY = "error";
// standard message keys
public static final String LABEL = "label";
public static final String HEADER = "header";
public static final String TEXT = "text";
public static final String TITLE = "title";
public static final String MESSAGE = "message";
public static final String DETAIL = "detail";
public static final String CAPTION = "caption";
public static final String ICON = "icon";
public static final int YES_OPTION = 0;
public static final int OK_OPTION = 0;
public static final int NO_OPTION = 1;
public static final int CANCEL_OPTION = 2;
private static MessageSourceAccessor messageSourceAccessor;
private static CommandConfigurer commandConfigurer;
private static ApplicationContext applicationContext;
private static ApplicationObjectConfigurer applicationObjectConfigurer;
private static IconSource iconSource;
private static Map<Integer, Object[]> optionsMap;
static
{
optionsMap = new HashMap<Integer, Object[]>();
String yes = getMessage(null, "OptionPane.yesButtonText", LABEL);
String no = getMessage(null, "OptionPane.noButtonText", LABEL);
String cancel = getMessage(null, "OptionPane.cancelButtonText", LABEL);
String ok = getMessage(null, "OptionPane.okButtonText", LABEL);
optionsMap.put(Integer.valueOf(JOptionPane.DEFAULT_OPTION), new Object[]{ok});
optionsMap.put(Integer.valueOf(JOptionPane.YES_NO_OPTION), new Object[]{yes, no});
optionsMap.put(Integer.valueOf(JOptionPane.YES_NO_CANCEL_OPTION), new Object[]{yes, no, cancel});
optionsMap.put(Integer.valueOf(JOptionPane.OK_CANCEL_OPTION), new Object[]{ok, cancel});
}
public static String[] getMessageKeys(String id, String name, String type)
{
boolean idNotEmpty = (id == null) || id.trim().equals("") ? false : true;
String[] keys = new String[idNotEmpty ? 3 : 2];
int i = 0;
if (idNotEmpty)
{
keys[i++] = id + "." + name + "." + type;
}
keys[i++] = name + "." + type;
keys[i] = name;
return keys;
}
public static String getMessage(String id, String name, String type)
{
String[] messageKeys = getMessageKeys(id, name, type);
if (messageSourceAccessor == null)
messageSourceAccessor = (MessageSourceAccessor) ApplicationServicesLocator.services().getService(
MessageSourceAccessor.class);
return messageSourceAccessor.getMessage(new DefaultMessageSourceResolvable(messageKeys, null,
messageKeys[messageKeys.length - 1]));
}
public static String getMessage(MessageSourceResolvable msr)
{
if (messageSourceAccessor == null)
messageSourceAccessor = (MessageSourceAccessor) ApplicationServicesLocator.services().getService(
MessageSourceAccessor.class);
return messageSourceAccessor.getMessage(msr);
}
public static String getMessage(String id)
{
if (messageSourceAccessor == null)
messageSourceAccessor = (MessageSourceAccessor) ApplicationServicesLocator.services().getService(
MessageSourceAccessor.class);
return messageSourceAccessor.getMessage(id, "");
}
public static String getMessage(String id, String name, String type, Object[] params)
{
String message = getMessage(id, name, type);
if (params != null)
return MessageFormat.format(message, params);
return message;
}
public static void configure(AbstractCommand command)
{
if (commandConfigurer == null)
commandConfigurer = (CommandConfigurer) ApplicationServicesLocator.services().getService(
CommandConfigurer.class);
commandConfigurer.configure(command);
}
public static void configure(Object object, String id)
{
if (applicationObjectConfigurer == null)
applicationObjectConfigurer = (ApplicationObjectConfigurer) ApplicationServicesLocator.services()
.getService(ApplicationObjectConfigurer.class);
applicationObjectConfigurer.configure(object, id);
}
public static Icon getIcon(String key)
{
if (iconSource == null)
iconSource = (IconSource) ApplicationServicesLocator.services().getService(IconSource.class);
return iconSource.getIcon(key);
}
public static <T> T getBean(String id)
{
if (applicationContext == null)
applicationContext = ((DefaultApplicationServices) ApplicationServicesLocator.services())
.getApplicationContext();
return (T) applicationContext.getBean(id);
}
public static <T> T getCommand(String commandId)
{
return (T) Application.instance().getActiveWindow().getCommandManager().getCommand(commandId);
}
/**
* Converts the incoming string to an escaped output string. This method is far from perfect, only
* escaping <, > and & characters
*/
private static String escapeXml(String input)
{
return input == null ? "" : input.replace("&", "&").replace("<", "<").replace(">", ">");
}
/**
* Creates and returns HTML representing the details of this incident info. This method is only called if
* the details needs to be generated: ie: the detailed error message property of the incident info is
* null.
*/
private static String getDetailsAsHTML(String title, Level level, Throwable e)
{
if (e != null)
{
// convert the stacktrace into a more pleasent bit of HTML
StringBuffer html = new StringBuffer("<html>");
html.append("<h2>" + escapeXml(title) + "</h2>");
html.append("<HR size='1' noshade>");
html.append("<div></div>");
html.append("<b>Message:</b>");
html.append("<pre>");
html.append(" " + escapeXml(e.toString()));
html.append("</pre>");
html.append("<b>Level:</b>");
html.append("<pre>");
html.append(" " + level);
html.append("</pre>");
html.append("<b>Stack Trace:</b>");
html.append("<pre>");
for (StackTraceElement el : e.getStackTrace())
{
html.append(" " + el.toString().replace("<init>", "<init>") + "\n");
}
if (e.getCause() != null)
{
html.append("</pre>");
html.append("<b>Cause:</b>");
html.append("<pre>");
html.append(e.getCause().getMessage());
html.append("</pre><pre>");
for (StackTraceElement el : e.getCause().getStackTrace())
{
html.append(" " + el.toString().replace("<init>", "<init>") + "\n");
}
}
html.append("</pre></html>");
return html.toString();
}
else
{
return null;
}
}
public static void handleException(Throwable t)
{
Application.instance().getLifecycleAdvisor().getRegisterableExceptionHandler().uncaughtException(
Thread.currentThread(), t);
}
public static void showErrorDialog(Throwable t)
{
String title = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String shortMessage = RcpSupport.getMessage(t.getClass().getName() + "." + RcpSupport.MESSAGE);
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = t.getMessage();
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
}
}
showErrorDialog(null, new ErrorInfo(title, shortMessage, getDetailsAsHTML(title, Level.SEVERE, t),
null, t, Level.SEVERE, null));
}
public static void showSQLExceptionErrorDialog(SQLException sqlException)
{
String title = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String shortMessage = RcpSupport.getMessage(sqlException.getClass().getName() + "."
+ sqlException.getErrorCode() + "." + RcpSupport.MESSAGE);
if (!StringUtils.hasText(shortMessage))
{
shortMessage = RcpSupport
.getMessage(sqlException.getClass().getName() + "." + RcpSupport.MESSAGE);
shortMessage += "\nSQL error " + sqlException.getErrorCode();
}
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = sqlException.getMessage();
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
}
}
showErrorDialog(null, new ErrorInfo(title, shortMessage, getDetailsAsHTML(title, Level.SEVERE,
sqlException), null, sqlException, Level.SEVERE, null));
}
public static void showErrorDialogResolveMessages(String id)
{
String title = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String message = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
String detail = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.DETAIL);
detail = detail == RcpSupport.ERROR_KEY ? "" : detail;
showErrorDialog(title, message, detail);
}
public static void showErrorDialog(String message)
{
showErrorDialog(message, (String) null);
}
public static void showErrorDialog(String message, String detail)
{
showErrorDialog(RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.TITLE), message, detail);
}
public static void showErrorDialog(String id, Throwable cause)
{
String title = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String message = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
showErrorDialog(null, new ErrorInfo(title, message, getDetailsAsHTML(title, Level.SEVERE, cause),
null, cause, Level.SEVERE, null));
}
public static void showErrorDialog(String title, String message, String detail)
{
showErrorDialog(null, new ErrorInfo(title, message, detail, null, null, Level.SEVERE, null));
}
public static void showErrorDialog(Component parent, ErrorInfo errorInfo)
{
if (parent == null)
{
if (org.springframework.richclient.application.Application.isLoaded())
{
ApplicationWindow activeWindow = org.springframework.richclient.application.Application
.instance().getActiveWindow();
if (activeWindow != null)
parent = activeWindow.getControl();
}
}
JXErrorPane pane = new JXErrorPane();
pane.setErrorInfo(errorInfo);
pane.setErrorReporter(new JdicEmailNotifierErrorReporter());
JXErrorPane.showDialog(parent, pane);
}
/**
* @see RcpSupport#showWarningDialog(Component, String, int)
*/
public static int showWarningDialog(String id, int optionType)
{
return showWarningDialog(Application.instance().getActiveWindow().getControl(), id, optionType);
}
/**
* @see RcpSupport#showWarningDialog(Component, String, int)
*/
public static int showWarningDialog(Component parent, String id, int optionType)
{
return showWarningDialog(parent, id, null, optionType);
}
public static int showWarningDialog(Component parent, String id, Object[] parameters, int optionType)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
return JOptionPane.showConfirmDialog(parent, message, title, optionType, JOptionPane.WARNING_MESSAGE);
}
/**
* @see RcpSupport#showWarningDialog(Component, String, Object[], int, int)
*/
public static int showWarningDialog(String id, int optionType, int initialValue)
{
return showWarningDialog(Application.instance().getActiveWindow().getControl(), id, null, optionType,
initialValue);
}
public static int showWarningDialog(Component parent, String id, Object[] parameters, int optionType,
int initialValue)
{
Object[] options = optionsMap.get(Integer.valueOf(optionType));
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
if (optionType == JOptionPane.OK_CANCEL_OPTION && initialValue == CANCEL_OPTION)
initialValue = 1;
if (initialValue >= options.length)
throw new IllegalArgumentException(
"De waarde van het argument initialValue is niet gekend door het gekozen optionType");
return JOptionPane.showOptionDialog(parent, message, title, optionType, JOptionPane.WARNING_MESSAGE,
null, options, options[initialValue]);
}
public static ActionCommand createDummyCommand(final String id, final String msg)
{
ActionCommand newCommand = new ActionCommand(id)
{
protected void doExecuteCommand()
{
System.out.println(msg);
}
};
((CommandConfigurer) ApplicationServicesLocator.services().getService(CommandConfigurer.class))
.configure(newCommand);
return newCommand;
}
public static void showWarningDialog(String id)
{
showWarningDialog(Application.instance().getActiveWindow().getControl(), id);
}
public static void showWarningDialog(Component parent, String id)
{
showWarningDialog(parent, id, null);
}
public static void showWarningDialog(Component parent, String id, Object[] parameters)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
JOptionPane.showMessageDialog(parent, message, title, JOptionPane.WARNING_MESSAGE);
}
public static int showConfirmationDialog(String id)
{
return showConfirmationDialog(Application.instance().getActiveWindow().getControl(), id);
}
public static int showConfirmationDialog(Component parent, String id)
{
return showConfirmationDialog(parent, id, null);
}
public static int showConfirmationDialog(Component parent, String id, Object[] parameters)
{
return showConfirmationDialog(parent, id, parameters, JOptionPane.YES_NO_CANCEL_OPTION);
}
public static int showConfirmationDialog(Component parent, String id, Object[] parameters, int optionType)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
return JOptionPane.showConfirmDialog(parent, message, title, optionType);
}
public static void showMessageDialog(Component parent, String id, Object[] parameters, int optionType)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
JOptionPane.showMessageDialog(parent, message, title, optionType);
}
/**
* This method tries to map the values of the given object on the valueModels of the formModel. Instead of
* setting the object as a backing object, all valueModels are processed one by one and the corresponding
* property value is fetched from the objectToMap and set on that valueModel. This triggers the usual
* buffering etc. just as if the user entered the values.
*
* @param formModel
* @param objectToMap
*/
public static void mapObjectOnFormModel(FormModel formModel, Object objectToMap)
{
BeanWrapper beanWrapper = new BeanWrapperImpl(objectToMap);
for (String fieldName : (Set<String>) formModel.getFieldNames())
{
try
{
formModel.getValueModel(fieldName).setValue(beanWrapper.getPropertyValue(fieldName));
}
catch (BeansException be)
{
// silently ignoring, just mapping values, so if there's one missing, don't bother
}
}
}
private static Object clonePublicCloneableObject(Object value)
{
try
{
return ((PublicCloneable) value).clone();
}
catch (CloneNotSupportedException e)
{
throw new RuntimeException("Clone not support for object " + value.getClass());
}
}
public static Object getClone(Object value)
{
if (value instanceof PublicCloneable)
{
return clonePublicCloneableObject(value);
}
else if (value instanceof Collection)
{
Collection valueCollection = (Collection) value;
Collection clonedCollection;
if (valueCollection instanceof java.util.List)
{
clonedCollection = (valueCollection instanceof LinkedList)
? new LinkedList()
: new ArrayList();
}
else if (valueCollection instanceof Set)
{
clonedCollection = (valueCollection instanceof SortedSet)
? new TreeSet()
: (valueCollection instanceof LinkedHashSet) ? new LinkedHashSet() : new HashSet();
}
else
{
clonedCollection = (Collection) BeanUtils.instantiateClass(value.getClass());
}
for (Object valueElement : valueCollection)
{
if (valueElement instanceof PublicCloneable)
{
clonedCollection.add(clonePublicCloneableObject(valueElement));
}
else
{
// there isn't much else we can do?
clonedCollection.add(valueElement);
}
}
return clonedCollection;
}
else if (value instanceof Map)
{
Map valueMap = (Map) value;
Map clonedMap = (valueMap instanceof SortedMap)
? new TreeMap()
: (valueMap instanceof LinkedHashMap) ? new LinkedHashMap() : new HashMap();
for (Iterator entryIter = valueMap.entrySet().iterator(); entryIter.hasNext();)
{
Map.Entry entry = (Map.Entry) entryIter.next();
if (entry.getValue() instanceof PublicCloneable)
{
clonedMap.put(entry.getKey(), clonePublicCloneableObject(entry.getValue()));
}
else
{
// there isn't much else we can do?
clonedMap.put(entry.getKey(), entry.getValue());
}
}
return clonedMap;
}
return value;
}
public static JPanel createIconButtonPanel(List<? extends AbstractCommand> commands)
{
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
ButtonFactory factory = new DefaultButtonFactory();
CommandButtonConfigurer configurer = new CommandButtonConfigurer()
{
public void configure(AbstractButton button, AbstractCommand command,
CommandFaceDescriptor faceDescriptor)
{
faceDescriptor.configureIcon(button);
button.setToolTipText(faceDescriptor.getCaption());
}
};
for (AbstractCommand command : commands)
{
buttons.add(command.createButton(factory, configurer));
}
return buttons;
}
public static JComponent createDummyPanel(String vakske)
{
JPanel dummy = new JPanel();
dummy.add(new JLabel(vakske));
return dummy;
}
/**
* Toon een dataeditor in de huidige applicationwindow op basis van een command
*
* @param command
* De command die de dataeditor toont (mag niet null zijn)
* @param filter
* Eventueel initieel filterobject voor de dataeditor
* @param defaultSelectedObject
* Eventueel initieel geselecteerd item in de lijst
*
* @author ldo
* @since 0.4.4
*/
public static void executeViewDataEditorCommand(DataEditorWidgetViewCommand command, Object filter,
Object defaultSelectedObject)
{
org.springframework.util.Assert.notNull(command, "Command mag niet null zijn!");
Map<String, Object> dataEditorParameters = new HashMap<String, Object>(2);
dataEditorParameters.put(DefaultDataEditorWidget.PARAMETER_FILTER, filter);
dataEditorParameters.put(DefaultDataEditorWidget.PARAMETER_DEFAULT_SELECTED_OBJECT,
defaultSelectedObject);
Map<String, Object> commandParameters = new HashMap<String, Object>(1);
commandParameters.put(DefaultDataEditorWidget.PARAMETER_MAP, dataEditorParameters);
command.execute(commandParameters);
}
}
| shevek/spring-rich-client | spring-richclient-core/src/main/java/org/springframework/richclient/util/RcpSupport.java | 5,472 | /**
* Toon een dataeditor in de huidige applicationwindow op basis van een command
*
* @param command
* De command die de dataeditor toont (mag niet null zijn)
* @param filter
* Eventueel initieel filterobject voor de dataeditor
* @param defaultSelectedObject
* Eventueel initieel geselecteerd item in de lijst
*
* @author ldo
* @since 0.4.4
*/ | block_comment | nl | package org.springframework.richclient.util;
import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.error.ErrorInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.binding.form.FormModel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.richclient.application.Application;
import org.springframework.richclient.application.ApplicationServicesLocator;
import org.springframework.richclient.application.ApplicationWindow;
import org.springframework.richclient.application.config.ApplicationObjectConfigurer;
import org.springframework.richclient.application.support.DefaultApplicationServices;
import org.springframework.richclient.command.AbstractCommand;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.command.config.CommandButtonConfigurer;
import org.springframework.richclient.command.config.CommandConfigurer;
import org.springframework.richclient.command.config.CommandFaceDescriptor;
import org.springframework.richclient.command.support.DataEditorWidgetViewCommand;
import org.springframework.richclient.exceptionhandling.JdicEmailNotifierErrorReporter;
import org.springframework.richclient.factory.ButtonFactory;
import org.springframework.richclient.factory.DefaultButtonFactory;
import org.springframework.richclient.image.IconSource;
import org.springframework.richclient.widget.editor.DefaultDataEditorWidget;
import org.springframework.util.StringUtils;
import javax.swing.*;
import java.awt.*;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
public class RcpSupport
{
public static final String ERROR_KEY = "error";
// standard message keys
public static final String LABEL = "label";
public static final String HEADER = "header";
public static final String TEXT = "text";
public static final String TITLE = "title";
public static final String MESSAGE = "message";
public static final String DETAIL = "detail";
public static final String CAPTION = "caption";
public static final String ICON = "icon";
public static final int YES_OPTION = 0;
public static final int OK_OPTION = 0;
public static final int NO_OPTION = 1;
public static final int CANCEL_OPTION = 2;
private static MessageSourceAccessor messageSourceAccessor;
private static CommandConfigurer commandConfigurer;
private static ApplicationContext applicationContext;
private static ApplicationObjectConfigurer applicationObjectConfigurer;
private static IconSource iconSource;
private static Map<Integer, Object[]> optionsMap;
static
{
optionsMap = new HashMap<Integer, Object[]>();
String yes = getMessage(null, "OptionPane.yesButtonText", LABEL);
String no = getMessage(null, "OptionPane.noButtonText", LABEL);
String cancel = getMessage(null, "OptionPane.cancelButtonText", LABEL);
String ok = getMessage(null, "OptionPane.okButtonText", LABEL);
optionsMap.put(Integer.valueOf(JOptionPane.DEFAULT_OPTION), new Object[]{ok});
optionsMap.put(Integer.valueOf(JOptionPane.YES_NO_OPTION), new Object[]{yes, no});
optionsMap.put(Integer.valueOf(JOptionPane.YES_NO_CANCEL_OPTION), new Object[]{yes, no, cancel});
optionsMap.put(Integer.valueOf(JOptionPane.OK_CANCEL_OPTION), new Object[]{ok, cancel});
}
public static String[] getMessageKeys(String id, String name, String type)
{
boolean idNotEmpty = (id == null) || id.trim().equals("") ? false : true;
String[] keys = new String[idNotEmpty ? 3 : 2];
int i = 0;
if (idNotEmpty)
{
keys[i++] = id + "." + name + "." + type;
}
keys[i++] = name + "." + type;
keys[i] = name;
return keys;
}
public static String getMessage(String id, String name, String type)
{
String[] messageKeys = getMessageKeys(id, name, type);
if (messageSourceAccessor == null)
messageSourceAccessor = (MessageSourceAccessor) ApplicationServicesLocator.services().getService(
MessageSourceAccessor.class);
return messageSourceAccessor.getMessage(new DefaultMessageSourceResolvable(messageKeys, null,
messageKeys[messageKeys.length - 1]));
}
public static String getMessage(MessageSourceResolvable msr)
{
if (messageSourceAccessor == null)
messageSourceAccessor = (MessageSourceAccessor) ApplicationServicesLocator.services().getService(
MessageSourceAccessor.class);
return messageSourceAccessor.getMessage(msr);
}
public static String getMessage(String id)
{
if (messageSourceAccessor == null)
messageSourceAccessor = (MessageSourceAccessor) ApplicationServicesLocator.services().getService(
MessageSourceAccessor.class);
return messageSourceAccessor.getMessage(id, "");
}
public static String getMessage(String id, String name, String type, Object[] params)
{
String message = getMessage(id, name, type);
if (params != null)
return MessageFormat.format(message, params);
return message;
}
public static void configure(AbstractCommand command)
{
if (commandConfigurer == null)
commandConfigurer = (CommandConfigurer) ApplicationServicesLocator.services().getService(
CommandConfigurer.class);
commandConfigurer.configure(command);
}
public static void configure(Object object, String id)
{
if (applicationObjectConfigurer == null)
applicationObjectConfigurer = (ApplicationObjectConfigurer) ApplicationServicesLocator.services()
.getService(ApplicationObjectConfigurer.class);
applicationObjectConfigurer.configure(object, id);
}
public static Icon getIcon(String key)
{
if (iconSource == null)
iconSource = (IconSource) ApplicationServicesLocator.services().getService(IconSource.class);
return iconSource.getIcon(key);
}
public static <T> T getBean(String id)
{
if (applicationContext == null)
applicationContext = ((DefaultApplicationServices) ApplicationServicesLocator.services())
.getApplicationContext();
return (T) applicationContext.getBean(id);
}
public static <T> T getCommand(String commandId)
{
return (T) Application.instance().getActiveWindow().getCommandManager().getCommand(commandId);
}
/**
* Converts the incoming string to an escaped output string. This method is far from perfect, only
* escaping <, > and & characters
*/
private static String escapeXml(String input)
{
return input == null ? "" : input.replace("&", "&").replace("<", "<").replace(">", ">");
}
/**
* Creates and returns HTML representing the details of this incident info. This method is only called if
* the details needs to be generated: ie: the detailed error message property of the incident info is
* null.
*/
private static String getDetailsAsHTML(String title, Level level, Throwable e)
{
if (e != null)
{
// convert the stacktrace into a more pleasent bit of HTML
StringBuffer html = new StringBuffer("<html>");
html.append("<h2>" + escapeXml(title) + "</h2>");
html.append("<HR size='1' noshade>");
html.append("<div></div>");
html.append("<b>Message:</b>");
html.append("<pre>");
html.append(" " + escapeXml(e.toString()));
html.append("</pre>");
html.append("<b>Level:</b>");
html.append("<pre>");
html.append(" " + level);
html.append("</pre>");
html.append("<b>Stack Trace:</b>");
html.append("<pre>");
for (StackTraceElement el : e.getStackTrace())
{
html.append(" " + el.toString().replace("<init>", "<init>") + "\n");
}
if (e.getCause() != null)
{
html.append("</pre>");
html.append("<b>Cause:</b>");
html.append("<pre>");
html.append(e.getCause().getMessage());
html.append("</pre><pre>");
for (StackTraceElement el : e.getCause().getStackTrace())
{
html.append(" " + el.toString().replace("<init>", "<init>") + "\n");
}
}
html.append("</pre></html>");
return html.toString();
}
else
{
return null;
}
}
public static void handleException(Throwable t)
{
Application.instance().getLifecycleAdvisor().getRegisterableExceptionHandler().uncaughtException(
Thread.currentThread(), t);
}
public static void showErrorDialog(Throwable t)
{
String title = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String shortMessage = RcpSupport.getMessage(t.getClass().getName() + "." + RcpSupport.MESSAGE);
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = t.getMessage();
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
}
}
showErrorDialog(null, new ErrorInfo(title, shortMessage, getDetailsAsHTML(title, Level.SEVERE, t),
null, t, Level.SEVERE, null));
}
public static void showSQLExceptionErrorDialog(SQLException sqlException)
{
String title = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String shortMessage = RcpSupport.getMessage(sqlException.getClass().getName() + "."
+ sqlException.getErrorCode() + "." + RcpSupport.MESSAGE);
if (!StringUtils.hasText(shortMessage))
{
shortMessage = RcpSupport
.getMessage(sqlException.getClass().getName() + "." + RcpSupport.MESSAGE);
shortMessage += "\nSQL error " + sqlException.getErrorCode();
}
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = sqlException.getMessage();
if (shortMessage == null || "".equals(shortMessage))
{
shortMessage = RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
}
}
showErrorDialog(null, new ErrorInfo(title, shortMessage, getDetailsAsHTML(title, Level.SEVERE,
sqlException), null, sqlException, Level.SEVERE, null));
}
public static void showErrorDialogResolveMessages(String id)
{
String title = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String message = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
String detail = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.DETAIL);
detail = detail == RcpSupport.ERROR_KEY ? "" : detail;
showErrorDialog(title, message, detail);
}
public static void showErrorDialog(String message)
{
showErrorDialog(message, (String) null);
}
public static void showErrorDialog(String message, String detail)
{
showErrorDialog(RcpSupport.getMessage(null, RcpSupport.ERROR_KEY, RcpSupport.TITLE), message, detail);
}
public static void showErrorDialog(String id, Throwable cause)
{
String title = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.TITLE);
String message = RcpSupport.getMessage(id, RcpSupport.ERROR_KEY, RcpSupport.MESSAGE);
showErrorDialog(null, new ErrorInfo(title, message, getDetailsAsHTML(title, Level.SEVERE, cause),
null, cause, Level.SEVERE, null));
}
public static void showErrorDialog(String title, String message, String detail)
{
showErrorDialog(null, new ErrorInfo(title, message, detail, null, null, Level.SEVERE, null));
}
public static void showErrorDialog(Component parent, ErrorInfo errorInfo)
{
if (parent == null)
{
if (org.springframework.richclient.application.Application.isLoaded())
{
ApplicationWindow activeWindow = org.springframework.richclient.application.Application
.instance().getActiveWindow();
if (activeWindow != null)
parent = activeWindow.getControl();
}
}
JXErrorPane pane = new JXErrorPane();
pane.setErrorInfo(errorInfo);
pane.setErrorReporter(new JdicEmailNotifierErrorReporter());
JXErrorPane.showDialog(parent, pane);
}
/**
* @see RcpSupport#showWarningDialog(Component, String, int)
*/
public static int showWarningDialog(String id, int optionType)
{
return showWarningDialog(Application.instance().getActiveWindow().getControl(), id, optionType);
}
/**
* @see RcpSupport#showWarningDialog(Component, String, int)
*/
public static int showWarningDialog(Component parent, String id, int optionType)
{
return showWarningDialog(parent, id, null, optionType);
}
public static int showWarningDialog(Component parent, String id, Object[] parameters, int optionType)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
return JOptionPane.showConfirmDialog(parent, message, title, optionType, JOptionPane.WARNING_MESSAGE);
}
/**
* @see RcpSupport#showWarningDialog(Component, String, Object[], int, int)
*/
public static int showWarningDialog(String id, int optionType, int initialValue)
{
return showWarningDialog(Application.instance().getActiveWindow().getControl(), id, null, optionType,
initialValue);
}
public static int showWarningDialog(Component parent, String id, Object[] parameters, int optionType,
int initialValue)
{
Object[] options = optionsMap.get(Integer.valueOf(optionType));
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
if (optionType == JOptionPane.OK_CANCEL_OPTION && initialValue == CANCEL_OPTION)
initialValue = 1;
if (initialValue >= options.length)
throw new IllegalArgumentException(
"De waarde van het argument initialValue is niet gekend door het gekozen optionType");
return JOptionPane.showOptionDialog(parent, message, title, optionType, JOptionPane.WARNING_MESSAGE,
null, options, options[initialValue]);
}
public static ActionCommand createDummyCommand(final String id, final String msg)
{
ActionCommand newCommand = new ActionCommand(id)
{
protected void doExecuteCommand()
{
System.out.println(msg);
}
};
((CommandConfigurer) ApplicationServicesLocator.services().getService(CommandConfigurer.class))
.configure(newCommand);
return newCommand;
}
public static void showWarningDialog(String id)
{
showWarningDialog(Application.instance().getActiveWindow().getControl(), id);
}
public static void showWarningDialog(Component parent, String id)
{
showWarningDialog(parent, id, null);
}
public static void showWarningDialog(Component parent, String id, Object[] parameters)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
JOptionPane.showMessageDialog(parent, message, title, JOptionPane.WARNING_MESSAGE);
}
public static int showConfirmationDialog(String id)
{
return showConfirmationDialog(Application.instance().getActiveWindow().getControl(), id);
}
public static int showConfirmationDialog(Component parent, String id)
{
return showConfirmationDialog(parent, id, null);
}
public static int showConfirmationDialog(Component parent, String id, Object[] parameters)
{
return showConfirmationDialog(parent, id, parameters, JOptionPane.YES_NO_CANCEL_OPTION);
}
public static int showConfirmationDialog(Component parent, String id, Object[] parameters, int optionType)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
return JOptionPane.showConfirmDialog(parent, message, title, optionType);
}
public static void showMessageDialog(Component parent, String id, Object[] parameters, int optionType)
{
String message = getMessage(null, id, TEXT, parameters);
String title = getMessage(null, id, TITLE);
JOptionPane.showMessageDialog(parent, message, title, optionType);
}
/**
* This method tries to map the values of the given object on the valueModels of the formModel. Instead of
* setting the object as a backing object, all valueModels are processed one by one and the corresponding
* property value is fetched from the objectToMap and set on that valueModel. This triggers the usual
* buffering etc. just as if the user entered the values.
*
* @param formModel
* @param objectToMap
*/
public static void mapObjectOnFormModel(FormModel formModel, Object objectToMap)
{
BeanWrapper beanWrapper = new BeanWrapperImpl(objectToMap);
for (String fieldName : (Set<String>) formModel.getFieldNames())
{
try
{
formModel.getValueModel(fieldName).setValue(beanWrapper.getPropertyValue(fieldName));
}
catch (BeansException be)
{
// silently ignoring, just mapping values, so if there's one missing, don't bother
}
}
}
private static Object clonePublicCloneableObject(Object value)
{
try
{
return ((PublicCloneable) value).clone();
}
catch (CloneNotSupportedException e)
{
throw new RuntimeException("Clone not support for object " + value.getClass());
}
}
public static Object getClone(Object value)
{
if (value instanceof PublicCloneable)
{
return clonePublicCloneableObject(value);
}
else if (value instanceof Collection)
{
Collection valueCollection = (Collection) value;
Collection clonedCollection;
if (valueCollection instanceof java.util.List)
{
clonedCollection = (valueCollection instanceof LinkedList)
? new LinkedList()
: new ArrayList();
}
else if (valueCollection instanceof Set)
{
clonedCollection = (valueCollection instanceof SortedSet)
? new TreeSet()
: (valueCollection instanceof LinkedHashSet) ? new LinkedHashSet() : new HashSet();
}
else
{
clonedCollection = (Collection) BeanUtils.instantiateClass(value.getClass());
}
for (Object valueElement : valueCollection)
{
if (valueElement instanceof PublicCloneable)
{
clonedCollection.add(clonePublicCloneableObject(valueElement));
}
else
{
// there isn't much else we can do?
clonedCollection.add(valueElement);
}
}
return clonedCollection;
}
else if (value instanceof Map)
{
Map valueMap = (Map) value;
Map clonedMap = (valueMap instanceof SortedMap)
? new TreeMap()
: (valueMap instanceof LinkedHashMap) ? new LinkedHashMap() : new HashMap();
for (Iterator entryIter = valueMap.entrySet().iterator(); entryIter.hasNext();)
{
Map.Entry entry = (Map.Entry) entryIter.next();
if (entry.getValue() instanceof PublicCloneable)
{
clonedMap.put(entry.getKey(), clonePublicCloneableObject(entry.getValue()));
}
else
{
// there isn't much else we can do?
clonedMap.put(entry.getKey(), entry.getValue());
}
}
return clonedMap;
}
return value;
}
public static JPanel createIconButtonPanel(List<? extends AbstractCommand> commands)
{
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
ButtonFactory factory = new DefaultButtonFactory();
CommandButtonConfigurer configurer = new CommandButtonConfigurer()
{
public void configure(AbstractButton button, AbstractCommand command,
CommandFaceDescriptor faceDescriptor)
{
faceDescriptor.configureIcon(button);
button.setToolTipText(faceDescriptor.getCaption());
}
};
for (AbstractCommand command : commands)
{
buttons.add(command.createButton(factory, configurer));
}
return buttons;
}
public static JComponent createDummyPanel(String vakske)
{
JPanel dummy = new JPanel();
dummy.add(new JLabel(vakske));
return dummy;
}
/**
* Toon een dataeditor<SUF>*/
public static void executeViewDataEditorCommand(DataEditorWidgetViewCommand command, Object filter,
Object defaultSelectedObject)
{
org.springframework.util.Assert.notNull(command, "Command mag niet null zijn!");
Map<String, Object> dataEditorParameters = new HashMap<String, Object>(2);
dataEditorParameters.put(DefaultDataEditorWidget.PARAMETER_FILTER, filter);
dataEditorParameters.put(DefaultDataEditorWidget.PARAMETER_DEFAULT_SELECTED_OBJECT,
defaultSelectedObject);
Map<String, Object> commandParameters = new HashMap<String, Object>(1);
commandParameters.put(DefaultDataEditorWidget.PARAMETER_MAP, dataEditorParameters);
command.execute(commandParameters);
}
}
|
203480_0 | package testen;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* geen public
* Testklassen zijn enkel gekend in de package zelf
*/
class VoorbeeldTest
{
/*
* alle methoden met @Test zal JUnit uitvoeren
* methode met @Test is ATLIJD VOID methode
* ALTIJD methode met 0 argumenten
*/
/*
@Test
// geen public
void test()
{
fail("Not yet implemented");
}
@Test
void test2() {
fail("not yes implemented");
}
/*
* Welke volgorde worden de testenmethoden opgroepen? / JUnit kiest zelf => willekeurig
* testmethoden mogen Niet afhangen van elkaar!
* testmethode test 1 iets uit
*/
}
| kodarakK/hogent | Object-oriented Software Development/H08_Theorie_JUnit/src/testen/VoorbeeldTest.java | 241 | /*
* geen public
* Testklassen zijn enkel gekend in de package zelf
*/ | block_comment | nl | package testen;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* geen public
<SUF>*/
class VoorbeeldTest
{
/*
* alle methoden met @Test zal JUnit uitvoeren
* methode met @Test is ATLIJD VOID methode
* ALTIJD methode met 0 argumenten
*/
/*
@Test
// geen public
void test()
{
fail("Not yet implemented");
}
@Test
void test2() {
fail("not yes implemented");
}
/*
* Welke volgorde worden de testenmethoden opgroepen? / JUnit kiest zelf => willekeurig
* testmethoden mogen Niet afhangen van elkaar!
* testmethode test 1 iets uit
*/
}
|
203480_1 | package testen;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* geen public
* Testklassen zijn enkel gekend in de package zelf
*/
class VoorbeeldTest
{
/*
* alle methoden met @Test zal JUnit uitvoeren
* methode met @Test is ATLIJD VOID methode
* ALTIJD methode met 0 argumenten
*/
/*
@Test
// geen public
void test()
{
fail("Not yet implemented");
}
@Test
void test2() {
fail("not yes implemented");
}
/*
* Welke volgorde worden de testenmethoden opgroepen? / JUnit kiest zelf => willekeurig
* testmethoden mogen Niet afhangen van elkaar!
* testmethode test 1 iets uit
*/
}
| kodarakK/hogent | Object-oriented Software Development/H08_Theorie_JUnit/src/testen/VoorbeeldTest.java | 241 | /*
* alle methoden met @Test zal JUnit uitvoeren
* methode met @Test is ATLIJD VOID methode
* ALTIJD methode met 0 argumenten
*/ | block_comment | nl | package testen;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* geen public
* Testklassen zijn enkel gekend in de package zelf
*/
class VoorbeeldTest
{
/*
* alle methoden met<SUF>*/
/*
@Test
// geen public
void test()
{
fail("Not yet implemented");
}
@Test
void test2() {
fail("not yes implemented");
}
/*
* Welke volgorde worden de testenmethoden opgroepen? / JUnit kiest zelf => willekeurig
* testmethoden mogen Niet afhangen van elkaar!
* testmethode test 1 iets uit
*/
}
|
203480_2 | package testen;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* geen public
* Testklassen zijn enkel gekend in de package zelf
*/
class VoorbeeldTest
{
/*
* alle methoden met @Test zal JUnit uitvoeren
* methode met @Test is ATLIJD VOID methode
* ALTIJD methode met 0 argumenten
*/
/*
@Test
// geen public
void test()
{
fail("Not yet implemented");
}
@Test
void test2() {
fail("not yes implemented");
}
/*
* Welke volgorde worden de testenmethoden opgroepen? / JUnit kiest zelf => willekeurig
* testmethoden mogen Niet afhangen van elkaar!
* testmethode test 1 iets uit
*/
}
| kodarakK/hogent | Object-oriented Software Development/H08_Theorie_JUnit/src/testen/VoorbeeldTest.java | 241 | /*
@Test
// geen public
void test()
{
fail("Not yet implemented");
}
@Test
void test2() {
fail("not yes implemented");
}
/*
* Welke volgorde worden de testenmethoden opgroepen? / JUnit kiest zelf => willekeurig
* testmethoden mogen Niet afhangen van elkaar!
* testmethode test 1 iets uit
*/ | block_comment | nl | package testen;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* geen public
* Testklassen zijn enkel gekend in de package zelf
*/
class VoorbeeldTest
{
/*
* alle methoden met @Test zal JUnit uitvoeren
* methode met @Test is ATLIJD VOID methode
* ALTIJD methode met 0 argumenten
*/
/*
@Test
//<SUF>*/
}
|
203492_0 | package main;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import daos.FileDAO;
import entities.Element;
import entities.Form;
import entities.JSForm;
import entities.LogEntry;
import enums.ElementTypeID;
import enums.Filename;
import enums.LogLevel;
import enums.LogType;
import enums.UUIDmap;
import exceptions.JSFormCreationException;
// TODO : gekende problemen :
/*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/
public class JSFormCreator {
public static List<LogEntry> logEntries = new ArrayList<>();
public static void main(String[] args) {
try {
// do not apply a default name if element has none
Element.setAllowNullableName(true);
//String path = "C:/Users/geert.haegens/workspaces/GO8ws_DO_NOT_USE/globis_articles/forms";
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/struct_multiparents/forms/";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
logEntries.addAll(FileDAO.logEntries);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<JSForm> newForms = new HashSet<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
logEntries.addAll(FileDAO.logEntries);
}
// transform all forms
String parentUuid = null;
for (Form oldForm : oldForms) {
JSForm newJSform = JSForm.createJSform(oldForm);
if (newJSform != null) {
newForms.add(newJSform);
parentUuid = newJSform.getUUID();
JSForm newTMPform = JSForm.createTMPform(oldForm, parentUuid);
if (newTMPform != null) {
UUIDmap.uuidMapAdd(newTMPform.getUUID(), oldForm.getUUID());
newForms.add(newTMPform);
}
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "INVALID_TRANSFORMATION"));
}
/*
if (!oldForm.isTransformed()) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "TRANSFORMATION FAILED"));
}*/
logEntries.addAll(oldForm.logEntries);
}
// WRITE all js$ & tmp$ forms for (Form newForm : newForms) {
for (JSForm newForm : newForms) {
FileDAO.writeForm(newForm);
logEntries.addAll(FileDAO.logEntries);
}
// IF tmp$ : delete original + rename tmp$
for (JSForm newForm : newForms) {
if (newForm.getName().startsWith(Filename.TMP_PREFIX)) {
FileDAO.replaceOriginalByTMPform(newForm);
logEntries.addAll(FileDAO.logEntries);
}
}
// WRITE log file
FileDAO.writeLog(path + "JSFormCreator", logEntries);
System.out.println("Forms written : " + newForms.size());
System.err.println("Done.");
} catch (JSFormCreationException e) {
e.printStackTrace();
}
}
}
| globisnv/servoy-8-transformation-tool | jsFormCreationTool/src/main/JSFormCreator.java | 977 | // TODO : gekende problemen : | line_comment | nl | package main;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import daos.FileDAO;
import entities.Element;
import entities.Form;
import entities.JSForm;
import entities.LogEntry;
import enums.ElementTypeID;
import enums.Filename;
import enums.LogLevel;
import enums.LogType;
import enums.UUIDmap;
import exceptions.JSFormCreationException;
// TODO :<SUF>
/*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/
public class JSFormCreator {
public static List<LogEntry> logEntries = new ArrayList<>();
public static void main(String[] args) {
try {
// do not apply a default name if element has none
Element.setAllowNullableName(true);
//String path = "C:/Users/geert.haegens/workspaces/GO8ws_DO_NOT_USE/globis_articles/forms";
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/struct_multiparents/forms/";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
logEntries.addAll(FileDAO.logEntries);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<JSForm> newForms = new HashSet<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
logEntries.addAll(FileDAO.logEntries);
}
// transform all forms
String parentUuid = null;
for (Form oldForm : oldForms) {
JSForm newJSform = JSForm.createJSform(oldForm);
if (newJSform != null) {
newForms.add(newJSform);
parentUuid = newJSform.getUUID();
JSForm newTMPform = JSForm.createTMPform(oldForm, parentUuid);
if (newTMPform != null) {
UUIDmap.uuidMapAdd(newTMPform.getUUID(), oldForm.getUUID());
newForms.add(newTMPform);
}
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "INVALID_TRANSFORMATION"));
}
/*
if (!oldForm.isTransformed()) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "TRANSFORMATION FAILED"));
}*/
logEntries.addAll(oldForm.logEntries);
}
// WRITE all js$ & tmp$ forms for (Form newForm : newForms) {
for (JSForm newForm : newForms) {
FileDAO.writeForm(newForm);
logEntries.addAll(FileDAO.logEntries);
}
// IF tmp$ : delete original + rename tmp$
for (JSForm newForm : newForms) {
if (newForm.getName().startsWith(Filename.TMP_PREFIX)) {
FileDAO.replaceOriginalByTMPform(newForm);
logEntries.addAll(FileDAO.logEntries);
}
}
// WRITE log file
FileDAO.writeLog(path + "JSFormCreator", logEntries);
System.out.println("Forms written : " + newForms.size());
System.err.println("Done.");
} catch (JSFormCreationException e) {
e.printStackTrace();
}
}
}
|
203492_1 | package main;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import daos.FileDAO;
import entities.Element;
import entities.Form;
import entities.JSForm;
import entities.LogEntry;
import enums.ElementTypeID;
import enums.Filename;
import enums.LogLevel;
import enums.LogType;
import enums.UUIDmap;
import exceptions.JSFormCreationException;
// TODO : gekende problemen :
/*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/
public class JSFormCreator {
public static List<LogEntry> logEntries = new ArrayList<>();
public static void main(String[] args) {
try {
// do not apply a default name if element has none
Element.setAllowNullableName(true);
//String path = "C:/Users/geert.haegens/workspaces/GO8ws_DO_NOT_USE/globis_articles/forms";
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/struct_multiparents/forms/";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
logEntries.addAll(FileDAO.logEntries);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<JSForm> newForms = new HashSet<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
logEntries.addAll(FileDAO.logEntries);
}
// transform all forms
String parentUuid = null;
for (Form oldForm : oldForms) {
JSForm newJSform = JSForm.createJSform(oldForm);
if (newJSform != null) {
newForms.add(newJSform);
parentUuid = newJSform.getUUID();
JSForm newTMPform = JSForm.createTMPform(oldForm, parentUuid);
if (newTMPform != null) {
UUIDmap.uuidMapAdd(newTMPform.getUUID(), oldForm.getUUID());
newForms.add(newTMPform);
}
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "INVALID_TRANSFORMATION"));
}
/*
if (!oldForm.isTransformed()) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "TRANSFORMATION FAILED"));
}*/
logEntries.addAll(oldForm.logEntries);
}
// WRITE all js$ & tmp$ forms for (Form newForm : newForms) {
for (JSForm newForm : newForms) {
FileDAO.writeForm(newForm);
logEntries.addAll(FileDAO.logEntries);
}
// IF tmp$ : delete original + rename tmp$
for (JSForm newForm : newForms) {
if (newForm.getName().startsWith(Filename.TMP_PREFIX)) {
FileDAO.replaceOriginalByTMPform(newForm);
logEntries.addAll(FileDAO.logEntries);
}
}
// WRITE log file
FileDAO.writeLog(path + "JSFormCreator", logEntries);
System.out.println("Forms written : " + newForms.size());
System.err.println("Done.");
} catch (JSFormCreationException e) {
e.printStackTrace();
}
}
}
| globisnv/servoy-8-transformation-tool | jsFormCreationTool/src/main/JSFormCreator.java | 977 | /*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/ | block_comment | nl | package main;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import daos.FileDAO;
import entities.Element;
import entities.Form;
import entities.JSForm;
import entities.LogEntry;
import enums.ElementTypeID;
import enums.Filename;
import enums.LogLevel;
import enums.LogType;
import enums.UUIDmap;
import exceptions.JSFormCreationException;
// TODO : gekende problemen :
/*
* methodID = "-1"<SUF>*/
public class JSFormCreator {
public static List<LogEntry> logEntries = new ArrayList<>();
public static void main(String[] args) {
try {
// do not apply a default name if element has none
Element.setAllowNullableName(true);
//String path = "C:/Users/geert.haegens/workspaces/GO8ws_DO_NOT_USE/globis_articles/forms";
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/struct_multiparents/forms/";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
logEntries.addAll(FileDAO.logEntries);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<JSForm> newForms = new HashSet<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
logEntries.addAll(FileDAO.logEntries);
}
// transform all forms
String parentUuid = null;
for (Form oldForm : oldForms) {
JSForm newJSform = JSForm.createJSform(oldForm);
if (newJSform != null) {
newForms.add(newJSform);
parentUuid = newJSform.getUUID();
JSForm newTMPform = JSForm.createTMPform(oldForm, parentUuid);
if (newTMPform != null) {
UUIDmap.uuidMapAdd(newTMPform.getUUID(), oldForm.getUUID());
newForms.add(newTMPform);
}
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "INVALID_TRANSFORMATION"));
}
/*
if (!oldForm.isTransformed()) {
logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "TRANSFORMATION FAILED"));
}*/
logEntries.addAll(oldForm.logEntries);
}
// WRITE all js$ & tmp$ forms for (Form newForm : newForms) {
for (JSForm newForm : newForms) {
FileDAO.writeForm(newForm);
logEntries.addAll(FileDAO.logEntries);
}
// IF tmp$ : delete original + rename tmp$
for (JSForm newForm : newForms) {
if (newForm.getName().startsWith(Filename.TMP_PREFIX)) {
FileDAO.replaceOriginalByTMPform(newForm);
logEntries.addAll(FileDAO.logEntries);
}
}
// WRITE log file
FileDAO.writeLog(path + "JSFormCreator", logEntries);
System.out.println("Forms written : " + newForms.size());
System.err.println("Done.");
} catch (JSFormCreationException e) {
e.printStackTrace();
}
}
}
|
203493_0 | package main;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import daos.FileDAO;
import entities.Form;
import entities.FormElement;
import enums.ElementTypeID;
import enums.FormView;
import exceptions.FormTransformerException;
// TODO : gekende problemen :
/*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/
public class FormTransformer {
private static Map<String, String> uuidMap = new HashMap<>();
private static Set<String> uuidImmutables = new HashSet<>();
public static final String NG_PREFIX = "ng$";
public static final String FORM_EXT = ".frm";
public static final String JS_EXT = ".js";
public static final String CRLF = System.getProperty("line.separator");
public static final char QM = '"'; // quotation mark
public static final String SEARCH_ICON_IMAGEMEDIA_ID = "07a009d2-0a86-49d1-b28c-bff40b764c40";
public static final int DEFAULT_INPUT_HEIGHT = 50;
public static final int DEFAULT_BUTTON_HEIGHT = 30;
public static void main(String[] args) {
try {
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/ghaTest/forms";
//String path = "C:/Users/geert.haegens/workspaces/servoy8new12022016/globis_articles/forms";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<Form> newForms = new HashSet<>();
// true = nothing to do ; false = ERROR
Map<String, Boolean> logForms = new LinkedHashMap<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
}
// transform all forms
for (Form oldForm : oldForms) {
Form newForm = null;
switch (oldForm.getView()) {
case FormView.RECORD_VIEW:
newForm = oldForm.transform7dtl();
break;
case FormView.TABLE_VIEW:
FormElement parentFe = Form.findParentFormElement(oldForm.getUUID(), oldForms);
newForm = oldForm.transform7lst(parentFe);
newForms.add(newForm);
break;
default:
break;
}
if (oldForm.isTransformed() && newForm != null) {
uuidMap.put(oldForm.getUUID(), newForm.getUUID());
newForms.add(newForm);
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logForms.put(oldForm.getPath() + FormTransformer.FORM_EXT, false);
}
if (!oldForm.isTransformed()) {
logForms.put(oldForm.getPath() + "/" + oldForm.getName() + FormTransformer.FORM_EXT, true);
}
}
// WRITE log file
FileDAO.writeLog(path, logForms);
// WRITE all ng$ forms for (Form newForm : newForms) {
for (Form newForm : newForms) {
FileDAO.writeForm(newForm);
}
System.out.println("Forms written : "+newForms.size());
System.err.println("Done.");
} catch (FormTransformerException e) {
e.printStackTrace();
}
}
// GETTERS & SETTERS
public static Map<String, String> getUuidMap() {
return uuidMap;
}
// OTHERS
public static void scanForUuids(String string) {
Pattern REG_EX = Pattern.compile("uuid:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
String uuid = m.group(1);
if (!uuidImmutables.contains(uuid) && !uuidMap.containsKey(uuid)) {
uuidMap.put(uuid, UUID.randomUUID().toString());
}
}
}
public static void scanForImmutableUuids(String string) {
// valuelistIDs = immutable
Pattern REG_EX = Pattern.compile("valuelistID:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
uuidImmutables.add(m.group(1));
}
}
}
| globisnv/servoy-8-transformation-tool | jsFormSyncTool/src/main/FormTransformer.java | 1,344 | // TODO : gekende problemen :
| line_comment | nl | package main;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import daos.FileDAO;
import entities.Form;
import entities.FormElement;
import enums.ElementTypeID;
import enums.FormView;
import exceptions.FormTransformerException;
// TODO :<SUF>
/*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/
public class FormTransformer {
private static Map<String, String> uuidMap = new HashMap<>();
private static Set<String> uuidImmutables = new HashSet<>();
public static final String NG_PREFIX = "ng$";
public static final String FORM_EXT = ".frm";
public static final String JS_EXT = ".js";
public static final String CRLF = System.getProperty("line.separator");
public static final char QM = '"'; // quotation mark
public static final String SEARCH_ICON_IMAGEMEDIA_ID = "07a009d2-0a86-49d1-b28c-bff40b764c40";
public static final int DEFAULT_INPUT_HEIGHT = 50;
public static final int DEFAULT_BUTTON_HEIGHT = 30;
public static void main(String[] args) {
try {
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/ghaTest/forms";
//String path = "C:/Users/geert.haegens/workspaces/servoy8new12022016/globis_articles/forms";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<Form> newForms = new HashSet<>();
// true = nothing to do ; false = ERROR
Map<String, Boolean> logForms = new LinkedHashMap<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
}
// transform all forms
for (Form oldForm : oldForms) {
Form newForm = null;
switch (oldForm.getView()) {
case FormView.RECORD_VIEW:
newForm = oldForm.transform7dtl();
break;
case FormView.TABLE_VIEW:
FormElement parentFe = Form.findParentFormElement(oldForm.getUUID(), oldForms);
newForm = oldForm.transform7lst(parentFe);
newForms.add(newForm);
break;
default:
break;
}
if (oldForm.isTransformed() && newForm != null) {
uuidMap.put(oldForm.getUUID(), newForm.getUUID());
newForms.add(newForm);
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logForms.put(oldForm.getPath() + FormTransformer.FORM_EXT, false);
}
if (!oldForm.isTransformed()) {
logForms.put(oldForm.getPath() + "/" + oldForm.getName() + FormTransformer.FORM_EXT, true);
}
}
// WRITE log file
FileDAO.writeLog(path, logForms);
// WRITE all ng$ forms for (Form newForm : newForms) {
for (Form newForm : newForms) {
FileDAO.writeForm(newForm);
}
System.out.println("Forms written : "+newForms.size());
System.err.println("Done.");
} catch (FormTransformerException e) {
e.printStackTrace();
}
}
// GETTERS & SETTERS
public static Map<String, String> getUuidMap() {
return uuidMap;
}
// OTHERS
public static void scanForUuids(String string) {
Pattern REG_EX = Pattern.compile("uuid:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
String uuid = m.group(1);
if (!uuidImmutables.contains(uuid) && !uuidMap.containsKey(uuid)) {
uuidMap.put(uuid, UUID.randomUUID().toString());
}
}
}
public static void scanForImmutableUuids(String string) {
// valuelistIDs = immutable
Pattern REG_EX = Pattern.compile("valuelistID:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
uuidImmutables.add(m.group(1));
}
}
}
|
203493_1 | package main;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import daos.FileDAO;
import entities.Form;
import entities.FormElement;
import enums.ElementTypeID;
import enums.FormView;
import exceptions.FormTransformerException;
// TODO : gekende problemen :
/*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/
public class FormTransformer {
private static Map<String, String> uuidMap = new HashMap<>();
private static Set<String> uuidImmutables = new HashSet<>();
public static final String NG_PREFIX = "ng$";
public static final String FORM_EXT = ".frm";
public static final String JS_EXT = ".js";
public static final String CRLF = System.getProperty("line.separator");
public static final char QM = '"'; // quotation mark
public static final String SEARCH_ICON_IMAGEMEDIA_ID = "07a009d2-0a86-49d1-b28c-bff40b764c40";
public static final int DEFAULT_INPUT_HEIGHT = 50;
public static final int DEFAULT_BUTTON_HEIGHT = 30;
public static void main(String[] args) {
try {
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/ghaTest/forms";
//String path = "C:/Users/geert.haegens/workspaces/servoy8new12022016/globis_articles/forms";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<Form> newForms = new HashSet<>();
// true = nothing to do ; false = ERROR
Map<String, Boolean> logForms = new LinkedHashMap<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
}
// transform all forms
for (Form oldForm : oldForms) {
Form newForm = null;
switch (oldForm.getView()) {
case FormView.RECORD_VIEW:
newForm = oldForm.transform7dtl();
break;
case FormView.TABLE_VIEW:
FormElement parentFe = Form.findParentFormElement(oldForm.getUUID(), oldForms);
newForm = oldForm.transform7lst(parentFe);
newForms.add(newForm);
break;
default:
break;
}
if (oldForm.isTransformed() && newForm != null) {
uuidMap.put(oldForm.getUUID(), newForm.getUUID());
newForms.add(newForm);
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logForms.put(oldForm.getPath() + FormTransformer.FORM_EXT, false);
}
if (!oldForm.isTransformed()) {
logForms.put(oldForm.getPath() + "/" + oldForm.getName() + FormTransformer.FORM_EXT, true);
}
}
// WRITE log file
FileDAO.writeLog(path, logForms);
// WRITE all ng$ forms for (Form newForm : newForms) {
for (Form newForm : newForms) {
FileDAO.writeForm(newForm);
}
System.out.println("Forms written : "+newForms.size());
System.err.println("Done.");
} catch (FormTransformerException e) {
e.printStackTrace();
}
}
// GETTERS & SETTERS
public static Map<String, String> getUuidMap() {
return uuidMap;
}
// OTHERS
public static void scanForUuids(String string) {
Pattern REG_EX = Pattern.compile("uuid:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
String uuid = m.group(1);
if (!uuidImmutables.contains(uuid) && !uuidMap.containsKey(uuid)) {
uuidMap.put(uuid, UUID.randomUUID().toString());
}
}
}
public static void scanForImmutableUuids(String string) {
// valuelistIDs = immutable
Pattern REG_EX = Pattern.compile("valuelistID:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
uuidImmutables.add(m.group(1));
}
}
}
| globisnv/servoy-8-transformation-tool | jsFormSyncTool/src/main/FormTransformer.java | 1,344 | /*
* methodID = "-1" => -1 (zoniet : error in UUID string -1
* forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm
* ng$ form heeft ALERTS ?
*/ | block_comment | nl | package main;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import daos.FileDAO;
import entities.Form;
import entities.FormElement;
import enums.ElementTypeID;
import enums.FormView;
import exceptions.FormTransformerException;
// TODO : gekende problemen :
/*
* methodID = "-1"<SUF>*/
public class FormTransformer {
private static Map<String, String> uuidMap = new HashMap<>();
private static Set<String> uuidImmutables = new HashSet<>();
public static final String NG_PREFIX = "ng$";
public static final String FORM_EXT = ".frm";
public static final String JS_EXT = ".js";
public static final String CRLF = System.getProperty("line.separator");
public static final char QM = '"'; // quotation mark
public static final String SEARCH_ICON_IMAGEMEDIA_ID = "07a009d2-0a86-49d1-b28c-bff40b764c40";
public static final int DEFAULT_INPUT_HEIGHT = 50;
public static final int DEFAULT_BUTTON_HEIGHT = 30;
public static void main(String[] args) {
try {
String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/ghaTest/forms";
//String path = "C:/Users/geert.haegens/workspaces/servoy8new12022016/globis_articles/forms";
Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path);
System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size());
Set<Form> oldForms = new HashSet<>();
Set<Form> newForms = new HashSet<>();
// true = nothing to do ; false = ERROR
Map<String, Boolean> logForms = new LinkedHashMap<>();
// read all forms
for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) {
oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt));
}
// transform all forms
for (Form oldForm : oldForms) {
Form newForm = null;
switch (oldForm.getView()) {
case FormView.RECORD_VIEW:
newForm = oldForm.transform7dtl();
break;
case FormView.TABLE_VIEW:
FormElement parentFe = Form.findParentFormElement(oldForm.getUUID(), oldForms);
newForm = oldForm.transform7lst(parentFe);
newForms.add(newForm);
break;
default:
break;
}
if (oldForm.isTransformed() && newForm != null) {
uuidMap.put(oldForm.getUUID(), newForm.getUUID());
newForms.add(newForm);
}
// add log
if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) {
logForms.put(oldForm.getPath() + FormTransformer.FORM_EXT, false);
}
if (!oldForm.isTransformed()) {
logForms.put(oldForm.getPath() + "/" + oldForm.getName() + FormTransformer.FORM_EXT, true);
}
}
// WRITE log file
FileDAO.writeLog(path, logForms);
// WRITE all ng$ forms for (Form newForm : newForms) {
for (Form newForm : newForms) {
FileDAO.writeForm(newForm);
}
System.out.println("Forms written : "+newForms.size());
System.err.println("Done.");
} catch (FormTransformerException e) {
e.printStackTrace();
}
}
// GETTERS & SETTERS
public static Map<String, String> getUuidMap() {
return uuidMap;
}
// OTHERS
public static void scanForUuids(String string) {
Pattern REG_EX = Pattern.compile("uuid:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
String uuid = m.group(1);
if (!uuidImmutables.contains(uuid) && !uuidMap.containsKey(uuid)) {
uuidMap.put(uuid, UUID.randomUUID().toString());
}
}
}
public static void scanForImmutableUuids(String string) {
// valuelistIDs = immutable
Pattern REG_EX = Pattern.compile("valuelistID:.([-0-9A-Za-z]{36})");
Matcher m = REG_EX.matcher(string);
while (m.find()) {
uuidImmutables.add(m.group(1));
}
}
}
|
203495_8 | //package be.pxl.h1.opdracht5;
//
//public class Opdracht {
// public static void main(String[] args) {
// int x = 1;
// System.out.println("x = " + x + " en y = " + y); //y bestaat niet!
// {
// int y = 5;
// System.out.println("x = " + x + " en y = " + y);
// }
// System.out.println("x = " + " en y = " + y); //y is niet gedefinieerd!
// }
// System.out.println("x = " + " en y = " + y); //y niet gekend!
//}
// y is enkel gekend tussen de {accolades} waarin hij gedefinieerd werd, ergens anders in het programma is hij niet gekend!!! | hursittarcan/pxl | YEAR 1/Java Essentials/H1/src/be/pxl/h1/opdracht5/Opdracht.java | 213 | // y is enkel gekend tussen de {accolades} waarin hij gedefinieerd werd, ergens anders in het programma is hij niet gekend!!! | line_comment | nl | //package be.pxl.h1.opdracht5;
//
//public class Opdracht {
// public static void main(String[] args) {
// int x = 1;
// System.out.println("x = " + x + " en y = " + y); //y bestaat niet!
// {
// int y = 5;
// System.out.println("x = " + x + " en y = " + y);
// }
// System.out.println("x = " + " en y = " + y); //y is niet gedefinieerd!
// }
// System.out.println("x = " + " en y = " + y); //y niet gekend!
//}
// y is<SUF> |
203503_2 | package proeftentamen.voertuig_bus_trein;
public class Application {
public static void main(String[] args) {
// Bus b1 = new Voertuig("Daf", 100);
// Niet toegestaan, Voertuig IS geen (sub)type van Bus, en kan dus niet aan een Bus-variabele toegekend worden
// Daarnaast is Voertuig abstract, en kan er überhaupt geen object van gemaakt worden.
Voertuig v1 = new Trein("Fyra", 275);
// Toegestaan, Trein IS een (sub)type van Voertuig, en kan dus toegekend worden aan een Voertuig-variabele.
// Voertuig v2 = new Voertuig("Daf", 100);
// Niet toegestaan, Voertuig is abstract, en er kan dus geen object van gemaakt worden.
}
}
| BvEijkelenburg/v1oop-proeftentamen | src/proeftentamen/voertuig_bus_trein/Application.java | 210 | // Daarnaast is Voertuig abstract, en kan er überhaupt geen object van gemaakt worden. | line_comment | nl | package proeftentamen.voertuig_bus_trein;
public class Application {
public static void main(String[] args) {
// Bus b1 = new Voertuig("Daf", 100);
// Niet toegestaan, Voertuig IS geen (sub)type van Bus, en kan dus niet aan een Bus-variabele toegekend worden
// Daarnaast is<SUF>
Voertuig v1 = new Trein("Fyra", 275);
// Toegestaan, Trein IS een (sub)type van Voertuig, en kan dus toegekend worden aan een Voertuig-variabele.
// Voertuig v2 = new Voertuig("Daf", 100);
// Niet toegestaan, Voertuig is abstract, en er kan dus geen object van gemaakt worden.
}
}
|
203503_5 | package proeftentamen.voertuig_bus_trein;
public class Application {
public static void main(String[] args) {
// Bus b1 = new Voertuig("Daf", 100);
// Niet toegestaan, Voertuig IS geen (sub)type van Bus, en kan dus niet aan een Bus-variabele toegekend worden
// Daarnaast is Voertuig abstract, en kan er überhaupt geen object van gemaakt worden.
Voertuig v1 = new Trein("Fyra", 275);
// Toegestaan, Trein IS een (sub)type van Voertuig, en kan dus toegekend worden aan een Voertuig-variabele.
// Voertuig v2 = new Voertuig("Daf", 100);
// Niet toegestaan, Voertuig is abstract, en er kan dus geen object van gemaakt worden.
}
}
| BvEijkelenburg/v1oop-proeftentamen | src/proeftentamen/voertuig_bus_trein/Application.java | 210 | // Niet toegestaan, Voertuig is abstract, en er kan dus geen object van gemaakt worden. | line_comment | nl | package proeftentamen.voertuig_bus_trein;
public class Application {
public static void main(String[] args) {
// Bus b1 = new Voertuig("Daf", 100);
// Niet toegestaan, Voertuig IS geen (sub)type van Bus, en kan dus niet aan een Bus-variabele toegekend worden
// Daarnaast is Voertuig abstract, en kan er überhaupt geen object van gemaakt worden.
Voertuig v1 = new Trein("Fyra", 275);
// Toegestaan, Trein IS een (sub)type van Voertuig, en kan dus toegekend worden aan een Voertuig-variabele.
// Voertuig v2 = new Voertuig("Daf", 100);
// Niet toegestaan,<SUF>
}
}
|
203517_1 | package be.ehb.koalaexpress.Tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import be.ehb.koalaexpress.KoalaDataRepository;
import be.ehb.koalaexpress.LocalFileOperations;
import be.ehb.koalaexpress.R;
public class Task_ImageLoad extends AsyncTask<String, Object, Bitmap> {
private ImageView mImageView;
private Context mContext;
public Boolean mFileIsGevonden;
public Task_ImageLoad(ImageView imageView) {
mImageView = imageView;
mContext = imageView.getContext();
mFileIsGevonden=false;
}
@Override
protected Bitmap doInBackground(String... params) {
// this executes in a background thread
Bitmap returnBitmap = null;
try {
// Imagenaam komt binnen via parameter van execute
String filename = params[0];
String localfoldername = "/images";
String localfilename = localfoldername+ "/" + filename;
//controleer eerst of filename lokaal gekend is
if(!LocalFileOperations.FileExists(localfilename, mContext) && KoalaDataRepository.getInstance().mServerIsOnline) {
// img niet on local file, try to get from web als online bent
String url = "http://www.Jursairplanefactory.com/koalaimg/" + filename;
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
if (input != null) {
//bitmap is correct ontvangen van web, nu opslaan lokaal voor toekomstig rechtstreeks lezen
LocalFileOperations.createFolderIfNotExists(localfoldername, mContext);
LocalFileOperations.saveInputStreamToLocalFile(input, localfilename, mContext);
}
}
if(LocalFileOperations.FileExists(localfilename, mContext)) {
// als file nu bestaat al lokaal, openen via lokale file /data/user/0/be.ehb.koalaexpress/files/test.bmp
InputStream inputStreamFromFile = LocalFileOperations.loadInputStreamFromLocalFile(localfilename, mContext);
if (inputStreamFromFile != null) {
returnBitmap = BitmapFactory.decodeStream(inputStreamFromFile);
try {
inputStreamFromFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
mFileIsGevonden = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// this exectutes in the main UI thread
if (mFileIsGevonden == true) {
mImageView.setImageBitmap(result);
}
else {
mImageView.setImageResource(R.mipmap.ic_no_image);
}
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/Tasks/Task_ImageLoad.java | 775 | // Imagenaam komt binnen via parameter van execute | line_comment | nl | package be.ehb.koalaexpress.Tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import be.ehb.koalaexpress.KoalaDataRepository;
import be.ehb.koalaexpress.LocalFileOperations;
import be.ehb.koalaexpress.R;
public class Task_ImageLoad extends AsyncTask<String, Object, Bitmap> {
private ImageView mImageView;
private Context mContext;
public Boolean mFileIsGevonden;
public Task_ImageLoad(ImageView imageView) {
mImageView = imageView;
mContext = imageView.getContext();
mFileIsGevonden=false;
}
@Override
protected Bitmap doInBackground(String... params) {
// this executes in a background thread
Bitmap returnBitmap = null;
try {
// Imagenaam komt<SUF>
String filename = params[0];
String localfoldername = "/images";
String localfilename = localfoldername+ "/" + filename;
//controleer eerst of filename lokaal gekend is
if(!LocalFileOperations.FileExists(localfilename, mContext) && KoalaDataRepository.getInstance().mServerIsOnline) {
// img niet on local file, try to get from web als online bent
String url = "http://www.Jursairplanefactory.com/koalaimg/" + filename;
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
if (input != null) {
//bitmap is correct ontvangen van web, nu opslaan lokaal voor toekomstig rechtstreeks lezen
LocalFileOperations.createFolderIfNotExists(localfoldername, mContext);
LocalFileOperations.saveInputStreamToLocalFile(input, localfilename, mContext);
}
}
if(LocalFileOperations.FileExists(localfilename, mContext)) {
// als file nu bestaat al lokaal, openen via lokale file /data/user/0/be.ehb.koalaexpress/files/test.bmp
InputStream inputStreamFromFile = LocalFileOperations.loadInputStreamFromLocalFile(localfilename, mContext);
if (inputStreamFromFile != null) {
returnBitmap = BitmapFactory.decodeStream(inputStreamFromFile);
try {
inputStreamFromFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
mFileIsGevonden = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// this exectutes in the main UI thread
if (mFileIsGevonden == true) {
mImageView.setImageBitmap(result);
}
else {
mImageView.setImageResource(R.mipmap.ic_no_image);
}
}
} |
203517_2 | package be.ehb.koalaexpress.Tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import be.ehb.koalaexpress.KoalaDataRepository;
import be.ehb.koalaexpress.LocalFileOperations;
import be.ehb.koalaexpress.R;
public class Task_ImageLoad extends AsyncTask<String, Object, Bitmap> {
private ImageView mImageView;
private Context mContext;
public Boolean mFileIsGevonden;
public Task_ImageLoad(ImageView imageView) {
mImageView = imageView;
mContext = imageView.getContext();
mFileIsGevonden=false;
}
@Override
protected Bitmap doInBackground(String... params) {
// this executes in a background thread
Bitmap returnBitmap = null;
try {
// Imagenaam komt binnen via parameter van execute
String filename = params[0];
String localfoldername = "/images";
String localfilename = localfoldername+ "/" + filename;
//controleer eerst of filename lokaal gekend is
if(!LocalFileOperations.FileExists(localfilename, mContext) && KoalaDataRepository.getInstance().mServerIsOnline) {
// img niet on local file, try to get from web als online bent
String url = "http://www.Jursairplanefactory.com/koalaimg/" + filename;
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
if (input != null) {
//bitmap is correct ontvangen van web, nu opslaan lokaal voor toekomstig rechtstreeks lezen
LocalFileOperations.createFolderIfNotExists(localfoldername, mContext);
LocalFileOperations.saveInputStreamToLocalFile(input, localfilename, mContext);
}
}
if(LocalFileOperations.FileExists(localfilename, mContext)) {
// als file nu bestaat al lokaal, openen via lokale file /data/user/0/be.ehb.koalaexpress/files/test.bmp
InputStream inputStreamFromFile = LocalFileOperations.loadInputStreamFromLocalFile(localfilename, mContext);
if (inputStreamFromFile != null) {
returnBitmap = BitmapFactory.decodeStream(inputStreamFromFile);
try {
inputStreamFromFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
mFileIsGevonden = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// this exectutes in the main UI thread
if (mFileIsGevonden == true) {
mImageView.setImageBitmap(result);
}
else {
mImageView.setImageResource(R.mipmap.ic_no_image);
}
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/Tasks/Task_ImageLoad.java | 775 | //controleer eerst of filename lokaal gekend is | line_comment | nl | package be.ehb.koalaexpress.Tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import be.ehb.koalaexpress.KoalaDataRepository;
import be.ehb.koalaexpress.LocalFileOperations;
import be.ehb.koalaexpress.R;
public class Task_ImageLoad extends AsyncTask<String, Object, Bitmap> {
private ImageView mImageView;
private Context mContext;
public Boolean mFileIsGevonden;
public Task_ImageLoad(ImageView imageView) {
mImageView = imageView;
mContext = imageView.getContext();
mFileIsGevonden=false;
}
@Override
protected Bitmap doInBackground(String... params) {
// this executes in a background thread
Bitmap returnBitmap = null;
try {
// Imagenaam komt binnen via parameter van execute
String filename = params[0];
String localfoldername = "/images";
String localfilename = localfoldername+ "/" + filename;
//controleer eerst<SUF>
if(!LocalFileOperations.FileExists(localfilename, mContext) && KoalaDataRepository.getInstance().mServerIsOnline) {
// img niet on local file, try to get from web als online bent
String url = "http://www.Jursairplanefactory.com/koalaimg/" + filename;
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
if (input != null) {
//bitmap is correct ontvangen van web, nu opslaan lokaal voor toekomstig rechtstreeks lezen
LocalFileOperations.createFolderIfNotExists(localfoldername, mContext);
LocalFileOperations.saveInputStreamToLocalFile(input, localfilename, mContext);
}
}
if(LocalFileOperations.FileExists(localfilename, mContext)) {
// als file nu bestaat al lokaal, openen via lokale file /data/user/0/be.ehb.koalaexpress/files/test.bmp
InputStream inputStreamFromFile = LocalFileOperations.loadInputStreamFromLocalFile(localfilename, mContext);
if (inputStreamFromFile != null) {
returnBitmap = BitmapFactory.decodeStream(inputStreamFromFile);
try {
inputStreamFromFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
mFileIsGevonden = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// this exectutes in the main UI thread
if (mFileIsGevonden == true) {
mImageView.setImageBitmap(result);
}
else {
mImageView.setImageResource(R.mipmap.ic_no_image);
}
}
} |
203517_5 | package be.ehb.koalaexpress.Tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import be.ehb.koalaexpress.KoalaDataRepository;
import be.ehb.koalaexpress.LocalFileOperations;
import be.ehb.koalaexpress.R;
public class Task_ImageLoad extends AsyncTask<String, Object, Bitmap> {
private ImageView mImageView;
private Context mContext;
public Boolean mFileIsGevonden;
public Task_ImageLoad(ImageView imageView) {
mImageView = imageView;
mContext = imageView.getContext();
mFileIsGevonden=false;
}
@Override
protected Bitmap doInBackground(String... params) {
// this executes in a background thread
Bitmap returnBitmap = null;
try {
// Imagenaam komt binnen via parameter van execute
String filename = params[0];
String localfoldername = "/images";
String localfilename = localfoldername+ "/" + filename;
//controleer eerst of filename lokaal gekend is
if(!LocalFileOperations.FileExists(localfilename, mContext) && KoalaDataRepository.getInstance().mServerIsOnline) {
// img niet on local file, try to get from web als online bent
String url = "http://www.Jursairplanefactory.com/koalaimg/" + filename;
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
if (input != null) {
//bitmap is correct ontvangen van web, nu opslaan lokaal voor toekomstig rechtstreeks lezen
LocalFileOperations.createFolderIfNotExists(localfoldername, mContext);
LocalFileOperations.saveInputStreamToLocalFile(input, localfilename, mContext);
}
}
if(LocalFileOperations.FileExists(localfilename, mContext)) {
// als file nu bestaat al lokaal, openen via lokale file /data/user/0/be.ehb.koalaexpress/files/test.bmp
InputStream inputStreamFromFile = LocalFileOperations.loadInputStreamFromLocalFile(localfilename, mContext);
if (inputStreamFromFile != null) {
returnBitmap = BitmapFactory.decodeStream(inputStreamFromFile);
try {
inputStreamFromFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
mFileIsGevonden = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// this exectutes in the main UI thread
if (mFileIsGevonden == true) {
mImageView.setImageBitmap(result);
}
else {
mImageView.setImageResource(R.mipmap.ic_no_image);
}
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/Tasks/Task_ImageLoad.java | 775 | //bitmap is correct ontvangen van web, nu opslaan lokaal voor toekomstig rechtstreeks lezen | line_comment | nl | package be.ehb.koalaexpress.Tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import be.ehb.koalaexpress.KoalaDataRepository;
import be.ehb.koalaexpress.LocalFileOperations;
import be.ehb.koalaexpress.R;
public class Task_ImageLoad extends AsyncTask<String, Object, Bitmap> {
private ImageView mImageView;
private Context mContext;
public Boolean mFileIsGevonden;
public Task_ImageLoad(ImageView imageView) {
mImageView = imageView;
mContext = imageView.getContext();
mFileIsGevonden=false;
}
@Override
protected Bitmap doInBackground(String... params) {
// this executes in a background thread
Bitmap returnBitmap = null;
try {
// Imagenaam komt binnen via parameter van execute
String filename = params[0];
String localfoldername = "/images";
String localfilename = localfoldername+ "/" + filename;
//controleer eerst of filename lokaal gekend is
if(!LocalFileOperations.FileExists(localfilename, mContext) && KoalaDataRepository.getInstance().mServerIsOnline) {
// img niet on local file, try to get from web als online bent
String url = "http://www.Jursairplanefactory.com/koalaimg/" + filename;
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
if (input != null) {
//bitmap is<SUF>
LocalFileOperations.createFolderIfNotExists(localfoldername, mContext);
LocalFileOperations.saveInputStreamToLocalFile(input, localfilename, mContext);
}
}
if(LocalFileOperations.FileExists(localfilename, mContext)) {
// als file nu bestaat al lokaal, openen via lokale file /data/user/0/be.ehb.koalaexpress/files/test.bmp
InputStream inputStreamFromFile = LocalFileOperations.loadInputStreamFromLocalFile(localfilename, mContext);
if (inputStreamFromFile != null) {
returnBitmap = BitmapFactory.decodeStream(inputStreamFromFile);
try {
inputStreamFromFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
mFileIsGevonden = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// this exectutes in the main UI thread
if (mFileIsGevonden == true) {
mImageView.setImageBitmap(result);
}
else {
mImageView.setImageResource(R.mipmap.ic_no_image);
}
}
} |
203519_0 | package be.hogent.team10.catan_businesslogic.model.tileBehaviour;
import be.hogent.team10.catan_businesslogic.model.TileType;
/* mergedate : OK
*
*/
/**
*
* @author HP
*/
public class DesertTileBehaviour implements TileBehaviour {
TileType tileType = TileType.DESERT;
public DesertTileBehaviour(){
}
public void validateSetRobber() {
// empty
}
public void validateSetNumber(int number) throws Exception {
if(number != 0)
throw new UnsupportedOperationException("Er kan geen nummer toegekend worden aan een woestijntegel");
}
public void validateSetResource() throws Exception {
throw new UnsupportedOperationException("Er kan geen grondstof toegekend worden aan de woestijntegel");
}
public TileType getTileType() {
return TileType.DESERT;
}
}
| janseeuw/Settlers-of-Catan | catan_businesslogic/src/main/java/be/hogent/team10/catan_businesslogic/model/tileBehaviour/DesertTileBehaviour.java | 247 | /* mergedate : OK
*
*/ | block_comment | nl | package be.hogent.team10.catan_businesslogic.model.tileBehaviour;
import be.hogent.team10.catan_businesslogic.model.TileType;
/* mergedate : OK
<SUF>*/
/**
*
* @author HP
*/
public class DesertTileBehaviour implements TileBehaviour {
TileType tileType = TileType.DESERT;
public DesertTileBehaviour(){
}
public void validateSetRobber() {
// empty
}
public void validateSetNumber(int number) throws Exception {
if(number != 0)
throw new UnsupportedOperationException("Er kan geen nummer toegekend worden aan een woestijntegel");
}
public void validateSetResource() throws Exception {
throw new UnsupportedOperationException("Er kan geen grondstof toegekend worden aan de woestijntegel");
}
public TileType getTileType() {
return TileType.DESERT;
}
}
|
203520_0 | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
| iDeebSee/LEAP | backend/src/main/java/ap/be/backend/controllers/AuthController.java | 1,834 | /**
* @return alle rollen worden opgehaald.
*/ | block_comment | nl | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen<SUF>*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
|
203520_1 | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
| iDeebSee/LEAP | backend/src/main/java/ap/be/backend/controllers/AuthController.java | 1,834 | /**
* @return alle users worden hier opgehaald.
*/ | block_comment | nl | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users<SUF>*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
|
203520_2 | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
| iDeebSee/LEAP | backend/src/main/java/ap/be/backend/controllers/AuthController.java | 1,834 | /**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/ | block_comment | nl | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in<SUF>*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
|
203520_3 | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
| iDeebSee/LEAP | backend/src/main/java/ap/be/backend/controllers/AuthController.java | 1,834 | /**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/ | block_comment | nl | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om<SUF>*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
|
203520_4 | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
| iDeebSee/LEAP | backend/src/main/java/ap/be/backend/controllers/AuthController.java | 1,834 | /**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/ | block_comment | nl | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om<SUF>*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
|
203520_5 | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
| iDeebSee/LEAP | backend/src/main/java/ap/be/backend/controllers/AuthController.java | 1,834 | /**
* @return dient om een bepaalde gebruiker te verwijderen per id.
*/ | block_comment | nl | package ap.be.backend.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ap.be.backend.dtos.createdtos.UserCreateDto;
import ap.be.backend.dtos.editdtos.UserEditDto;
import ap.be.backend.dtos.readdtos.UserReadDto;
import ap.be.backend.models.Role;
import ap.be.backend.models.RolesEnum;
import ap.be.backend.models.User;
import ap.be.backend.payload.request.LoginRequest;
import ap.be.backend.payload.response.JwtResponse;
import ap.be.backend.payload.response.MessageResponse;
import ap.be.backend.repositories.RoleRepository;
import ap.be.backend.repositories.UserRepository;
import ap.be.backend.security.jwt.JwtUtils;
import ap.be.backend.security.services.UserDetailsImpl;
import ap.be.backend.services.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class AuthController {
@Autowired
UserMapper userMapper;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
/**
* @return alle rollen worden opgehaald.
*/
@GetMapping("/roles")
public ResponseEntity<List<String>> getRoles() {
List<String> roles = new ArrayList<String>();
roleRepository.findAll().forEach(role -> roles.add(role.getName().name().toLowerCase()));
return ResponseEntity.ok(roles);
}
/**
* @return alle users worden hier opgehaald.
*/
@GetMapping("/users")
public ResponseEntity<List<UserReadDto>> getUsers() {
List<UserReadDto> users = new ArrayList<UserReadDto>();
userRepository.findAll().forEach(user -> users.add(userMapper.convertToDTO(user.getId())));
return ResponseEntity.ok(users);
}
/**
* Dient om in te loggen, er word gecontrolleerd of de email en wachtwoord kloppen.
* verder is er ook een token van 24h, indien deze verloopt kan je geen api calls meer doen.
*/
@PostMapping("/signin")
public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
Set<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toSet());
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
/**
* @return dient om te registeren, er word een rol toegekend en een controle op email en gebruikersnaam
*/
@PostMapping("/register")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody UserCreateDto newUser) {
if(userRepository.existsByName(newUser.getName())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
if(userRepository.existsByEmail((newUser.getEmail()))) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email already in use!"));
}
User user = new User(newUser.getName(), newUser.getEmail(), null);
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully"));
}
/**
* @return dient om een gebruiker te bewerken, eventueel rollen veranderen.
*/
@PutMapping("/user/{id}")
public ResponseEntity<MessageResponse> editUser(@PathVariable("id") String id, @Valid @RequestBody UserEditDto newUser ) {
try {
User user = userRepository.findById(id).orElseThrow(RuntimeException::new);
user.setName(newUser.getName());
user.setEmail(newUser.getEmail());
Set<String> strRoles = newUser.getRoles();
Set<Role> roles = new HashSet<Role>();
if(strRoles == null) {
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RolesEnum.ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
default:
Role userRole = roleRepository.findByName(RolesEnum.USER)
.orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User edited successfully!"));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(new MessageResponse("Failed to edit user"));
}
}
/**
* @return dient om<SUF>*/
@DeleteMapping("/user/{id}")
public ResponseEntity<MessageResponse> deleteUser(@PathVariable("id") String id) {
if(userRepository.existsById(id)) {
userRepository.deleteById(id);
return ResponseEntity.ok(new MessageResponse("User was successfully deleted!"));
} else {
return ResponseEntity.badRequest().body(new MessageResponse("No user with that id could be found"));
}
}
}
|